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

> ## Agent Instructions
> Money is always a decimal string at the currency's precision (for example "29.00"), paired with an ISO 4217 currency field. Never use minor units.
> Build against the sandbox first: base URL https://sandbox-api.bachs.io with sk_sandbox_ keys. Production is https://api.bachs.io with sk_live_ keys; going live is a key swap.
> Treat webhooks (for example collection.succeeded) as the source of truth for fulfilment, never client-side events or redirects.
> Subscriptions are created by completing a checkout for a recurring product. There is no direct create-subscription endpoint.
> IDs carry resource prefixes (cust_, prod_, sub_, chk_, inv_, ref_) and timestamps are ISO 8601 UTC.

# Connect a business

> Send a business to Bachs to approve your app, swap the code for tokens and call the API for it.

This is the flow your app runs each time a business connects. It needs your
app's `client_id`, a client secret on your server and a registered callback
address. See [Create an app](https://docs.bachs.io/apps/create-an-app.md).

Sandbox uses `https://sandbox-api.bachs.io`. Live uses `https://api.bachs.io`,
with your live app's id and secret.

**1. Send the business to Bachs**

Make a new, unguessable `state` and a PKCE verifier for each attempt, and keep
both in the user's server-side session. The verifier is 43 to 128 unreserved
characters. Its challenge is the unpadded base64url SHA-256 of the verifier.

```javascript Node.js theme={"dark"}
import { randomBytes, createHash } from "node:crypto";

const state = randomBytes(32).toString("base64url");
const verifier = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
// Save state and verifier in this user's server-side session.
const authorizeUrl = new URL("https://sandbox-api.bachs.io/connect/oauth/authorize");
authorizeUrl.search = new URLSearchParams({
  client_id: "app_9Kd2Mw7Qx1Lr5Tn8Vb3Hs6Pz",
  response_type: "code",
  redirect_uri: "https://deskly.example/bachs/callback",
  scope: "payments:read refunds:write",
  state,
  code_challenge: challenge,
  code_challenge_method: "S256",
}).toString();
```

Send the browser to `authorizeUrl`, in a popup or a normal redirect. Leave out
`scope` to ask for all your app's permissions. A request lasts ten minutes.

An unknown `client_id` or a callback you did not register is refused without
sending the browser anywhere. See the [OAuth reference](https://docs.bachs.io/apps/reference/oauth.md).

**2. The business approves**

The business signs in and sees your icon and name, "by" your business with a
**Verified business** mark (or a warning if your app is private), a picker of
the businesses it can connect, each permission with your reason under it, the
events your app will hear about, and your privacy and terms links.

It clicks **Allow** or **Cancel**. For a private app, the picker only offers
businesses that may install it.

**3. Check the callback and swap the code**

**Allow** sends the browser to your callback with `code` and your `state`.
**Cancel** sends `error=access_denied` and `state`. Check for `error`, then check
`state` matches the session before you use the code.

Swap the code from your server. Authenticate with your client secret, as HTTP
Basic or as `client_secret` in the body. JSON and form bodies both work.

```bash cURL theme={"dark"}
curl -X POST https://sandbox-api.bachs.io/v1/connect/oauth/token \
  -u "app_9Kd2Mw7Qx1Lr5Tn8Vb3Hs6Pz:$BACHS_CLIENT_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "authorization_code",
    "client_id": "app_9Kd2Mw7Qx1Lr5Tn8Vb3Hs6Pz",
    "redirect_uri": "https://deskly.example/bachs/callback",
    "code": "dQ6Bt0y2QmJc_XO-x-zZS1POIRsOPdCmDueYpYBEvyI",
    "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
}'
```

```json Response theme={"dark"}
{
  "account_id": "acct_8Qz4k2Bp6NvR7dHc",
  "livemode": false,
  "token_type": "Bearer",
  "access_token": "sk_sandbox_9cfa0c7e_o7ozvw-rhGzcnD214SWK33C2C1s44Q4UA3kTmxRWcZs",
  "refresh_token": "9w42ebfsXyghxLDgN0ZM0h6tYYyjrW0nXUTvVLnup2g",
  "expires_in": 3600,
  "scope": "payments:read refunds:write",
  "webhook_endpoint_id": "whe_7Qm2cN6vR4pK8dLs",
  "webhook_signing_secret": "whsec_68e0eec57fcfdba7aff2465787b23ceca5325257d72c5426aa735305ce193da3"
}
```

Store the tokens and the webhook signing secret on your server. The webhook
fields come only when your app has a webhook URL, and only in this response.

> [!WARNING]
>
> A code works once. Using it again ends the connection. A new approval for the
> same app and business replaces the old connection and its webhook.

For a popup, finish the swap on your server before you tell your own page the
result with `postMessage`, using your exact origin. Never put tokens in that
message. Offer a normal redirect when a popup cannot open.

**4. Call the API for the business**

Send the access token as the bearer credential. It acts as the business that
approved, with only the permissions it approved. Do not send your own secret key
or `X-Account-Id`.

```bash cURL theme={"dark"}
curl 'https://sandbox-api.bachs.io/v1/payments?limit=1' \
  -H "Authorization: Bearer $MERCHANT_ACCESS_TOKEN"
```

```json Response theme={"dark"}
{
  "items": [],
  "pagination": {
    "next_cursor": null,
    "prev_cursor": null,
    "has_more": false,
    "limit": 1,
    "offset": 0,
    "returned": 0,
    "total": 0
  }
}
```

A call that needs a permission the business did not approve gets `403`. Your
app's calls have their own rate limit for each business, separate from that
business's own limit. Verify each event's signature with the signing secret
before you act on it. See [Webhook events](https://docs.bachs.io/developer-portal/events.md).

**5. Refresh about every hour**

Access tokens last one hour. Send the current refresh token to the same
endpoint, with your client secret.

```bash cURL theme={"dark"}
curl -X POST https://sandbox-api.bachs.io/v1/connect/oauth/token \
  -u "app_9Kd2Mw7Qx1Lr5Tn8Vb3Hs6Pz:$BACHS_CLIENT_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "refresh_token",
    "client_id": "app_9Kd2Mw7Qx1Lr5Tn8Vb3Hs6Pz",
    "refresh_token": "9w42ebfsXyghxLDgN0ZM0h6tYYyjrW0nXUTvVLnup2g"
}'
```

```json Response theme={"dark"}
{
  "account_id": "acct_8Qz4k2Bp6NvR7dHc",
  "livemode": false,
  "token_type": "Bearer",
  "access_token": "sk_sandbox_a92c15f8_mbMJKw3mAK6D4GDJP_FbHJeA2S9tBNQFGFVSKjW5iJ0",
  "refresh_token": "Dm4vRslV9MwtKLyjA3U3TT9jEhBM7wtnX-F7axtZZJo",
  "expires_in": 3600,
  "scope": "payments:read refunds:write"
}
```

You get a new access token and a new refresh token, and the old pair stops
working. Store both together and send one refresh at a time per connection.
Each refresh moves the connection's end to 90 days from now. A connection you
do not refresh for 90 days ends.

> [!WARNING]
>
> Never send an old refresh token again. Bachs takes that as a stolen token and
> ends the connection. Never keep tokens or signing secrets in browser storage,
> URLs or logs.

## Ask for more permissions later

Add the permission to your app. The [checks](https://docs.bachs.io/apps/publish.md#the-checks) run again
before the change saves. New connections get it at once. A business already
connected keeps what it approved until it approves the new permission in
**Connected apps**, where your app shows "Asks for more access". The new
permission arrives with your next refresh after that.

## Test before you go live

In sandbox, run through: approval and cancel, a wrong `state`, a permitted call,
a refused call, a signed event at your webhook, a refresh, a reused old refresh
token, and a disconnect that sends you `app.deauthorized`. See
[When a connection ends](https://docs.bachs.io/apps/disconnect.md).


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