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

# Partners

> The RoutaPartner client, in @routa-chat/sdk/partner: create one project per customer, issue its key, sign the connection link and follow the channels. Experimental.

> [!WARNING]
>
> **Experimental.** `@routa-chat/sdk/partner` can change in a minor version until an external partner uses it. The Partner API also only exists on plans that include it. Routa is the one that grants this access: without it, every call responds `404 partner_api_not_available`.

If your platform resells WhatsApp to its own customers, the [Partner API](https://docs.routa.chat/en/partners/overview.md) creates **one project per customer**, tied to your ID for them (`externalRef`). `RoutaPartner` is the client of that API. For the concepts, see [Partners](https://docs.routa.chat/en/partners/overview.md) and the step by step in [Connect a customer's number](https://docs.routa.chat/en/partners/onboarding.md).

## Import

`RoutaPartner` lives in a subpath of its own, on purpose. A partner key reaches **all** your customers, so importing it should be a visible act that is easy to find with `grep`. `Routa` loads nothing from it.

```ts theme={null}
import { RoutaPartner } from '@routa-chat/sdk/partner'

const partner = new RoutaPartner(process.env['ROUTA_PARTNER_KEY']!)
```

`new RoutaPartner('rt_partner_...')` is a shortcut for `new RoutaPartner({ partnerKey: 'rt_partner_...' })`. The other options (`baseURL`, `timeout`, `maxRetries`, `logger` and `fetch`) are the same as those of `Routa`. See [Configuration](https://docs.routa.chat/en/sdk/configuration.md).

The credential is `partnerKey`, never `apiKey`. The constructor refuses a project key (`rt_live_...` or `rt_test_...`) with a message that points to `Routa`, and `Routa` refuses a partner key the same way.

A partner key **never sends messages**. After the connection, the customer's traffic uses the key of their project, with `Routa`.

## What a person does once, in the dashboard

The API does not do this for you, on purpose: a leaked key cannot replace itself. In the dashboard, open **Settings** and then the **Partner** tab:

1. Check that the plan includes the Partner API.
2. Create the partner profile. You get your `ptn_...` ID and the **signing secret** (`rt_psign_...`), shown only once.
3. Register the **redirect origins** your links can send the customer back to.
4. Issue a **partner key** (`rt_partner_...`), shown only once.

See [Partner keys](https://docs.routa.chat/en/partners/partner-keys.md) for the scopes.

## Resources

| Namespace | Operations | Scope |
| - | - | - |
| `partner.projects` | `create`, `list`, `retrieve`, `update`, `delete` | `projects:write`, `projects:read` and `projects:delete` |
| `partner.projects.apiKeys` | `create`, `rotate`, `revoke` | `api_keys:write` |
| `partner.channels` | `list`, `delete` | `projects:read` and `channels:write` |
| `partner.webhook` | `retrieve`, `set`, `rotateSecret` | `webhooks:write` |
| `buildOnboardingLink()` | Builds and signs the connection link. Makes no request. | n/a |

A new key only has `projects:read` and `projects:write`. The `api_keys:write`, `webhooks:write`, `channels:write` and `projects:delete` scopes are optional: ask for each one on purpose. `webhooks:write` is needed even to read the webhook, because there is no read-only scope.

## From customer to connected number

The cycle: create the customer project, issue its key, sign the link the customer opens to connect the number, confirm through the API and send with the project key.

```ts theme={null}
import { Routa } from '@routa-chat/sdk'
import { buildOnboardingLink, RoutaPartner } from '@routa-chat/sdk/partner'

function required(name: string): string {
  const value = process.env[name]
  if (!value) {
    throw new Error(`${name} is not set`)
  }
  return value
}

const partner = new RoutaPartner(required('ROUTA_PARTNER_KEY'))

// 1 and 2: the customer project and its key. Run it on your server,
// once per customer, when they sign up.
async function provision(customerId: string, customerName: string) {
  // `customerId` is YOUR ID for the customer: it becomes the project's `externalRef`.
  // Repeating the call returns the same project (`created` is false).
  const { project } = await partner.projects.create({
    name: customerName,
    externalRef: customerId,
  })

  // Needs the `api_keys:write` scope. The secret comes back ONCE: store it
  // now, in your secrets vault.
  const key = await partner.projects.apiKeys.create(project.id, {
    name: customerName,
    scopes: ['messages:write', 'messages:read'], // the smallest set that works
  })

  return { projectId: project.id, projectApiKey: key.secret }
}

// 3: sign the link WHEN THE CUSTOMER CLICKS (it is valid for ten minutes), on your
// server. The signing secret never leaves it.
async function connectLink(customerId: string): Promise<string> {
  return buildOnboardingLink({
    partnerId: required('ROUTA_PARTNER_ID'), // ptn_...
    signingSecret: required('ROUTA_PARTNER_SIGNING_SECRET'),
    externalRef: customerId,
    redirectUrl: 'https://app.example.com/connected', // an origin you registered
    state: 'a-value-you-check-against-the-customer-session',
  })
}

// 4: confirm through the API. The redirect to your `redirectUrl` is only a
// hint, never proof: anyone can forge it. Read the project.
async function isConnected(customerId: string): Promise<boolean> {
  const found = await partner.projects.list({ externalRef: customerId }).page()
  const project = found.data[0]
  if (!project) {
    return false
  }
  const detail = await partner.projects.retrieve(project.id)
  return detail.channels.some(channel => channel.status === 'active')
}

// 5: from here on, the customer's traffic uses the project key, not the partner key.
function forCustomer(projectApiKey: string): Routa {
  return new Routa(projectApiKey)
}
```

Open the link with `window.open` on your page, or in a new tab. The page that opens belongs to Routa, and Meta's window does not run in an iframe. When the attempt ends, the customer's browser goes back to your `redirectUrl` with your `state` unchanged, plus `status`, `project_id` and `channel_id` (or `error`). Check the `state` against the customer session and confirm as in step 4. See [Signed connection link](https://docs.routa.chat/en/partners/signed-link.md).

There is no "confirm channel" method. Confirming is a read, as in step 4. Without a webhook, poll `projects.retrieve()` (or `channels.list({ externalRef })`) at a reasonable interval and with a deadline: a customer may never finish.

## Projects

```ts theme={null}
const { project, created } = await partner.projects.create({
  name: 'Acme Store',
  externalRef: 'lead_123',
})
```

`projects.create()` returns `{ project, created }`. `created` is `true` when the call created the project (`201`) and `false` when that `externalRef` already had one and it was returned as it was (`200`). In the second case, the `name` you sent is ignored.

`externalRef` is **your** ID for the customer: 1 to 128 characters among `A-Z a-z 0-9 . _ : -`. Never use an email address, a phone number or a name. It is unique in your organization and set once.

| Method | What it does |
| - | - |
| `create({ name, externalRef })` | Creates the project, or returns the one that already has this `externalRef`. |
| `list({ externalRef?, hasChannel?, limit?, cursor? })` | Lists projects, with [pagination](https://docs.routa.chat/en/sdk/pagination.md). `hasChannel: false` finds the ones that never finished the link. |
| `retrieve(id)` | Reads a project **with its channels**. This is how you confirm a connection. |
| `update(id, { name })` | Renames. The `externalRef` does not change. |
| `delete(id)` | Deletes the project and everything it has. Needs `projects:delete`. |

`hasChannel: false` excludes a project that only has `disabled` channels, because it has a channel in some status.

### Delete a project

Deleting frees the slot in the project limit of your plan. It erases the project's messages, templates, events, contacts, keys, webhook endpoints, media and disabled channels, and their numbers become free again. Nothing changes on WhatsApp.

`delete()` returns `{ status: 'deleted' }` when the project is gone, or `{ status: 'deleting', projectId }` when it was large and only part of it was deleted. In that case, call again until you get `deleted`.

```ts theme={null}
let result = await partner.projects.delete(projectId)
while (result.status === 'deleting') {
  result = await partner.projects.delete(result.projectId)
}
```

A project with a channel that is not `disabled`, or the last project of the organization, responds `409 project_not_deletable` as a `RoutaConflictError`, and `reason` gives the cause: `has_enabled_channel` or `last_project`.

## Project keys

`partner.projects.apiKeys` issues, rotates and revokes the key of a project. It needs the `api_keys:write` scope.

```ts theme={null}
const key = await partner.projects.apiKeys.create(project.id, {
  name: 'Backend of customer 123',
  scopes: ['messages:write', 'messages:read'],
  expiresAt: new Date('2027-06-01'),
  ipAllowlist: ['203.0.113.10'],
})

console.log(key.secret) // shown ONCE
```

| Parameter | Description |
| - | - |
| `scopes` | The scopes of the key. The smallest set that works. The API ignores a value it does not know, so a misspelled scope is dropped, not refused. |
| `name` | A label, up to 80 characters. |
| `expiresAt` | When the key stops working: a `Date` or an ISO 8601 string. |
| `ipAllowlist` | Addresses the key can be used from. Empty or absent means any. |

`rotate(projectId, keyId)` issues a replacement with the same scopes, expiry and address list, and returns its secret, once. The original keeps working until you call `revoke(projectId, keyId)`, so you can move traffic over before you cut it off.

The secret only comes in the `ProjectApiKeyWithSecret` types, from `create` and `rotate`. Reads and `revoke` return `ProjectApiKey`, without a secret.

> [!WARNING]
>
> `apiKeys.create()` and `apiKeys.rotate()` are not safe to retry. The API ignores `Idempotency-Key` on them, and the client retries a request whose response never arrived: a lost response can leave two keys issued, or rotate twice and leave you with a secret that was already replaced. If that matters more to you than riding out a network failure, use a client with `maxRetries: 0` for these calls: `new RoutaPartner({ partnerKey, maxRetries: 0 })`. Creating a *project* is different: it is idempotent by `externalRef`.

## Channels

`partner.channels.list()` lists the channels of every project you created, in any status, each with the `externalRef` of the project. It answers "who has a number and who has a problem" in one call.

```ts theme={null}
for await (const channel of partner.channels.list({ status: 'disabled' })) {
  console.log(channel.externalRef, channel.address, channel.disconnectionReason)
}
```

| Filter | Description |
| - | - |
| `status` | `pending`, `active`, `degraded` or `disabled`. |
| `projectId` | Only the channels of this project. |
| `externalRef` | Only the channels of the project with this `externalRef`. |

Filters combine. A project or an `externalRef` nobody has gives an empty page, not an error. Each `PartnerChannel` has `id`, `projectId`, `externalRef`, `address` (E.164), `status`, `statusReasonCode`, `connectionMode` (`cloud_api` or `coexistence`), `disconnectionReason` and `createdAt`.

`partner.channels.delete(projectId, channelId)` deletes a **disabled** channel and frees its number. This serves a customer who disconnected in the WhatsApp Business app and holds the number until then. It needs the `channels:write` scope. The deletion removes the channel, its credential and its templates. Messages, usage and events keep referring to the channel, and nothing changes at the provider. A channel in any other status responds `409 channel_not_disabled`.

## Receive the events of every customer

`partner.webhook` manages the **single organization webhook**, which receives the events of all your customers. Each event carries `projectId` and `externalRef`, so you route by your own ID. See [Partner webhook](https://docs.routa.chat/en/partners/webhook.md).

```ts theme={null}
const { webhook, secret } = await partner.webhook.set({
  url: 'https://crm.example.com/routa',
  subscribedTypes: ['message.*', 'channel.status_changed'],
})

if (secret) {
  // The first call creates the webhook and returns the secret, once.
}
```

`set()` creates the webhook the first time, with the signing secret (shown only once), and replaces and re-enables it after that, without a new secret. That is why `secret` is optional in the result. `subscribedTypes` needs at least one type. `retrieve()` returns `404 webhook_endpoint_not_found` until the first call to `set()`. `rotateSecret()` issues a new secret and returns it once. The previous one keeps signing for 24 hours.

The `Webhook` is the same as that of `routa.webhooks.*`. Signature verification is also the same, and `partner.webhook.constructEvent()` does it with the `RoutaPartner` you already have. It runs locally, with no network call, and returns the same `RoutaEvent`:

```ts theme={null}
const event = await partner.webhook.constructEvent(
  rawBody,
  request.headers.get('routa-signature'),
  process.env['ROUTA_PARTNER_WEBHOOK_SECRET']!
)

if ('id' in event) {
  console.log(event.projectId, event.externalRef, event.type)
}
```

During a [secret rotation](https://docs.routa.chat/en/partners/webhook.md#rotate-the-secret), pass both secrets in a list: `[newSecret, previousSecret]`.

> [!NOTE]
>
> `partner.webhook.constructEvent()` exists from version 0.4.0. On 0.3.0, verification only exists in `routa.webhooks.constructEvent()`, which requires a `Routa` instance.

See [Webhooks](https://docs.routa.chat/en/sdk/webhooks.md) for `rawBody` and secret rotation. An endpoint with many customers is the limit for all of them: answer fast and queue the work on your side.

## The connection link

`buildOnboardingLink()` builds and signs the link the customer opens to connect their number. It is a pure function: it makes no request and only uses Web Crypto.

```ts theme={null}
import { buildOnboardingLink } from '@routa-chat/sdk/partner'

const link = await buildOnboardingLink({
  partnerId: 'ptn_...',
  signingSecret: process.env['ROUTA_PARTNER_SIGNING_SECRET']!,
  externalRef: 'lead_123',
  name: 'Acme Store',
  redirectUrl: 'https://app.example.com/connected',
  state: 'opaque-value',
})
```

| Parameter | Required | Description |
| - | - | - |
| `partnerId` | yes | Your `ptn_...` ID, shown in the dashboard. |
| `signingSecret` | yes | The signing secret (`rt_psign_...`). It is **not** the partner key. |
| `externalRef` | yes | Your ID for the customer. |
| `name` | no | The project name, up to 200 characters. Without it, the default is the `externalRef`. |
| `redirectUrl` | no | `https://...`, on an origin registered in the dashboard, up to 2048 characters. |
| `state` | no | Opaque, up to 256 characters. It comes back to your `redirectUrl` unchanged. |
| `now` | no | The instant of the signature. Only to reproduce a link in a test. |
| `origin` | no | The origin of the connect page. Only to point at a local instance. |

The function has no language parameter. To choose the language of the connect page, add `&lang=en` or `&lang=pt-BR` to the link it returns. See [Page language](https://docs.routa.chat/en/partners/signed-link.md#page-language).

The API answers every bad link with the same "this link is not valid" page, without saying why. That is why the function validates its input and throws an `Error` naming the parameter at fault: it is the only place where you find out why. It cannot check what lives on Routa's side: the signing secret in use (a rotation keeps the old one for 24 hours), whether the `redirectUrl` origin is registered and whether the plan still has the Partner API.

> [!WARNING]
>
> Sign the link **when the customer clicks**. It is valid for 10 minutes, so a link signed when you sent an email has already expired by the time the customer opens it. Host your own redirector that signs on click. Build the link only on your server: the signing secret can never go to the browser.

## Errors

`RoutaPartner` throws the same classes as `Routa`, from a single copy, so `error instanceof RoutaApiError`, imported from `@routa-chat/sdk`, works in ESM and in CommonJS.

| Response | Class | When |
| - | - | - |
| `401` `partner_key_invalid` | `RoutaAuthenticationError` | The key is missing, unknown, revoked, expired or comes from an address outside the list. A project key also gets this error. |
| `404` `partner_api_not_available` | `RoutaInvalidRequestError` | The organization's plan does not have the Partner API, or no longer has it. |
| `403` `insufficient_scope` | `RoutaInvalidRequestError` | The key lacks the scope the call requires. |
| `402` `project_limit_exceeded` | `RoutaBillingError` | The plan allows no more projects. `limit` carries the limit. |
| `409` `project_not_deletable`, `channel_not_disabled` | `RoutaConflictError` | The deletion cannot happen now. `reason` explains the first one. |
| `422` `request_invalid`, `invalid_external_ref`, `external_ref_immutable`, `invalid_project_name`, `invalid_webhook_url`, `invalid_subscribed_types` | `RoutaInvalidRequestError` | An invalid parameter. |
| `429` | `RoutaRateLimitError` | The limit is per organization: a single bucket for all `/v1/partner/*` routes. |

Check `error.code`, not only the class. See [Error handling](https://docs.routa.chat/en/sdk/error-handling.md) and [Error codes](https://docs.routa.chat/en/errors/error-codes.md).

## Security

Treat `ROUTA_PARTNER_KEY` as an administrator credential.

* **What a leaked key reaches.** With the `api_keys:write` scope, it issues a project key with `messages:write` for *any* project of your organization, so it reaches sending for **all your customers**. That is the price of provisioning through the API. Without the scope, it still reads and creates projects. It never reads an existing secret (keys are shown once), never sends a message and never creates or changes a partner key, a signing secret or a redirect origin. Everything done with it stays in the audit log, with the key as the author, and you revoke it right away in the dashboard.
* **Grant the smallest scope.** For a job that needs a single scope, such as a report that reads projects, issue a key that only has it.
* **Restrict it to your servers and give it an expiry.** Use `ipAllowlist` with the addresses your servers call from, set an expiry and rotate the key from time to time. The same goes for the keys you issue with `apiKeys.create()`.
* **Never in the browser.** The partner key and the signing secret belong to your server, never to a page, a mobile app, a front-end bundle or a public repository. The browser only receives the finished link.
* **Out of logs and version control.** Read it from the environment or a secrets vault. The client never writes the key to a log, an error message or a `logger` call.

## API reference

Each method maps to a [Partner API](https://docs.routa.chat/en/api-reference/endpoint/partner/create-project.md) endpoint. Every route is authenticated by a partner key, and none reads `Idempotency-Key`.


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