# Connect ads for a platform API Reference

Starts connecting a platform's ads account, giving you a dedicated ads connection to manage campaigns without touching posting accounts. It creates a dedicated ads SocialAccount for the specified platform.

Ads accounts appear as regular SocialAccount documents with ads platform values (e.g., metaads, tiktokads) in GET /v1/accounts.

### Meta business login (opt-in)

Set `loginMode=business` for `facebook` or `instagram` to use Facebook Login for Business and a Business Integration System User token. No posting account is created or required.

This mode always returns an authUrl. It returns 503 when the server has no META_ADS_CONFIG_ID. Complete the dialog in a browser.

The callback creates or reconnects only the metaads account, preserving its ID and history. Non-empty successful subscription results replace subscribedAdAccountIds to remove stale grants; an empty result leaves routing unchanged.

#### Reconnecting

A reconnect is accepted when the new grant shares at least one ad account with the existing connection, so re-running the dialog can add, drop or swap ad accounts.

The existing connection's ad accounts are its scopedAdAccountIds plus the previous grant, or the ad accounts its old token can read when neither is stored.

- A grant with zero overlap is refused before changing the account and redirects with `error=invalid_field_value` and `error_reason=reconnect_mismatch` (disconnect and connect again to switch).
- When the previous ad accounts cannot be read at all, it redirects with `error=reconnect_required`.

On an accepted reconnect the scope is rebuilt from the new grant:

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

#### Page selection

Pass `pageId` to select a granted Page for creatives and lead forms. API integrations otherwise reuse the previous Page or the sole granted Page.

Multiple Pages without a selection return 400 with available Page IDs for API integrations; restart with pageId. Dashboard session logins use the sole current grant automatically, or open the existing Facebook Page picker for several grants, including reconnects. Selection completes the Meta Ads connection.

#### Result redirects

Success redirects with connected=metaads, profileId and accountId.

Every failure after Meta's dialog redirects to redirect_url (or the dashboard) with `error`, `platform=metaads`, `error_message`, `request_id` and `stage`, plus `is_user_fixable` and `error_reason` when known. `error` is the API error code:

- `invalid_field_value`, with `error_reason`:
  - `no_pages_granted`: no Page ticked
  - `page_not_granted`: pageId not in the grant
  - `ad_accounts_not_granted`
  - `reconnect_mismatch`: the grant shares no ad account with the existing connection
- `reconnect_required`, `ads_addon_required`, `payment_required` and the profile gates of GET /v1/connect/{platform}
- `invalid_state` with `error_reason=state_expired`: after the 30-minute window
- `connection_failed`: Meta refuses the code (e.g. a replayed callback)
- `meta_ads_authorization_denied`: a denial in the dialog, with the `platform_error*` params

Only a state that cannot be decrypted at all still answers 400 JSON, since it names no redirect_url.

#### Tokens

Business login reports metadata.tokenType=system-user in GET /v1/accounts. An absent Meta expires_in leaves tokenExpiresAt absent; no personal-token re-exchange occurs.

Subsequent classic requests can change the ad-account scope using the business token. force=true (or disconnecting the business connection first) switches the profile to the standard Facebook login; the ads account is then held by the user token.

### Same-token platforms (facebook, instagram, linkedin, pinterest)

The ads SocialAccount (metaads, linkedinads, pinterestads) reuses the OAuth token of the parent posting account, but only when:

- an active parent exists, and
- for facebook and instagram, its stored token carries ads_management and ads_read (linkedin and pinterest need no extra scope).

In that case no extra OAuth happens and the response is alreadyConnected: true.

When no such parent exists, or the scopes are missing, the endpoint returns an authUrl and a full OAuth round trip is required.

Errors:

- 400 RECONNECT_REQUIRED: a parent exists but carries no token usable for ad accounts
- 403 ADS_ADDON_REQUIRED: no ads add-on (independently of the branch)
- 402 PAYMENT_REQUIRED: the billing gate is closed (independently of the branch)

#### Meta Ads needs a Facebook Page

Connecting Meta Ads (via facebook or instagram) requires a Facebook Page. Not because the ad account is read through a Page, but because both parent posting accounts are:

- the facebook flow only offers Pages you manage
- the instagram flow with loginMethod=facebook_login only offers Instagram accounts linked to one of those Pages

Without a Page there is no parent account to inherit a token from. A user who manages no Facebook Page cannot complete this connection, and the facebook flow ends with error=no_facebook_pages.

### Separate-token platforms (tiktok, twitter)

Starts the platform-specific marketing API OAuth flow and creates an ads SocialAccount (tiktokads, xads) with its own token. If the ads account already exists, returns alreadyConnected: true.

- twitter (X Ads): accountId is REQUIRED. There's no ads-only mode, because tweets need to be authored by a real X user.
- tiktok: accountId is OPTIONAL.

#### TikTok with or without accountId

- With accountId, the new tiktokads account links to that posting account (parentAccountId set), so Spark Ads + standalone ads using the posting TT_USER identity become available.
- Without accountId, ads-only mode kicks in: the new tiktokads account has parentAccountId=null and standalone ads use a synthetic CUSTOMIZED_USER ("Brand Identity"). Spark Ads are unavailable because TikTok requires a posting account for them.

The Brand Identity is configured separately via PATCH /v1/connect/tiktok-ads (or inline on POST /v1/ads/create via the brandIdentity field).

### Standalone platforms (googleads)

Starts the Google Ads OAuth flow and creates a standalone ads SocialAccount (googleads) with no parent.

- If the account already exists and has at least one discovered Google Ads customer account, returns alreadyConnected: true.
- When the profile's accounts are already one per ad account of a single Google login, it also returns alreadyConnected: true and adds an account per new `adAccountIds` entry. Existing accounts are never de-scoped, and `accountId` is a reused account.
- Accounts of several Google logins return an authUrl to sign in again.
- When the existing connection has zero customer accounts (metadata.googleAdsCustomerIds is empty) or is flagged needsReconnection, it returns an authUrl instead. Completing it reconnects the same account (same accountId) and re-runs ad account discovery.

