> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Payments API — Flutter

Source: `modules/Payments/Routes/api.php` on `main` of `alalmiyalhura/outlet`.

**Verified route inventory:** 5 method/path entries. Route names and permissions are sourced from GitLab.

> **Contract completeness:** The five endpoint controllers, payment presenter, and fake-gateway FormRequests were inspected on GitLab `main`. Business-error envelope and gateway-specific webhook signatures still require separate verification.

## Common contracts

- Routes below are relative to `/api/v1`; the payment itself is initiated from the Orders pay/checkout endpoints, **not** from `POST /payments`.
- `GET /payments/methods` is public; `GET /payments/attempts/{id}` and fake-gateway actions require the authenticated payer. Other users receive the same not-found result as a missing attempt.
- The payment amount is `{ "amount": "123.45", "currency": "SAR" }`: decimal amount is a **string**, not a floating-point number.
- The controller returns `ApiResponse::ok(payload)` for these endpoints; the examples below show the **payload inside `data`**. Verify the global envelope against the Core response class before hard-coding it.
- Strings used as labels are localized. Nullable fields must be handled as nullable, and screens should use the backend `status`, `is_final`, `next_action`, `can_retry` and `poll_after_seconds` rather than infer gateway state.

## `GET /payments/methods`

**Access:** Public. **Request:** No body or endpoint-specific query parameters.

| Response field (`data`) | Type | Meaning |
|---|---|---|
| `title` | string | Localized screen title |
| `methods` | array<object> | Enabled methods in display order; can be empty |
| `methods[].code` | string | Method code to pass to Orders payment start |
| `methods[].label` | string | Localized method name |
| `methods[].sub_label` | string | Localized description |
| `methods[].card_form` | boolean | Card input belongs to gateway SDK, not backend |
| `methods[].is_default` | boolean | Recommended default method |
| `default_method` | string\|null | Default code; null if no enabled methods |
| `secure_note` | string | Localized security note |

Illustrative `data` (method code and translations vary by configuration):

```json
{
  "title": "Choose a payment method",
  "methods": [{"code": "card", "label": "Card", "sub_label": "Pay securely", "card_form": true, "is_default": true}],
  "default_method": "card",
  "secure_note": "Secure payment"
}
```

## `GET /payments/attempts/{id}`

**Access:** Authenticated payer only. **Path:** `id` is the numeric payment-attempt ID. **Request body:** None. While a pending attempt has a gateway reference, the backend may sync its status with the gateway when its configured polling interval has elapsed. Gateway unavailability leaves the attempt pending instead of forcing failure.

| Response field (`data`) | Type | Meaning |
|---|---|---|
| `id` | integer | Attempt ID |
| `reference` | string | Payment reference |
| `status` | string | Attempt status (`pending`, `succeeded`, etc.; use returned value) |
| `status_label` | string | Localized status |
| `is_final` / `is_paid` | boolean | Terminal / successful flags |
| `amount` | object `{amount:string,currency:string}` | Attempt amount |
| `method` | object `{code,label,sub_label,card_form}` | Method metadata |
| `created_at`, `paid_at` | ISO-8601 string\|null | Attempt creation / successful completion |
| `success` | `{title:string}`\|null | Present for successful payment |
| `failure` | object\|null | Final non-success outcome; see below |
| `money_taken` | boolean | True for captured-but-unaccepted anomaly |
| `anomaly` | mixed\|null | Gateway/payment anomaly data |
| `processing` | `{title:string,subtitle:string}`\|null | Present while pending |
| `next_action` | object\|null | Gateway step when payer action is required |
| `poll_after_seconds` | integer\|null | Server-provided delay while pending |
| `can_retry` | boolean | Retry eligibility of payable reference |

`next_action` when present: `type: "redirect" | "sdk"`, `driver`, `gateway_ref`, `client_secret`, `redirect_url` (nullable where applicable). Treat secrets as sensitive and do not log them. `failure` includes `code`, `title`, `message`, `causes_title` (nullable) and `causes` (array of strings). An anomaly can return `failure.code = "captured_refund_due"` and `money_taken = true`: **do not show “nothing was charged”** in that case.

Illustrative pending `data` (values are placeholders):

