---
name: flowpayra-integration
description: Integrate a business system (online shop, SaaS billing, membership site, marketplace) with a FlowPayra Lite deployment to accept crypto payments - create orders and subscriptions through its REST API, send payers to the hosted checkout (redirect or embedded modal), verify FlowPay-Signature webhooks and signed return URLs, fulfil only from server state, and handle duplicates, refunds, frozen payments, plan changes and the risk address list API. Use this skill whenever the user wants to add FlowPayra or FlowPay payments, a USDC / USDT / stablecoin or crypto checkout backed by a self-hosted FlowPayra Lite instance, recurring on-chain subscriptions, or mentions fpk_live_ / fpk_test_ keys, whsec_ secrets, /v1/orders, checkout_url or FlowPay-Signature, even when they do not say "integration". It is not for installing or operating the FlowPayra server itself (that is the flowpayra-deploy skill).
---

# Integrating FlowPayra Lite

FlowPayra Lite is a self-hosted, self-custodial crypto payment system. One deployment serves one merchant at its own
domain (`$FLOWPAY_BASE_URL`, for example `https://pay.example.com`). Your code talks to that deployment's REST API;
the payer pays on its hosted checkout with their own wallet; the funds settle on chain directly to the merchant's payee
addresses. The integration never touches private keys, wallets or chain RPC, and it never decides that something was
paid on its own: the deployment tells it, and the integration double-checks with the deployment.

## What to read, and when

This file is the whole flow and the rules. Open a reference only when the task needs it:

| File | Read it when |
|---|---|
| `references/orders.md` | Creating orders with options (tokens, chains, per-token prices, splits, expiry, locale, metadata), the order statuses, the return URL, the embedded checkout (`embed.js`) |
| `references/webhooks.md` | Writing the webhook receiver: the signature, delivery and retry behaviour, every event type and what to do with it, the event feed |
| `references/subscriptions.md` | Anything recurring: plans, subscription links, states and events, pause / resume / cancel, plan changes, "My subscriptions", migrations |
| `references/errors.md` | Handling API errors and retries: the error envelope, every error code and the right reaction, idempotency rules |
| `references/testing.md` | Testing: test mode keys, the local devnet, the signature test vectors, the go-live checklist |
| `references/risk-api.md` | Only if the user wants to sync a deny / allow list of payer addresses from their own risk system |
| `scripts/` | Signature helpers in Node.js, Python, Go, PHP and Java, tested against `scripts/vectors.json` |

The deployment's own OpenAPI document, `GET $FLOWPAY_BASE_URL/v1/openapi.yaml` (no authentication), is the authority
for fields, status codes and error codes of that deployment's version. Fetch it instead of guessing; if it disagrees
with this skill, the deployment wins.

## Before writing code, collect

1. `FLOWPAY_BASE_URL`: the deployment's public URL.
2. `FLOWPAY_API_KEY`: start with a **test** key (`fpk_test_…`); live keys are `fpk_live_…`. Keys carry scopes
   (`orders:write`, `orders:read`, `subscriptions:write`, `subscriptions:read`, `events:read`, and on request
   `risk:read` / `risk:write`); a key without an operation's scope gets `403 insufficient_scope`.
3. `FLOWPAY_WEBHOOK_SECRET`: the `whsec_…` secret of the **same mode** (live and test each have their own webhook URL
   and secret, set by the merchant in the console under **Developers → Webhooks**).
4. The public HTTPS URL of the webhook endpoint you are about to add, so the user can enter it in the console.

Read the three secrets from environment variables or the project's secret store. Do not hard-code, log, print or
commit them, and do not ask the user to paste them into the chat: a leaked API key creates orders in the merchant's
name, and a leaked webhook secret lets anyone forge "paid" events.

## The integration in six steps

### 1. Create the order (server side)

```sh
curl -X POST "$FLOWPAY_BASE_URL/v1/orders" \
  -H "Authorization: Bearer $FLOWPAY_API_KEY" \
  -H "Idempotency-Key: ord-SO-10023" \
  -H 'Content-Type: application/json' \
  -d '{"merchant_order_no":"SO-10023","amount":"100.00","currency":"USD",
       "customer_email":"payer@example.com","return_url":"https://shop.example/orders/SO-10023/done",
       "metadata":{"cart":"c_8812"}}'
```

- `amount` is a **decimal string** (at most 8 decimals) in `currency`; stablecoins pegged to the currency pay 1:1.
  Floats lose cents and are refused.
- `merchant_order_no` is your order number, unique per mode; a repeat answers `409 duplicate_order` (then look the
  order up with `GET /v1/orders?merchant_order_no=…` instead of creating it again).
- `Idempotency-Key` is required on every create request. Derive it from your order number and, on a network error,
  a timeout or a 5xx, retry with the **same key and the same body bytes**: the deployment then returns the first
  answer instead of creating a second order. Keys never expire, so this only works if order numbers are never
  reused: a counter that restarts (an in-memory sequence, a reset test database) would get an old, possibly paid,
  order back. Where that can happen, generate a random key once and store it with the order. The rules for 4xx
  answers are in `references/errors.md`.
- The `201` answer carries `id`, `status: "pending"` and `checkout_url`. Store `id` next to your order.
- A `422 no_payable_route` (or `split_*`, `amount_out_of_range`) means the merchant's configuration cannot take this
  payment: show "payment unavailable", log `error.params`, and do not retry in a loop.

