> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rydhm.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rydhm.ai/_mcp/server.

# Connect Rydhm

If your app is used by other teams (a CRM, a dialer, a helpdesk), each of them has their own Rydhm workspace. With **Connect Rydhm**, an admin of that workspace clicks **Connect Rydhm** in your app, signs in to Rydhm, checks what your app may do and clicks **Allow**. Your server gets a key for their workspace, and the signing secret of a webhook Rydhm adds for your app. Nobody copies a key.

It's OAuth 2.0 with the authorization code and PKCE (S256), so any standard OAuth library works too.

```mermaid
sequenceDiagram
    participant A as Admin (browser)
    participant App as Your app's server
    participant R as Rydhm
    A->>App: Clicks "Connect Rydhm"
    App-->>A: Redirect to Rydhm (client_id, redirect_uri, state, code_challenge)
    A->>R: Signs in, picks the workspace, clicks Allow
    R-->>A: Redirect to your redirect_uri?code=…&state=…
    A->>App: GET /callback?code=…&state=…
    App->>R: POST /v1/oauth/token (code, code_verifier, client secret)
    R-->>App: { access_token, workspace, webhook_secret }
```

## 1. Register your app

In the Rydhm app, **Developers → Connect Rydhm → Register an app**:

| Field                | What to put                                                                                                                                                                                               |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Name                 | What your customers see on the Connect screen, like *AIX CRM*.                                                                                                                                            |
| Send people back to  | Your callback address, exactly as your app sends it (one per line). `https://` only; `http://localhost` is allowed while you develop. Matching is exact: no trailing-slash or query leniency.             |
| What it may do       | **Make and read sales calls** (`calls:read` + `calls:write`) is preselected. **Choose** picks any permission.                                                                                             |
| Send call updates to | Optional. Rydhm adds a webhook endpoint for it in each workspace that connects, for the sales-call events (`call.completed`, `call.summary.ready`, …), and your app gets its signing secret with the key. |

Rydhm shows the **client id** (`rydhm_app_…`) and the **client secret** (`rydhm_cs_…`). The secret is shown **once**: save both in your app's settings (`RYDHM_CLIENT_ID`, `RYDHM_CLIENT_SECRET`, on the server). Lost it? **Roll** a new one; workspaces already connected keep working.

## 2. The Connect button

Make a PKCE pair and a `state`, keep both in the user's session, and send them to the consent page.

#### TypeScript

**`connect.ts`**

```typescript title="connect.ts"
import { oauth } from "@rydhm/sdk";

app.get("/api/rydhm/connect", requireAdmin, async (req, res) => {
  const { codeVerifier, codeChallenge } = await oauth.pkce();
  const state = crypto.randomUUID();
  req.session.rydhm = { codeVerifier, state };
  res.redirect(oauth.authorizeUrl({ clientId: process.env.RYDHM_CLIENT_ID!, redirectUri: REDIRECT_URI, state, codeChallenge }));
});
```

#### Python

**`connect.py`**

```python title="connect.py"
import secrets
from rydhm import oauth

@app.get("/api/rydhm/connect")
def connect():
    p = oauth.pkce()
    state = secrets.token_urlsafe(16)
    session["rydhm"] = {"verifier": p.code_verifier, "state": state}
    return redirect(oauth.authorize_url(client_id=os.environ["RYDHM_CLIENT_ID"], redirect_uri=REDIRECT_URI, state=state, code_challenge=p.code_challenge))
```

#### Any language

```text
https://app.rydhm.ai/connect/authorize
  ?client_id=rydhm_app_…
  &redirect_uri=<exactly a registered address>
  &response_type=code
  &state=<random, up to 500 characters>
  &code_challenge=<base64url(SHA-256(code_verifier))>
  &code_challenge_method=S256
  &scope=calls:write            (optional; default: everything the app is registered for)
```

On Rydhm, the admin sees which workspace they're connecting (they can switch), what your app may do in plain words, and where they'll go back. Only a workspace **admin** can allow. **Cancel** sends them back with `error=access_denied&state=…`. An unknown `client_id` or an address you didn't register shows an error on Rydhm and never redirects.

## 3. The callback

Check `state`, then swap the one-time `code` for the workspace's key. A code works **once**, for **10 minutes**.

#### TypeScript

**`callback.ts`**