```json
{
  "id": 42, "reference": "ORDER-EXAMPLE", "status": "pending", "status_label": "Processing",
  "is_final": false, "is_paid": false,
  "amount": {"amount": "125.00", "currency": "SAR"},
  "method": {"code": "card", "label": "Card", "sub_label": "Pay securely", "card_form": true},
  "created_at": "2026-11-22T10:00:00+00:00", "paid_at": null,
  "success": null, "failure": null, "money_taken": false, "anomaly": null,
  "processing": {"title": "Processing", "subtitle": "Please wait"},
  "next_action": null, "poll_after_seconds": 3, "can_retry": false
}
```

**Flutter flow:** After starting payment through Orders, follow `next_action` when non-null; poll this endpoint at `poll_after_seconds` while `is_final == false`; stop polling on final state and render `success` or `failure`. The interval is configurable (minimum 1 second), not always 3.

## `POST /payments/webhooks/{driver}`

**Audience:** Payment gateway server-to-server, **not a Flutter call**. **Access:** No user token; the selected gateway driver verifies the signature over the **raw request body** and request headers. **Path:** `driver` identifies the gateway. Payload and signature headers are driver-specific and were not established from this controller.

| Response field (`data`) | Type | Meaning |
|---|---|---|
| `received` | boolean | `true` on acknowledged event |
| `attempt_id` | integer\|null | Matched attempt ID, if any |
| `status` | string\|null | Matched attempt status, if any |

Illustrative `data`: `{"received":true,"attempt_id":null,"status":null}`. Unknown intents and duplicate events are acknowledged with HTTP 200 to prevent gateway retries; signature verification still applies.

## `POST /payments/fake/attempts/{id}/simulate`

**Access:** Authenticated owner of a **fake-driver** attempt. **Availability:** Development only; returns 404 in production or when `PAYMENTS_FAKE_SIMULATOR=false`. Never integrate this into production Flutter UI.

| Request field | Type | Validation / default |
|---|---|---|
| `id` (path) | integer | Owned fake payment attempt with gateway reference |
| `outcome` | string | **Required**; `succeeded`, `insufficient_funds`, `invalid_card_data`, `card_not_enabled_online`, `declined`, `pending_then_succeeded`, `pending_then_failed`, `abandoned` |
| `deliver_webhook` | boolean | Optional; defaults to `true` |

```json
{"outcome":"succeeded","deliver_webhook":true}
```

**Response:** Same `data` schema as `GET /payments/attempts/{id}` after refreshing the attempt. With `deliver_webhook=true`, the controller runs the signed event through the real webhook handler.

## `POST /payments/fake/attempts/{id}/webhook`

**Access/availability:** Same fake-only restrictions as `simulate`.

| Request field | Type | Validation |
|---|---|---|
| `id` (path) | integer | Owned fake attempt |
| `event_id` | string | Optional; max 100, regex `^[A-Za-z0-9_-]+$` |

```json
{"event_id":"evt_demo_123"}
```

**Response:** Same `data` schema as `GET /payments/attempts/{id}`. Reusing an event ID exercises duplicate-webhook idempotency.

## Errors and implementation notes

| Situation | Verified behavior |
|---|---|
| Missing attempt or attempt owned by someone else | `PaymentAttemptNotFound` (not-found response) |
| Fake endpoint in production / simulator disabled | HTTP 404 |
| Attempt is not fake or lacks a gateway reference | HTTP 409 |
| Invalid fake request fields | Laravel FormRequest validation; exact global envelope not inspected |
| Pending gateway poll fails temporarily | Remains pending; client may poll again |
| Webhook invalid signature / unknown driver | Verify exact driver-specific error contract before implementing integration |

**Source review:** [`PaymentController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Payments/Interfaces/Http/Controllers/PaymentController.php), [`FakeGatewayController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Payments/Interfaces/Http/Controllers/FakeGatewayController.php), [`WebhookController.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Payments/Interfaces/Http/Controllers/WebhookController.php), [`PaymentPresenter.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Payments/Interfaces/Http/Presenters/PaymentPresenter.php), `SimulateRequest.php`, `FakeWebhookRequest.php`. Source-level verified, **not live API-tested**.