### 2. Send the payer to the checkout

Redirect the browser to `checkout_url`, or open it in a modal with `$FLOWPAY_BASE_URL/pay/embed.js`
(`references/orders.md`). The checkout handles tokens, networks, wallets and confirmations; your system waits.

### 3. Show the result on return (display only)

When the order is final, the payer comes back to `return_url` with `order_id`, `status` (`paid` or `expired`), `ts`
and `sig` appended, `sig = hex(HMAC-SHA256(webhook_secret, "<order_id>.<status>.<ts>"))`. Verify it with the bundled
helper (`verifyReturnUrl` / `verify_return_url`), which also takes the **last** occurrence of each parameter and
checks the age of `ts`. Use it only to choose which page to show: the payer may never come back, or may replay a link.

### 4. Receive the webhook

The deployment POSTs each event as JSON with `FlowPay-Signature: t=<unix seconds>,v1=<hex>`, where
`v1 = hex(HMAC-SHA256(secret, "<t>.<raw request body>"))`. In the receiver:

1. Read the **raw body bytes** and verify before parsing: a re-serialized JSON body never verifies. Copy the helper
   for the project's language from `scripts/examples/<lang>/` (or port it and test it with `scripts/vectors.json`);
   it also rejects timestamps older than 300 seconds and accepts any matching `v1`.
2. Answer 400 to a bad signature. Otherwise record the event `id` (the same event can arrive twice), store or enqueue
   the event durably, and answer 2xx within 10 seconds. Do the work asynchronously.
3. Answer 2xx to event types you do not handle and to events you have seen before. Events of a mode are delivered
   strictly in order, so a receiver that keeps failing one event holds back every later event; business problems
   belong in your own logs and alerts, not in the HTTP status.
4. Check `livemode`: a live endpoint should ignore `livemode: false`.

Every event type and its handling is in `references/webhooks.md`.

### 5. Fulfil from server state

Before shipping, read the order: `GET /v1/orders/{id}`. Event data is the object as it was when the event was
written; the read rules out forged requests and out-of-order events. Fulfil when `status` is `paid` (or
`duplicate_paid`, which is still paid; the merchant refunds the extra payment in the console) and `risk_flag` is
null. `review` means hold for a manual check; `frozen` means a payment came from an address that failed screening:
do not fulfil and do not refund it. `reverted` means a confirmed payment left the chain: stop or reverse fulfilment.
Amounts in `payment` and `splits[]` are token base units (`amount / 10^payment.decimals`).

### 6. Add a safety net

Poll `GET /v1/events?since=<next_since>` (scope `events:read`) every 10 to 30 seconds, or check orders that stay
`pending` too long. Persist `next_since` and deduplicate with the same event-id table as the webhook. If the system has
no public inbound endpoint, the feed can be the only channel.

## Subscriptions in one paragraph

Plans live in the console; list them with `GET /v1/plans`, create a subscription with `POST /v1/subscriptions`
(`plan_id`, `customer_ref`, `customer_email`, `return_url`, `metadata`; needs an `Idempotency-Key`) and send the payer
to its `checkout_url` (`/pay/sub/{id}`). The payer signs the terms once and approves a capped allowance; the deployment
charges each period. Start the service on `subscription.activated` (or `subscription.plan_changed` for a plan change),
extend it on `subscription.charged`, stop it on `unpaid`, `canceled` and `completed` (a plan change's old
subscription gets `subscription.replaced` instead: keep the service, its `replaced_by` carries on), and refund on
`subscription.charged_after_cancel`. The subscription return parameters are not signed. Link the customer's account
page to `$FLOWPAY_BASE_URL/my/subscriptions`. Read `references/subscriptions.md` before writing any of it.

## Rules that prevent incidents

- Fulfil only from a verified webhook followed by a read of the object, or from the read alone. Never from the return
  URL, a browser callback, the embed script's events or an unverified request.
- Verify the signature over the raw bytes before parsing; compare in constant time (the helpers do).
- Send amounts as decimal strings, never floats.
- Reuse the idempotency key when retrying the same request; never generate a fresh key for a retry.
- Acknowledge fast and work asynchronously; never let business logic turn a webhook into a non-2xx answer.
- Do not call chain RPC, read wallets or handle private keys: the deployment does all of that.
- Refunds are made by the merchant in the console (there is no refund API); your system reacts to `order.refunded`.
- Do not invent endpoints, fields or event names. When unsure, read `/v1/openapi.yaml`.

## What to deliver

- Configuration read from the environment or secret store (base URL, API key, webhook secret).
- A small API client: bearer authentication, JSON, decimal-string amounts, a 30-second timeout, stable idempotency
  keys reused on retry, error handling by `error.code`.
- Order creation at checkout time, the FlowPayra order `id` stored with the local order, the redirect or embed.
- A return page that verifies `sig` / `ts` and only displays.
- A webhook endpoint on the raw body: verify, deduplicate by event `id`, persist, 2xx fast, process asynchronously,
  acknowledge unknown types.
- Fulfilment after re-reading the order, with every status and `risk_flag` handled (`references/orders.md`).
- The event-feed fallback job with a persisted `next_since`.
- Tests that run the signature code against `scripts/vectors.json` (`references/testing.md`).
- A short note for the user listing what to set in the console: the webhook URL for test and for live, the API key
  scopes the code needs, and, for the embedded checkout, the site origins allowed to embed it.
