> ## Documentation Index
> Fetch the complete documentation index at: https://paymanai.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# The wire protocol

> The HTTP contract underneath the SDK

The SDK exposes money tasks through `run()` and structured records through
`forUser(id).data`. Read this page when porting to another runtime or inspecting
the requests the SDK sends. Schemas are in the **API reference** tab.

Four HTTP calls and one browser redirect: the token exchange, interact (blocking or streaming, one call on two routes), the approvals poll, and user-action. Consent is a navigation, never an API call. Two optional GETs sit beside them: `/connect/tool-definition` (unauthenticated, static) and `/connect/apps/me` (the app self-read).

Two base URLs appear below. Server requests go to Railway; consent and approval pages live on the console. Set `PAYMAN_BASE_URL` to the Railway origin when using the SDK, especially older builds that default to the unavailable custom hostname. The SDK discovers the console origin from your app registration.

| Name | What it is |
| - | - |
| `PAYGENT_CLOUD_URL` | The API. Every server-to-server call. Default `https://paygent-cloud-server-production.up.railway.app`. |
| `CONSOLE_URL` | Your customer's Payman console, where they consent and approve. |

| Header | Carries |
| - | - |
| `x-paygent-connect-app-key` | Your app key. Every call. |
| `x-paygent-connect-grant` | The [grant](https://paymanai.mintlify.site/reference/keys.md) token. Every call after the exchange. |
| `x-paygent-environment` | `sandbox` or `live`, on the interact and stream responses; the stream's only environment signal. |

Confidential clients send the first two together. Public OAuth clients send
their token in `x-paygent-connect-grant` without an app key; omitting a key does
not make a confidential grant public. Hosted `/mcp` uses `Authorization: Bearer`
instead of these REST headers.

## The consent redirect

When your app offers Plaid and multi-provider wallets are enabled, customers can
add several banks inside one Plaid session. They approve each bank with its own
sign-in, then finish the session. Payman saves each bank separately and includes
all of those bank connections in the app's approved wallet. Plaid's optional phone
sign-in is separate from signing in to Payman or approving access at a bank.

Build the link on your server and navigate top-level. No iframe, no popup: the customer is signing in to Payman. The SDK's popup consent depends on the SDK-served callback page; hand-rolled flows keep the plain navigation.

```js Node theme={null}
import { randomBytes } from "node:crypto";

// CSPRNG, stored against this signed-in user, single use, 10-minute TTL.
const state = randomBytes(32).toString("base64url");
await saveState(user.id, state, { ttlMs: 10 * 60 * 1000 });

// Hold the question they asked, so you can answer it when they return.
await savePendingQuestion(user.id, message);

const authorize = new URL("/connect/authorize", CONSOLE_URL);
authorize.searchParams.set("app_id", APP_ID);
authorize.searchParams.set("redirect_uri", REDIRECT_URI); // exactly as registered
authorize.searchParams.set("state", state);
```

`scopes` defaults to `interact`. Request `financial_data:read` explicitly for
[structured financial records](https://paymanai.mintlify.site/build/financial-data.md), or use the comma-separated
`interact,financial_data:read` value when both permissions are needed. OAuth
authorization uses the singular `scope` parameter with space-separated values.
Existing grants need new consent before they can use additional permissions.

## Structured read endpoints

On an enabled environment, `GET /connect/data/connections` discovers the
connections shared by the grant. `POST /connect/reads` queues a typed read and
returns a durable `runId`; `GET /connect/reads/{runId}` returns status and saved
pages. All three require `financial_data:read`. The SDK calls these through
`forUser(id).data`. See [the data guide](https://paymanai.mintlify.site/build/financial-data.md) for complete
SDK and MCP examples, native Plaid sync, partial results, and checkpoint storage.

## Complete the callback

On your callback, verify `state` first:

```js Node theme={null}
app.get("/callback", async (req, res) => {
  const owner = await consumeState(req.query.state); // atomic, single use
  if (!owner) return res.status(400).send("Rejected: unknown state");

  // access_denied. Nothing was issued. Offer the button again.
  if (req.query.error) return res.redirect(303, "/#latest");

  const grant = await exchangeCode(req.query.code);
  // ...store it, then replay the held question.
});
```

> [!WARNING]
>
> `state` is your CSRF token and nobody checks it for you. Verify it before `code`, before `error`, before anything leaves your server. An unknown or reused state is somebody else's redirect: exchange nothing.

## `POST /connect/token`

The only credential call in the handshake. The browser is not part of it.

```js Node theme={null}
const response = await fetch(`${PAYGENT_CLOUD_URL}/connect/token`, {
  method: "POST",
  headers: {
    "content-type": "application/json",
    "x-paygent-connect-app-key": APP_KEY,
  },
  body: JSON.stringify({
    code,
    redirectUri: REDIRECT_URI, // the same bytes the code was issued for
  }),
});

// 200
// {
//   "id": "…", "grantToken": "pgc_grant_…", "grantTokenMasked": "pgc_grant_••••ab01",
//   "appId": "…", "deploymentId": "…", "scopes": ["interact"],
//   "environment": "live", "createdAt": "…", "lastUsedAt": null, "expiresAt": "…",
//   "deploymentIds": ["…"], "mergedGrantIds": []
// }
//
// 401 invalid_connect_credentials: the code was older than 60 seconds, already
// used, issued to a different app, or bound to a different redirectUri. One
// answer for all of them.
```

If the customer already had a live grant for this app, consenting again replaces it. You never hold two credentials for one connection.

### When the customer connects more than one account

One consent can seat several accounts, and a later one can add to a connection you already hold. Three fields on this response say what happened.

| Field | Read it as |
| - | - |
| `grantToken` | **Null** when the consent attached an account to the grant you already hold. No new secret is minted, by design: keep the token you have. |
| `deploymentIds` | Every account this exchange seated, primary first. |
| `mergedGrantIds` | Older grants this exchange folded in and revoked. Tokens for these no longer work, so drop any you stored. |

Nothing else in your integration changes. See [the Wallet](https://paymanai.mintlify.site/build/wallet.md).

> [!WARNING]
>
> `grantToken` appears on this response only. Store it encrypted, server-side. Never retry the exchange: the code is single use and burns even on a failed attempt. Start the flow again instead.

## `POST /connect/interact`

```js Node theme={null}
const response = await fetch(`${PAYGENT_CLOUD_URL}/connect/interact`, {
  method: "POST",
  headers: {
    "content-type": "application/json",
    "x-paygent-connect-app-key": APP_KEY,
    "x-paygent-connect-grant": grantToken,
  },
  body: JSON.stringify({
    userInput: "what's my balance?",
    sessionId: chatSessionId, // yours, stable per conversation
    provider: "BREX",         // optional: route to one connected account
  }),
});

// 200
// { "status": "COMPLETED", "message": "…", "sessionId": "…",
//   "agentId": "…", "environment": "live", … }
//
// 200, frozen for the account owner's approval
// { "status": "APPROVAL_REQUIRED", "message": "",
//   "approvalRef": "pgtk_…", "approvalUrl": "…", "approvalExpiresAt": "…", … }
//
// 200, the router asking which connected account to use
// { "status": "needs_provider", "message": "…", "howToProceed": "…",
//   "candidates": [{ "provider": "BREX", "institutionName": "Brex",
//                    "accountLabel": "…", "capabilities": "…" }], … }
```

Render `message` labelled as the customer's own agent. `POST /connect/interact/stream` is the same call on a second route: that same customer-side agent's NDJSON relayed verbatim, one JSON object per line, with `x-paygent-environment` as the stream's only environment signal.

### The routing statuses

A customer with several connected accounts has a [Wallet](https://paymanai.mintlify.site/build/wallet.md), and two more `status` values come out of it. Both are ordinary 200s.

| `status` | Means | Next |
| - | - | - |
| `needs_provider` | Several accounts could do this | Resend the same `userInput` naming the account, or set `provider` |
| `no_capable_provider` | None of them can | Show `message`. Do not retry |

`provider` takes an institution type (`BREX`) or an account label, exactly as a candidate names it. A value matching nothing, or several things, gets the same ask back rather than a guess.

### Not running it twice

Both interact routes accept an optional `Idempotency-Key` header: 16 to 255 URL-safe characters, minted by you, one per customer intent.

The same key presented again by the same grant is answered with the first turn's stored response, byte for byte, and carries `idempotency-replayed: true`. The same key with a different body is refused rather than resolved.

### Result names, wire and SDK

The served tool definition names four results; the SDK renames two of them.

| On the wire | SDK `result.kind` |
| - | - |
| `success` | `ok` |
| `needs_connection` | `needs_connection` |
| `approval_required` | `approval` |
| `error` | `error` |

`GET /connect/tool-definition` carries this mapping machine-readable as `wireMapping`. The two routing statuses above also land in `ok`, with the wire's `status` kept on `result.agentStatus`.

## `GET /connect/approvals/{ref}`

Poll the ticket the interact response named.

```js Node theme={null}
const response = await fetch(`${PAYGENT_CLOUD_URL}/connect/approvals/${ref}`, {
  headers: {
    "x-paygent-connect-app-key": APP_KEY,
    "x-paygent-connect-grant": grantToken,
  },
});

// 200 while pending
// { "ref": "pgtk_…", "state": "pending", "expiresAt": "…", "approvalUrl": "…" }
//
// 200 once executed
// { "ref": "pgtk_…", "state": "consumed", "expiresAt": "…",
//   "executable": true, "executionStatus": "succeeded",
//   "providerTransactionId": "…" }
```

`approvalUrl` is present only while `state` is `pending`. Send the customer there: the owner approves on Payman's page with an emailed code, and there is no endpoint through which your app could approve or submit one. A 404 is a uniform refusal, never a verdict; keep polling until the clock runs out.

The wire reports five states. `consumed` means the gate spent the ticket, which happens before the bank is called, so the SDK derives two states from it:

| On the wire | SDK approval state |
| - | - |
| `pending` | `pending` |
| `approved` | `approved` |
| `consumed`, no `executionStatus` | `settling` |
| `consumed` with `executionStatus: "succeeded"` | `posted`, receipt from `providerTransactionId` |
| `declined` | `declined` |
| `expired` | `expired` |
| anything unrecognised | `unknown` |

## `POST /connect/interact/user-action/{userActionId}/{action}`

A run can stop to ask a question: which vendor, confirm this transfer. The question arrives as a frame on the stream carrying `userActionId`, a field key, and the options. Answer it here; the path accepts `submit`, `cancel`, `resend` and `expired`, and apps send the first three.

```js Node theme={null}
await fetch(
  `${PAYGENT_CLOUD_URL}/connect/interact/user-action/${userActionId}/submit`,
  {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-paygent-connect-app-key": APP_KEY,
      "x-paygent-connect-grant": grantToken,
    },
    body: JSON.stringify({ [fieldKey]: optionId }), // one of the offered options
  },
);
```

Only `submit` carries a body, and the body is always a chosen option id: never free text, never a code. `cancel` and `resend` post empty.

That is the whole protocol. After the consent return, answer the question the customer asked before the detour: the SDK stashes and replays it for you; hand-rolled, the stash and the replay are yours.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.