# Build an integration (Developers)

URL: https://qrdx.dev/docs/developers/build-an-integration
Source: https://github.com/qrdxinc/qrdx/blob/main/apps/docs/content/docs/developers/build-an-integration.mdx

Create an OAuth app, send people through QRdx's consent screen with OAuth 2.0 and PKCE, call the REST API for them, get their events and list your integration.

By the end of this page, people can click **Connect QRdx** in your product, approve your app on the QRdx consent screen, and your server holds an access token that calls `https://api.qrdx.dev/v1` for them, limited to the scopes they approved.

An integration is an OAuth app. Unlike an [API key](https://qrdx.dev/docs/developers/api-keys), which acts as you in one workspace, a token acts as the person who approved your app, on their own workspace, and they can take that access back at any time.

## Before you start [#before-you-start]

- A QRdx account. Free workspaces can have 1 OAuth app, Pro 5 and Business 25; a workspace uses the best plan among its owners.
- A server that can keep a secret and receive a redirect. The code samples are Node.js with the Fetch API; any language with HTTPS and SHA-256 works.
- The two `https://` redirect URIs you will use: one for production, one for development (`http://localhost` is allowed for that).

## 1. Create an OAuth app [#1-create-an-oauth-app]

Open [Settings → API keys & apps](https://qrdx.dev/dashboard?to=settings/developers) and choose **New app**. The app belongs to the workspace that's open. Only the workspace's owners can create and change apps; admins and members can see them.

![The New OAuth app form: App details with a logo, name, description and website, and OAuth with the redirect URIs, a checkbox for each scope and the Require PKCE switch.](https://qrdx.dev/docs-static/shots/oauth-new-app-form.light.webp)

| Field | What it's for |
| --- | --- |
| **Name**, **Description**, **Logo**, **Website** | Shown on the consent screen. Upload a square logo of at least 128 × 128 px, or paste an `https://` link to one |
| **Redirect URIs** | Where QRdx sends people back to, one per line, up to 10. `https://` only, plus `http://localhost` for development. No wildcards or `#fragments`: every request must send one of them exactly |
| **Scopes** | The most your app may request. Each authorization asks for some or all of them |
| **Require PKCE** | Every authorization must send an `S256` code challenge. Recommended, and on by default |

After you save, QRdx shows the **Client ID** and the **Client secret**. Copy the secret then: QRdx keeps only a hash of it and can't show it again. If you lose it or it leaks, choose **Regenerate secret** on the app's page. The old secret stops working at once; people who already connected stay connected. Creating an app and regenerating its secret ask you to [confirm it's you](https://qrdx.dev/docs/help/privacy-and-security/two-step-verification#confirm-its-you) first, unless you did in that browser in the last 10 minutes.

![The Credentials section of an OAuth app's page: the client ID with a copy button, and the client secret, hidden, with Regenerate secret.](https://qrdx.dev/docs-static/shots/oauth-app-credentials.light.webp)

Keep both values on your server:

```bash title=".env"
QRDX_CLIENT_ID=qrdx_app_...
QRDX_CLIENT_SECRET=qrdx_secret_...
```

## 2. Send people to QRdx [#2-send-people-to-qrdx]

Generate a random `state` and a PKCE `code_verifier`, keep both in the person's session, and redirect to the authorize URL:

```txt title="Authorize URL"
https://qrdx.dev/api/oauth/authorize
  ?response_type=code
  &client_id=<client id>
  &redirect_uri=https://acme.example/oauth/qrdx/callback
  &scope=profile:read codes:read codes:write
  &state=<random value>
  &code_challenge=<BASE64URL(SHA256(code_verifier))>
  &code_challenge_method=S256
```

| Parameter | Required | Value |
| --- | --- | --- |
| `response_type` | Yes | `code` |
| `client_id` | Yes | Your app's client ID |
| `redirect_uri` | Yes | One of the app's redirect URIs, character for character |
| `scope` | Yes | Space- or comma-separated; only scopes the app has |
| `state` | Recommended | Any value; QRdx sends it back unchanged. Check it on return to stop cross-site request forgery |
| `code_challenge` | If the app requires PKCE | 43 to 128 characters: the base64url SHA-256 of your `code_verifier` |
| `code_challenge_method` | No | `S256`, the default and the only method accepted. `plain` is refused with `invalid_request` |
| `prompt` | No | `consent` shows the consent screen even if the person approved these scopes before |

```ts title="lib/qrdx-oauth.ts"
import { createHash, randomBytes } from "node:crypto";

export const QRDX_AUTHORIZE_URL = "https://qrdx.dev/api/oauth/authorize";

export function createPkce() {
  const verifier = randomBytes(32).toString("base64url"); // 43 characters
  const challenge = createHash("sha256").update(verifier).digest("base64url");
  return { verifier, challenge };
}

export function authorizeUrl({ state, challenge }: { state: string; challenge: string }) {
  const url = new URL(QRDX_AUTHORIZE_URL);
  url.search = new URLSearchParams({
    response_type: "code",
    client_id: process.env.QRDX_CLIENT_ID!,
    redirect_uri: "https://acme.example/oauth/qrdx/callback",
    scope: "profile:read codes:read codes:write",
    state,
    code_challenge: challenge,
    code_challenge_method: "S256",
  }).toString();
  return url.toString();
}
```

People who aren't signed in to QRdx sign in first. Then they see the consent screen: your app's logo, name, website and who built it, the permissions you asked for, and the account they're signed in with. Apps QRdx hasn't reviewed carry an **Unverified app.** note. **Authorize** asks them to [confirm it's them](https://qrdx.dev/docs/help/privacy-and-security/two-step-verification#confirm-its-you) unless they did in the last 10 minutes (a sign-in moments earlier counts). Someone who already approved the same scopes for your app goes straight back to you.

![The consent screen for an app QRdx hasn't reviewed: the app's name, who built it and its website, an Unverified app note, the permissions it asks for, the signed-in account with Switch, and the Cancel and Authorize buttons.](https://qrdx.dev/docs-static/shots/oauth-consent-screen.light.webp)

QRdx then redirects to your `redirect_uri`:

- Approved: `?code=<authorization code>&state=<your state>`. The code works once, within 10 minutes.
- Canceled: `?error=access_denied&error_description=...&state=<your state>`.

Invalid requests never redirect; they answer JSON in the OAuth 2.0 shape. An unknown `client_id` is `invalid_client`, an unregistered `redirect_uri` or a `plain` challenge is `invalid_request`, and a scope the app doesn't have is `invalid_scope`:

```json title="400 Bad Request"
{"error":"invalid_scope","error_description":"Invalid or unsupported scope"}
```

## 3. Exchange the code for tokens [#3-exchange-the-code-for-tokens]

From your server, post the code to the token endpoint. The body is form-encoded, and `redirect_uri` must be the one you used in step 2.

```bash title="Terminal"
curl -X POST https://qrdx.dev/api/oauth/token \
  -d grant_type=authorization_code \
  -d client_id=$QRDX_CLIENT_ID \
  -d client_secret=$QRDX_CLIENT_SECRET \
  -d code=$CODE \
  -d redirect_uri=https://acme.example/oauth/qrdx/callback \
  -d code_verifier=$CODE_VERIFIER
```

```ts title="app/oauth/qrdx/callback/route.ts"
export async function GET(req: Request) {
  const params = new URL(req.url).searchParams;
  const session = await getSession(req); // your own session store
  if (params.get("state") !== session.qrdxState) {
    return new Response("Invalid state", { status: 400 });
  }
  if (params.get("error")) {
    return Response.redirect("https://acme.example/settings?qrdx=canceled");
  }

  const response = await fetch("https://qrdx.dev/api/oauth/token", {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "authorization_code",
      client_id: process.env.QRDX_CLIENT_ID!,
      client_secret: process.env.QRDX_CLIENT_SECRET!,
      code: params.get("code") ?? "",
      redirect_uri: "https://acme.example/oauth/qrdx/callback",
      code_verifier: session.qrdxVerifier,
    }),
  });
  if (!response.ok) {
    const { error, error_description } = await response.json();
    throw new Error(`QRdx token exchange failed: ${error} ${error_description}`);
  }

  const tokens: {
    access_token: string;
    token_type: "Bearer";
    expires_in: number;
    refresh_token: string;
    scope: string;
  } = await response.json();
  await saveQrdxTokens(session.userId, tokens); // encrypt at rest
  return Response.redirect("https://acme.example/settings?qrdx=connected");
}
```

```json title="Response fields"
{
  "access_token": "<send as Authorization: Bearer>",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "<store encrypted; it rotates on each refresh>",
  "scope": "profile:read codes:read codes:write"
}
```

`scope` lists what was granted, space-separated. Access tokens last 1 hour and refresh tokens 30 days. Send `code_verifier` exactly when the authorization had a `code_challenge`; a verifier for a code issued without one is refused. A wrong secret or a code that was already used answers `invalid_client` or `invalid_grant`, and a grant type other than the two supported ones:

```json title="400 Bad Request"
{"error":"unsupported_grant_type","error_description":"Supported: authorization_code, refresh_token"}
```

## 4. Refresh tokens [#4-refresh-tokens]

Before the access token expires, trade the refresh token for a new pair. Refresh tokens rotate: each works once, so store the new one every time.

```bash title="Terminal"
curl -X POST https://qrdx.dev/api/oauth/token \
  -d grant_type=refresh_token \
  -d client_id=$QRDX_CLIENT_ID \
  -d client_secret=$QRDX_CLIENT_SECRET \
  -d refresh_token=$REFRESH_TOKEN
```

```ts title="lib/qrdx-oauth.ts"
export async function refreshQrdxTokens(refreshToken: string) {
  const response = await fetch("https://qrdx.dev/api/oauth/token", {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "refresh_token",
      client_id: process.env.QRDX_CLIENT_ID!,
      client_secret: process.env.QRDX_CLIENT_SECRET!,
      refresh_token: refreshToken,
    }),
  });
  // invalid_grant: revoked, expired or already used. Ask the person to reconnect.
  if (!response.ok) throw new Error((await response.json()).error);
  return response.json();
}
```

The token endpoint allows 30 requests a minute per IP address.

## 5. Call the API [#5-call-the-api]

Send the access token as a Bearer token to `https://api.qrdx.dev/v1`. Token requests act on the own workspace of the person who authorized your app (every account has one), under that workspace's plan and [daily quota](https://qrdx.dev/docs/developers/rest-api#rate-limits). Ask for the least your integration needs; people see each scope on the consent screen.

| Scope | Allows |
| --- | --- |
| `profile:read` | The user's id, name, email and avatar: `GET /v1/me` and `GET /api/oauth/userinfo` |
| `themes:read` | Their saved QR themes: `GET /v1/themes`, `GET /v1/themes/{id}` |
| `codes:read` | Their dynamic codes, scan analytics and saved barcodes; listing hooks |
| `codes:write` | Everything `codes:read` allows, plus creating, editing and deleting codes and barcodes, reporting conversions and subscribing to events |

```ts title="lib/qrdx.ts"
const response = await fetch("https://api.qrdx.dev/v1/codes", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${accessToken}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    destinationUrl: "https://acme.example/menu",
    title: "Spring menu",
  }),
});
const { data: code } = await response.json(); // code.shortLink is what the QR encodes
```

A `401 INVALID_TOKEN` means the token expired or was revoked: refresh it, or ask the person to reconnect. A `403 INSUFFICIENT_SCOPE` means the token lacks the scope. The [API reference](https://qrdx.dev/docs/developers/api) lists every endpoint with its scope and errors.

## 6. Receive events with webhooks [#6-receive-events-with-webhooks]

Subscribe on the person's behalf with the REST Hooks API instead of asking them to paste a URL. It needs `codes:write`, and the person's plan must include [webhooks](https://qrdx.dev/docs/webhooks) (Business); otherwise it returns `402 PLAN_REQUIRED`.

```bash title="Terminal"
curl https://api.qrdx.dev/v1/hooks \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"target_url": "https://acme.example/webhooks/qrdx", "events": ["scan.created", "form.submitted"]}'
```

The `201` response carries the subscription `id` and a signing `secret`, shown once. Every delivery is signed with it in `X-QRdx-Signature`; see [Verify signatures](https://qrdx.dev/docs/webhooks#verify-signatures). Unsubscribe with `DELETE /v1/hooks/{id}` when the person disconnects. Subscriptions also appear in **Settings → Webhooks** of their own workspace, where they can remove them.

## 7. Disconnect and identify people [#7-disconnect-and-identify-people]

When someone disconnects QRdx in your product, revoke their tokens. Revoking either token of a pair revokes the pair; the endpoint answers `200` even for unknown tokens.

```bash title="Terminal"
curl -X POST https://qrdx.dev/api/oauth/revoke -d token=$REFRESH_TOKEN
```

People can take access back themselves at any time, in **Settings → Authorized apps** on QRdx, with **Revoke access**. Every token your app holds for their account stops working at once: API calls answer `401` with `invalid_token` and refreshing answers `invalid_grant`. Treat both as "disconnected" and ask them to connect again; they'll see the consent screen again.

To identify who connected, call `GET /api/oauth/userinfo` with a `profile:read` token. It returns OpenID-style claims, `sub`, `name`, `email` and `picture`; use `sub` as the stable account id, since emails can change.

```bash title="Terminal"
curl https://qrdx.dev/api/oauth/userinfo -H "Authorization: Bearer $ACCESS_TOKEN"
```

```json title="401 Unauthorized: an expired or revoked token"
{"error":"invalid_token","error_description":"Invalid or expired token"}
```

## 8. Get listed [#8-get-listed]

When your integration works end to end, ask to have it added to the [integrations directory](https://qrdx.dev/integrations), where it appears as a community integration built by you. On your app's page, **Get listed** opens an email to [support@qrdx.dev](mailto:support@qrdx.dev?subject=List%20my%20integration) with the details filled in:

- your app's name and client ID;
- one line on what it does, and who it's for;
- setup steps, or a link to them;
- a support contact.

The QRdx team reviews listed apps and marks them **Verified**, which removes the **Unverified app.** note from the consent screen. Changing a verified app's name, logo or website removes the badge until it's reviewed again.

## If something goes wrong [#if-something-goes-wrong]

### `invalid_request: redirect_uri not registered` [#invalid_request-redirect_uri-not-registered]

The `redirect_uri` in the authorize URL doesn't match one of the app's redirect URIs character for character, scheme and trailing slash included. Add it to the app, or fix the URL.

### `invalid_scope` [#invalid_scope]

The authorize URL asks for a scope the app doesn't have. Add the scope to the app in **Settings → API keys & apps**, then ask for it again.

### `invalid_grant` on refresh [#invalid_grant-on-refresh]

The refresh token was already used (each refresh returns a new one), expired after 30 days, or the person revoked your app. Send them through authorization again.

### Tokens stop working after you regenerated the secret [#tokens-stop-working-after-you-regenerated-the-secret]

Only new token requests use the new secret; existing access and refresh tokens stay valid. Check that every server instance reads the new `QRDX_CLIENT_SECRET`.

## Security checklist [#security-checklist]

- Keep the client secret on your server. Browser and mobile code must never see it.
- Use PKCE (`S256`) and a fresh `state` for every authorization, and check `state` on return.
- Register exact redirect URIs; QRdx compares them character for character.
- Store access and refresh tokens encrypted, and save the new refresh token after every refresh.
- Revoke tokens when people disconnect. Deleting your app in **Settings → API keys & apps** revokes every token it issued; pausing it refuses them until you resume it.

## Related [#related]

- [REST API and OAuth](https://qrdx.dev/docs/developers/rest-api): the endpoints, scopes, lifetimes and limits in one place
- [Webhooks](https://qrdx.dev/docs/webhooks): payloads, signatures and retries for the events you subscribe to
- [API reference](https://qrdx.dev/docs/developers/api): every endpoint your tokens can call
- [Integrations directory](https://qrdx.dev/integrations): where listed apps appear
