Claude Platform Docs
AdminClaude Platform OAuth

Linked billing

Let your customers link their Claude Platform organization to your app with OAuth, and bill Claude usage to the customer’s organization.

Linked billing lets your customers pay for the Claude usage in your app through their own Claude organization. A customer links their Claude organization to your app once. The API calls this link a connection. After the customer has linked, you choose on each Claude API request whether the customer or you pays. The customer can unlink your app at any time. If a request you mark for the customer can’t be billed to them, the Claude API refuses it rather than billing you.

This guide is for developers whose app users are primarily Claude Platform customers. You add a “Link your Claude organization” button to your app. Your user clicks it, signs in to Claude, and approves your app to bill their Claude organization for the Claude API requests the customer directs you to make. Your app then adds a billing_policy field to the requests that the customer pays for.

Eligible customers and endpoints

Eligible customers: A customer can be billed this way only if their Claude Platform organization pays Anthropic directly for its API usage. Prepaid credits and invoiced billing both count. Organizations billed through a cloud marketplace (AWS, Google Cloud, or Azure) can’t be billed through this integration. The same is true of organizations that have only a Claude subscription plan. Requests for them are refused with 403 user_profile_not_billable.

Requests run in your organization, so your rate limits, model access, service tier, data retention, and encryption keys apply. Your customer’s own data arrangements don’t apply to these requests, including zero data retention (ZDR), a business associate agreement (BAA), and customer-managed encryption keys (CMEK). Don’t link customers that need HIPAA, FERPA, or CMEK coverage for this usage.

Supported endpoints: billing_policy is supported on:

  • /v1/messages
    • Known limitation: a request that bills your customer (bill_to: "user_profile") can’t use billable code execution features (the API returns a 400), so send those requests with bill_to: "self" or without billing_policy.
  • /v1/chat/completions
  • /v1/messages/count_tokens accepts the billing_policy field and ignores it, so you can count tokens on the exact body you’re about to send.

Message Batches (/v1/messages/batches) doesn’t currently support billing your customer. Send the requests in a batch with bill_to: "self" or without billing_policy, and they’re billed to you as usual. A request in a batch that sets bill_to: "user_profile" is refused: its result is errored with an invalid_request_error, neither you nor your customer is billed for it, and the batch’s other requests run as usual.

To ask for support on another endpoint, contact your Anthropic account team.

Which credits can pay

Not all credit can pay for a request that a platform bills to a customer. What can pay depends on the organization that’s billed: the customer if you bill a customer, or your organization if a platform bills you.

Credit bought in the Claude Console for that organization can pay for these requests. If that organization has invoiced billing, it’s invoiced for these requests.

Some promotional credits from Anthropic can’t pay for these requests. These include the monthly API credits that come with Claude Max, Ultra, and Team plans. Credits from Anthropic’s partner, VC, and startup programs aren’t eligible to pay for these requests.

When nothing on that organization’s account can pay for a request, the Claude API can refuse it with a 402. The response doesn’t say whether a lack of credit or a spend limit caused the refusal. See Expected errors.

Setup process

You do these three steps once. They register your app with Anthropic. After them, Which user profile to link explains a rule that you need before you create user profiles.

Step 1: Create the app

Create the OAuth app in the Claude Console. It is the registration that identifies your product to Anthropic: it ties your redirect URI to a client ID, and its name is what your user sees on the approval page.

A member of your organization with the Admin role opens the OAuth apps page in the Console and clicks Create. Enter your app’s name and redirect URI (the address in your app that the browser returns to after the approval). Under What the app can do, select Bill and link to organizations.

The new app’s page opens. Copy the client ID that the Console shows for the app. Your app sends it in Step 5 when it requests an approval page, in Step 6 when it redirects the browser, and in Step 8 when it exchanges the code, so that Anthropic knows which app is asking. The client ID is public. On the Appearance tab, set your app’s name, homepage, and logo URL.

On the Settings tab, Who can link reads Test users only for a new app, which starts in testing. After you publish your app and it is live, the setting reads Any Claude user.

Step 2: Set up client authentication

Set up how your back end proves to auth.claude.com that its requests come from your app. This takes the place of a client secret: Anthropic does not issue client secrets for OAuth apps.

On the app’s Client authentication tab, select your Identity provider (the issuer that signs your back end’s tokens). To add one, click Register a new issuer. Then set a Subject pattern, or claim conditions under Advanced match options, that those tokens must match. After you save, the tab shows the expected audience. Your client assertion’s aud claim must be exactly that value.

Step 3: Set up your back end’s identity

Your back end needs an identity of its own to call the Claude API. Create two things:

  • A service account. This is a non-human account in your Claude organization. Your back end authenticates as this account when it calls the Claude API.
  • A second federation rule. Like the rule for the app’s client authentication in Step 2, it lets your back end authenticate with tokens from your own identity provider.

To set them up in the Claude Console, follow the Workload Identity Federation guide.

Then, on the app’s Client authentication tab, select that service account as the app’s operator service account. Only that service account is authorized to send inference requests and attribute billing to the linked user profiles. A service account can be the operator of only one OAuth app.

By default, any authenticated request as that service account can bill every linked customer, by setting the user profile header and bill_to in the Messages API. To obtain authentication tokens constrained only to a specific connection, see OAuth tokens for each connection. Before you link customers, set a workspace for your app. Step 8 returns such a token for each customer, and requires the app to specify a default workspace in your organization against which inference runs. If you want refresh tokens for each connection, also turn on Offline access for your app. Then request offline_access in the authorization flow, in Step 5, before you link customers.

A user profile is a record in your own Claude organization that represents one of your customers. Each request that bills the customer includes the profile’s ID, so that Anthropic knows which customer to bill. For the rest of what profiles do, see User profiles for end-customer attribution.

Settle which user profile stands for each customer before you link your first customer. Within one app, connections are one to one:

  • A customer’s Claude organization can be linked to only one of your user profiles.
  • A user profile can be linked to only one Claude organization.

The customer’s Claude organization is the one that the user selects when they approve your app. To learn how a customer’s teams use Claude organizations, ask the customer. To apply the one-to-one rule to your customer records:

  • Several teams of one customer share a Claude organization: Use one user profile for all of the teams.
  • Each team has its own Claude organization: Create a user profile for each organization.

Any active user profile in your organization can be linked, as long as the one-to-one rule holds. Linking doesn’t change the profile, its ID, or its usage history. If you link a second user profile to a Claude organization that is already linked, the approval is refused: see user_profile_already_linked.

A user profile for each person

You might already have a user profile for each person who uses your product. Several of those people might work for the same customer. In that case, Anthropic recommends that you create one more user profile for the customer’s Claude organization and link that profile.

The profile ID to send depends on who pays for the request:

  • Requests that you bill to the customer: Send the ID of the customer’s profile. To also identify the person on a /v1/messages request, set metadata.user_idPreview with links to the API reference available — press Tab until focus enters the card, Escape to return. to an identifier for that person. This identifier is optional and helps Anthropic detect misuse by one person. Use an opaque value, not a name, an email address, or a phone number.
  • Requests that you pay for: You can keep sending the person’s own profile ID.