Discovery includes the client accounts under every manager (MCC) the Google user can reach. It also includes Google Ads test accounts, which Google always reports with status CLOSED.

When discovery finds no usable customer account, the callback saves nothing and redirects with `error=google_ads_no_ad_accounts`, `platform=googleads` and an `error_message`.

The message names each customer the Google user can reach and why it was left out (for example CUSTOMER_NOT_ENABLED). Sign in with a Google user that has access to the ad account or to its manager account.

When the user unticks the Google Ads permission on Google's consent screen, the callback saves nothing and redirects with `error=missing_google_permissions`, `platform=googleads`, `is_user_fixable=true` and `missing_scopes`.

An existing connection whose token lacks that permission is flagged needsReconnection, and the health endpoints report "Google Ads permission not granted". This endpoint then returns an authUrl for it.

### Standalone platforms (redditads)

Starts the Reddit Ads OAuth flow (Reddit permissions `adsread`, `adsedit` and `adsconversions`) and creates a standalone ads SocialAccount (redditads) with no parent, separate from any organic `reddit` posting account. It is reached only as `redditads` in the path.

If an active Reddit Ads connection already exists on the profile, is not flagged needsReconnection and holds every one of those permissions, returns alreadyConnected: true. Otherwise it returns an authUrl; completing it reconnects the same account (same accountId).

A connection authorized without `adsconversions` keeps managing ads, but:

- the health endpoints list an issue asking to reconnect Reddit Ads and allow every permission
- the Conversions API answers 403 `reconnect_required`
- this endpoint returns an authUrl for it

Discovery lists every Reddit ad account the Reddit user can reach. The callback redirects with `platform=redditads` and:

- `error=reddit_ads_scope_not_granted`: the user unticks `adsread` or `adsedit` on Reddit's consent screen (nothing is saved)
- `error=reddit_ads_no_ad_accounts`: the user reaches no Reddit ad account

Without `redirect_url` the browser lands on the Zernio dashboard's ad account picker for the new connection.

### Standalone platforms (microsoftads)

Starts the Microsoft Advertising OAuth flow and creates a standalone ads SocialAccount (microsoftads) with no parent. It is reached only as `microsoftads` in the path.

Microsoft Advertising users sign in with a Microsoft account by default. A user who signs in to ads.microsoft.com with Google passes `identityProvider=google`, and the flow runs on Google's consent screen instead.

If an active Microsoft Ads connection already exists on the profile, is not flagged needsReconnection and was signed in with the same identity provider, returns alreadyConnected: true. Otherwise it returns an authUrl; completing it reconnects the same account (same accountId).

Discovery lists every Microsoft Advertising ad account the user can reach. The callback redirects with `platform=microsoftads` and:

- `error=microsoft_ads_scope_not_granted`: the user declines the Microsoft Advertising permission (nothing is saved)
- `error=microsoft_ads_unknown_user`: the account that signed in is not a Microsoft Advertising user, for example a Google user connecting without `identityProvider=google` (nothing is saved)
- `error=microsoft_ads_no_ad_accounts`: the user reaches no Microsoft Advertising ad account

Without `redirect_url` the browser lands on the Zernio dashboard's ad account picker for the new connection.


## GET /v1/connect/{platform}/ads

**Connect ads for a platform**

Starts connecting a platform's ads account, giving you a dedicated ads connection to manage campaigns without touching posting accounts. It creates a dedicated ads SocialAccount for the specified platform.

Ads accounts appear as regular SocialAccount documents with ads platform values (e.g., metaads, tiktokads) in GET /v1/accounts.

### Meta business login (opt-in)

Set `loginMode=business` for `facebook` or `instagram` to use Facebook Login for Business and a Business Integration System User token. No posting account is created or required.

This mode always returns an authUrl. It returns 503 when the server has no META_ADS_CONFIG_ID. Complete the dialog in a browser.

The callback creates or reconnects only the metaads account, preserving its ID and history. Non-empty successful subscription results replace subscribedAdAccountIds to remove stale grants; an empty result leaves routing unchanged.

#### Reconnecting

A reconnect is accepted when the new grant shares at least one ad account with the existing connection, so re-running the dialog can add, drop or swap ad accounts.

The existing connection's ad accounts are its scopedAdAccountIds plus the previous grant, or the ad accounts its old token can read when neither is stored.

- A grant with zero overlap is refused before changing the account and redirects with `error=invalid_field_value` and `error_reason=reconnect_mismatch` (disconnect and connect again to switch).
- When the previous ad accounts cannot be read at all, it redirects with `error=reconnect_required`.

On an accepted reconnect the scope is rebuilt from the new grant:

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

#### Page selection

Pass `pageId` to select a granted Page for creatives and lead forms. API integrations otherwise reuse the previous Page or the sole granted Page.

Multiple Pages without a selection return 400 with available Page IDs for API integrations; restart with pageId. Dashboard session logins use the sole current grant automatically, or open the existing Facebook Page picker for several grants, including reconnects. Selection completes the Meta Ads connection.

#### Result redirects

Success redirects with connected=metaads, profileId and accountId.

Every failure after Meta's dialog redirects to redirect_url (or the dashboard) with `error`, `platform=metaads`, `error_message`, `request_id` and `stage`, plus `is_user_fixable` and `error_reason` when known. `error` is the API error code:

- `invalid_field_value`, with `error_reason`:
  - `no_pages_granted`: no Page ticked
  - `page_not_granted`: pageId not in the grant
  - `ad_accounts_not_granted`
  - `reconnect_mismatch`: the grant shares no ad account with the existing connection
- `reconnect_required`, `ads_addon_required`, `payment_required` and the profile gates of GET /v1/connect/{platform}
- `invalid_state` with `error_reason=state_expired`: after the 30-minute window
- `connection_failed`: Meta refuses the code (e.g. a replayed callback)
- `meta_ads_authorization_denied`: a denial in the dialog, with the `platform_error*` params

Only a state that cannot be decrypted at all still answers 400 JSON, since it names no redirect_url.

#### Tokens

Business login reports metadata.tokenType=system-user in GET /v1/accounts. An absent Meta expires_in leaves tokenExpiresAt absent; no personal-token re-exchange occurs.