```typescript title="callback.ts"
import { oauth, Rydhm } from "@rydhm/sdk";

app.get("/api/rydhm/callback", requireAdmin, async (req, res) => {
  const saved = req.session.rydhm;
  if (!saved || req.query.state !== saved.state || !req.query.code) return res.redirect("/settings?rydhm=cancelled");
  const t = await oauth.exchangeCode({
    code: String(req.query.code),
    redirectUri: REDIRECT_URI,
    codeVerifier: saved.codeVerifier,
    clientId: process.env.RYDHM_CLIENT_ID!,
    clientSecret: process.env.RYDHM_CLIENT_SECRET,
  });
  await saveConnection({ key: t.accessToken, workspace: t.workspace, webhookSecret: t.webhookSecret }); // encrypted
  res.redirect("/settings?rydhm=connected");
});
```

#### Python

**`callback.py`**

```python title="callback.py"
from rydhm import oauth

@app.get("/api/rydhm/callback")
def callback():
    saved = session.pop("rydhm", None)
    if not saved or request.args.get("state") != saved["state"] or "code" not in request.args:
        return redirect("/settings?rydhm=cancelled")
    t = oauth.exchange_code(code=request.args["code"], redirect_uri=REDIRECT_URI, code_verifier=saved["verifier"],
                            client_id=os.environ["RYDHM_CLIENT_ID"], client_secret=os.environ["RYDHM_CLIENT_SECRET"])
    save_connection(key=t.access_token, workspace=t.workspace, webhook_secret=t.webhook_secret)  # encrypted
    return redirect("/settings?rydhm=connected")
```

#### HTTP

```bash
curl -X POST https://api.rydhm.ai/v1/oauth/token \
  -H "Content-Type: application/json" \
  -d '{"grant_type":"authorization_code","code":"…","redirect_uri":"https://crm.example.com/api/rydhm/callback",
       "client_id":"rydhm_app_…","client_secret":"rydhm_cs_…","code_verifier":"…"}'
# → {"access_token":"rydhm_live_…","token_type":"bearer","scope":"calls:write",
#    "workspace":{"id":"…","name":"AIX Staging"},"connection_id":"…",
#    "webhook_id":"…","webhook_secret":"whsec_…"}
```

The client secret may also be sent as HTTP Basic (`Authorization: Basic base64(client_id:client_secret)`). Errors follow RFC 6749 (`error`, `error_description`):

| Status | `error`                  | When                                                                                                                |
| ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| 400    | `invalid_request`        | A field is missing.                                                                                                 |
| 401    | `invalid_client`         | Unknown `client_id`, or a wrong or missing client secret.                                                           |
| 400    | `invalid_grant`          | The code is unknown, expired, already used, for another app; `redirect_uri` differs; `code_verifier` doesn't match. |
| 400    | `unsupported_grant_type` | `grant_type` isn't `authorization_code`.                                                                            |
| 429    | `rate_limited`           | More than 30 a minute from one address, or 60 for one app.                                                          |

Never retry an exchange with the same code: if a code is presented twice, the connection it made is revoked, in case it leaked. Start the connection again instead.

## 4. Use the key

`access_token` is an ordinary Rydhm API key for that workspace, with the permissions the admin allowed. Use it like any key, for example to [start sales calls](/engine/sales-calls-quickstart):

```typescript
const rydhm = new Rydhm({ apiKey: connection.key });
const { workspace, salesCalls } = await rydhm.oauth.connection();
// "Connected to AIX Staging · calls go out from (628) 212-6768"
if (!salesCalls.ready) showSetupLink(salesCalls.setupUrl); // no number switched on for sales calls yet
```

`GET /v1/oauth/connection` takes only a key Connect Rydhm issued (`403 not_a_connected_app` otherwise).

The key doesn't expire, even in a workspace that requires API keys to: an admin allowed it, and disconnecting ends it at once. In that workspace it shows in **Developers → API keys**, locked, as *Managed by the AIX CRM connection*.

## Disconnecting

* **From your app**: `DELETE /v1/oauth/connection` (`rydhm.oauth.disconnect()`). Then forget the key and the webhook secret.
* **From Rydhm**: an admin clicks **Disconnect** in **Settings → Connected apps**. Your next request with the key gets `401`: show **Connect Rydhm** again.

Either way the key stops working at once and the webhook endpoint Rydhm added is removed. Connecting the same app to the same workspace again replaces the old connection (with a new key and webhook secret). Every connect and disconnect is in the workspace's audit log.

## Webhooks

When your app has a **Send call updates to** address, each connection adds an endpoint for it in that workspace. Deliveries are [Standard Webhooks](/developers/webhooks), signed with the `webhook_secret` from the token exchange: verify them with `verifyWebhook` (`@rydhm/sdk`) or `verify_webhook` (`rydhm`). If the endpoint can't be added (the workspace already has 10), the token answer has `webhook_error` and the connection still works.