Link each customer

You do Steps 4 to 8 for each customer that links their organization. The following Python code snippets require the Anthropic SDK and some standard imports; see Code snippet initialization. The examples in other languages and the CLI take their credentials from the environment. Ensure ANTHROPIC_API_KEY is not set, because your app needs to authenticate with Workload Identity Federation.

Add a “Link your Claude organization” button where your customers manage billing or integrations in your product (for the button’s HTML, colors, and logo, see Branding samples). Tell them that to link, they must have the Admin or Billing role in their Claude organization.

To go through the steps yourself first, see Test as a customer.

Browser
Your back end
auth.claude.com
Click “Link your Claude organization”
5
Pushed authorization request with the user profile ID and a client assertion
request_uri
6
Redirect to the approval page (the authorization endpoint)
7
The user signs in to Claude, picks the organization, and approves
Redirect to your redirect URI with a one-time code and the state
Deliver the code and state
Check that state matches
8
Token request with the code, the PKCE code verifier, and a client assertion
connection_id
Store the connection ID on the customer’s record

Step 4: Create a user profile for the customer

Create one user profile for each customer’s Claude organization, and store the profile’s ID against the customer’s record in your product.

If you already have a user profile for this customer’s Claude organization, skip this step and use that profile’s ID. To decide which profile that is, see Which user profile to link.

def create_user_profile(name: str, customer_id: str) -> str:
    profile = client.user_profiles.create(
        name=name,
        external_user_details={"reference_id": customer_id},
    )
    return profile.id  # "uprof_..."


user_profile_id = create_user_profile("Example Customer Inc.", "your-customer-id-123")

If your organization resells API access, also send "access_type": "passthrough" when you create this profile. These samples leave access_type out, which creates an application profile. For the two types, see Decide who gets a profile.

The response contains the profile’s id, for example uprof_01HV9Z.

Step 5: Create a pushed authorization request URL

Create a pushed authorization request that references the customer’s user profile from Step 4. The response gives you a request_uri. In the next step, you use it to redirect your user to the approval page.

Before it sends the request, your back end creates two random values and stores them against the browser session and the customer record. It uses both again in Step 8:

  • A state value, which lets you check that the browser that comes back to your app is the one that started this request.
  • A PKCE code verifier, a secret that only your back end knows. The request carries a hash of it (the code challenge), and Step 8 sends the verifier itself, so that only your back end can use the code that comes back.
def push_authorization_request(user_profile_id: str) -> dict:
    state = secrets.token_urlsafe(32)
    code_verifier = secrets.token_urlsafe(64)
    code_challenge = create_s256_code_challenge(code_verifier)

    response = httpx.post(
        f"{AUTH}/v1/oauth/par",
        json={
            "response_type": "code",
            "client_id": CLIENT_ID,
            "redirect_uri": REDIRECT_URI,
            "scope": "billing:attribution",
            "connection_type": "organization_shared",
            "connection_auth_target": "platform",
            "user_profile_id": user_profile_id,
            "state": state,
            "code_challenge": code_challenge,
            "code_challenge_method": "S256",
            "client_assertion_type": JWT_BEARER,
            "client_assertion": client_assertion(),
        },
    )
    response.raise_for_status()  # on an error, do not redirect the browser

    return {
        "state": state,
        "code_verifier": code_verifier,
        "request_uri": response.json()["request_uri"],  # valid for 600 seconds
        "user_profile_id": user_profile_id,
    }


par = push_authorization_request(user_profile_id)

auth.claude.com responds with HTTP 201, a request_uri, and expires_in of 600 seconds. The request_uri identifies the approval page for this request. The scope must be exactly billing:attribution or billing:attribution offline_access. See Scopes for a billing connection for details. The examples send billing:attribution. If your app doesn’t have this scope, add it under Billing on the app’s Permissions tab.

connection_auth_target must be platform: inference requests run in your own organization and authenticate as the operator service account, but they can bill the customer.

user_profile_id must be the ID of an active user profile in your organization. If the pushed authorization request fails, auth.claude.com returns an OAuth error response to your back end. Do not redirect the browser in that case.

Step 6: Send your user to the Claude approval page

First, show your user which account in your product they are linking, and tell them to check the Claude account that the approval page shows. The page shows which Claude account is signed in and lets the user switch to another. The approval page offers only the organizations of the Claude account that is signed in to the browser, so the wrong account can link the wrong organization. The organization that the user links pays.

Then, redirect your user to the authorization endpoint, which shows an approval page. Include only your client_id and the request_uri from Step 5.

def authorize_url(par: dict) -> str:
    query = urlencode({"client_id": CLIENT_ID, "request_uri": par["request_uri"]})
    return f"{AUTH}/oauth/authorize?{query}"


redirect_to = authorize_url(par)  # answer the click with a 302 to this URL

Step 7: The user approves

Your app does nothing in this step. The user goes through these steps on auth.claude.com:

  1. The user signs in to Claude, unless the browser is already signed in.
  2. The approval page shows the following screens, each with your app’s name. For what the user does on each screen, see Linking.
    1. Select an organization, only if the user has a choice of organization.
    2. How billing works.
    3. Set a monthly spend limit.
    4. A last screen with a Link and authorize button.
  3. When the user clicks Link and authorize, auth.claude.com sends the browser back to your app. The approval page shows no confirmation screen.

If the user cancels or can’t approve, no connection is made: see If linking doesn’t complete.

Step 8: Handle the callback and save the connection

After the approval, auth.claude.com sends the browser back to your redirect URI with a one-time code and your state value. This request to your redirect URI is called the callback. Your back end exchanges the code for a connection ID and stores it on the customer’s record. This completes the connection. The callback can carry an error parameter and no code. No connection was made then: see If linking doesn’t complete.

Check that the state matches the value you stored in Step 5, then exchange the code immediately from your back end, together with the PKCE code verifier. The code is single-use and expires after 5 minutes.

def handle_callback(par: dict, params: dict) -> str:
    if not secrets.compare_digest(
        params.get("state", "").encode(), par["state"].encode()
    ):
        raise ValueError("state does not match")
    if "error" in params:  # for example access_denied
        raise PermissionError(params["error"])
    code = params["code"]  # single-use, expires after 5 minutes
    response = httpx.post(
        f"{AUTH}/v1/oauth/token",
        json={
            "grant_type": "authorization_code",
            "code": code,
            "code_verifier": par["code_verifier"],
            "redirect_uri": REDIRECT_URI,
            "client_id": CLIENT_ID,
            "client_assertion_type": JWT_BEARER,
            "client_assertion": client_assertion(),
        },
        timeout=10,  # a response that times out loses the tokens in it
    )
    response.raise_for_status()
    tokens = response.json()
    # To use the connection's tokens, store tokens["access_token"], its expiry
    # time (from tokens["expires_in"]), and, with offline_access,
    # tokens["refresh_token"] as secrets here: the code can't be exchanged again.
    # "ocon_..."; store it on the customer record
    return tokens["connection_id"]

