# Errors

> The NorthechPay error envelope, every error code the API returns with its HTTP status, and which errors are safe to retry.

Every error from `/api/v1` has the same JSON shape, whatever went wrong:

```json
{
    "error": {
        "code": "validation_failed",
        "message": "The given data was invalid.",
        "details": {
            "amount": ["The amount field must be at least 50."]
        },
        "request_id": "6f1d2c3b-4a5e-4f60-9a7b-8c9d0e1f2a3b"
    }
}
```

| Field        | Meaning                                                                                     |
| ------------ | ------------------------------------------------------------------------------------------- |
| `code`       | Stable, machine-readable. Branch on this.                                                   |
| `message`    | Human-readable. It can change. Do not parse it.                                             |
| `details`    | An object. Field errors for `validation_failed`, extra data for some codes, otherwise `{}`. |
| `request_id` | The same value as the `X-Request-Id` response header. Log it.                               |

Send `Accept: application/json` on every request.

## Retry rules

| Kind of error                                                                        | Retry?                                                             |
| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------ |
| `validation_failed`, `insufficient_scope`, `not_found` and other 4xx business errors | No. Fix the request.                                               |
| `idempotency_conflict`                                                               | No. You reused a key for a different request.                      |
| `rate_limited` (429)                                                                 | Yes, after `Retry-After` seconds, with the same idempotency key.   |
| `provider_unavailable`, `provider_rate_limited` (503)                                | Yes, later, with the same idempotency key.                         |
| `provider_outcome_unknown` (504), or your own timeout                                | Read the resource first. Retry only with the same idempotency key. |
| `server_error` (500)                                                                 | Read the resource first. Retry with the same key.                  |

> **Warning:** Never retry a money-moving request with a new idempotency key unless you have confirmed the first one failed.

## Error codes

### Request and access

| HTTP | `code`                 | Meaning                                                                                    |
| ---- | ---------------------- | ------------------------------------------------------------------------------------------ |
| 401  | `unauthenticated`      | Missing, invalid, revoked or expired token.                                                |
| 403  | `insufficient_scope`   | The token lacks an ability. The message names it, for example `[checkouts:write]`.         |
| 403  | `forbidden`            | The action is not allowed for this credential.                                             |
| 403  | `logout_not_supported` | `DELETE /auth/token` was called with an API key or a browser session. Nothing was revoked. |
| 404  | `not_found`            | No such resource for this merchant. Other merchants' IDs also return this.                 |
| 422  | `validation_failed`    | Invalid fields. `details` maps each field to a list of messages.                           |
| 429  | `rate_limited`         | Too many requests. See the `Retry-After` header.                                           |
| 4xx  | `http_error`           | Another HTTP error, for example a wrong method on a path.                                  |
| 500  | `server_error`         | Unexpected error.                                                                          |

### Business rules

| HTTP | `code`                       | Meaning                                                                                                                                                    |
| ---- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 409  | `idempotency_conflict`       | This `Idempotency-Key` was already used with different parameters.                                                                                         |
| 409  | `merchant_required`          | A user token has no merchant selected or created.                                                                                                          |
| 409  | `merchant_exists`            | The user already belongs to a merchant.                                                                                                                    |
| 422  | `merchant_not_ready`         | The merchant is not onboarded to Moov, has no wallet payment method yet, or lacks a capability. `details.missing_capabilities` lists missing capabilities. |
| 409  | `checkout_not_disableable`   | The checkout has no Moov link to disable.                                                                                                                  |
| 409  | `not_refundable`             | Only completed incoming card payments can be refunded, and not while disputed.                                                                             |
| 422  | `invalid_amount`             | A refund or payout amount is out of range. For refunds, `details.refundable`.                                                                              |
| 422  | `insufficient_balance`       | The Moov available balance is lower than the payout. `details.available`.                                                                                  |
| 422  | `bank_account_not_eligible`  | The bank account is not verified for this payout method. `details.bank_account_id`, `details.method`.                                                      |
| 409  | `dispute_not_open`           | The dispute is not waiting for a response, or a response was already sent.                                                                                 |
| 409  | `dispute_action_in_progress` | Another submit or accept for this dispute is running.                                                                                                      |
| 422  | `evidence_required`          | Upload evidence before submitting.                                                                                                                         |