Subsequent classic requests can change the ad-account scope using the business token. force=true (or disconnecting the business connection first) switches the profile to the standard Facebook login; the ads account is then held by the user token.

### Same-token platforms (facebook, instagram, linkedin, pinterest)

The ads SocialAccount (metaads, linkedinads, pinterestads) reuses the OAuth token of the parent posting account, but only when:

- an active parent exists, and
- for facebook and instagram, its stored token carries ads_management and ads_read (linkedin and pinterest need no extra scope).

In that case no extra OAuth happens and the response is alreadyConnected: true.

When no such parent exists, or the scopes are missing, the endpoint returns an authUrl and a full OAuth round trip is required.

Errors:

- 400 RECONNECT_REQUIRED: a parent exists but carries no token usable for ad accounts
- 403 ADS_ADDON_REQUIRED: no ads add-on (independently of the branch)
- 402 PAYMENT_REQUIRED: the billing gate is closed (independently of the branch)

#### Meta Ads needs a Facebook Page

Connecting Meta Ads (via facebook or instagram) requires a Facebook Page. Not because the ad account is read through a Page, but because both parent posting accounts are:

- the facebook flow only offers Pages you manage
- the instagram flow with loginMethod=facebook_login only offers Instagram accounts linked to one of those Pages

Without a Page there is no parent account to inherit a token from. A user who manages no Facebook Page cannot complete this connection, and the facebook flow ends with error=no_facebook_pages.

### Separate-token platforms (tiktok, twitter)

Starts the platform-specific marketing API OAuth flow and creates an ads SocialAccount (tiktokads, xads) with its own token. If the ads account already exists, returns alreadyConnected: true.

- twitter (X Ads): accountId is REQUIRED. There's no ads-only mode, because tweets need to be authored by a real X user.
- tiktok: accountId is OPTIONAL.

#### TikTok with or without accountId

- With accountId, the new tiktokads account links to that posting account (parentAccountId set), so Spark Ads + standalone ads using the posting TT_USER identity become available.
- Without accountId, ads-only mode kicks in: the new tiktokads account has parentAccountId=null and standalone ads use a synthetic CUSTOMIZED_USER ("Brand Identity"). Spark Ads are unavailable because TikTok requires a posting account for them.

The Brand Identity is configured separately via PATCH /v1/connect/tiktok-ads (or inline on POST /v1/ads/create via the brandIdentity field).

### Standalone platforms (googleads)

Starts the Google Ads OAuth flow and creates a standalone ads SocialAccount (googleads) with no parent.

- If the account already exists and has at least one discovered Google Ads customer account, returns alreadyConnected: true.
- When the profile's accounts are already one per ad account of a single Google login, it also returns alreadyConnected: true and adds an account per new `adAccountIds` entry. Existing accounts are never de-scoped, and `accountId` is a reused account.
- Accounts of several Google logins return an authUrl to sign in again.
- When the existing connection has zero customer accounts (metadata.googleAdsCustomerIds is empty) or is flagged needsReconnection, it returns an authUrl instead. Completing it reconnects the same account (same accountId) and re-runs ad account discovery.

Discovery includes the client accounts under every manager (MCC) the Google user can reach. It also includes Google Ads test accounts, which Google always reports with status CLOSED.

When discovery finds no usable customer account, the callback saves nothing and redirects with `error=google_ads_no_ad_accounts`, `platform=googleads` and an `error_message`.

The message names each customer the Google user can reach and why it was left out (for example CUSTOMER_NOT_ENABLED). Sign in with a Google user that has access to the ad account or to its manager account.

When the user unticks the Google Ads permission on Google's consent screen, the callback saves nothing and redirects with `error=missing_google_permissions`, `platform=googleads`, `is_user_fixable=true` and `missing_scopes`.

An existing connection whose token lacks that permission is flagged needsReconnection, and the health endpoints report "Google Ads permission not granted". This endpoint then returns an authUrl for it.

### Standalone platforms (redditads)

Starts the Reddit Ads OAuth flow (Reddit permissions `adsread`, `adsedit` and `adsconversions`) and creates a standalone ads SocialAccount (redditads) with no parent, separate from any organic `reddit` posting account. It is reached only as `redditads` in the path.

If an active Reddit Ads connection already exists on the profile, is not flagged needsReconnection and holds every one of those permissions, returns alreadyConnected: true. Otherwise it returns an authUrl; completing it reconnects the same account (same accountId).

A connection authorized without `adsconversions` keeps managing ads, but:

- the health endpoints list an issue asking to reconnect Reddit Ads and allow every permission
- the Conversions API answers 403 `reconnect_required`
- this endpoint returns an authUrl for it

Discovery lists every Reddit ad account the Reddit user can reach. The callback redirects with `platform=redditads` and:

- `error=reddit_ads_scope_not_granted`: the user unticks `adsread` or `adsedit` on Reddit's consent screen (nothing is saved)
- `error=reddit_ads_no_ad_accounts`: the user reaches no Reddit ad account

Without `redirect_url` the browser lands on the Zernio dashboard's ad account picker for the new connection.

### Standalone platforms (microsoftads)

Starts the Microsoft Advertising OAuth flow and creates a standalone ads SocialAccount (microsoftads) with no parent. It is reached only as `microsoftads` in the path.

Microsoft Advertising users sign in with a Microsoft account by default. A user who signs in to ads.microsoft.com with Google passes `identityProvider=google`, and the flow runs on Google's consent screen instead.

If an active Microsoft Ads connection already exists on the profile, is not flagged needsReconnection and was signed in with the same identity provider, returns alreadyConnected: true. Otherwise it returns an authUrl; completing it reconnects the same account (same accountId).

Discovery lists every Microsoft Advertising ad account the user can reach. The callback redirects with `platform=microsoftads` and:

- `error=microsoft_ads_scope_not_granted`: the user declines the Microsoft Advertising permission (nothing is saved)
- `error=microsoft_ads_unknown_user`: the account that signed in is not a Microsoft Advertising user, for example a Google user connecting without `identityProvider=google` (nothing is saved)
- `error=microsoft_ads_no_ad_accounts`: the user reaches no Microsoft Advertising ad account

