# Connecting accounts

Connect an account to a profile with OAuth, a hosted or headless selection step, or credentials for Bluesky, Telegram, Shopify, self-hosted WordPress and IMAP mailboxes.

import { Tab, Tabs } from 'fumadocs-ui/components/tabs';

Connect a social account, ad account or store to a profile and get back its `accountId`.

## Before you start

- **You need** an API key, a profile id ([create a profile](/profiles/create-profile)) and a login on the platform.
- **Most platforms** use OAuth. Bluesky, Telegram, Shopify and self-hosted WordPress have [their own flows](#credential-and-store-specific-connections).
- **Mailboxes:** `GET /v1/connect/email` returns one hosted link for any address. Gmail and Microsoft addresses go to their sign-in, every other mailbox connects over IMAP. See [IMAP connect](/platforms/imap/connect).
- **Per-platform rules:** each [platform page](/platforms).

## Start the OAuth flow [#oauth-flow-most-platforms]

Call `GET /v1/connect/{platform}` with your `profileId` and send the user's browser to the returned `authUrl`. Approving connects the account.

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
import Zernio from '@zernio/node';

const zernio = new Zernio();
const profileId = '66a1f0c2a4b9d3e8f1a2b3c4';

const { data: connect } = await zernio.connect.getConnectUrl({
  path: { platform: 'linkedin' },
  query: { profileId, redirect_url: 'https://myapp.com/callback' }
});
// Send the user's browser to connect.authUrl
```
</Tab>
<Tab value="Python">
```python
from zernio import Zernio

client = Zernio()
profile_id = "66a1f0c2a4b9d3e8f1a2b3c4"

connect = client.connect.get_connect_url(
    platform="linkedin",
    profile_id=profile_id,
    redirect_url="https://myapp.com/callback",
)
# Send the user's browser to connect["authUrl"]
```
</Tab>
<Tab value="curl">
```bash
curl "https://zernio.com/api/v1/connect/linkedin?profileId=66a1f0c2a4b9d3e8f1a2b3c4&redirect_url=https://myapp.com/callback" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```
</Tab>
</Tabs>

```json
{ "authUrl": "https://www.linkedin.com/oauth/v2/authorization?client_id=..." }
```

`{platform}` is one of:

<PlatformConnectTable />

- **Callback params:** `connected`, `profileId`, `accountId`, `username`, plus `request_id` and `stage` ([correlation params](#request-ids)), added to your `redirect_url`. Your own params are kept unless they share a name with ours.
- **`redirect_url`:** an absolute http(s) URL or an app scheme such as `myapp://callback`.
- **Every parameter:** [Start OAuth endpoint](/connect/get-connect-url).

## Show a branded welcome screen

Add `welcome=true` (recommended) and `authUrl` opens a Zernio-hosted screen with your name and logo ("Acme wants to connect to your LinkedIn"), which forwards to the platform after a second.

```bash
curl "https://zernio.com/api/v1/connect/linkedin?profileId=66a1f0c2a4b9d3e8f1a2b3c4&welcome=true&brandName=Acme&logoUrl=https://acme.com/logo.png&redirect_url=https://myapp.com/callback" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```

- **Why:** users who see whose app it is finish more often. Later pickers and the closing screen carry the same brand.
- **Brand:** `brandName` and `logoUrl` on the call, or saved once in the dashboard (Settings, White Labeling) or with [`PUT /v1/connect/welcome-screen`](/connect/update-connect-welcome-screen).
- **Show by default:** once saved, every link shows it without `welcome=true`. `welcome=false` skips it on one link.
- **Not with** `headless=true` or `signup=hosted`.

## Finish on a phone

Add `handoff=true` to get a short link to show as a QR code. Users on a computer then log in on their phone, where the platform's app already has them signed in.

```bash
curl "https://zernio.com/api/v1/connect/instagram?profileId=66a1f0c2a4b9d3e8f1a2b3c4&handoff=true&brandName=Acme" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```

```json
{
  "authUrl": "https://zernio.com/connect/welcome?ticket=...",
  "state": "...",
  "handoff": {
    "id": "79c6dbf2-97ba-4f34-b615-5bf9435526db",
    "url": "https://zernio.com/connect/m/79c6dbf2-97ba-4f34-b615-5bf9435526db",
    "expiresAt": "2026-10-22T18:30:00.000Z"
  }
}
```

1. Draw `handoff.url` as a QR code (any library). It works for 30 minutes.
2. The user scans it, sees your welcome screen, logs in on the phone and is told to go back to the computer.
3. Poll [`GET /v1/connect/handoffs/{handoffId}`](/connect/get-connect-handoff) every few seconds, or wait for the `account.connected` webhook.

| `status` | Meaning |
|---|---|
| `waiting` | Not scanned yet. |
| `opened` | The code was scanned. |
| `connected` | Done, with the new `accounts`. |
| `failed` | With the `error` code. |
| `expired` | Not scanned within 30 minutes. |

`handoff=true` always shows the welcome screen, so it excludes `welcome=false`, `headless=true`, `signup`, `redirect=true` or `redirect_url`.

## Ask for fewer scopes [#scopes]

The flow asks for every scope Zernio supports unless you pass `scopes` with the areas you use: `posting`, `analytics`, `comments`, `messaging`, `ads`.

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
const { data: connect } = await zernio.connect.getConnectUrl({
  path: { platform: 'linkedin' },
  query: { profileId, scopes: 'posting,analytics', redirect_url: 'https://myapp.com/callback' }
});
```
</Tab>
<Tab value="Python">
```python
connect = client.connect.get_connect_url(
    platform="linkedin",
    profile_id=profile_id,
    scopes="posting,analytics",
    redirect_url="https://myapp.com/callback",
)
```
</Tab>
<Tab value="curl">
```bash
curl "https://zernio.com/api/v1/connect/linkedin?profileId=66a1f0c2a4b9d3e8f1a2b3c4&scopes=posting,analytics&redirect_url=https://myapp.com/callback" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```
</Tab>
</Tabs>

<Callout type="warn">
A `posting`-only account cannot read analytics or the inbox and skips first comments (they need `comments`). Adding areas means connecting again.
</Callout>

- **Consent screen:** only those areas' scopes, plus identity, token refresh, and listing the Pages, organizations or channels to pick from.
- **Scope per area:** each platform page; full table on the [Start OAuth endpoint](/connect/get-connect-url).
- **Not asked, not granted:** missing from `permissions`, and reported by [Account health](/accounts/get-all-accounts-health) through `canPost` and `canFetchAnalytics`.
- **Supported:** Facebook, Instagram (both login methods), LinkedIn, X, TikTok, YouTube, Threads, Reddit, Pinterest, Google Business Profile and Slack (`GET /v1/connect/slack`).
- **Rejected** by Bluesky, Telegram, Discord, Snapchat and WhatsApp, whose consent screen cannot be reduced.
- **Google and Microsoft** require `scopes`, with their own areas `email`, `calendar`, `files`, `contacts`. Reconnecting with more areas widens the same account. See [Connect a Google account](/platforms/google/connect) and [Connect a Microsoft account](/platforms/microsoft/connect).

## Pick a Page, organization or board [#platforms-requiring-secondary-selection]

Six platforms need a pick after OAuth.

| Platform | What to select | Endpoints |
|----------|---------------|-----------|
| Facebook | Page | [List Pages](/connect/list-facebook-pages) → [Select Page](/connect/select-facebook-page) |
| LinkedIn | Organization or personal profile | [List orgs](/connect/list-linkedin-organizations) → [Select org](/connect/select-linkedin-organization) |
| Pinterest | Board | [List boards](/connect/list-pinterest-boards-for-selection) → [Select board](/connect/select-pinterest-board) |
| Google Business Profile | Location | [List locations](/connect/list-google-business-locations) → [Select location](/connect/select-google-business-location) |
| Snapchat | Public profile | [List profiles](/connect/list-snapchat-profiles) → [Select profile](/connect/select-snapchat-profile) |
| Instagram (`loginMethod=facebook_login` only) | Page with a linked Instagram account | [List Pages](/connect/list-instagram-pages) → [Select account](/connect/select-instagram-account) |

The default Instagram Login has no selection step ([login methods](/platforms/instagram#login-methods)).

### Standard vs headless mode

- **Standard** (default): Zernio hosts the selection screen, then sends the user to your `redirect_url`.
- **Headless** (`headless=true`): you build the screen. Your `redirect_url` gets `tempToken`, `userProfile` (JSON, encoded twice), `step` and `connect_token` for the list and select endpoints.

LinkedIn only: add `pendingDataOnly=true` to your `redirect_url` and the `select_organization` redirect carries only `profileId`, `platform`, `step`, `pendingDataToken` and `connect_token`, never `tempToken`, `userProfile` or `organizations`. Read them with `GET /v1/connect/pending-data`. Other platforms ignore it.

`step` names the selection endpoint to call next. Instagram sends no `userProfile`: its select-account endpoint takes none.

| `step` | Platform |
|--------|----------|
| `select_page` | Facebook |
| `select_organization` | LinkedIn |
| `select_board` | Pinterest |
| `select_location` | Google Business Profile |
| `select_public_profile` | Snapchat |
| `select_phone_number` | WhatsApp |
| `select_account` | Instagram via Facebook Login |

### Headless example: a Facebook Page

Start it like any OAuth flow, with `headless: true`:

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
const { data: start } = await zernio.connect.getConnectUrl({
  path: { platform: 'facebook' },
  query: { profileId, headless: true, redirect_url: 'https://your-app.com/cb' },
});
// Send the user's browser to start.authUrl
```
</Tab>
<Tab value="Python">
```python
start = client.connect.get_connect_url(
    platform="facebook",
    profile_id=profile_id,
    headless=True,
    redirect_url="https://your-app.com/cb",
)
# Send the user's browser to start["authUrl"]
```
</Tab>
<Tab value="curl">
```bash
curl "https://zernio.com/api/v1/connect/facebook?profileId=66a1f0c2a4b9d3e8f1a2b3c4&headless=true&redirect_url=https://your-app.com/cb" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```
</Tab>
</Tabs>

```json
{ "authUrl": "https://www.facebook.com/v21.0/dialog/oauth?client_id=..." }
```

After consent, Meta sends the user to your callback:

```
https://your-app.com/cb?profileId=...&tempToken=...&userProfile=...&platform=facebook&step=select_page&connect_token=...
```

Read `tempToken` and `userProfile` from it. Decode `userProfile` once more after your framework decodes the query, then parse the JSON (`tempToken` and `connect_token` are plain). List the user's Pages:

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
// requestUrl: the URL your handler received; searchParams decodes the values once
const { tempToken, userProfile: encodedProfile } = Object.fromEntries(new URL(requestUrl).searchParams);
const userProfile = JSON.parse(decodeURIComponent(encodedProfile));

const { data: pages } = await zernio.connect.facebook.listFacebookPages({
  query: { profileId, tempToken },
});
```
</Tab>
<Tab value="Python">
```python
import json
from urllib.parse import parse_qs, unquote, urlparse

# request_url: the URL your handler received; parse_qs decodes the values once
query = parse_qs(urlparse(request_url).query)
temp_token = query["tempToken"][0]
user_profile = json.loads(unquote(query["userProfile"][0]))

pages = client.connect.list_facebook_pages(
    profile_id=profile_id,
    temp_token=temp_token,
)
```
</Tab>
<Tab value="curl">
```bash
# TEMP_TOKEN holds tempToken from the callback query string
curl "https://zernio.com/api/v1/connect/facebook/select-page?profileId=66a1f0c2a4b9d3e8f1a2b3c4&tempToken=$TEMP_TOKEN" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```
</Tab>
</Tabs>

```json
{ "pages": [{ "id": "123456789", "name": "My Brand Page", "username": "mybrand", "category": "Brand" }] }
```

Connect the chosen Page with `POST /v1/connect/facebook/select-page`, passing `userProfile` as the decoded object:

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
const { data: result } = await zernio.connect.facebook.selectFacebookPage({
  body: {
    profileId,
    pageId: pages.pages[0].id,
    tempToken,
    userProfile,
    redirect_url: 'https://your-app.com/final-success',
  },
});
// Send the browser to result.redirect_url
```
</Tab>
<Tab value="Python">
```python
result = client.connect.select_facebook_page(
    profile_id=profile_id,
    page_id=pages["pages"][0]["id"],
    temp_token=temp_token,
    user_profile=user_profile,
    redirect_url="https://your-app.com/final-success",
)
# Send the browser to result["redirect_url"]
```
</Tab>
<Tab value="curl">
```bash
curl -X POST "https://zernio.com/api/v1/connect/facebook/select-page" \
  -H "Authorization: Bearer $ZERNIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "profileId": "66a1f0c2a4b9d3e8f1a2b3c4",
    "pageId": "123456789",
    "tempToken": "'"$TEMP_TOKEN"'",
    "userProfile": { "id": "1234567890", "username": "mybrand", "displayName": "My Brand Page" },
    "redirect_url": "https://your-app.com/final-success"
  }'
```
</Tab>
</Tabs>

```json
{
  "message": "Facebook page connected successfully",
  "redirect_url": "https://your-app.com/final-success?connected=facebook&profileId=66a1f0c2a4b9d3e8f1a2b3c4&accountId=66b2e19d8c3f5a7e9d0b1c2d&username=My+Brand+Page&request_id=...&stage=select_page",
  "account": {
    "accountId": "66b2e19d8c3f5a7e9d0b1c2d",
    "platform": "facebook",
    "username": "mybrand",
    "isActive": true,
    "selectedPageName": "My Brand Page"
  }
}
```

`account.accountId` is the new account's id.

## Connect Meta Ads only [#connect-meta-ads-only-skip-the-page-picker]

For ads only (audience uploads, the [Conversions API](/platforms/meta-ads/conversions), analytics, listing ads and campaigns), start at `GET /v1/connect/facebook/ads`. Your backend picks the first Page, so no picker.

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
const { data: adsStart } = await zernio.connect.connectAds({
  path: { platform: 'facebook' },
  query: { profileId, headless: true, redirect_url: 'https://your-app.com/cb' },
});
// Send the user's browser to adsStart.authUrl, then list and select
// as above with pages.pages[0].id and no picker.
```
</Tab>
<Tab value="Python">
```python
ads_start = client.connect.connect_ads(
    platform="facebook",
    profile_id=profile_id,
    headless=True,
    redirect_url="https://your-app.com/cb",
)
# Send the user's browser to ads_start["authUrl"], then list and select
# as above with pages["pages"][0]["id"] and no picker.
```
</Tab>
<Tab value="curl">
```bash
curl "https://zernio.com/api/v1/connect/facebook/ads?profileId=66a1f0c2a4b9d3e8f1a2b3c4&headless=true&redirect_url=https://your-app.com/cb" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
# then list and select as above, passing the first page id and showing no picker
```
</Tab>
</Tabs>

```json
{ "authUrl": "https://www.facebook.com/v21.0/dialog/oauth?client_id=..." }
```

- **Flow:** callback, list and select as in the headless flow; the user goes from Meta's consent straight to your "Connected" screen.
- **Login mode:** classic login (`loginMode=classic`, the default). To connect ads without a posting account, use [Facebook Login for Business](#facebook-login-for-business).
- **`adsAccountId`** (select response body and `redirect_url`): the `metaads` account created alongside, for the `/v1/ads` endpoints. Absent if it could not be created; `account.accountId` stays the Facebook posting account.
- **Instagram:** `POST /v1/connect/instagram/select-account` works the same on an Instagram ads connect (`loginMethod=facebook_login`).
- **First Page is fine** for roughly 70% of the `metaads` API: anything not sending `object_story_spec.page_id`.
- **Page-specific 30%:** boosting Page posts, [Click-to-WhatsApp ads](/platforms/meta-ads/ctwa#click-to-whatsapp-ads), Lead Gen Forms. Show a picker then and POST the `pageId` to `/v1/connect/facebook/select-page`; the Facebook account updates in place, no second OAuth.
- **Hidden Facebook account:** if the profile had none for that Page, the new one has `enabled: false`: hidden, not postable and not billed. See [Connections and billing](/platforms/meta-ads#connections-and-billing).

### Facebook Login for Business

Call [`GET /v1/connect/{platform}/ads`](/connect/connect-ads) with `platform` set to `facebook` or `instagram`, plus `profileId` and `loginMode=business`. Without `loginMode`, the flow is `classic`.

```
GET /v1/connect/facebook/ads?profileId=...&loginMode=business
```

- **Result:** always an `authUrl` for the user's browser. The callback creates or reconnects a standalone `metaads` account with a Business Integration System User token; no posting account is needed.
- **Token:** `GET /v1/accounts` shows `metadata.tokenType: "system-user"`. Without Meta's `expires_in`, `tokenExpiresAt` is absent and Zernio never re-exchanges it as a personal token.
- **Pages** live on the `metaads` account; no Facebook account is created. [Connections and billing](/platforms/meta-ads#connections-and-billing) covers organic accounts and which accounts bill.

The bound Page serves ad creatives and lead forms:

- **`pageId`** on the connect picks a granted Page; one outside the grant fails with `page_not_granted`.
- **No `pageId`:** a reconnect reuses the previous Page, a new connection binds the first granted one. Change it later with `PUT /v1/accounts/{accountId}/facebook-page`.
- **Zero granted Pages:** refused with `no_pages_granted`.

**Reconnecting** (re-run the dialog to add, drop or swap ad accounts) keeps the connection's id and history.

- **Must overlap:** the new grant shares at least one ad account, or it is refused first with `error=invalid_field_value` and `error_reason=reconnect_mismatch`. For unrelated ad accounts, disconnect and connect again.

An accepted reconnect rebuilds the ad-account scope:

- `adAccountIds` passed on the re-auth become the scope.
- Otherwise, a narrowed scope keeps its still-granted ad accounts, plus any granted for the first time.
- An unscoped connection follows the new grant.

Errors: [If it fails](#facebook-login-for-business-errors).

### Scoping sync to specific ad accounts

Sync covers every `act_*` ad account the token sees, which for agencies means every Business Manager the user has a role on. Pass `adAccountId` (one) or `adAccountIds` (several) on `GET /v1/connect/facebook/ads` to sync an allowlist:

```
?adAccountId=act_1330190928038136
?adAccountIds=act_1330190928038136,act_3686966528111132
```

- **Checked** against the token's `/me/adaccounts`, then stored. The latest connect replaces the list; omit both to sync everything.
- **Confirm** with the `account.ads.initial_sync_completed` webhook. It always carries `account.platformAdAccountIds`, and `account.platformAdAccountId` when the scope is exactly one account.

## Connect without OAuth or with a store [#credential-and-store-specific-connections]

### Bluesky

Bluesky uses an app password. `state` is `{userId}-{profileId}`: `userId` is `currentUserId` from `GET /v1/users`, `profileId` from `GET /v1/profiles`.

<Tabs items={['Node.js', 'Python', 'curl']}>
<Tab value="Node.js">
```typescript
const { data: bluesky } = await zernio.connect.bluesky.connectBlueskyCredentials({
  body: {
    identifier: 'yourhandle.bsky.social',
    appPassword: 'your-app-password',
    state: '66a0e8b1c2d3e4f5a6b7c8d9-66a1f0c2a4b9d3e8f1a2b3c4',
  },
});
console.log(`Connected ${bluesky.account.username}`);
```
</Tab>
<Tab value="Python">
```python
bluesky = client.connect.connect_bluesky_credentials(
    identifier="yourhandle.bsky.social",
    app_password="your-app-password",
    state="66a0e8b1c2d3e4f5a6b7c8d9-66a1f0c2a4b9d3e8f1a2b3c4",
)
print(f"Connected {bluesky['account']['username']}")
```
</Tab>
<Tab value="curl">
```bash
curl -X POST "https://zernio.com/api/v1/connect/bluesky/credentials" \
  -H "Authorization: Bearer $ZERNIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "identifier": "yourhandle.bsky.social",
    "appPassword": "your-app-password",
    "state": "66a0e8b1c2d3e4f5a6b7c8d9-66a1f0c2a4b9d3e8f1a2b3c4"
  }'