The response contains the connection ID and the connection’s access token, which can authenticate and bill the approving customer. If the customer approved offline_access, the response also contains a refresh token. Store connection_id and the tokens now: the exchange returns the tokens only once. Store the tokens describes the response.

The examples on this page that call the Claude API authenticate as the service account from Step 3, not with a token from this response. Call Claude with a connection’s access token says how to use the token in its place.

The response does not identify which Claude organization the user linked.

A completed connection does not guarantee that Anthropic can bill the customer. For example, the customer’s organization might not be one of the eligible customers. See Update calls to Claude and Expected errors for how the Claude API checks this. Because of that check, word your success message as “linked” rather than “billing active.”

If the exchange is refused with unauthorized_client, see The code exchange returns unauthorized_client.

Test as a customer

To check that linking works, link an organization of your own. You need these first:

  • A second Claude organization of yours to act as the customer. You can’t link your app to the organization that owns it. The approval page doesn’t offer that organization. The second organization must be one of the eligible customers.
  • A person with the Admin or Billing role in that organization to approve the link.
  • Until your app is live, that person must be on your app’s Test users list. The list is on the app’s Settings tab under Who can link. Add the person by the email address of their Claude account and click Save changes. While your app is in testing has the spend cap that applies. Removing someone from the list ends the links that they approved.

Then, run Steps 4 to 8, and have that person approve in Step 7. When the link is made, the user profile reads Linked on your User profiles page in the Console.

If linking doesn’t complete

When the user doesn’t finish the approval, or auth.claude.com refuses it, no connection is made. These entries cover the outcomes that are specific to Linked billing. For every other error, see Errors in the OAuth reference.

Your redirect URI receives error=access_denied

The request also carries your state value. Your redirect URI receives this error in cases such as these:

  1. The user clicks Cancel on any approval screen.
  2. The approval page has no organization to offer the user, and the user clicks the button that returns to your app. For example:
    • The user doesn’t have the Admin or Billing role in any Claude Platform organization.
    • The user’s only organization is the one that owns your app. See Test as a customer.
    • The user profile is already linked to another Claude organization, and the user doesn’t have the Admin or Billing role in that organization.
    • Until your app is live, the user isn’t on its Test users list.

In each case in this list, the error_description reads the user declined the request, so you can’t use it to tell them apart.

One more cause is in your app’s settings. If your app is live and Who can link shows your organization only, nobody outside your organization can link the app. Select Any Claude user and click Save changes.

Tell the user that linking didn’t complete, and don’t assume that they declined. Ask them to check which Claude account they signed in with and their role in the organization that they want to link. A request_uri can’t be used again after the user cancels or returns, so to let the user try again, start again from Step 5.

Your app receives user_profile_already_linked

The customer’s Claude organization is already linked to your app through another of your user profiles. auth.claude.com asks the user to contact you. If the user returns to your app, your redirect URI receives error=user_profile_already_linked and your state value. The token endpoint can also return this error when you exchange the code in Step 8. That happens, for example, when the organization was linked through another user profile in the meantime.

Anthropic doesn’t tell you which Claude organization a customer links, so you can’t see this in advance. The pushed authorization request in Step 5 succeeds, and auth.claude.com refuses the connection only when the user approves.

The error doesn’t name the user profile that holds the connection. The likeliest holder is another linked profile of this customer. Anthropic doesn’t show which organization a profile is linked to, so confirm with the customer before you act. If that profile holds the connection, do one of the following:

  • On the requests that you bill to this customer, send the ID of that user profile.
  • End that connection, as Unlinking a customer describes, and then run Steps 5 to 8 again with the user profile that was refused.

If none of this customer’s profiles is linked, the user might have selected an organization that belongs to another of your customers. Start again from Step 5, and have the user check which organization they select.

Your redirect URI receives nothing

Your app can’t detect these two cases:

  • The user closes the approval page.
  • The request_uri has expired or was already used. The approval page then shows an error and doesn’t send the browser back to your app.

If the user comes back to your product without a callback, start again from Step 5. A request_uri that wasn’t used expires 10 minutes after you created it.

The code exchange returns unauthorized_client

Your app is not set up for this request. For a workspace problem, the error_description names the cause. For a missing operator service account, it reads only the client is not registered for this grant. The refusal doesn’t use up the code, so you can exchange the same code again until it expires. First, check these in the Claude Console:

CheckWhereFix
The app has an operator service accountOperator service account on the app’s Client authentication tabSelect one and click Save. Step 3 says how to set one up.
The app’s workspace isn’t missing or archivedSet up your appChoose a workspace. While the app has none, the exchange is refused with unauthorized_client too.

A saved service account can take a minute or two to reach auth.claude.com, so if the exchange is refused again, wait that long and retry. If the code has expired by then, have the user approve again (Steps 5 to 8). For the causes that error_description names for a connection’s tokens, see Store the tokens and Refresh the tokens.

In any other case, contact your Anthropic account team. Do the same if the Console says that the service account no longer exists.

Publish your app

Until your app is live, only the people on its Test users list can link it, so your customers can’t. To publish the app, click Publish app on the app’s page in the Claude Console. A dialog box opens.

  • If your organization has invoiced billing, the app is live as soon as you confirm in that dialog box.
  • Otherwise, you first prove in that dialog box that you control the app’s domain, and Anthropic then reviews the app.

The domain proof: The domain is the domain of your app’s homepage. Every redirect URI must be on that domain or on a subdomain of it, except one on localhost, 127.0.0.1, or [::1]. The proof is a DNS TXT record. DNS changes can take up to 48 hours, so start before you need customers to link. If your organization has already proven a domain that covers the homepage and those redirect URIs, the dialog box skips the proof. A proven domain covers its subdomains.

You confirm on the dialog box’s last step. If that step shows a checkbox to accept the Linked Billing Terms, select it. Then, click Publish app in the dialog box.

The review: During the review, the app’s status in the Console reads In review. The app is live when Anthropic approves it. If Anthropic doesn’t approve it, the status reads Not approved, and you can’t publish the app again yourself. To ask about the decision, contact support.

Unless your organization has invoiced billing, a change to a live app’s name, logo, homepage, or redirect URIs sends the app back to review. Customers who are already linked stay linked and keep the cap that they saved. Until Anthropic approves the change, only the people on the Test users list can link the app.

Update calls to Claude

Send the anthropic-user-profile-id header on each call to /v1/messages and /v1/chat/completions for a linked customer. On a request that you bill to the customer, the header’s value is the ID of the user profile that holds that customer’s connection. Calls that set billing_policy must also send the user-profiles-billing-2026-10-01 beta header.

Each request for a linked customer is billed either to the customer or to you, and you choose which on each request. The following examples show both.