Without `redirect_url` the browser lands on the Zernio dashboard's ad account picker for the new connection.


### Parameters

- **identityProvider** (optional) in query: Microsoft Ads only. How the user signs in to Microsoft Advertising: `google` for a Microsoft Advertising login that is a Google account. `google` on any other platform returns 400 `invalid_field_value`.
- **loginMode** (optional) in query: Meta ads authorization mode. Business login is opt-in for Facebook and Instagram; classic preserves the posting-account flow.
- **permissionLevel** (optional) in query: Business login only. Ad-account permission the connection's system user will hold.

- `full`: asks the owner for Full control (MANAGE). Required to create pixels and other account-level assets through Zernio.
- `advertise`: asks for Manage campaigns (ADVERTISE), enough for campaigns, ad sets, creatives, ads, media and reporting. For owners who will not grant billing-level control to an integration.

Either way, Meta only lets a business admin complete the grant. 503 if the advertise configuration is not set up.

- **pageId** (optional) in query: Business login only. Facebook Page ID to select from the token grants for ad creatives and lead forms.
- **platform** (required) in path: Platform to connect ads for. Only platforms with ads support are accepted.

In classic mode, `instagram` requires an Instagram account connected with loginMethod=facebook_login whose
token carries ads_management and ads_read. With an account connected through the default
instagram_login flow no ads account can be created; do not use this value for those accounts.

- **profileId** (required) in query: Your Zernio profile ID
- **accountId** (optional) in query: Existing SocialAccount ID.

- `twitter` (X Ads): required.
- `tiktok`: optional. Omit it for ads-only mode (no TikTok posting account linked; ad creation uses a Brand Identity instead of a TT_USER).
- Same-token platforms (`facebook`, `instagram`, `linkedin`, `pinterest`): picks which posting account the ads connection uses when the profile holds several of that platform. With one, it can be omitted.
- Standalone platforms (`googleads`, `redditads`, `microsoftads`): ignored.

On same-token platforms, an id that names no active account of the platform on the profile is ignored. Exception: with `force=true`, when it names the posting account the profile's ads connection hangs off, that account is no longer connected.

In that case the call returns 409 `reconnect_required` instead of reconnecting another account. Reconnect it via GET /v1/connect/{platform} first.

- **redirect_url** (optional) in query: Custom URL the browser is sent to once the OAuth flow finishes. When omitted, the browser lands on the Zernio dashboard. Honored on every ads platform, including the separate-token (`tiktok`, `twitter`) and standalone (`googleads`, `redditads`, `microsoftads`) flows.