```
</Tab>
</Tabs>

```json
{
  "message": "Bluesky connected successfully",
  "account": { "platform": "bluesky", "username": "yourhandle.bsky.social", "displayName": "Your Name", "isActive": true }
}
```

The [Connect Bluesky endpoint](/connect/connect-bluesky-credentials) lists every field.

### Telegram

Telegram connects with an access code:

1. Call `GET /v1/connect/telegram` to [generate an access code](/connect/get-telegram-connect-status), valid for 15 minutes.
2. The user makes the Zernio Telegram bot an admin of the channel or group and sends it the code.
3. Poll `PATCH /v1/connect/telegram` to [check the status](/connect/complete-telegram-connect) until it reports connected.

Bot already an admin? Skip the code and [connect directly](/connect/initiate-telegram-connect) with `POST /v1/connect/telegram` and the chat id.

### Shopify

Shopify OAuth is per store, with no store picker or shop lookup, so you need the merchant's `myshopify.com` domain first.

1. Collect the store domain (`your-store.myshopify.com`; the bare `your-store` prefix is accepted).
2. Call `GET /v1/connect/shopify` with `profileId` and `shop` to [get the authorization URL](/connect/get-shopify-connect-url).
3. Redirect the merchant to `authUrl`. They return to your `redirect_url` with `connected`, `profileId`, `accountId` and `username`, like every OAuth platform.

- **`username`** is the real `myshopify.com` domain of the store they approved, which may differ from `shop` (merchants often type a brand name). Keep the `accountId` from the redirect (or `account.connected` webhook), not your domain.
- **App Store installs** link only for the store in `shop`, within an hour of your call. They return with the same params and `account.connected` fires. A store another profile holds is not linked; the merchant stays in their Shopify admin.
- **No browser flow:** the merchant creates a custom app with the `read_content`, `write_content`, `read_products` and `write_products` scopes and gives you its Admin API access token. [Exchange it](/connect/connect-shopify-with-token) with `POST /v1/connect/shopify/token`; `shop` is required, because an Admin token does not identify its store.
- **No social posts:** a store powers the [Blogs API](/blogs/list-blogs) and the [Commerce API](/guides/commerce); see the [Shopify page](/platforms/shopify).

### WordPress

- **WordPress.com:** `GET /v1/connect/wordpress` with `profileId` and `redirect_url`, then send the user to `authUrl`; the callback returns the chosen site. See [Get WordPress.com authorization URL](/connect/get-wordpress-auth-url).
- **Self-hosted:** create an Application Password in WordPress admin, then send the site's HTTPS URL, login username and that password to [`POST /v1/connect/wordpress/token`](/connect/connect-wordpress-with-application-password).
- **Checks:** Zernio finds the REST API and confirms the user can publish posts and upload media. Never put the username or the Application Password in `siteUrl`.
- **One site, one blog** per account, no social posts: use the [Blogs API](/blogs/list-blogs) and the [WordPress guide](/platforms/wordpress). A self-hosted WooCommerce site is also a store for the [Commerce API](/guides/commerce).

## Change a selection without reconnecting

Change an account's Page, organization, board, location or subreddit with no second OAuth:

- [Update Facebook Page](/connect/update-facebook-page)
- [Update LinkedIn organization](/connect/update-linkedin-organization)
- [Update Pinterest board](/connect/update-pinterest-boards)
- [Update Google Business Profile location](/connect/update-gmb-location)
- [Update Reddit subreddit](/connect/update-reddit-subreddits)

## If it fails

A denied or rejected OAuth adds `error` and `platform` to your `redirect_url`. Check `error` first; treat unknown values as generic failures, since new ones appear without notice.

```
?error=oauth_denied&platform=linkedin&request_id=...&stage=authorize
```

| Error | Cause | Fix |
|---|---|---|
| `oauth_denied` | Consent denied or refused. | Read `platform_error*`; let the user retry. |
| `no_facebook_pages` (`is_user_fixable=true`, with `error_message`) | No usable Page (`error_reason` below). | Reconnect, click "Edit previous settings" in Meta's dialog and tick the Page, or create a Page first. |
| `400 INVALID_REDIRECT_URL` | `redirect_url` is a relative path. | Use an absolute URL or app scheme. |
| `400` | Malformed `profileId`. | Pass a valid profile id. |
| `400 INVALID_FIELD_VALUE` | `scopes` empty, with an unknown area, sent to a platform that rejects it, or missing for Google or Microsoft. | Fix or drop `scopes`. |
| `402` `PAYMENT_REQUIRED` | Billing blocks the connect ([billing gates](#billing-gates)). | Send the user to `dashboard_url`. |

Known `error` values: [Start OAuth endpoint](/connect/get-connect-url). Optional params:

| Param | Meaning |
|-------|---------|
| `error_message` | Human-readable explanation you can show the user. |
| `is_user_fixable` | `true` when connecting again fixes it (cancelled, declined a permission, ticked no Page). |
| `error_reason` | Finer reason for some `error` values, listed below. |
| `platform_error`, `platform_error_reason`, `platform_error_description` | On `oauth_denied` and `meta_ads_authorization_denied`, the platform's own values if sent (`access_denied`, `user_denied`). Description truncated to 500 characters. |

Error redirects drop the internal `headless`, `pendingDataOnly`, `adsConnect` and `adsScope` markers.

`no_facebook_pages` cases (`error_reason`, when Meta's token debug answered):

| `error_reason` | Meaning |
|----------------|---------|
| `pages_permission_declined` | The user declined the `pages_show_list` permission. |
| `no_pages_granted` | Permission granted with no Page ticked, or the user manages no Page (Meta cannot tell them apart). |
| `granted_pages_not_listed` | Pages ticked, but Meta listed none the user can manage. |

### Facebook Login for Business errors

Failures after Meta's dialog redirect with `error` (the API error code), `platform=metaads`, `error_message`, `request_id`, `stage`, and `is_user_fixable` and `error_reason` when known.

| `error` | `error_reason` | Meaning |
|---------|----------------|---------|
| `invalid_field_value` | `no_pages_granted` | No Page was ticked in Meta's dialog. |
| `invalid_field_value` | `page_not_granted` | The `pageId` you passed is not in the grant. |
| `invalid_field_value` | `ad_accounts_not_granted` | No ad account was granted. |
| `invalid_field_value` | `reconnect_mismatch` | The grant shares no ad account with the existing connection. |
| `invalid_state` | `state_expired` | Back after the 30-minute window. Start again. |
| `connection_failed` | | Meta refused the code (for example a replayed callback). |

- **Gates** of `GET /v1/connect/{platform}` arrive the same way: `reconnect_required`, `ads_addon_required`, `payment_required`, profile gates.
- **Denial** in the dialog: `meta_ads_authorization_denied`, with `platform_error*`.
- **`400` JSON** only for an undecryptable state, which names no `redirect_url`.

### Request ids

- **`request_id` and `stage`:** on every OAuth callback redirect (success or failure) and on the `redirect_url` from select-page, select-account, select-organization, select-board, select-location, select-profile and select-phone-number.
- **`X-Request-Id`:** header on every API response. Quote it or `request_id` to support; we log the request under it.

`stage` says where the flow ended:

- `authorize`: the consent dialog returned an error or denial, not a code.
- `callback`: Zernio processed the code (success, a selection step or a failure).
- `select_page`: a selection endpoint finished the flow.

### Billing gates

The connect call returns `402` when billing blocks it; send the user to `dashboard_url`.

```json
{
  "error": "X (Twitter) requires a payment method due to API pass-through costs. Add a payment method to connect an X account.",
  "code": "PAYMENT_REQUIRED",
  "reason": "twitter_passthrough",
  "dashboard_url": "https://zernio.com/dashboard?tab=billing"
}
```

| `reason` | Cause |
|---|---|
| `free_tier_exceeded` | Over the free connected accounts, no card on file. |
| `twitter_passthrough` | Any X account without a card, on accounts billed monthly. Accounts on the prepaid balance connect X without one. |
| `enterprise_required` | A contract cap. |

## Related

- [List accounts](/accounts/list-accounts): accounts and their `isActive` state.
- [Update an account](/accounts/update-account): default Pages, boards and other settings.
- [Account health](/accounts/get-all-accounts-health): tokens and permissions.
- [Disconnect an account](/accounts/delete-account).
- [Instagram](/platforms/instagram#login-methods): Instagram Login versus Facebook Login.