OAuth tokens for each connection describes another way to authenticate a customer’s requests: an access token that can bill only that customer. On /v1/messages and /v1/chat/completions, a request with such a token can’t be billed to you. It is billed to that customer, even without billing_policy or the anthropic-user-profile-id header, where those are optional: see the note in Call Claude with a connection’s access token. If it names another user profile or sets bill_to: "self", it is refused. Never use one for a request that you pay for.

Your customer pays

Add billing_policy with bill_to: "user_profile" to the request body, and send the billing beta header and the profile ID header.

Set bill_to: "user_profile" only on requests the customer directs you to make: the Claude usage that the customer and their users cause in your product. Don’t bill a customer for your own usage, such as testing, evaluations, or work for other customers. The Claude API can’t check this for you, so it’s your responsibility.

def message_billed_to_user(user_profile_id: str, prompt: str) -> BetaMessage:
    return client.beta.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
        betas=[BILLING_BETA],
        extra_headers={"anthropic-user-profile-id": user_profile_id},
        extra_body={
            "billing_policy": {"type": "billing_policy", "bill_to": "user_profile"}
        },
    )

If the request is refused, see Expected errors.

You pay

To pay yourself, either omit the billing_policy entirely (in which case the billing beta header is optional):

def message_billed_to_you(user_profile_id: str, prompt: str) -> Message:
    return client.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
        user_profile_id=user_profile_id,
    )

or use bill_to: "self":

def message_billed_to_self(user_profile_id: str, prompt: str) -> BetaMessage:
    return client.beta.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
        betas=[BILLING_BETA],
        extra_headers={"anthropic-user-profile-id": user_profile_id},
        extra_body={"billing_policy": {"type": "billing_policy", "bill_to": "self"}},
    )

OAuth tokens for each connection

Your back end calls the Claude API as your app’s operator service account (Step 3). By default, any authenticated request as that service account can bill every linked customer, by passing a user profile ID header and including bill_to in Messages API requests. This default is called operator-only tokenless authentication.

To handle single-tenant deployments of your product, or customer-controlled sandbox environments, you can obtain connection-bound OAuth access and refresh tokens instead of using operator-only tokenless authentication.

For each connection, the code exchange in Step 8 returns that connection’s own access token. The token authenticates as your operator service account, but it can bill only that connection’s customer. It expires within 1 hour.

To authenticate each connection separately:

  • Use offline access. Turn on Offline access for your app, and request offline_access in Step 5. Each connection then also gets a refresh token, which your back end uses to request new access tokens. Without it, the customer must approve again to give you a new access token: run Steps 5 to 8 again with the same scope.
  • Set a default workspace. Choose a workspace in your organization for requests with these tokens to run in.
  • Optionally, turn off operator-only tokenless authentication. By default, you can still bill a linked customer as your operator service account (by passing a user profile header and bill_to), even after the customer’s access token expires. After you turn off operator-only authentication, every request that bills a customer must authenticate with that customer’s access token.
  • Use billing:attribution. Only this scope gives a connection its own tokens. You can still bill a linked customer as your operator service account, as with org:billing_attribution, which is deprecated. See Scopes for a billing connection.

Set up your app

Requests with a connection’s access token run in one workspace of your organization. Every app needs one, even if you don’t use these tokens: while your app has no workspace, the code exchange in Step 8 is refused with unauthorized_client.

A member of your organization with the Admin role opens the app’s Client authentication tab in the Console. Under the operator service account, find Default workspace for platform auth mode OAuth tokens (the app’s connection_token_workspace_id setting) and click Choose workspace. Select a workspace that the operator service account (Step 3) is a member of. The workspace must not be archived.

To get refresh tokens, turn on Offline access on the app’s Permissions tab. A change to the app’s scopes takes a few minutes to reach auth.claude.com.

Scopes for a billing connection

In Step 5, send scope as billing:attribution. To also get a refresh token, send billing:attribution offline_access.

To change the scopes of a customer who is already linked, for example to add offline_access, run Steps 5 to 8 again with the customer’s existing user profile and the new scope. You don’t unlink first. The code exchange returns a new connection_id, and the new connection replaces the earlier one. See the note in Step 8.

An app can have billing:attribution and the deprecated org:billing_attribution at once. You add billing:attribution under Billing on the app’s Permissions tab. If you remove org:billing_attribution there, you can’t add it again. A connection that a customer approved with org:billing_attribution keeps billing through your operator service account until the connection ends or you turn off operator-only authentication.

Store the tokens

The code exchange returns the tokens only once, so store them in Step 8. The response contains access_token, expires_in (at most 1 hour, in seconds), and connection_id. If the customer approved offline_access, it also contains refresh_token and refresh_token_expires_in. A refresh token lasts at most 1 year, and a refresh doesn’t extend that. After that, link the customer again.

Store the tokens and their expiry times in a secret store that only the service that refreshes can read.

If the exchange is refused with unauthorized_client, error_description gives the cause, such as a missing or archived workspace. The code isn’t used up: correct the cause, and send the same code again before it expires.

Call Claude with a connection’s access token

Send the connection’s access token as a bearer token in the Authorization header, in place of your operator service account’s own credential. Don’t send an x-api-key header. In the Anthropic SDK, pass the token as auth_token, or set the ANTHROPIC_AUTH_TOKEN environment variable.

On /v1/messages and /v1/chat/completions, the request is billed to that connection’s customer. The anthropic-user-profile-id header and billing_policy are optional. You need the billing beta header only with billing_policy.

On these two endpoints, you can’t pay for a request with this token. Use the token only on these two endpoints, /v1/messages/count_tokens, and the Models endpoints. Send every other request, and every request that you pay for, as your operator service account, from your own back end. That includes a request that uses billable code execution features, which can’t bill a customer.

The Claude API refuses these requests:

  • 400 invalid_request_error, with no error code: the request named another user profile or set bill_to: "self".
  • 403 permission_error, with no error code: the request went to a Message Batches endpoint.
  • 401 authentication_error: the token expired, a refresh replaced it, or its connection ended. After a connection ends, the response can also be 403 user_profile_not_billable.

Refresh the tokens

To renew a connection’s access token, send its refresh token to the token endpoint, https://auth.claude.com/v1/oauth/token, with your app’s client authentication. Don’t send a scope parameter.

connection_locks: defaultdict[str, threading.Lock] = defaultdict(threading.Lock)


def error_body(response: httpx.Response) -> dict:
    try:
        body = response.json()
    except ValueError:
        return {}
    return body if isinstance(body, dict) else {}


def is_lost(response: httpx.Response) -> bool:
    """True for a 5xx response that can follow a refresh that took effect."""
    if response.status_code < 500:
        return False
    # A 503 in the Claude API's format with a retry-after header is a refusal
    # that doesn't use the refresh token. Every other 5xx response counts as lost.
    paused = (
        response.status_code == 503
        and error_body(response).get("type") == "error"
        and "retry-after" in response.headers
    )
    return not paused


def hold_error(connection_id: str, reason: str) -> RefreshOnHold:
    return RefreshOnHold(
        f"Connection {connection_id} is on hold. {reason} Don't send its refresh token"
        ' again: that can end the connection. See "Link a customer again" in the'
        " Linked billing guide."
    )


