# Integration guide

> Build a complete NorthechPay checkout flow for a website, from order creation to webhooks, fulfilment, retries and reconciliation.

This guide builds the full flow for a website that sells goods. It assumes you finished the [Quickstart](/docs/quickstart).

## The flow

```text
1. Buyer clicks "Pay"            → your server creates (or reuses) a checkout for the order
2. Your server redirects         → buyer pays on the Moov-hosted checkout_url
3. Buyer comes back by hand      → your order page shows the status your server knows
4. NorthechPay sends webhooks    → your server verifies, deduplicates, re-reads, marks paid once
5. Your scheduled job            → re-reads anything still pending (missed webhooks)
6. Fulfilment                    → only from your server's "paid" state
```

## 1. Store what you need on the order

Add these columns to your orders table:

| Column                     | Why                                                                          |
| -------------------------- | ---------------------------------------------------------------------------- |
| `amount_cents`             | The amount you expect, to compare with the checkout.                         |
| `payment_status`           | Your own state: `awaiting_payment`, `paid`, `checkout_closed`, `refunded`, … |
| `checkout_id`              | The NorthechPay checkout `id`.                                               |
| `checkout_attempt`         | A counter, starting at 1. It goes into the idempotency key.                  |
| `checkout_idempotency_key` | The key for the current attempt, saved before the API call.                  |
| `paid_at`                  | When the checkout became paid.                                               |

And one table for webhook events, with a unique index on the event `id`.

## 2. Create the checkout when the buyer clicks "Pay"

Rules:

- Save the idempotency key on the order before you call the API. Reuse it on every retry of the same attempt.
- If the order already has an `open` checkout, send the buyer to the same `checkout_url`. Do not create another.
- Create a new attempt (new key) only when the previous checkout is `expired`, `disabled` or `creation_failed`.

```js
// POST /orders/:id/pay
app.post('/orders/:id/pay', async (req, res) => {
    const order = await orders.findForCurrentBuyer(req, req.params.id); // never trust the ID alone
    if (order.paymentStatus === 'paid')
        return res.redirect(`/orders/${order.id}`);

    if (!order.checkoutIdempotencyKey) {
        order.checkoutAttempt = 1;
        order.checkoutIdempotencyKey = `order-${order.id}-1`;
        await orders.save(order); // saved BEFORE the API call
    }

    const checkout = await createCheckout(order); // see the Checkouts page; same key on every retry

    if (['expired', 'disabled', 'creation_failed'].includes(checkout.status)) {
        // This attempt is over. The next click on "Pay" uses a new key.
        order.checkoutAttempt += 1;
        order.checkoutIdempotencyKey = `order-${order.id}-${order.checkoutAttempt}`;
        await orders.save(order);
        return res.redirect(`/orders/${order.id}?payment_page=closed`);
    }

    order.checkoutId = checkout.id;
    await orders.save(order);

    if (!checkout.checkout_url) {
        // status "creating": the outcome at Moov is not known yet.
        return res.redirect(`/orders/${order.id}?checking=1`);
    }
    return res.redirect(303, checkout.checkout_url);
});
```

```php
// POST /orders/{order}/pay
public function pay(Request $request, Order $order): RedirectResponse
{
    $this->authorize('pay', $order); // never trust the ID alone

    if ($order->payment_status === 'paid') {
        return redirect()->route('orders.show', $order);
    }

    if ($order->checkout_idempotency_key === null) {
        $order->update(['checkout_attempt' => 1, 'checkout_idempotency_key' => "order-{$order->id}-1"]);
    }

    $checkout = $this->northechpay->createCheckout($order); // same key on every retry

    if (in_array($checkout['status'], ['expired', 'disabled', 'creation_failed'], true)) {
        // This attempt is over. The next click on "Pay" uses a new key.
        $attempt = $order->checkout_attempt + 1;
        $order->update(['checkout_attempt' => $attempt, 'checkout_idempotency_key' => "order-{$order->id}-{$attempt}"]);

        return redirect()->route('orders.show', [$order, 'payment_page' => 'closed']);
    }

    $order->update(['checkout_id' => $checkout['id']]);

    if ($checkout['checkout_url'] === null) {
        return redirect()->route('orders.show', [$order, 'checking' => 1]); // status "creating"
    }

    return redirect()->away($checkout['checkout_url'], 303);
}
```

Because the same key returns the same checkout, a double click, a browser retry or a server retry all land on one checkout.

