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

# OAuth Install Flow and Tokens

> Install your app in a merchant business with the OAuth authorization code flow and PKCE. Exchange the code, call the API, refresh tokens, and handle revocation, with curl and TypeScript examples.

## The flow

The authorization server is `https://auth.dodopayments.com`. Your app uses the authorization code flow with PKCE (`S256`) and the client secret.

```mermaid theme={null}
sequenceDiagram
    participant M as Merchant
    participant A as Your app
    participant D as Dodo Payments
    A->>M: Redirect to /oauth2/authorize with code_challenge and resource
    M->>D: Sign in and approve on the consent screen
    D->>A: Redirect to redirect_uri with code and state
    A->>D: POST /oauth2/token with code and code_verifier
    D-->>A: access_token and refresh_token
    A->>D: API call with the access token
```

The merchant must be an owner or an admin of the business. The merchant approves all scopes or none.

## Choose the mode

Set `resource` in each authorization request to the API host of the mode:

| Mode | `resource` |
| - | - |
| Test | `https://test.dodopayments.com` |
| Live | `https://live.dodopayments.com` |

A request with no `resource` fails with `invalid_target`. The API calls for an install go to the same host. The examples on this page use the test host.

## Step 1: Send the merchant to the authorize URL

Create a random `code_verifier`. Compute `code_challenge` as the Base64URL SHA-256 hash of the verifier. Store the verifier and a random `state` for the callback.

```text Authorize URL theme={null}
https://auth.dodopayments.com/oauth2/authorize
  ?response_type=code
  &client_id=app_xxx
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
  &scope=payments%3Aread%20customers%3Aread
  &resource=https%3A%2F%2Ftest.dodopayments.com
  &code_challenge=CODE_CHALLENGE
  &code_challenge_method=S256
  &state=RANDOM_STATE
```

```typescript TypeScript theme={null}
import { createHash, randomBytes } from "node:crypto";

const b64url = (buf: Buffer) => buf.toString("base64url");

export function buildAuthorizeUrl(mode: "test" | "live") {
  const codeVerifier = b64url(randomBytes(32));
  const codeChallenge = b64url(createHash("sha256").update(codeVerifier).digest());
  const state = b64url(randomBytes(16));

  const url = new URL("https://auth.dodopayments.com/oauth2/authorize");
  url.search = new URLSearchParams({
    response_type: "code",
    client_id: process.env.DODO_APP_CLIENT_ID!,
    redirect_uri: "https://app.example.com/callback",
    scope: "payments:read customers:read",
    resource: `https://${mode}.dodopayments.com`,
    code_challenge: codeChallenge,
    code_challenge_method: "S256",
    state,
  }).toString();

  return { url: url.toString(), codeVerifier, state };
}
```

The `client_id` is the app ID. The merchant sees the consent screen with your reasons for each scope.

![The consent screen of an app that is being installed, with the app name, the business, the mode, and the permissions with the reasons of the developer](https://mintcdn.com/dodopayments/clOL2gp3BmPo5w6L/images/app-marketplace/developer/09-consent-screen-developer-view.png?fit=max\&auto=format\&n=clOL2gp3BmPo5w6L\&q=85\&s=2779b7d7ebf54ed7be586d93ebd7ef44)

## Step 2: Receive the code

Dodo Payments redirects to your `redirect_uri` with `code` and `state`. Check that `state` matches the stored value. The redirect URI must be one of the approved redirect URIs, with an exact match.

## Step 3: Exchange the code for tokens

Send the client ID and the client secret with HTTP Basic authentication.

```bash cURL theme={null}
curl https://auth.dodopayments.com/oauth2/token \
  -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=authorization_code \
  -d code="$CODE" \
  -d redirect_uri="https://app.example.com/callback" \
  -d code_verifier="$CODE_VERIFIER"