def refresh_connection(connection_id: str, *, force: bool = False) -> tuple[str, int]:
    """Refreshes the connection if its access token is close to its expiry.

    Returns the current access token and its expiry time in Unix seconds. Call
    this from your schedule, and pass force=True to refresh a token that isn't
    close to its expiry. Raises RefreshOnHold when the refresh token can't be sent
    again, now and on every later call, and httpx.HTTPStatusError for a refusal
    that keeps the refresh token. After RefreshOnHold for a lost refresh, pause
    your schedule. Resume with one connection, and resume the others only after
    that refresh succeeds or gets a 4xx.
    """
    # This lock works inside one process. If the service has replicas, use a lock
    # that all of them share.
    with connection_locks[connection_id]:
        tokens = load_tokens(connection_id)
        if tokens.on_hold:
            raise hold_error(
                connection_id, "An earlier refresh might have used its refresh token."
            )
        if not force and tokens.expires_at - time.time() > REFRESH_MARGIN_SECONDS:
            return tokens.access_token, tokens.expires_at  # not close to expiry
        request = {
            "grant_type": "refresh_token",
            "refresh_token": tokens.refresh_token,
            "client_id": CLIENT_ID,
            "client_assertion_type": JWT_BEARER,
            "client_assertion": client_assertion(),
        }
        url = f"{AUTH}/v1/oauth/token"
        # Put the connection on hold before the refresh token leaves this process.
        # If the process stops before the new tokens are saved, the hold stays.
        save_tokens(connection_id, replace(tokens, on_hold=True))
        issued_at = int(time.time())
        started = time.monotonic()
        # httpx doesn't retry by itself. Don't add retries: a late retry ends the
        # connection.
        try:
            response = httpx.post(url, json=request, timeout=REQUEST_TIMEOUT)
            lost = is_lost(response)
        except (httpx.ConnectError, httpx.ConnectTimeout):
            # No connection was made, so the refresh token never left this process.
            save_tokens(connection_id, tokens)
            raise
        except httpx.TransportError:
            lost = True
        if lost:
            # The first request might have used the refresh token. A second request
            # is safe only inside the limit above, so send one at once or not at
            # all.
            if time.monotonic() - started > SECOND_REQUEST_DEADLINE_SECONDS:
                raise hold_error(connection_id, "A refresh got no usable answer.")
            try:
                response = httpx.post(url, json=request, timeout=REQUEST_TIMEOUT)
            except httpx.TransportError:
                raise hold_error(
                    connection_id, "Two refreshes got no answer."
                ) from None
            if response.status_code != 200:
                # After any answer but new tokens you can't tell whether the
                # first request took effect, and a later request isn't safe.
                raise hold_error(connection_id, "The second refresh failed.")
        if error_body(response).get("error") == "invalid_grant":
            # Expired, already used, or the connection ended. Sending it again
            # can end the connection.
            raise hold_error(connection_id, "The refresh returned invalid_grant.")
        if response.status_code != 200:
            # A refusal that keeps the refresh token, so take the hold off.
            save_tokens(connection_id, tokens)
            response.raise_for_status()
        body = response.json()
        tokens = ConnectionTokens(
            refresh_token=body["refresh_token"],
            access_token=body["access_token"],
            expires_at=issued_at + body["expires_in"],
            refresh_expires_at=issued_at + body["refresh_token_expires_in"],
        )
        # If the write fails, try the write again. Don't refresh again.
        for attempt in range(5):
            try:
                save_tokens(connection_id, tokens)
                return tokens.access_token, tokens.expires_at
            except OSError:  # your secret store's error type
                if attempt < 4:
                    time.sleep(2**attempt)
        # The new tokens exist only in this process, and the stored refresh token
        # is used up. The stored record is still on hold. The error carries the new
        # tokens, so that the caller can store them when the secret store is back.
        error = hold_error(
            connection_id,
            "The refresh succeeded, but the new tokens could not be saved.",
        )
        error.new_tokens = tokens
        raise error

The response contains a new access_token and a new refresh_token. The refresh token that you sent is replaced: don’t send it again, except as the list of failures that follows says. The earlier access token stops working within a few minutes. OAuth token snippet initialization defines the functions that the example calls.

  • Store the new refresh token before you use the new access token.
  • Refresh each connection’s tokens from one service, one refresh at a time. If the service has replicas, use a lock that all of them share. A used refresh token that arrives again more than 30 seconds after its first use ends the connection. Every token is revoked, the customer displays as Unlinked, and no credential can bill them until they link again.
  • Turn off automatic retries for the refresh request, in your HTTP client and in any proxy.

If the first request with a refresh token fails:

  • The request couldn’t connect: the refresh token wasn’t sent. Try again later.
  • A dropped connection, or any 5xx response other than the 503 in this list: you can’t tell whether the request took effect, so send the same refresh token one more time.
    1. Send it at once, and only if less than 30 seconds have passed since you sent the first request.
    2. If it returns new tokens, store them and use only them. If the first request did take effect, its tokens, which never reached you, are revoked.
    3. If it returns anything else or gets no answer, or if the 30 seconds have passed, don’t send that refresh token again. Stop refreshing that connection, and link the customer again.
  • A timeout: the request might still be running. Don’t send that refresh token again. Stop refreshing that connection, and link the customer again.
  • 429, or 503 with a retry-after header and "type": "error" at the top level of its body: nothing is revoked. Wait at least as long as the header says, and send the same refresh token again.
  • unauthorized_client or invalid_client: nothing is revoked. error_description gives the cause, such as a missing workspace, offline_access no longer registered for your app, or a failed client assertion. Correct it, and send the same refresh token again.
  • invalid_scope: the request sent a scope parameter, or billing:attribution is no longer registered for your app. Nothing is revoked. Correct the cause, and send the same refresh token again.
  • invalid_grant: the refresh token expired or was already used, the connection ended, or the customer’s organization is suspended. Stop refreshing that connection, and follow Link a customer again, which starts with a check for a suspension.

If a dropped connection, a 5xx response, or a timeout has made you stop refreshing a connection, also pause the refreshes of your other connections. When you resume, refresh one connection first, and resume the others only after that refresh succeeds or gets a 4xx response.

Run an agent in a sandbox

Give a sandbox only the access token, never the refresh token. Your back end refreshes, and it sends each new access token to the sandbox. It decides which customer a sandbox serves from the sandbox’s own identity, such as its pod identity, and never from a value that the sandbox sends. It sends a sandbox only that customer’s token. The sandbox must not be able to get a JWT that matches one of your federation rules or your app’s client authentication. Give it no mounted identity token and no access to a cloud metadata server.

Claude Code, the Claude Agent SDK, and the Anthropic SDK can read the token from a credentials file in a configuration profile (see Profile configuration file). In the sandbox, create a configuration directory with this profile. Don’t add a client_id to it: with one, the SDK tries to refresh the token itself.