### Moov (provider) errors

| HTTP | `code`                         | Meaning                                                                         |
| ---- | ------------------------------ | ------------------------------------------------------------------------------- |
| 422  | `provider_validation_failed`   | Moov rejected the request as invalid.                                           |
| 409  | `provider_conflict`            | Moov reported a conflict.                                                       |
| 502  | `provider_unauthorized`        | Moov refused NorthechPay's credentials. Contact the platform operator.          |
| 502  | `provider_forbidden`           | Moov refused the action.                                                        |
| 502  | `provider_not_found`           | Moov could not find the resource.                                               |
| 502  | `provider_error`               | Moov failed in another way.                                                     |
| 502  | `provider_mismatch`            | Moov returned data for a different account or mode. It was not used.            |
| 503  | `provider_rate_limited`        | Moov is rate-limiting NorthechPay. Retry later.                                 |
| 503  | `provider_unavailable`         | Moov could not be reached. Retry later with the same key.                       |
| 503  | `provider_environment_blocked` | The safety guard blocked a change because Moov did not report test mode.        |
| 504  | `provider_outcome_unknown`     | Moov may have applied the change. Read the resource; NorthechPay reconciles it. |

When Moov rejects a request, `message` starts with `Moov rejected the request:` and `details` can include `provider_status` and `provider_request_id`.

### Onboarding (first-party apps only)

These come from the onboarding endpoints, which website API keys cannot call.

| HTTP | `code`                          | Meaning                                                    |
| ---- | ------------------------------- | ---------------------------------------------------------- |
| 409  | `account_already_linked`        | The business is linked to a different Moov account.        |
| 409  | `account_mismatch`              | The Moov account belongs to another business or session.   |
| 409  | `onboarding_session_expired`    | The secure onboarding session expired. Open it again.      |
| 409  | `secure_onboarding_unavailable` | Secure Moov onboarding is turned off on this server.       |
| 410  | `secure_onboarding_required`    | The old representative form is off. Use secure onboarding. |
| 422  | `invalid_account`               | Not a Moov account ID.                                     |
| 422  | `account_not_found`             | Moov does not show that account on this platform.          |
| 422  | `unsupported_account_type`      | Only business accounts can accept payments.                |

## Handling errors in code

```js
async function northechpay(path, init = {}) {
    const response = await fetch(`${process.env.NORTHECHPAY_API_BASE}${path}`, {
        ...init,
        headers: {
            Authorization: `Bearer ${process.env.NORTHECHPAY_API_KEY}`,
            Accept: 'application/json',
            ...(init.body ? { 'Content-Type': 'application/json' } : {}),
            ...init.headers,
        },
    });

    if (response.status === 204) return null;
    const body = await response.json();

    if (!response.ok) {
        const error = new Error(
            body.error?.message ?? `HTTP ${response.status}`,
        );
        error.status = response.status;
        error.code = body.error?.code;
        error.details = body.error?.details;
        error.requestId =
            body.error?.request_id ?? response.headers.get('X-Request-Id');
        error.retryAfter = Number(response.headers.get('Retry-After')) || null;
        throw error;
    }

    return body;
}
```

```php
use Illuminate\Http\Client\RequestException;

try {
    $checkout = $client->withHeaders(['Idempotency-Key' => $key])
        ->post('/merchant/checkouts', $payload)
        ->throw()
        ->json('data');
} catch (RequestException $exception) {
    $error = $exception->response->json('error') ?? [];
    $code = $error['code'] ?? 'unknown';

    logger()->warning('NorthechPay error', [
        'code' => $code,
        'request_id' => $error['request_id'] ?? $exception->response->header('X-Request-Id'),
    ]);

    if (in_array($code, ['provider_outcome_unknown', 'provider_unavailable', 'rate_limited'], true)) {
        // Retry later with the SAME $key, or read the checkout first.
    }

    throw $exception;
}
```