```

```typescript TypeScript theme={null}
export async function exchangeCode(code: string, codeVerifier: string) {
  const basic = Buffer.from(
    `${process.env.DODO_APP_CLIENT_ID}:${process.env.DODO_APP_CLIENT_SECRET}`,
  ).toString("base64");

  const res = await fetch("https://auth.dodopayments.com/oauth2/token", {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code,
      redirect_uri: "https://app.example.com/callback",
      code_verifier: codeVerifier,
    }),
  });
  if (!res.ok) throw new Error(`Token request failed: ${res.status}`);
  return res.json() as Promise<{
    access_token: string;
    refresh_token: string;
    expires_in: number;
    scope: string;
  }>;
}
```

The response holds `access_token`, `refresh_token`, `expires_in`, and `scope`. Store the tokens with the installation of the merchant. The `installation_id` arrives in the `app.installed` webhook.

> [!NOTE]
>
> Activation is asynchronous. Your app can receive the code and call the API before the installation is `active` and before the `app.installed` webhook arrives. Do not wait for the webhook to exchange the code.

## Step 4: Call the API

```bash cURL theme={null}
curl https://test.dodopayments.com/payments \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

```typescript TypeScript theme={null}
const res = await fetch("https://test.dodopayments.com/payments", {
  headers: { Authorization: `Bearer ${accessToken}` },
});
if (res.status === 401) {
  // Refresh the token, then retry one time.
}
```

A token is for one installation. It works only for that business, in that mode, and only for the granted scopes. A call that needs a scope that the install does not have returns `403`. For example, a token with the scope `payments:read` gets `403` on a route of a different scope.

## Scopes for each installation

The scopes are set for each installation. If you add a scope to the app later, existing installs keep their old scopes. The merchant sees a banner and must approve the new scopes. Calls that need a new scope fail until the merchant approves. If you remove a scope from a live app, the scopes of the current installs are reduced too.

Dodo Payments adds the `app_settings:read` scope to the tokens of your app automatically. See [Read settings](https://docs.dodopayments.com/developer-resources/apps/app-settings/read-settings.md).

## Refresh tokens

| Token | Lifetime |
| - | - |
| Access token | 1 hour |
| Refresh token | 365 days, rolling. Each refresh gives a new refresh token. |

```bash cURL theme={null}
curl https://auth.dodopayments.com/oauth2/token \
  -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=refresh_token \
  -d refresh_token="$REFRESH_TOKEN" \
  -d resource="https://test.dodopayments.com"
```

```typescript TypeScript theme={null}
export async function refresh(refreshToken: string, mode: "test" | "live") {
  const basic = Buffer.from(
    `${process.env.DODO_APP_CLIENT_ID}:${process.env.DODO_APP_CLIENT_SECRET}`,
  ).toString("base64");

  const res = await fetch("https://auth.dodopayments.com/oauth2/token", {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: refreshToken,
      resource: `https://${mode}.dodopayments.com`,
    }),
  });
  if (!res.ok) throw new Error(`Refresh failed: ${res.status}`);
  return res.json();
}
```

Store the new refresh token and discard the old one. If you use an old refresh token a second time, Dodo Payments revokes the grant, and the install gets `app.uninstalled`.

> [!WARNING]
>
> Refresh one token at a time for each installation. Two parallel refreshes with the same refresh token can revoke the grant.

## Revocation and uninstall

* A merchant owner or admin can uninstall your app at any time. The install stays active if the person who installed it leaves the business.
* Revocation takes effect within 2 minutes. During that time a revoked token can still work. After that time the API returns `401`.
* You can revoke a token at `https://auth.dodopayments.com/oauth2/revoke`.
* If you rotate the client secret, the old secret stops working at once.
* If a reviewer suspends your app, introspection and the token endpoint refuse its tokens, and its webhooks stop.

## Rate limits

Each pair of app and business is limited to 20 requests each second and 120 requests each minute. A call over the limit returns `429`. Retry with a back-off.

## Common errors

| Error | Cause |
| - | - |
| `invalid_target` | The authorization request has no `resource`, or the value is not a Dodo Payments API host. |
| `invalid_grant` | The code or the refresh token was used, expired, or revoked. |
| `401` from the API | The token expired or was revoked. Refresh it. |
| `403` from the API | The install does not have the scope that the call needs. |
| `429` from the API | The rate limit. Retry with a back-off. |


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