configs/customer.json
{
  "version": "1.0",
  "authentication": {
    "type": "user_oauth"
  }
}

Write the access token as credentials/customer.json in the same directory, before the agent starts and after each refresh. expires_at is the expiry time in Unix seconds. Write a new file with mode 0600, and rename it over the old one:

credentials/customer.json
{
  "type": "oauth_token",
  "access_token": "sk-ant-oat01-...",
  "expires_at": 1793635200
}

Set ANTHROPIC_CONFIG_DIR to the configuration directory and ANTHROPIC_PROFILE to customer. Unset every other credential in the sandbox, such as ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, CLAUDE_CODE_OAUTH_TOKEN, and Claude Code’s apiKeyHelper setting, because each can take precedence over the profile. The agent reads the file again in the last 2 minutes before expires_at, and after a 401 response.

def write_credentials_file(
    config_dir: Path, profile: str, token: str, expires_at: int
) -> None:
    credentials_dir = config_dir / "credentials"
    credentials_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    body = {"type": "oauth_token", "access_token": token, "expires_at": expires_at}
    # Rename a finished file into place, so that the agent never reads half a file.
    # mkstemp sets mode 0600 with the current user as owner, so run this as the
    # agent's user.
    handle, temporary_path = tempfile.mkstemp(dir=credentials_dir)
    with os.fdopen(handle, "w") as temporary_file:
        json.dump(body, temporary_file)
    os.replace(temporary_path, credentials_dir / f"{profile}.json")

Link a customer again

Link a customer again in these cases:

  • A refresh returned invalid_grant.
  • You lost a refresh token, or one leaked.
  • You lost the response in Step 8 for billing:attribution offline_access, or Step 8 returned invalid_grant for such a connection.
  • A refresh token is close to its expiry.

Follow these steps:

  1. On your User profiles page, check whether the customer displays as Linked. After invalid_grant, first ask your Anthropic account team whether the customer’s organization is suspended: after a suspension ends, the refresh token that you hold works again. If every connection returns invalid_grant at the same time, look for a cause on your side, such as an archived workspace, before you unlink anyone.
  2. If the customer displays as Linked, unlink them, as Unlinking a customer describes. Unlinking revokes the connection’s tokens. Do it when an administrator of the customer’s organization is ready to approve, because billing through the connection stops until they do.
  3. Run Steps 5 to 8 again with the customer’s existing user profile. Store the new connection ID and the new tokens in place of the earlier ones.

Turn off operator-only authentication

To stop requests that authenticate only as your operator service account from billing customers, turn on Disable operator-only tokenless authentication (the app’s disable_operator_only_auth setting). It is on the app’s Client authentication tab, under the operator service account. Your app must have the billing:attribution and offline_access scopes and a workspace for its OAuth tokens. Before you turn it on, make sure that every linked customer has approved billing:attribution offline_access and that your requests with their access tokens work. While it is on, only the access token of a billing:attribution connection can bill that connection’s customer. A request that authenticates as the service account alone and sets bill_to: "user_profile" is refused with 403 user_profile_not_billable. The customer still displays as Linked, so watch for this error in your logs. The service account can still manage user profiles and send the requests that you pay for. You can turn the setting off again.

OAuth token snippet initialization

The examples in this section share the following setup. It defines:

  • the imports, which include the httpx package
  • your app’s client ID and the client assertion type
  • ConnectionTokens, which holds a connection’s tokens, their expiry times, and its on_hold mark
  • RefreshOnHold, the error that refresh_connection() raises when a refresh token must not be sent again: it might already have been used, or the token endpoint answered invalid_grant. refresh_connection() raises it on every later call too, until you clear on_hold in the stored tokens, for example after a suspension ends. When a refresh succeeded and only your secret store refused the write, its new_tokens holds the tokens to store.
  • client_assertion(), which reads your identity provider’s JWT from the file that ANTHROPIC_IDENTITY_TOKEN_FILE names. The JWT’s aud claim must be the audience in your app’s client authentication settings.
  • load_tokens() and save_tokens(), which you write for your own secret store
import json
import os
import tempfile
import threading
import time
from collections import defaultdict
from dataclasses import dataclass, field, replace
from pathlib import Path

import httpx

AUTH = "https://auth.claude.com"
# copy from platform.claude.com after you register your OAuth app.
CLIENT_ID = "YOUR_CLIENT_ID"
JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
REFRESH_MARGIN_SECONDS = 600
# A refresh that times out here loses its new tokens, so allow 10 seconds for the
# answer. A connection that can't be made fails within 2.
REQUEST_TIMEOUT = httpx.Timeout(10, connect=2)
# A second request must start this soon after the first, or not at all. The
# page gives 30 seconds, but keep this under REQUEST_TIMEOUT's read timeout: a
# request that timed out must not be sent again.
SECOND_REQUEST_DEADLINE_SECONDS = 4


@dataclass
class ConnectionTokens:
    refresh_token: str = field(repr=False)
    access_token: str = field(repr=False)
    expires_at: int  # the access token's expiry time, in Unix seconds
    refresh_expires_at: int  # the refresh token's expiry time, in Unix seconds
    # True: the refresh token might have been used. Don't send it again.
    on_hold: bool = False


class RefreshOnHold(Exception):
    """The refresh token might have been used, so a person decides what to do next.

    Don't catch this to try again. If new_tokens is set, the refresh succeeded and
    only the write failed: store those tokens.
    """

    new_tokens: ConnectionTokens | None = None


def client_assertion() -> str:
    """Reads your identity provider's JWT on every call, because its file rotates."""
    return Path(os.environ["ANTHROPIC_IDENTITY_TOKEN_FILE"]).read_text().strip()


def load_tokens(connection_id: str) -> ConnectionTokens:
    """Reads the connection's newest tokens from your secret store."""
    raise NotImplementedError("Read the tokens from your secret store.")


def save_tokens(connection_id: str, tokens: ConnectionTokens) -> None:
    """Writes the connection's newest tokens to your secret store."""
    raise NotImplementedError("Write the tokens to your secret store.")

Managing your connections

Viewing customers in Console

Besides the OAuth apps page, you can view all your user profiles on the User profiles page in the Console. On that list and on each user profile’s detail page, Your spend is your own cost for that user profile’s requests. It is the cost before Anthropic applies any credits. These pages call a connection a link: a user profile with an active connection reads Linked, and one whose connection has ended reads Unlinked.

Click a user profile for a more detailed view of its usage over the last 7, 28, or 90 days.

Monitoring each customer’s usage

The Claude Console and the Usage and Cost Analytics API both report usage for each user profile. Both count the requests that you pay for and the requests that your customer pays for. Neither shows what the customer paid or the customer’s rates.

In the Console, the User profiles page lists Requests, Tokens, and Your spend for each user profile over the last 28 days. A request that your customer pays for adds to the profile’s Requests and Tokens and adds nothing to Your spend.

