# Connect platform accounts

> Understand the Koil connection flow before publishing content or subscribing to events.

Start here to connect your customer's platform account, page, channel, or workspace to Koil. To try the flow without an app, use a [magic connection](https://docs.koil.co/sandbox#magic-connections) in sandbox mode.

A Connection is created after each successful platform authorization or credential import. Koil stores and renews one user's credentials for one external API, then retrieves them at scale for platform operations without your product passing raw credentials at request time.

Koil setup has two parts. First, create a Connection so Koil can manage platform authorization and credential renewal. Then, create a Profile so Koil knows which platform profile to use for API operations.

Why both?

A Connection represents one authorization: who authorized access, which app was used, which scopes are available, and whether Koil can retrieve fresh credentials when an operation runs. A Profile represents the publishing or event target. One authorized user may be able to post to multiple pages, channels, or workspaces, so Koil asks you to choose the exact profile before publishing or subscribing to events.

## The flow

1.  Create a Connection. Use Koil-hosted OAuth for new user authorization, or import existing credentials if you already have a renewable platform grant.
    
2.  Create a Profile. Choose the specific platform profile, page, channel, location, or account Koil should use.
    
3.  Check capabilities. Capabilities list the platform's collections with the operations, events, and backfill the Profile's credential covers.
    
4.  Choose what to build next. Use the Profile's `id`, as the `profileId` of a request, to [publish content](https://docs.koil.co/guides/publishing) or [subscribe to events](https://docs.koil.co/guides/subscribe-to-events).
    

## Key terms

-   `Connection`: the Koil-managed authorization for one user's access to one platform API.
-   `Profile`: the platform profile Koil can access through one Connection.
-   `profileId`: a Profile's `id`, as you send it with publish, event, read, and reply calls.
-   `collection`: the platform content collection, such as `instagram.media.posts`.
-   `variant`: a platform-specific operation shape, such as `feed` or `reel`.
-   Capabilities (`GET /v1/profiles/{profileId}/capabilities`): a Profile's `collections`, each with the operations, events, and backfill its credential covers, and its `settings`, each with the operations its credential covers.

## Create a Connection