If the API call itself times out, show "We are preparing your payment page, please wait" and try again with the same key. See [Checkouts](/docs/checkouts#timeouts-and-unknown-outcomes).

## 3. Show the order page

The buyer comes back to your site by hand. Moov payment links have no return URL. On the order page:

- Show your own `payment_status`, not anything from the URL.
- While it is `awaiting_payment`, say "Waiting for payment confirmation" and offer a "Check payment status" button.
- The button calls your server, which calls `POST /merchant/checkouts/{id}/refresh` once and applies the result with the same rules as the webhook handler.
- If the checkout is `authorized`, say "Card approved. Confirming payment." Do not show "Paid" yet.

## 4. Handle webhooks

Follow [Webhooks](/docs/webhooks): verify the signature against the raw body, record the event `id` once, respond `2xx` quickly, and process in the background.

In the background job, apply one function to the current checkout, whether it came from a webhook, a refresh or the scheduled job:

```js
async function applyCheckout(order, checkout) {
    if (checkout.id !== order.checkoutId) {
        // An older attempt. It should not be paid; if it is, a person must check for a double payment.
        if (checkout.paid)
            await alerts.raise('An older checkout for this order was paid', {
                orderId: order.id,
                checkoutId: checkout.id,
            });
        return;
    }

    const amountMatches =
        checkout.amount.amount === order.amountCents &&
        checkout.amount.currency === 'USD';

    if (checkout.paid && !amountMatches) {
        await alerts.raise('Paid amount does not match order', {
            orderId: order.id,
            checkoutId: checkout.id,
        });
        return;
    }

    if (checkout.paid && order.paymentStatus !== 'paid') {
        // Conditional update so two workers cannot both fulfil.
        const changed = await orders.updateWhere(
            { id: order.id, paymentStatus: 'awaiting_payment' },
            { paymentStatus: 'paid', paidAt: checkout.paid_at },
        );
        if (changed) await fulfilment.start(order.id);
    }

    if (
        !checkout.paid &&
        ['expired', 'disabled', 'creation_failed'].includes(checkout.status)
    ) {
        await orders.updateWhere(
            { id: order.id, paymentStatus: 'awaiting_payment' },
            { paymentStatus: 'checkout_closed' },
        );
    }

    if (
        ['partially_refunded', 'refunded', 'disputed', 'reversed'].includes(
            checkout.status,
        )
    ) {
        await orders.flagForReview(order.id, checkout.status);
    }
}
```

```php
public function applyCheckout(Order $order, array $checkout): void
{
    if ($checkout['id'] !== $order->checkout_id) {
        // An older attempt. It should not be paid; if it is, a person must check for a double payment.
        if ($checkout['paid'] === true) {
            report(new RuntimeException("An older checkout {$checkout['id']} for order {$order->id} was paid"));
        }

        return;
    }

    $amountMatches = $checkout['amount']['amount'] === $order->amount_cents && $checkout['amount']['currency'] === 'USD';

    if ($checkout['paid'] === true && ! $amountMatches) {
        report(new RuntimeException("Paid amount does not match order {$order->id}"));

        return;
    }

    if ($checkout['paid'] === true) {
        // Conditional update so two workers cannot both fulfil.
        $changed = Order::whereKey($order->id)
            ->where('payment_status', 'awaiting_payment')
            ->update(['payment_status' => 'paid', 'paid_at' => $checkout['paid_at']]);

        if ($changed === 1) {
            StartFulfilment::dispatch($order->id);
        }
    }

    if ($checkout['paid'] !== true && in_array($checkout['status'], ['expired', 'disabled', 'creation_failed'], true)) {
        Order::whereKey($order->id)->where('payment_status', 'awaiting_payment')->update(['payment_status' => 'checkout_closed']);
    }

    if (in_array($checkout['status'], ['partially_refunded', 'refunded', 'disputed', 'reversed'], true)) {
        $order->flagForReview($checkout['status']);
    }
}
```

This function never moves an order backwards, so late or duplicate events are harmless.

## 5. Reconcile on a schedule

Run a job every 5 to 15 minutes that reads the checkout of every order still `awaiting_payment` and calls the same `applyCheckout`. Add a daily check of completed transactions against paid orders. See [Reconciliation](/docs/reconciliation).

## 6. Cancel, expire and retry

| Situation                                  | Do this                                                                                                                  |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| The buyer cancels the order before paying  | `DELETE /merchant/checkouts/{id}`, then re-read: a payment in flight can still complete.                                 |
| The checkout expired (24 hours by default) | When the buyer clicks "Pay" again, start a new attempt with a new key.                                                   |
| The card was declined (`failed`)           | Send the buyer back to the same `checkout_url` while it is open.                                                         |
| A timeout while creating                   | Retry with the same key, or wait for `open` or `creation_failed`.                                                        |
| The order total changes before payment     | Disable the open checkout, then start a new attempt with a new key. The old key would return `409 idempotency_conflict`. |

## 7. Refunds (optional)

If your back office issues refunds, use a separate key with `refunds:write`. Find the payment in the checkout's `transactions` (the `incoming` one with `status: completed`), then follow [Refunds](/docs/refunds). Use one idempotency key per intended refund, such as `refund-{order}-{n}`, and confirm the result with `refunded_amount`.

## 8. Test it

Run each of these in test mode before you call the integration done:

| Test                                                            | Expected result                                                    |
| --------------------------------------------------------------- | ------------------------------------------------------------------ |
| Pay with `4111 1111 1111 1111`                                  | `authorized`, then `paid`. The order is fulfilled once.            |
| Pay with `4000 0200 0000 0000`                                  | `failed`. The order stays unpaid. The buyer can retry.             |
| Double-click "Pay"                                              | One checkout. The second response has `Idempotent-Replayed: true`. |
| Send a webhook with a wrong signature                           | Your endpoint answers `400` and changes nothing.                   |
| Deliver the same event twice                                    | Processed once.                                                    |
| Stop your webhook endpoint, pay, start it again                 | The scheduled job marks the order paid.                            |
| Let a checkout expire (or create one with a short `expires_at`) | The order shows the checkout closed. "Pay" creates a new attempt.  |
| Return to the order page right after paying                     | It shows "Waiting for payment confirmation", not "Paid".           |

Then go through the [Go-live checklist](/docs/go-live-checklist).