Call the API with an Admin API credential, such as an OAuth access token with the org:admin scope or an Admin API key. Don’t use your operator service account (Step 3). Its federation rule grants workspace:developer by default, not org:admin. The org:admin scope covers the whole Admin API, so don’t add it to the operator service account.

To report by user profile through the API, call its usage endpoint or its cost endpoint. To get one row for each user profile, group by user_profile_id alone and leave out time_bucket_width. Only a user profile that has usage in the time range that you request gets a row. One more row has a null user_profile_id. It holds usage that named no profile and usage that is metered outside requests, such as code execution container time.

On the cost endpoint, a request that your customer pays for adds 0 to amount and its list price to list_amount. The amount field is the same measure as Your spend. The API has no field, filter, or group_by[] value for who paid. A row with an amount of 0 and a list_amount above 0 usually means that the customer paid for every request in that row.

Don’t use these figures to stop a customer’s usage at an amount that you choose. Neither the Console nor the API reports in real time. The Console’s figures refresh about once an hour, and a request can take a few hours to appear. For the API’s delay, see Data freshness. Spend caps says what the customer’s own limits do.

Unlinking a customer

To unlink a customer in the Console, use the list on the User profiles page or the Unlink button at the top right of a user profile’s detail page.

To unlink a customer from your back end, send the connection ID that you stored in Step 8 to the revocation endpoint, with the same client authentication as the code exchange. To name the connection by its user profile instead, send user_profile_id in place of connection_id.

def revoke_connection(connection_id: str) -> list[str]:
    response = httpx.post(
        f"{AUTH}/v1/oauth/revoke",
        json={
            "connection_id": connection_id,
            "client_id": CLIENT_ID,
            "client_assertion_type": JWT_BEARER,
            "client_assertion": client_assertion(),
        },
    )
    response.raise_for_status()
    # IDs of the connections this request ended. The list is empty if the
    # connection had already ended or the ID is unknown.
    return response.json()["revoked_connection_ids"]

auth.claude.com responds with HTTP 200 and revoked_connection_ids, the IDs of the connections that this request ended. The list is empty if the connection has already ended, so you can safely repeat a request that sends connection_id. It is also empty if the ID is unknown, so an empty list doesn’t prove that the connection existed. See Revocation for the other parameters and Errors from the revocation endpoint.

After the connection ends, the user profile displays as Unlinked, and a request that sets bill_to: "user_profile" for this customer receives user_profile_not_billable. You can still serve the customer at your own cost with bill_to: "self". After linking says what your customer sees, and Emails about linking and unlinking says which way of unlinking sends them an email.

Linking a customer to a different Claude organization

To link a customer’s user profile to a different Claude organization, unlink the customer and then link them again.

After you unlink, requests that you bill to this customer are refused. That lasts until a user approves for the other organization and you exchange the code in Step 8. Follow these steps when that user is ready to approve:

  1. Skip this step if your customer has already unlinked your app on their Linked platforms page. Otherwise, unlink the customer, as Unlinking a customer describes. The user profile then displays as Unlinked on your User profiles page.
  2. Run Steps 5 to 8 again with the same user profile. For Step 7, the user needs an account that has the Admin or Billing role in the other organization. Have the user approve for that organization.
  3. Store the new connection ID in place of the earlier one. If you use the connection’s tokens, do the same with the new tokens.

Until the customer is unlinked, the approval page lets a user approve only for the organization that is already linked.

A spend cap belongs to one customer organization and your app, so the first organization’s cap doesn’t carry over. Spend caps has the rules.

Expected errors

When a request sets bill_to: "user_profile", Anthropic either bills your customer or refuses the request. It never silently bills you instead. On /v1/messages the code in the following list is in error.details.error_code. On /v1/chat/completions you get the same HTTP status and message in OpenAI format, without the code:

  • 403 permission_error, user_profile_not_billable: Anthropic can’t bill this customer for this request, and the response doesn’t say why. Not retryable, except in the first 10 seconds after a new connection. Before you ask the customer to link again, see Causes of user_profile_not_billable: linking again fixes only some of them. You can still serve the customer at your own cost by resending with bill_to: "self". In the Anthropic SDK, handle user_profile_not_billable by the error class for the 403 status, which is PermissionDeniedError. This also matches other 403 errors, so check the error code too.
  • 402 billing_error, linked_organization_billing_unavailable: Anthropic can’t currently bill the customer’s organization (for example, it’s suspended, or its credit runs out after Claude has started a reply). The response doesn’t say why. A customer that has no credit when the request arrives gets linked_organization_spend_limit_reached instead. Not retryable. Tell the customer to check their Claude Platform account. You can still serve them at your own cost by resending with bill_to: "self".
  • 402 billing_error, linked_organization_spend_limit_reached: the customer’s organization has reached a spend limit that it set. The limit is either the spend cap that applies to your app or the monthly spend limit for the whole organization. The Claude API sends the same code when the organization has no credit that can pay for the request. The response doesn’t say which. The request was refused before Claude started a reply. Not retryable. You can still serve the customer at your own cost by resending with bill_to: "self". Ask the customer to check these in the Claude Console:
    • The spend cap for your app: On the page for your app under Linked platforms, they can set or raise the spend cap. A cap set there replaces any default cap that they set for all linked platforms.
    • The organization’s Monthly spend limit: Under Spend limits, they can raise it.
    • The credit balance: On their Billing page, they can see their credit balance and buy credits. Some credits can’t pay for these requests: see Which credits can pay.
  • 503 overloaded_error: Anthropic couldn’t confirm right now whether the customer can be billed. Retry with backoff and honor the retry-after header. The request wasn’t served or billed.
  • 400 invalid_request_error, user_profile_required: you set bill_to: "user_profile" without the anthropic-user-profile-id header. Such a request needs the header unless it uses a connection’s access token and the header is optional. To find out whether the header is optional, see the note in Call Claude with a connection’s access token.
  • 400 invalid_request_error, with no error code: the anthropic-user-profile-id header holds an ID that is malformed or isn’t a user profile of your organization.
  • 400 invalid_request_error, with no error code: the request authenticated with a connection’s access token, and either set bill_to: "self" or named a user profile other than the one that the token is limited to. See Call Claude with a connection’s access token.

On /v1/messages and /v1/chat/completions, a connection’s access token can’t send a request that you pay for. To resend a refused request with bill_to: "self", authenticate from your own back end with your operator service account’s own credential. Call Claude with a connection’s access token lists the refusals of the token itself.

A successful response doesn’t say who was billed, so keep your own record of which requests you sent with bill_to: "user_profile".

Causes of user_profile_not_billable

