# Reconciliation

> Keep your orders in step with Moov when webhooks are late, retried or missed, and resolve unknown outcomes without paying twice.

Webhooks are fast, but they are not a guarantee. Your server can be down, a delivery can be abandoned after its last retry, and events can arrive out of order. Reconciliation is a scheduled job on your side that reads the API and fixes any gap.

## What NorthechPay already does

- Moov sends its events to NorthechPay, which updates checkouts, transactions, payouts and disputes.
- Every 5 minutes, NorthechPay re-reads Moov for checkouts in `creating`, `open`, `processing`, `authorized` or `failed` that were created in the last 30 days and not synced in the last 2 minutes. It also re-reads unfinished payouts and disputes. Each run handles a bounded batch.
- Transfer statuses only move forward, so a late or repeated update cannot undo a completed payment.

So the API's view is usually only minutes behind Moov. Your job is to keep **your** orders in step with the API.

## A reconciliation job for pending orders

Run it every 5 to 15 minutes. For each order still waiting for payment, read its checkout and apply the same rules as your webhook handler.

```js
async function reconcilePendingOrders() {
    const pending = await orders.findAwaitingPayment({
        createdAfter: daysAgo(2),
    });

    for (const order of pending) {
        const response = await fetch(
            `${process.env.NORTHECHPAY_API_BASE}/merchant/checkouts/${order.checkoutId}`,
            {
                headers: {
                    Authorization: `Bearer ${process.env.NORTHECHPAY_API_KEY}`,
                    Accept: 'application/json',
                },
            },
        );

        if (response.status === 429) {
            const wait = Number(response.headers.get('Retry-After') ?? 60);
            await sleep(wait * 1000);
            continue; // picked up again on the next run
        }
        if (!response.ok) continue;

        const { data: checkout } = await response.json();
        const amountMatches =
            checkout.amount.amount === order.amountCents &&
            checkout.amount.currency === 'USD';

        if (checkout.paid && amountMatches) {
            await orders.markPaidOnce(order.id, checkout.paid_at);
        } else if (
            ['expired', 'disabled', 'creation_failed'].includes(checkout.status)
        ) {
            await orders.markCheckoutClosed(order.id, checkout.status);
        }
    }
}
```

```php
use Illuminate\Support\Facades\Http;

public function handle(): void
{
    $client = Http::baseUrl(config('services.northechpay.api_base'))
        ->withToken(config('services.northechpay.api_key'))
        ->acceptJson();

    Order::awaitingPayment()->where('created_at', '>', now()->subDays(2))->each(function (Order $order) use ($client) {
        $response = $client->get("/merchant/checkouts/{$order->checkout_id}");

        if ($response->status() === 429) {
            sleep((int) $response->header('Retry-After') ?: 60);

            return; // picked up again on the next run
        }

        if (! $response->successful()) {
            return;
        }

        $checkout = $response->json('data');
        $amountMatches = $checkout['amount']['amount'] === $order->amount_cents && $checkout['amount']['currency'] === 'USD';

        if ($checkout['paid'] === true && $amountMatches) {
            $order->markPaidOnce($checkout['paid_at']);
        } elseif (in_array($checkout['status'], ['expired', 'disabled', 'creation_failed'], true)) {
            $order->markCheckoutClosed($checkout['status']);
        }
    });
}
```

Use `GET`, not `POST …/refresh`, in scheduled jobs. `last_synced_at` tells you how fresh the data is. Call refresh only for a single checkout when a person is waiting, for example when a buyer clicks "Check payment status".

## A daily check

Once a day, compare completed payments with your paid orders:

1. List `GET /merchant/transactions?direction=incoming&status=completed&from=…&to=…` for the previous day.
2. Match each transaction to an order by `checkout_id`.
3. Flag any completed transaction with no paid order, and any paid order with no completed transaction.
4. Check `refunded_amount` and `disputed_amount` against your records.

### Paging through a list

Lists return `links.next` until the last page.

```js
async function listAll(path) {
    const items = [];
    let url = `${process.env.NORTHECHPAY_API_BASE}${path}`;

    while (url) {
        const response = await fetch(url, {
            headers: {
                Authorization: `Bearer ${process.env.NORTHECHPAY_API_KEY}`,
                Accept: 'application/json',
            },
        });
        const body = await response.json();
        if (!response.ok)
            throw new Error(`${body.error.code}: ${body.error.message}`);
        items.push(...body.data);
        url = body.links?.next ?? null;
    }
    return items;
}

const completed = await listAll(
    '/merchant/transactions?direction=incoming&status=completed&per_page=100&from=2026-11-23T00:00:00Z&to=2026-11-24T00:00:00Z',
);
```

```php
function list_all(string $path, array $query): array
{
    $client = Http::baseUrl(config('services.northechpay.api_base'))
        ->withToken(config('services.northechpay.api_key'))
        ->acceptJson();

    $items = [];
    $page = 1;

    do {
        $body = $client->get($path, [...$query, 'per_page' => 100, 'page' => $page])->throw()->json();
        $items = [...$items, ...$body['data']];
        $page++;
    } while ($page <= $body['meta']['last_page']);

    return $items;
}

$completed = list_all('/merchant/transactions', [
    'direction' => 'incoming',
    'status' => 'completed',
    'from' => '2026-11-23T00:00:00Z',
    'to' => '2026-11-24T00:00:00Z',
]);
```

## Unknown outcomes

A timeout means you do not know whether the operation happened. Never retry it with a new idempotency key.

| Operation       | Signal                                                                                         | What to do                                                                                                                        |
| --------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Create checkout | Your timeout, `503 provider_unavailable`, `504 provider_outcome_unknown`, or status `creating` | Retry with the same key or read the checkout. Wait for `open` or `creation_failed`.                                               |
| Refund          | Your timeout, `503`, `504`                                                                     | Retry with the same key or read the transaction. Watch `refunded_amount`.                                                         |
| Payout          | Your timeout, `503`, or status `outcome_unknown`                                               | Retry with the same key or call `POST /merchant/payouts/{id}/refresh`.                                                            |
| Dispute submit  | Your timeout, `503`, `504`                                                                     | Call `POST /merchant/disputes/{id}/refresh`. If the status is `under-review` or `evidence_submitted_at` is set, it was submitted. |

A retry with the same key never sends a second request to Moov for a request NorthechPay has already recorded. It returns the stored result.

## Abandoned webhooks

After 8 failed attempts a delivery is abandoned, and there is no manual redelivery. If your endpoint was down for hours:

1. Fix the endpoint.
2. Run your pending-orders job for the whole outage window.
3. Run the daily check for the same window.