MUST be an absolute http(s) URL or a custom app scheme for mobile deeplinks (e.g. myapp://callback). A relative path is rejected with 400 INVALID_REDIRECT_URL.

On success:

- `tiktok`: lands on the URL unchanged.
- `twitter`, `googleads`, `redditads` and `microsoftads`: append `connected` (the ads platform id: `xads`, `googleads`, `redditads` or `microsoftads`), `profileId`, `accountId` (the ads connection) and `username`.
- Same-token platforms (`facebook`, `instagram`, `linkedin`, `pinterest`): append `connected`, `profileId`, `accountId`, `username` and, on API-key calls, `connect_token`.

On failure the same error contract applies as on GET /v1/connect/{platform}: `error` and `platform` are always appended, other params are optional, and the value list there is not exhaustive.

On the tiktok, twitter, googleads, redditads and microsoftads flows, `platform` carries the ads platform id (`tiktokads`, `xads`, `googleads`, `redditads`, `microsoftads`), not the value used in the request path.

- **headless** (optional) in query: Enable headless mode (same-token platforms only)
- **force** (optional) in query: Force a fresh OAuth even when an account already exists.

Normally the endpoint returns `alreadyConnected: true` whenever a connected account is found, keyed off its active state rather than token liveness. Set `force=true` to bypass that and always receive an `authUrl`. Completing the returned OAuth refreshes the stored token on the existing posting and ads accounts in place.

An `alreadyConnected` response re-runs ad discovery and webhook subscriptions in the background at most once every 15 minutes per ads account (always when the call changes the ad-account scope), so it is not a sync trigger.

To check the connection's health, read GET /v1/ads/accounts?accountId=<ads account ID>.

- **adAccountId** (optional) in query: Scopes ad sync to a single platform ad account. Without it, sync covers every ad account the connected token can see. For multiple accounts use `adAccountIds` instead.

Supported on:

- `facebook`/`instagram` (Meta): `act_<digits>`.
- `linkedin`: bare numeric sponsored-account id.
- `googleads`: bare customer id digits.
- `redditads`: Reddit ad account id, `a2_<id>` or `t2_<id>`.
- `microsoftads`: bare numeric account id (the Id, not the account number).
- `twitter` (X Ads): base36 account id.
- `tiktok` (TikTok Ads): numeric advertiser id.

`pinterest` has no ads discovery, so it ignores it.

**Meta validation** against the connected token:

- An id the token cannot see returns 400 `invalid_field_value`.
- An id it can see but that Meta marks unusable for ads (disabled, closed, under risk review, settlement pending) returns 400 `ad_account_unusable` with `details.accountStatus` (Meta's `account_status`) and, when Meta gives one, `details.disableReason`.
- Unsettled and in-grace accounts are accepted, matching the `selectable` flag of `GET /v1/ads/accounts`.

**Effects**: setting a scope removes already synced ads, campaigns, ad sets and keywords from de-scoped ad accounts. On Meta it also decides which ad accounts Zernio subscribes to ad-account webhooks: only the scoped ones, instead of every ad account the login can reach.

**Through OAuth**: on Meta the scope is kept when this call returns an `authUrl`, so the Meta Ads account created after OAuth is scoped (only its scoped ad accounts synced and subscribed) from the start.

On `googleads`, `redditads` and `microsoftads` it is kept through OAuth when `redirect_url` is set, so the new connection syncs only scoped ad accounts from the first sync.

On `tiktok` it is kept through OAuth with or without `redirect_url`. The TikTok Ads connection holds only the scoped advertisers from the first sync, and is named after the first of them. Its `platformUserId` and cached Brand Identity follow that advertiser too.

A TikTok login otherwise reaches every advertiser of every Business Center it belongs to. Advertisers the login does not reach are ignored; when it reaches none of them, the connection keeps every advertiser.

On an existing TikTok Ads connection, ids it does not reach are ignored, and a list it reaches none of returns 400 `invalid_field_value`. A reconnect keeps the stored scope, minus advertisers the new login no longer reaches.

**Reconnects**: business-login reconnects preserve the existing scope; supplied IDs are checked against the new grant. To change the scope after migration, call this endpoint with the IDs and omit loginMode.

- **adAccountIds** (optional) in query: Scope ad sync to multiple platform ad accounts (same platform support and id shapes as `adAccountId`). Repeat the param (`?adAccountIds=act_1&adAccountIds=act_2`) or comma-separate (`?adAccountIds=act_1,act_2`).

- Persisted server-side; the latest call wins. De-scoped ad accounts have their synced ads, campaigns, ad sets and keywords removed. Where ad accounts are already split into one account each, the call only adds accounts for new ids and never removes one (disconnect that account instead).
- On Meta only the scoped ad accounts get webhook subscriptions, including when the call starts a fresh OAuth.
- On Meta, ad accounts left out of the scope are unsubscribed from Zernio's ad-account webhooks (unless another connection still holds them) and are no longer stored, so syncs do not add them back. `GET /v1/ads/accounts` lists them (`selected: false`) only with `live=true`; passing them again reselects them.
- On TikTok, advertisers left out of the scope are no longer synced or stored either, and are listed (`selected: false`) only with `live=true`.
- On TikTok, pixels, tracking tags, offline events, targeting search and Brand Identity default to the first selected advertiser. A TikTok Ads connection with no scope keeps every advertiser the login reaches, as before.
- Omitting both `adAccountId` and `adAccountIds` keeps any previously persisted scope unchanged (no scope means every reachable ad account).

- **welcome** (optional) in query: When `true`, `authUrl` opens on the Zernio-hosted welcome screen with your brand, as on GET /v1/connect/{platform}, naming the ads platform ("<brandName> wants to connect to your Meta Ads").

- With no `redirect_url`, the flow ends on the branded result page instead of the Zernio dashboard.
- Shown only with `welcome=true`: the workspace's saved "on by default" (`PUT /v1/connect/welcome-screen`) applies to GET /v1/connect/{platform} only, so ads links behave as before unless you opt in. The saved brand still fills in what the call leaves out.
- Without `adAccountId` or `adAccountIds`, on Meta, Google, LinkedIn, X, Reddit, Microsoft and TikTok, the user then picks the ad accounts to connect on a branded Zernio-hosted page (skipped when the login reaches only one). On Meta and TikTok that page starts with no ad account selected and offers Select all.
- After that page the flow ends on your `redirect_url` with `connected` set to the ads platform and `accountId` to the ads connection.
- Cannot be combined with `headless=true` (400 `INVALID_FIELD_VALUE`).
- Responses with `alreadyConnected: true` carry no `authUrl`, so they show no screen.

- **brandName** (optional) in query: Welcome screen only: your product name in its heading. Same rules as on GET /v1/connect/{platform}.
- **logoUrl** (optional) in query: Welcome screen only: https URL of your square logo. Rejected with 400 `INVALID_FIELD_VALUE` when the welcome screen is not shown.
- **primaryColor** (optional) in query: Welcome screen only: hex colour (`#RRGGBB`) of its button.
- **welcomeTheme** (optional) in query: Welcome screen only: a URL-encoded JSON object restyling and rewording the welcome screen and the result page, with the keys documented on GET /v1/connect/{platform}. Rejected when the welcome screen is not shown.

### Responses

#### 200: Either an OAuth URL to redirect to, or confirmation that ads are already connected

**Response Body:**

*One of the following:*
  - **alreadyConnected** `boolean`: No description (example: true)
  - **accountId** `string`: No description
  - **platform** `string`: No description
  - **username** `string`: No description
  - **displayName** `string`: No description
  - **tokenType** `string`: Present for an existing business-login connection. - one of: system-user
  - **scopedAdAccountIds** `array[string]`: Echo of the persisted ad-account scope when the caller passed
`adAccountId` / `adAccountIds`. Omitted when no scope is set.

  - **authUrl** `string` (uri): No description
  - **state** `string`: No description

#### 400: Platform doesn't support ads, missing accountId for X Ads, or a non-absolute redirect_url

#### 401: Missing or invalid API key. `code` is `missing_credentials` when no Authorization header was sent and `invalid_credentials` when the key is unknown, revoked or expired.

**Response Body:**

- **error** `string`: Human-readable error message.
- **type** `string`: Error class for programmatic handling. - one of: invalid_request_error, authentication_error, permission_error, not_found, rate_limit_error, platform_error, api_error
- **code** `string`: Stable machine-readable error code.
- **param** `string`: The request field that caused the error, when applicable.
- **docUrl** `string`: Documentation page for resolving the error, when one applies.
- **platform** `string`: Upstream platform (e.g. meta, google, tiktok), present when type is platform_error.
- **platformError** `object`: Raw error payload from the upstream platform, passed through verbatim so
integrators can read provider-specific codes. For Meta this includes
error_subcode, error_user_title, and error_user_msg.

- **provider** `string`: Email API: the mailbox provider the error came from (`google`, `microsoft`).
- **providerError** `object`: Email API: the provider's own error code and message, for support and logs. Branch on `code`, not on this.
  - **code** `string,null`: No description
  - **message** `string,null`: No description
- **retryable** `boolean`: Email API: whether the same request can succeed if retried (with the same `Idempotency-Key` for sends).
- **requestId** `string`: Email API: the request id, also in the `X-Request-Id` header. Quote it when you contact support.
- **docsUrl** `string`: Email API: where this `code` is documented.
- **details** `object`: Additional structured context for the error (for example field-level validation errors). What it carries depends on the endpoint and platform.

**Meta ads refusals.** The ones customers hit most come back with their own `code` instead of `platform_api_error`, the field to fix in `param`, and an English `details.hint` saying how to fix it. `details.fix` ({ label, url }) links the Meta page that resolves it, when there is one.

The code is picked from Meta's numeric `code` and `error_subcode`, never from the message, so it is the same whatever language Meta wrote `error_user_msg` in. Branch on `code` and show `details.hint`.

- `ad_account_payment_required`: the ad account has no usable payment method (subcode 1815010, 1359188).
- `ad_account_policy_not_accepted`: a business admin has to accept Meta's non-discrimination policy (subcode 2859002, 2859024).
- `lead_ads_terms_not_accepted`: the Facebook Page has not accepted the Lead Ads terms (subcode 1815089).
- `verified_advertiser_required`: the market requires a verified beneficiary and payer; send `regionalRegulationIdentities` (subcode 3858634, 3858636, 3858442, 3858548, 3858495).
- `ad_account_unusable`: the ad account is not active, or the business is restricted from advertising (subcode 1885316, 2446325, and 2490592, 4841021 below).
- `meta_security_check_required`: the Facebook user behind the connection is held at a security check (code 31).
- `meta_action_blocked`: Meta temporarily blocked the Facebook user from this action (subcode 2859015).
- `meta_ad_consent_required`: the Page or Instagram owner chose Meta without ads or less personalized ads (subcode 3858231, 3858412).
- `instagram_account_restricted`: Meta restricted the Instagram account the ad runs as (subcode 2207070).
- `insufficient_permissions`: the ad account cannot use the Instagram account, or the Facebook user has no advertiser permission on the Page (subcode 1815199, 1815202, 1885499, 1341012, and the Advertise permission case below).
- `whatsapp_number_not_linked`: the WhatsApp number is no longer linked to the Page (subcode 2446880).
- `invalid_targeting`: Meta refused the audience or a placement (subcode 1487079, 1870247, 2909035, 1870189, 1870188, 1487756, 1487843, 2490562).
- `post_not_boostable`: Meta does not allow the post to be promoted (subcode 2446187, 2875030, 1487472).
- `budget_too_low`: the budget is below Meta's minimum, which `platformError.error_user_msg` states (subcode 1885272).
- `meta_object_not_accessible`: Meta cannot load an object the request names (wrong ID, deleted, or no access); `platformError.message` names the ID (subcode 33, on ads routes only).

Meta's own error stays in the message and in `platformError`.

**Private replies.** The private-reply endpoint adds:

- `privateReplyConsumed` on a 400: the comment's single reply is already spent.
- `privateReplyOutcome: "unknown"` on a 502: Meta answered a server error and the reply may have been delivered.
- `privateReplyOutcome: "not_sent"` on a 429: Instagram's rate limit refused the reply, so retry later.

**Google quota 429.** On a Google Ads or YouTube Analytics 429, `quotaExhausted: true` marks the failure as Google's own quota, not a Zernio rate limit, so you can keep calling other platforms instead of backing off everywhere. When Google names the scope, `quotaScope` is also set:

- `DEVELOPER`: the shared budget (the developer token for Google Ads, the Google Cloud project for YouTube Analytics). Every account on Zernio is affected and there is nothing to change on your side.
- `ACCOUNT`: your own ad account (Google Ads only).

A Meta 429 carries neither field.

**Zernio Google Ads burst-limit 429.** Carries `budgetScope` instead, never `quotaExhausted`. These are Zernio's own limits, applied before the call reaches Google, and both clear within a minute. They are separate axes from `quotaScope`, not the same pool named twice.

- `account`: the limit of 15 requests per minute per connected Google Ads account.
- `user`: the ceiling of 120 requests per minute per Zernio user across all their Google Ads accounts.

**Failed Meta ad create** (`POST /v1/ads/create`, `POST /v1/ads/boost`, `POST /v1/ads/ctwa`). Carries `stage` (where it failed), `adAccountId` (on which ad account) and `createdObjects` (every object this request had already created, with what cleanup did to it).

- `left_behind` objects still exist on the ad account (Meta refused the delete, typically on a held account, or the delete hit a network error). Delete them yourself or reuse them.
- `unconfirmedWrite` is set when Meta answered a create with a 5xx or a non-JSON body, or dropped the connection, and Zernio could not confirm whether the object exists. Check that parent before creating it again.

**Ineligible ad account: 422 `ad_account_unusable`.** When Meta refuses a write because the ad account's status is ineligible to manage ads (Meta subcode 2490592 or 4841021, on the write itself or on a cleanup delete), any Meta ads write answers it.

That covers create, boost, CTWA, campaign / ad set / ad updates and status changes.

The message names the ad account when known, links Meta's fix (https://www.facebook.com/business/help/422289316306981), lists the objects left behind and ends with Meta's original error, which also stays verbatim in `platformError`.

Meta often reports the first failure under an unrelated code (e.g. 1487194 on the creative), so branch on `code`, not on `platformError`.

**Missing Advertise permission: 403 `insufficient_permissions`.** When the Facebook user behind the connection's token lacks the Advertise permission on the ad account, any Meta ads write answers it.

Triggers: Meta subcode 2490585, 2490591 or 4841020 on the write, or a code 200 refusal such as 1487194 whose cleanup deletes Meta refused with 2490591 or 4841020.

Meta may still accept the campaign and ad set and refuse only the ad. The message names the ad account, asks for the Advertise or Manage permission on it (or a token granted `ads_management`, by reconnecting) and lists the objects left behind.

It ends with Meta's `error_user_title`, `error_user_msg` and subcode; the raw error stays in `platformError`.

  - **stage** `string`: Meta ad create failures only. The step that failed:

- `media`: image/video download or upload.
- `campaign`
- `adset`
- `creative`
- `ad`: the ad POST itself, where Meta's code 31 / 3858385 hold and 100 / 1359188 payment rejections land.
- `activation`: switching the created objects on. No longer returned: a refused switch to ACTIVE now answers 201 with an `activation_failed:` warning and the objects kept PAUSED.
- `other`: a read or check before any write.
 - one of: media, campaign, adset, creative, ad, activation, other
  - **adAccountId** `string`: Meta ad create failures only. The ad account the request wrote to (`act_...`).
  - **createdObjects** `array[object]`: Meta ad create failures only. Every object this request created before failing, in creation order. Objects you referenced (an existing campaign, ad set, creative or video) are never listed and never deleted.
    - **type** `string`: No description - one of: campaign, adset, creative, ad, video, image
    - **id** `string`: Meta object id; for `image` the image hash.
    - **cleanup** `string`: - `deleted`: Zernio deleted it.
- `left_behind`: cleanup could not delete it (Meta refused the delete, or the delete hit a network error), so it still exists.
- `kept`: deliberately not deleted. Either an image (hashes are shared by every upload of the same file), or an object Zernio found by name after Meta lost its answer to the create, which may belong to another request with the same name.
 - one of: deleted, left_behind, kept
  - **unconfirmedWrite** `object`: Meta ad create failures only. Set when Meta answered a create with a 5xx or a non-JSON body, or dropped the connection after the request was sent, and reading the parent back by name did not settle it. Zernio did not retry it.

One of these left it open:

- The read-back found several objects of the same name.
- The parent could not be read, or the object is a creative, which has no reliable read-back.
- The read-back found no such object, after a dropped connection, a non-JSON body, a 5xx with `retryOnServerError: false`, or a 5xx on a create whose own body is `status: ACTIVE`.

    - **type** `string`: No description - one of: campaign, adset, creative, ad
    - **parentId** `string`: Where to look for it: the ad set for an ad, the campaign for an ad set, the ad account otherwise.
  - **quotaExhausted** `boolean`: Google Ads and YouTube Analytics 429 only. True when the upstream Google quota is spent rather than a Zernio limit.
  - **quotaScope** `string`: Google Ads and YouTube Analytics 429 only, when the scope is known. DEVELOPER is the shared budget (the developer token for Google Ads, the Google Cloud project for YouTube Analytics); ACCOUNT is your ad account (Google Ads only). - one of: DEVELOPER, ACCOUNT
  - **budgetScope** `string`: Zernio Google Ads burst-limit 429 only (never set alongside `quotaExhausted`). `account` is the limit of 15 requests per minute per connected Google Ads account; `user` is the ceiling of 120 requests per minute per Zernio user across all their Google Ads accounts. Both clear within a minute. - one of: account, user

#### 403: Ads access required (Ads add-on on legacy plans, included on usage-based plans), or no access to profile

#### 404: Profile or posting account not found

#### 409: Conflict. One of:

- The Business Login connection needs reconnecting: reconnect it with loginMode=business, or pass force=true or disconnect it first to switch to the standard login.
- ambiguous_account: the profile holds several active accounts of the platform and no accountId names one.
- reconnect_required: force=true names the posting account the ads connection hangs off, and it is no longer connected.


#### 503: Business login is not configured or the platform is temporarily unavailable.

---


# Related Schema Definitions

## ErrorResponse

Canonical error envelope. `error` is the human-readable message; `type`,
`code`, `param`, `platform`, and `platformError` are top-level siblings
for programmatic handling. For upstream platform failures (`type:
platform_error`), `platformError` carries the provider's raw payload
verbatim (for Meta: `error_subcode`, `error_user_title`, `error_user_msg`).


### Properties

- **error** `string`: Human-readable error message.
- **type** `string`: Error class for programmatic handling. - one of: invalid_request_error, authentication_error, permission_error, not_found, rate_limit_error, platform_error, api_error
- **code** `string`: Stable machine-readable error code.
- **param** `string`: The request field that caused the error, when applicable.
- **docUrl** `string`: Documentation page for resolving the error, when one applies.
- **platform** `string`: Upstream platform (e.g. meta, google, tiktok), present when type is platform_error.
- **platformError** `object`: Raw error payload from the upstream platform, passed through verbatim so
integrators can read provider-specific codes. For Meta this includes
error_subcode, error_user_title, and error_user_msg.

- **provider** `string`: Email API: the mailbox provider the error came from (`google`, `microsoft`).
- **providerError** `object`: Email API: the provider's own error code and message, for support and logs. Branch on `code`, not on this.
  - **code** `string,null`: 
  - **message** `string,null`: 
- **retryable** `boolean`: Email API: whether the same request can succeed if retried (with the same `Idempotency-Key` for sends).
- **requestId** `string`: Email API: the request id, also in the `X-Request-Id` header. Quote it when you contact support.
- **docsUrl** `string`: Email API: where this `code` is documented.
- **details** `object`: Additional structured context for the error (for example field-level validation errors). What it carries depends on the endpoint and platform.

**Meta ads refusals.** The ones customers hit most come back with their own `code` instead of `platform_api_error`, the field to fix in `param`, and an English `details.hint` saying how to fix it. `details.fix` ({ label, url }) links the Meta page that resolves it, when there is one.

The code is picked from Meta's numeric `code` and `error_subcode`, never from the message, so it is the same whatever language Meta wrote `error_user_msg` in. Branch on `code` and show `details.hint`.

- `ad_account_payment_required`: the ad account has no usable payment method (subcode 1815010, 1359188).
- `ad_account_policy_not_accepted`: a business admin has to accept Meta's non-discrimination policy (subcode 2859002, 2859024).
- `lead_ads_terms_not_accepted`: the Facebook Page has not accepted the Lead Ads terms (subcode 1815089).
- `verified_advertiser_required`: the market requires a verified beneficiary and payer; send `regionalRegulationIdentities` (subcode 3858634, 3858636, 3858442, 3858548, 3858495).
- `ad_account_unusable`: the ad account is not active, or the business is restricted from advertising (subcode 1885316, 2446325, and 2490592, 4841021 below).
- `meta_security_check_required`: the Facebook user behind the connection is held at a security check (code 31).
- `meta_action_blocked`: Meta temporarily blocked the Facebook user from this action (subcode 2859015).
- `meta_ad_consent_required`: the Page or Instagram owner chose Meta without ads or less personalized ads (subcode 3858231, 3858412).
- `instagram_account_restricted`: Meta restricted the Instagram account the ad runs as (subcode 2207070).
- `insufficient_permissions`: the ad account cannot use the Instagram account, or the Facebook user has no advertiser permission on the Page (subcode 1815199, 1815202, 1885499, 1341012, and the Advertise permission case below).
- `whatsapp_number_not_linked`: the WhatsApp number is no longer linked to the Page (subcode 2446880).
- `invalid_targeting`: Meta refused the audience or a placement (subcode 1487079, 1870247, 2909035, 1870189, 1870188, 1487756, 1487843, 2490562).
- `post_not_boostable`: Meta does not allow the post to be promoted (subcode 2446187, 2875030, 1487472).
- `budget_too_low`: the budget is below Meta's minimum, which `platformError.error_user_msg` states (subcode 1885272).
- `meta_object_not_accessible`: Meta cannot load an object the request names (wrong ID, deleted, or no access); `platformError.message` names the ID (subcode 33, on ads routes only).

Meta's own error stays in the message and in `platformError`.

**Private replies.** The private-reply endpoint adds:

- `privateReplyConsumed` on a 400: the comment's single reply is already spent.
- `privateReplyOutcome: "unknown"` on a 502: Meta answered a server error and the reply may have been delivered.
- `privateReplyOutcome: "not_sent"` on a 429: Instagram's rate limit refused the reply, so retry later.

**Google quota 429.** On a Google Ads or YouTube Analytics 429, `quotaExhausted: true` marks the failure as Google's own quota, not a Zernio rate limit, so you can keep calling other platforms instead of backing off everywhere. When Google names the scope, `quotaScope` is also set:

- `DEVELOPER`: the shared budget (the developer token for Google Ads, the Google Cloud project for YouTube Analytics). Every account on Zernio is affected and there is nothing to change on your side.
- `ACCOUNT`: your own ad account (Google Ads only).

A Meta 429 carries neither field.

**Zernio Google Ads burst-limit 429.** Carries `budgetScope` instead, never `quotaExhausted`. These are Zernio's own limits, applied before the call reaches Google, and both clear within a minute. They are separate axes from `quotaScope`, not the same pool named twice.

- `account`: the limit of 15 requests per minute per connected Google Ads account.
- `user`: the ceiling of 120 requests per minute per Zernio user across all their Google Ads accounts.

**Failed Meta ad create** (`POST /v1/ads/create`, `POST /v1/ads/boost`, `POST /v1/ads/ctwa`). Carries `stage` (where it failed), `adAccountId` (on which ad account) and `createdObjects` (every object this request had already created, with what cleanup did to it).

- `left_behind` objects still exist on the ad account (Meta refused the delete, typically on a held account, or the delete hit a network error). Delete them yourself or reuse them.
- `unconfirmedWrite` is set when Meta answered a create with a 5xx or a non-JSON body, or dropped the connection, and Zernio could not confirm whether the object exists. Check that parent before creating it again.

**Ineligible ad account: 422 `ad_account_unusable`.** When Meta refuses a write because the ad account's status is ineligible to manage ads (Meta subcode 2490592 or 4841021, on the write itself or on a cleanup delete), any Meta ads write answers it.

That covers create, boost, CTWA, campaign / ad set / ad updates and status changes.

The message names the ad account when known, links Meta's fix (https://www.facebook.com/business/help/422289316306981), lists the objects left behind and ends with Meta's original error, which also stays verbatim in `platformError`.

Meta often reports the first failure under an unrelated code (e.g. 1487194 on the creative), so branch on `code`, not on `platformError`.

**Missing Advertise permission: 403 `insufficient_permissions`.** When the Facebook user behind the connection's token lacks the Advertise permission on the ad account, any Meta ads write answers it.

Triggers: Meta subcode 2490585, 2490591 or 4841020 on the write, or a code 200 refusal such as 1487194 whose cleanup deletes Meta refused with 2490591 or 4841020.

Meta may still accept the campaign and ad set and refuse only the ad. The message names the ad account, asks for the Advertise or Manage permission on it (or a token granted `ads_management`, by reconnecting) and lists the objects left behind.

It ends with Meta's `error_user_title`, `error_user_msg` and subcode; the raw error stays in `platformError`.

  - **stage** `string`: Meta ad create failures only. The step that failed:

- `media`: image/video download or upload.
- `campaign`
- `adset`
- `creative`
- `ad`: the ad POST itself, where Meta's code 31 / 3858385 hold and 100 / 1359188 payment rejections land.
- `activation`: switching the created objects on. No longer returned: a refused switch to ACTIVE now answers 201 with an `activation_failed:` warning and the objects kept PAUSED.
- `other`: a read or check before any write.
 - one of: media, campaign, adset, creative, ad, activation, other
  - **adAccountId** `string`: Meta ad create failures only. The ad account the request wrote to (`act_...`).
  - **createdObjects** `array`: Meta ad create failures only. Every object this request created before failing, in creation order. Objects you referenced (an existing campaign, ad set, creative or video) are never listed and never deleted.
  - **unconfirmedWrite** `object`: Meta ad create failures only. Set when Meta answered a create with a 5xx or a non-JSON body, or dropped the connection after the request was sent, and reading the parent back by name did not settle it. Zernio did not retry it.

One of these left it open:

- The read-back found several objects of the same name.
- The parent could not be read, or the object is a creative, which has no reliable read-back.
- The read-back found no such object, after a dropped connection, a non-JSON body, a 5xx with `retryOnServerError: false`, or a 5xx on a create whose own body is `status: ACTIVE`.

  - **quotaExhausted** `boolean`: Google Ads and YouTube Analytics 429 only. True when the upstream Google quota is spent rather than a Zernio limit.
  - **quotaScope** `string`: Google Ads and YouTube Analytics 429 only, when the scope is known. DEVELOPER is the shared budget (the developer token for Google Ads, the Google Cloud project for YouTube Analytics); ACCOUNT is your ad account (Google Ads only). - one of: DEVELOPER, ACCOUNT
  - **budgetScope** `string`: Zernio Google Ads burst-limit 429 only (never set alongside `quotaExhausted`). `account` is the limit of 15 requests per minute per connected Google Ads account; `user` is the ceiling of 120 requests per minute per Zernio user across all their Google Ads accounts. Both clear within a minute. - one of: account, user