A Connection is obtained by one `method`, which its issuer offers (`GET /v1/issuers` lists each issuer's):

-   `oauth`: your user authorizes your [App](https://docs.koil.co/byo-apps) at the platform. Every platform in the catalog today connects this way.
-   `key`: the brand gives you a key of its own, such as an App Store Connect API key, which you send to Koil, and there is no App. A key has a public `config` (a key's id, an account id), which the Connection returns as `key.config`, and a `secret`, which Koil seals and never returns or exports. An `oauth` Connection names its App as `oauth.appId`. Koil checks the key with the platform before it stores anything.

An `oauth` Connection is made through a Connect Session, which works like Stripe's Account Links:

-   **Create the session when the user clicks, and redirect at once.** Its `url` works once, in the first browser that opens it, for 30 minutes. Never store, email or send it. To invite someone by email or chat, send them a link to a page of your own that creates the session when they open it and redirects them to its `url`.
-   **A spent or expired link comes back to you.** Opened again, in any browser, the link sends it to your `returnUrl` with `connectSessionId` and the session's `status` added to its query: `pending` while the user may still be finishing where they first opened it, else `completed`, `failed` or `expired`. Unless it is `completed`, create a new session and redirect again if the user needs to start over, as you would for Stripe's `refresh_url`.

Use Koil-hosted OAuth when your users need to authorize a platform account from your product. Koil creates a short-lived Connect Session and returns the platform approval URL.

1.  Create a Connect Session against your [App](https://docs.koil.co/byo-apps), naming your own user, the `returnUrl` in your product to send them back to, and, optionally, the `metadata` a new Connection should carry.
    
    ```bash
    curl -X POST "https://api.koil.co/v1/connect-sessions" \
      -H "Authorization: Bearer $KOIL_API_KEY" \
      -H "Koil-Version: 2026-12-01" \
      -H "Content-Type: application/json" \
      -d '{
      "appId": "app_123",
      "clientUserId": "customer-user-123",
      "returnUrl": "https://app.example.com/integrations/connected",
      "metadata": {
        "accountId": "acct_42"
      }
    }'
    ```
    
    `returnUrl` is required and must be `https:`: however the session ends, Koil sends the user back there.
    
2.  Redirect your user to the returned `url` straight away. It takes them to the platform's consent screen with no Koil page between. The URL carries the session's secret: keep it out of logs, and never store or send it. The session's `id` beside it is not a secret and is safe to store.
    
3.  The user approves access with the platform. Koil then redirects their browser to your `returnUrl` with `connectSessionId` and `status` (`completed` or `failed`, or `expired` if the session expired first) added to its query. Treat that redirect as a hint to refresh your UI, not as proof: anyone can open your `returnUrl` with any query, so read the session (or wait for the event) before you act on it.
    
4.  Wait for the [`connection.created`](https://docs.koil.co/events#connection.created) event (or [`connection.updated`](https://docs.koil.co/events#connection.updated) when the session reauthorizes a Connection, or the user authorized the same account under this App and `clientUserId` before), or check the session status. `GET /v1/connect-sessions/{connectSessionId}`
    
    `status` is `pending` until the user finishes, then `completed` with the `connectionId`, or `failed` with an `error` (the user declined, or the platform refused). A session still `pending` at `expiresAt` (30 minutes after creation) reads as `expired` and can no longer be finished; create a new session. Every status but `pending` is final.
    
5.  Store the Connection's id: the session's `connectionId`, which `connection.created` carries as `data.id`.
    
6.  Check `missingScopes` on the completed session. Facebook Login and Google let the user untick permissions on the consent screen, and the session still completes, with the Connection holding only what the user granted. A completed session lists the scopes the user granted in `grantedScopes`, and the scopes it requested (your App's `scopes` when the user opened the link) that they did not grant in `missingScopes`, which is absent when there are none. Koil does not fail the session for a declined scope, since only you know which scopes your product needs; an operation that needs one is refused with `scope_insufficient`. If your product needs a missing scope, explain why to the user and send them through a new Connect Session with this `connectionId`. Neither field is present when the platform reported no scopes. No event carries them, since they describe this one authorization rather than the Connection: when `connection.created` (or `connection.updated`) arrives, read the session to see them.
    
    ```bash
    curl "https://api.koil.co/v1/connect-sessions/cs_456" \
      -H "Authorization: Bearer $KOIL_API_KEY" \
      -H "Koil-Version: 2026-12-01"
    ```
    
    Scopes are compared as the platform reports them, except where it names one scope two ways: Google reports `email` and `profile` as `https://www.googleapis.com/auth/userinfo.email` and `https://www.googleapis.com/auth/userinfo.profile`, and either spelling counts as the other.
    

To have a user re-authorize a Connection, for example one that went `invalid`, create the session with its `connectionId` (it must be a Connection of the same App):

```bash
curl -X POST "https://api.koil.co/v1/connect-sessions" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-01" \
  -H "Content-Type: application/json" \
  -d '{
  "appId": "app_123",
  "connectionId": "conn_123",
  "returnUrl": "https://app.example.com/integrations/connected"
}'
```

Finishing it re-authorizes that Connection in place: its `id` and `metadata`, its Profiles' ids, their poll state and their metadata all stay, and it is `active` again.

A Connection's `id` is the durable handle for credentials Koil stores, renews, and resolves when a Profile operation runs.

### Connect with a key

For an issuer that takes a key, there is no App or Connect Session: you collect the key from the brand in your own product and send it to Koil.

-   **Ask for the fields the issuer declares.** [`GET /v1/issuers`](https://docs.koil.co/api) lists each key issuer's `config` (public, such as a key's id) and `secret` (write-only) as JSON Schema, with any `title` and `description` the issuer gives a field, so you can build the form from it. A field that holds a file's contents, such as a `.p8` or PEM private key, names its `contentMediaType`: take it in a text area, since a one-line input strips the line breaks a key can't be read without.
-   **Send the key on, and keep no copy.** Koil seals the `secret` and never returns or exports it, so nothing needs to hold it once Koil has it.

Create the Connection with `POST /v1/connections`, `method: "key"`, the issuer's `config` and `secret` as `key`, and an `Idempotency-Key`. A field that breaks the issuer's schema is a `validation_error` at `/key/config/…` or `/key/secret/…`; a key the platform refuses is `connection_invalid`, a live key whose call the platform refuses with a 403 it doesn't explain is `scope_insufficient`, and nothing is stored. `scopes`, where you send them, name at least one scope, and Koil keeps them across renewals. `POST /v1/connections` always creates: a key for an account that already has a Connection under the issuer and `clientUserId` is refused with `conflict` (409), and `meta.resourceId` names that Connection, whose key `PUT /v1/connections/{connectionId}/credential` replaces.

```bash
curl -X POST "https://api.koil.co/v1/connections" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-01" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
  "method": "key",
  "issuerId": "app_store_connect",
  "clientUserId": "customer-user-123",
  "key": {
    "config": {
      "appleIssuerId": "57246542-96fe-1a63-e053-0824d011072a",
      "keyId": "2X9R4HXF34"
    },
    "secret": {
      "privateKey": "-----BEGIN PRIVATE KEY-----\nMIGT..."
    }
  },
  "scopes": [
    "customer_support"
  ]
}'
```

When the brand rotates its key, replace it in place with `PUT /v1/connections/{connectionId}/credential` (the same account only), which keeps the Connection's id and Profiles and makes an `invalid` Connection `active` again:

```bash
curl -X PUT "https://api.koil.co/v1/connections/conn_789/credential" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-01" \
  -H "Content-Type: application/json" \
  -d '{
  "method": "key",
  "key": {
    "config": {
      "appleIssuerId": "57246542-96fe-1a63-e053-0824d011072a",
      "keyId": "8QL3N7Y2ZT"
    },
    "secret": {
      "privateKey": "-----BEGIN PRIVATE KEY-----\nMIGT..."
    }
  }
}'
```

When calls with a key start being refused, Koil asks the platform whether the key itself is still live, at most once an hour, so a key revoked at the platform can take up to an hour to be noticed. Where the platform's refusal can be a passing one (App Store Connect answering a key Koil signs for with a 401), the Connection becomes `reauthorization_required` with `statusReason: key_refused`, and Koil keeps asking the platform about the key for 48 hours, polling and billing nothing meanwhile: if the platform takes the key again, the Connection is `active` again, and if it still refuses it after 48 hours, the Connection is `invalid`. Any other refused key, such as one the brand disabled or deleted, makes the Connection `invalid` at once. `invalid` is final, and Koil deletes the key with it: it stays `invalid` until the brand reconnects or you replace the key, even if the brand turns the old one back on.

The `clientUserId` you pass when creating the Connect Session (or the Connection itself) is your own id for the user, up to 255 characters. Koil returns it on the Connection, and `GET /v1/connections?clientUserId={yourUserId}` lists that user's Connections, so you can map Connections back to your users without storing every Connection's `id` yourself.

For your other ids, a Connection carries your own `metadata`. Set it on the Connect Session or `POST /v1/connections` that creates the Connection, and change it with `PATCH /v1/connections/{connectionId}`, which merges the keys you send into what is stored and removes a key sent as `""`; as with any resource's metadata, the change announces no event. A Connect Session that re-authorizes an existing Connection, by its `connectionId` or because the same user authorized before, leaves that Connection's `metadata` as it is and announces `connection.updated` rather than `connection.created`; `PATCH` the Connection then if its metadata should change.

```bash
curl -X PATCH "https://api.koil.co/v1/connections/conn_123" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-01" \
  -H "Content-Type: application/json" \
  -d '{
  "metadata": {
    "workspaceId": "ws_7"
  }
}'
```

A Connection's `status` is `active`; `reauthorization_required` while the user must connect again soon (`statusReason: expiring`: the token, or the refresh token that renews it, still works but expires within 14 days; `key_refused` for a key the platform refused, which Koil asks about for 48 hours); or `invalid` once the stored credential no longer authorizes, which is final (`renewal_failed`, `revoked`, `expired` or `key_refused`, or `duplicate` when the same user turns out to have another Connection under the App and `clientUserId`, which stays), and the user must connect again. `updatedAt` moves with each change, and [`connection.updated`](https://docs.koil.co/events#connection.updated) announces it. On any `status` other than `active`, send the user through a Connect Session created with this `connectionId`: it re-authorizes the Connection in place, keeping its id and Profiles, and returns it to `active`. For a `key` Connection, collect a new key and replace it with `PUT /v1/connections/{connectionId}/credential`, which does the same. Where the platform names the user who authorized (every platform but LinkedIn), the Connection carries it as `subject`.

A Profile has a `status` of its own. It is `active` while Koil can act for it, and `invalid` once the platform stops letting the Connection act for that profile while the Connection itself still works: `statusReason: revoked` when, on Facebook and Instagram, the user lost their role on the Page or the Page is gone, and `mint_failed` when Koil has failed to get a new credential for the profile for a day. [`profile.updated`](https://docs.koil.co/events#profile.updated) announces each change. Once the user has access again, send them through a Connect Session created with the profile's `connectionId`; the profile returns to `active` when Koil can act for it again.

While a Profile, or its Connection, is `invalid`, Koil stops working on it: it polls nothing, refuses backfill requests and other operations for it with `connection_invalid`, deletes the platform credential it can no longer use, and does not bill the profile. Polling resumes from where it stopped once the profile is `active` again. A Connection or Profile still `invalid` six days after it became so is deleted, announced by `connection.deleted` or `profile.deleted`. `reauthorization_required` with `statusReason: expiring` is a warning: everything keeps working until the credential expires. While a key is `key_refused`, Koil polls nothing and bills nothing for the Connection's Profiles.

A Connection carries what its credential states of itself as `credential` wherever it appears: its read, `GET /v1/connections`, and its events. `credential.scopes` are the scopes it holds, absent when Koil does not know them, which is not a credential of none. `credential.reauthorizeBy` is the date the user must connect again by: where Koil can renew the credential, the platform's deadline for that (TikTok's and LinkedIn's refresh tokens expire about a year after the user authorized); where nothing renews it (a LinkedIn grant without a refresh token), the access token's own expiry. Once that deadline has passed it stays, so the date never moves later. The Connection becomes `reauthorization_required` 14 days ahead of that date, announced by `connection.updated`. The expiry of an access token Koil renews is not part of the Connection. `credential` is absent while Koil holds no credential, as once the Connection is `invalid`.

Use credential import when your product already has a platform grant. Import it through the App of the app that issued the grant: a platform renews a token only for the app it issued it to.

1.  Import the platform grant. `POST /v1/connections` with `method: "oauth"`, with an [`Idempotency-Key`](https://docs.koil.co/concepts/idempotency): a retry with the same key returns the same Connection instead of importing the grant twice.
    
    ```bash
    curl -X POST "https://api.koil.co/v1/connections" \
      -H "Authorization: Bearer $KOIL_API_KEY" \
      -H "Koil-Version: 2026-12-01" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: $(uuidgen)" \
      -d '{
      "method": "oauth",
      "appId": "app_123",
      "clientUserId": "customer-user-123",
      "grant": {
        "accessToken": "EAAG...",
        "expiresAt": "2026-08-30T09:30:00.000Z"
      },
      "metadata": {
        "accountId": "acct_42"
      }
    }'
    ```
    
    `grant` takes the token fields your app stored, and nothing else:
    
    | Field |  |
    | --- | --- |
    | `accessToken` | Required. |
    | `refreshToken` | Where the platform issued one: TikTok, Google, and LinkedIn do; a Meta user token has none. |
    | `expiresAt` | When the access token expires, as an RFC 3339 date-time. Required with `refreshToken`, since Koil renews a token only once it knows when it expires; if you did not store the expiry, a time in the past makes Koil renew the token the first time it is used. Omit it for a token that never expires, such as a WhatsApp system-user token. |
    | `refreshTokenExpiresAt` | When the refresh token itself expires, where the platform said (TikTok's and LinkedIn's `refresh_token_expires_in`, about a year after the user authorized). Only with `refreshToken`, and refused once past, since such a refresh token renews nothing. It dates the Connection's `credential.reauthorizeBy` from the start; without it, a Connection learns the date at its first renewal, where the platform states it. |
    
    Koil asks the platform about the grant before keeping it, and records the scopes it reports; send `scopes` only to state them yourself (at least one, none twice, as for a key), and Koil keeps yours. The response lists the scopes your App requests that the grant lacks in `missingScopes`, as a completed Connect Session does; if your product needs one, send the user through a Connect Session with the Connection's `id` as `connectionId`.
    
    ```bash
    curl -X POST "https://api.koil.co/v1/connections" \
      -H "Authorization: Bearer $KOIL_API_KEY" \
      -H "Koil-Version: 2026-12-01" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: $(uuidgen)" \
      -d '{
      "method": "oauth",
      "appId": "app_456",
      "clientUserId": "customer-user-123",
      "grant": {
        "accessToken": "ya29...",
        "refreshToken": "1//0g...",
        "expiresAt": "2026-07-01T10:30:00.000Z"
      }
    }'
    ```
    
    A grant Koil cannot store comes back as a `validation_error` whose `meta.violations` name the field. A grant the platform rejects comes back as `connection_invalid` with the platform's reason, and that user must connect again. So does a Google grant issued to a different OAuth client than the App's, since Google would refuse to renew it. An import always creates: a grant for a user who already has a Connection under the App and `clientUserId` is refused with `conflict` (409), and `meta.resourceId` names that Connection. A fresh grant for the same user replaces a Connection's in place with `PUT /v1/connections/{connectionId}/credential` (`method: "oauth"`). Koil asks the platform who the grant is for first, and refuses it unless both the Connection and the grant name the same user: a grant for someone else is `subject_mismatch`, and one where either names no one (LinkedIn's) is `subject_unconfirmed`. Reconnect such a Connection through a Connect Session with its `connectionId` instead, where the user authorizes it.
    
2.  Koil stores the credential material securely.
    
3.  Store the returned Connection's `id`.
    
4.  Use Koil resource IDs for future calls instead of sending platform credentials again.
    

## Create a Profile

A Profile is the platform profile Koil can access through one Connection. Most Koil operations start with a `profileId`.

1.  List platform profiles available through the Connection. `GET /v1/connections/{connectionId}/eligible-platform-profiles`
    
    The list [pages](https://docs.koil.co/concepts/pagination): an agency's Facebook Pages or a chain's Business Profile locations can run to hundreds. Fetch further pages only as your customer needs them; creating a Profile works for any profile discovery lists, whichever page it is on.
    
2.  Let your customer or application choose the profile to use. Each profile carries its current `displayName`, `username` and `avatarUrl`; Profiles do not store them, so call this endpoint again whenever your UI needs them. `avatarUrl` is a short-lived platform URL: download the image if you want to keep it.
    
    `accountKind` says what kind of account each one is (a Facebook `page`, a YouTube `channel`, a Business Profile `location`, …), and `platformDetails` what else its platform reports about it, such as an Instagram account's linked Facebook Page or a WhatsApp number's quality rating. Profiles store neither.
    
3.  Create a Profile from the one chosen.
    
    ```bash
    curl -X POST "https://api.koil.co/v1/profiles" \
      -H "Authorization: Bearer $KOIL_API_KEY" \
      -H "Koil-Version: 2026-12-01" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: $(uuidgen)" \
      -d '{
      "platformId": "instagram",
      "connectionId": "conn_123",
      "platformProfileExternalId": "17841400000000000"
    }'
    ```
    
4.  Store the returned Profile's `id`. To tie the profile to your own records, keep your ids in its `metadata`, set at create or later with `PATCH /v1/profiles/{profileId}`.
    
5.  Check which operations it supports. `GET /v1/profiles/{profileId}/capabilities`
    

Two users can authorize the same platform profile. Koil keeps those Profiles separate by storing the selected platform profile together with the `connectionId`, so your product can choose the right actor for each action.

`GET /v1/profiles` lists the Organization's Profiles. `clientUserId` narrows it to the profiles connected through that user's Connections, `connectionId` to one Connection's, and `platformId` to one platform's. The filters combine.

```bash
curl "https://api.koil.co/v1/profiles?clientUserId=customer-user-123" \
  -H "Authorization: Bearer $KOIL_API_KEY" \
  -H "Koil-Version: 2026-12-01"
```

## Next steps

After setup, branch into [publishing](https://docs.koil.co/guides/publishing) for outbound content or [event destinations](https://docs.koil.co/guides/subscribe-to-events) for inbound content. To reply to platform content, set up events first, then use [reply to content](https://docs.koil.co/guides/reply-to-content) from the received event.
