# Refunds

> Refund a completed card payment in full or in part, safely retry with the same Idempotency-Key, and confirm the result from Moov.

You refund a payment by refunding its transaction. NorthechPay sends the refund to Moov and returns the transaction re-read from Moov.

```text
POST /merchant/transactions/{transaction_id}/refunds
```

Abilities: `transactions:read` and `refunds:write`.

## What can be refunded

| Rule                                                             | If not met           |
| ---------------------------------------------------------------- | -------------------- |
| The transaction is `incoming` and of type `card-payment`         | `409 not_refundable` |
| Its `status` is `completed` (not `authorized`, not pending)      | `409 not_refundable` |
| It is not disputed (`disputed_amount` is zero)                   | `409 not_refundable` |
| The amount is at least 1 cent and at most the refundable balance | `422 invalid_amount` |

The refundable balance is `amount − refunded_amount`. On `invalid_amount`, `error.details.refundable` is a money object with the current balance.

> **Note:** A disputed payment cannot be refunded. Moov already took the disputed amount from the wallet, so a refund would pay the cardholder twice. Respond to the dispute instead. See [Disputes](/docs/disputes).

To find the transaction for a checkout, read the checkout. Its `transactions` array lists the transfers, and the completed incoming one is the payment.

## Request

| Field             | Rules                                                                                 |
| ----------------- | ------------------------------------------------------------------------------------- |
| `amount`          | Optional integer, cents, at least `1`. Omit it to refund the full refundable balance. |
| `idempotency_key` | Optional body alternative to the `Idempotency-Key` header. The header wins.           |

```bash
curl -sS -X POST "$NORTHECHPAY_API_BASE/merchant/transactions/01a2093b-77c1-7e0a-b5d2-0c1d2e3f4a5b/refunds" \
  -H "Authorization: Bearer $NORTHECHPAY_API_KEY" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: refund-order-1001-1" \
  -d '{"amount": 275}'
```

```js
const response = await fetch(
    `${process.env.NORTHECHPAY_API_BASE}/merchant/transactions/${transactionId}/refunds`,
    {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${process.env.NORTHECHPAY_API_KEY}`,
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Idempotency-Key': 'refund-order-1001-1',
        },
        body: JSON.stringify({ amount: 275 }),
    },
);
const body = await response.json();
if (!response.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
console.log(
    body.data.refunded_amount.formatted,
    response.headers.get('Idempotent-Replayed'),
);
```

```php
$response = Http::baseUrl(config('services.northechpay.api_base'))
    ->withToken(config('services.northechpay.api_key'))
    ->acceptJson()
    ->withHeaders(['Idempotency-Key' => 'refund-order-1001-1'])
    ->post("/merchant/transactions/{$transactionId}/refunds", ['amount' => 275])
    ->throw();

$transaction = $response->json('data');
$replayed = $response->header('Idempotent-Replayed') === 'true';
```

## Response

`200 OK` with the [transaction](/docs/transactions), re-read from Moov, and the header `Idempotent-Replayed: true` or `false`.

Check the result on the transaction:

- `refunds`: every Moov refund of this payment, each with its own `id`, `amount`, `status` (`pending`, then `completed` or `failed`) and `moov_refund_id`. Refunds made outside NorthechPay (for example in the Moov Dashboard) are listed too, with `origin: provider`.
- `refunded_amount`: Moov's running total for the payment.
- `refundable_amount`: what is left to refund. Completed refunds and refunds still in progress are both subtracted, so two refunds at the same time can never exceed the payment.
- The checkout status becomes `partially_refunded` or `refunded`.

Webhooks: one `checkout.refunded` per refund, when Moov completes it, and one `checkout.refund_failed` if Moov fails a refund it had accepted (its amount becomes refundable again). Each carries the refund in `data.refund`. Example: on a $10.00 payment, refunds of $2.00, $3.00 and then the rest (no `amount`) send three `checkout.refunded` events for $2.00, $3.00 and $5.00, and `refundable_amount` ends at $0.00.

Before each refund NorthechPay re-reads the payment and its refunds from Moov. If Moov cannot be reached, nothing is requested and you get `503 provider_unavailable`; retry with the same key.

## Idempotency

Refund keys are per merchant and separate from checkout keys.

| You send                                              | Result                                                                           |
| ----------------------------------------------------- | -------------------------------------------------------------------------------- |
| Same key, same transaction, same `amount`             | The original request is replayed. No second refund. `Idempotent-Replayed: true`. |
| Same key, different `amount` or different transaction | `409 idempotency_conflict`                                                       |
| Same key, `amount` omitted versus `amount` sent       | Treated as different requests: `409 idempotency_conflict`                        |
| No key at all (API)                                   | `422 validation_failed`: refunds through the API require a key.                  |
| A header or body key that does not match the format   | `422 validation_failed`. Nothing is refunded.                                    |

Use one key per refund you intend to make, for example `refund-{order}-{n}`, saved before the call.

> **Warning:** A replay returns the transaction, not the refund result. If Moov rejected the first attempt (for example `422 provider_validation_failed`), a retry with the same key returns `200` with `Idempotent-Replayed: true` and makes no refund. Always confirm with `refunded_amount`. After a rejected refund, fix the request and use a new key.

## Timeouts and unknown outcomes

If the call times out, or returns `503 provider_unavailable` or `504 provider_outcome_unknown`, the refund may or may not exist at Moov.

1. Do not send a new refund with a new key. That can refund twice. Until it is resolved, the unknown refund keeps its amount reserved, so `refundable_amount` already excludes it.
2. Retry with the same key. NorthechPay first looks for the refund at Moov; if Moov has it, you get the transaction with that refund. If Moov never received it, NorthechPay sends it once, with the same Moov idempotency key, so it can never become two refunds. Retries are accepted for 24 hours; after that you get `409 refund_outcome_unknown` and should read the transaction's `refunds`.
3. Watch the transaction's `refunds` and `refunded_amount`. They come from Moov.

## Errors

| HTTP | `error.code`                 | Meaning                                                                              |
| ---- | ---------------------------- | ------------------------------------------------------------------------------------ |
| 403  | `insufficient_scope`         | The key lacks `refunds:write` or `transactions:read`.                                |
| 404  | `not_found`                  | No transaction with that ID for this merchant.                                       |
| 409  | `not_refundable`             | Not a completed incoming card payment, or it is disputed.                            |
| 409  | `idempotency_conflict`       | The key was used for a different refund.                                             |
| 409  | `provider_conflict`          | Moov reported a conflict, for example a refund already in progress.                  |
| 422  | `invalid_amount`             | Zero or more than the refundable balance. See `details.refundable`.                  |
| 422  | `provider_validation_failed` | Moov rejected the refund.                                                            |
| 503  | `provider_unavailable`       | Moov could not be reached. Read the transaction before retrying.                     |
| 504  | `provider_outcome_unknown`   | Moov may have created the refund. Retry with the same key.                           |
| 409  | `refund_outcome_unknown`     | A refund with this key was never confirmed and is over 24 hours old. Read `refunds`. |