Check these in order:

  • Your request. The request must authenticate as your OAuth app’s operator service account (Step 3). A connection’s access token also authenticates as that service account. A request that authenticates any other way is refused. Examples are a different service account and an API key that isn’t bound to that service account. If the anthropic-user-profile-id header names one of your profiles that isn’t linked, the request is refused. If the credential or the header is wrong, correct the request. A new connection doesn’t help.
  • The connection. The customer hasn’t linked through this app, or the connection has ended: an administrator of their organization or of yours ended it, or your back end did. An ended connection displays as Unlinked on your User profiles page. A profile linked only through your test app isn’t linked to your production app. Stop billing that customer until they link. A connection’s access token is limited to that connection, so after the customer links again, use the access token of the new connection. If your app has turned off operator-only authentication, you can bill a customer only with their connection’s access token. Then a customer for whom you hold no working token of a billing:attribution connection displays as Linked, but must approve again, as Link a customer again describes.
  • The customer’s organization. It must be an eligible customer. You can’t see that from your side, so ask your Anthropic account team.

A new connection usually works at once, but it can take about 10 seconds after the exchange in Step 8. If a request is refused with user_profile_not_billable in those 10 seconds, send it again. After that, waiting or retrying doesn’t change the result. Log the whole error.message and the request-id response header of each refused request. If a customer whose connection displays as Linked is still refused and your request is correct, send a refused request’s request-id to your Anthropic account team, so that Anthropic can look up why it was refused.

Your customer’s view

Linking

Your user approves on auth.claude.com after your app redirects them in Step 6. Step 7 lists the approval page’s screens. Each screen shows your app’s name and has a Cancel button. What the user does on each screen:

  • Select an organization: The user picks which of their Claude organizations to link. The page shows this screen only if the user has a choice of organization.
  • How billing works: The user reads the screen and clicks Continue.
  • Set a monthly spend limit: The user enters a limit for your app in whole US dollars and clicks Continue. The amount field starts empty, so the page doesn’t choose a limit for the user. Continue without a limit saves no new limit, and a cap or default that the customer saved earlier still applies. The limit that the user enters is the spend cap that Spend caps describes. This screen differs while your app is in testing: see While your app is in testing.
  • The last screen: This screen lists what your app will be able to do, including the limit that the user chose. The user clicks Link and authorize.

The approval page uses whichever Claude account is signed in to the browser and offers only that account’s Claude organizations. That account might not be the one that your user expects, for example a personal account instead of a work account. Your app can’t choose the account. The OpenID Connect parameters prompt=select_account and login_hint don’t change which account the page uses.

After linking

Your customers manage their connections on the Linked platforms page in the Claude Console. They can unlink your app at any time. Anthropic doesn’t notify you when they do: you get no webhook event and no email.

After a customer unlinks, requests that you bill to that customer are refused with 403 user_profile_not_billable (see Causes of user_profile_not_billable). The customer’s user profile displays as Unlinked on your User profiles page in the Console. To link again, run Steps 5 to 8 again with the customer’s existing user profile.

Emails about linking and unlinking

Anthropic’s emails about linking and unlinking go to the members of your customer’s organization who have the Admin or Billing role. Each email links to the customer’s Linked platforms page. Whether Anthropic sends an email depends on the event:

  • When the customer links your app: Anthropic sends an email when you exchange the code in Step 8. It sends nothing for an approval whose code you never exchange. It also sends nothing when a user approves again while the customer is still linked.
  • When the customer unlinks your app: Anthropic sends an email. It doesn’t name the person who unlinked your app.
  • When you unlink the customer from your back end: Anthropic sends an email.
  • When you unlink the customer in the Console: Anthropic sends no email.

Anthropic doesn’t guarantee that an email is sent or delivered. Tell your customer yourself when you unlink them. Don’t rely on these emails to tell a customer that they are linked.

Spend caps

Your customer can set a monthly spend cap for your app in US dollars (USD). The approval page calls this cap a monthly spend limit, and the user who links can set it there (see Linking). It is separate from the organization’s Monthly spend limit, which applies to the whole organization. You can’t read a customer’s cap or how much of it they have used.

When the customer’s spend through your app reaches the cap, the Claude API refuses the requests that you bill to them with a 402. See Expected errors. The refusals last until 00:00 UTC on the first day of the next month or until the customer raises or removes the cap. A change to the cap can take about a minute to apply.

After linking, a member of the customer’s organization with the Admin or Billing role manages caps on the Linked platforms page in the Console:

  • Set or change a cap: They click your app, then Set spend cap or Edit spend cap.
  • Set a default: Under Default spend cap, they click Set default or Edit. Each linked app that has no cap of its own can spend up to the default each month. The apps don’t share it.
  • Remove a cap: They click your app, Edit spend cap, and then Remove cap. Your app then uses the default. If there is no default, your app has no cap.

The smallest cap is $0 USD, which refuses every request that you bill to that customer. The Console accepts whole dollars and has no practical maximum. The cap counts token costs and web search fees at list prices before any negotiated discount. The customer’s bill can differ from the amount that the cap counts.

A cap can be higher than the organization’s Monthly spend limit, which the customer sets under Spend limits. The Claude API refuses the requests that you bill to the customer when either one is reached.

While your app is in testing

These limits apply whenever someone links your app or changes its cap while the app is in testing, in review, or not approved:

In testing, in review, or not approvedAfter the app is live
A monthly spend limit on the approval pageRequired, $50 USD or lessOptional
The amount field on the approval pageStarts at $50 USDStarts empty
Continue without a limit on the approval pageNot offeredOffered
Removing the cap in the ConsoleNot possiblePossible
The largest cap that a customer can set$50 USDNo practical maximum

Once your app is live, a cap that a customer saved before then stays in place. The customer can then raise or remove it.

Supporting your customers

You support your customers for everything about your app, including the Claude usage you bill to them. Anthropic gives your customers the approval page and the Linked platforms page in the Claude Console. On the Linked platforms page, a member with the Admin or Billing role can see what your app has cost the organization this month. They can also set a monthly spend cap for your app and unlink it. All other questions about your app should come to you, so tell your customers how to reach you.

Code snippet initialization

The Python examples on this page share the following setup, which you write once. It defines:

  • the imports
  • your app’s client ID and redirect URI
  • the billing beta header value
  • a Claude API client that authenticates as your service account
  • client_assertion, which returns the client assertion that your back end sends to auth.claude.com
# The Python examples assume the following initialization and variables
import secrets
from urllib.parse import urlencode

import anthropic
import httpx
from anthropic.lib.credentials import IdentityTokenFile
from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from authlib.oauth2.rfc7636 import create_s256_code_challenge

AUTH = "https://auth.claude.com"
# copy from platform.claude.com after you register your OAuth app.
CLIENT_ID = "YOUR_CLIENT_ID"
REDIRECT_URI = "https://app.example.com/claude/billing/callback"
JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
BILLING_BETA = "user-profiles-billing-2026-10-01"

# API client. The SDK exchanges your workload's identity JWT for an access
# token and refreshes it, so you never handle "Bearer <access token>" yourself.
client = anthropic.Anthropic()

# Client assertion for auth.claude.com: the identity JWT itself, read fresh on
# every call because the file rotates. If your app's client authentication
# settings name a different audience than your federation rule, point this at
# a second token file: IdentityTokenFile("/path/to/other/token").
client_assertion = IdentityTokenFile()

Was this page helpful?