Let users buy AI credits in your app, use them for AI requests, and earn a referral share on every one.

How it works

OpenCredits gives your users a single credit balance that works across AI models (Claude, GPT, Gemini, and more). Here's the flow:

  1. User buys credits via the checkout widget you embed in your app
  2. You make AI requests through our OpenAI/Anthropic-compatible API using the user's key
  3. Credits are deducted based on token price, plus a referral share that goes to you

What you get

  • A publishable key (oc_pk_...) to identify your app in the checkout widget
  • User keys (oc_sk_...) returned after purchase — use these to make API calls on behalf of your users
  • An OpenAI and Anthropic-compatible API that accepts the user key as auth
Base URL: All API requests go to https://api.opencredits.ai

Quickstart

Get credits working in your app in under 5 minutes.

Don't have a partner key yet? Sign up to become a partner and we'll get you set up.

1. Add the SDK

HTML
<script src="https://opencredits.ai/assets/sdk.js"></script>

2. Initialize

JavaScript
OpenCredits.init({
  publishableKey: 'oc_pk_your_key_here',
  currency: 'usd',

  // Called when the user completes a purchase
  onPurchaseCompleted(data) {
    console.log('User key:', data.user_key);
    console.log('Balance:', data.balance);
  }
});

3. Open the checkout

JavaScript
// Let user pick an amount
OpenCredits.open();

// Or preset the amount (in dollars/euros)
OpenCredits.open({ amount: 10 });

4. Make API calls

Once you have the user's key, make AI requests with it. The API is OpenAI and Anthropic-compatible — just change the base URL and auth header:

JavaScript (OpenAI)
// OpenAI-compatible endpoint
const response = await fetch('https://api.opencredits.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-User-Key': userKey,  // oc_sk_... from checkout
  },
  body: JSON.stringify({
    model: 'anthropic/claude-sonnet-4-20250514',
    messages: [{ role: 'user', content: 'Hello!' }],
  }),
});
JavaScript (Anthropic)
// Anthropic-compatible endpoint
const response = await fetch('https://api.opencredits.ai/v1/messages', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-User-Key': userKey,  // oc_sk_... from checkout
  },
  body: JSON.stringify({
    model: 'anthropic/claude-sonnet-4-20250514',
    max_tokens: 1024,
    messages: [{ role: 'user', content: 'Hello!' }],
  }),
});
Tip: The SDK automatically persists the user key in localStorage. For returning users, pass it back via OpenCredits.getUserKey() so they don't have to repurchase.

5. Works with OpenAI SDKs

Python
from openai import OpenAI

client = OpenAI(
    base_url="https://api.opencredits.ai/v1",
    api_key=user_key,  # oc_sk_... from checkout
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-4-20250514",
    messages=[{"role": "user", "content": "Hello!"}],
)
Node.js
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.opencredits.ai/v1',
  apiKey: userKey,  // oc_sk_... from checkout
});

const response = await client.chat.completions.create({
  model: 'anthropic/claude-sonnet-4-20250514',
  messages: [{ role: 'user', content: 'Hello!' }],
});

6. Works with Anthropic SDKs

Python
import anthropic

client = anthropic.Anthropic(
    base_url="https://api.opencredits.ai",
    api_key=user_key,  # oc_sk_... from checkout
)

message = client.messages.create(
    model="anthropic/claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello!"}],
)
Node.js
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  baseURL: 'https://api.opencredits.ai',
  apiKey: userKey,  // oc_sk_... from checkout
});

const message = await client.messages.create({
  model: 'anthropic/claude-sonnet-4-20250514',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello!' }],
});

7. Works with Vercel AI SDK

Node.js (OpenAI provider)
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const openai = createOpenAI({
  baseURL: 'https://api.opencredits.ai/v1',
  apiKey: userKey,  // oc_sk_... from checkout
});

const { text } = await generateText({
  model: openai('anthropic/claude-sonnet-4-20250514'),
  prompt: 'Hello!',
});
Node.js (Anthropic provider)
import { generateText } from 'ai';
import { createAnthropic } from '@ai-sdk/anthropic';

const anthropic = createAnthropic({
  baseURL: 'https://api.opencredits.ai/v1',
  apiKey: userKey,  // oc_sk_... from checkout
});

const { text } = await generateText({
  model: anthropic('anthropic/claude-sonnet-4-20250514'),
  prompt: 'Hello!',
});

8. Works with Claude Code

Point Claude Code at OpenCredits by setting environment variables:

Shell
export ANTHROPIC_BASE_URL=https://api.opencredits.ai
export ANTHROPIC_API_KEY=oc_sk_...  # user key from checkout

claude

Checkout SDK

The SDK opens a branded checkout modal in your app. It handles amount selection, Stripe payment, account login, and returns the user key when done.

OpenCredits.init(options)

Initialize the SDK. Call this once on page load.

OptionTypeDescription
publishableKeystringRequired. Your partner publishable key (oc_pk_...)
baseUrlstringOpenCredits URL. Default: 'https://opencredits.ai'
currencystring'usd' or 'eur'. Default: 'usd'
checkoutModestring'embedded' (default), 'new_tab', or 'manual'
onPurchaseCompletedfunctionCalled when payment succeeds. Receives { user_key, balance, credits_added }
onLoginCompletedfunctionCalled when user signs in. Receives { user_key, balance }
onCheckoutOpenedfunctionCalled when checkout session starts. Receives { session_id, user_key }
onPurchaseErrorfunctionCalled on payment failure. Receives { error }
onErrorfunctionCalled on any error. Receives { error }
onCompletefunctionCalled when the user dismisses the success screen after purchase. Receives { user_key, balance, credits_added }
onLoggedOutfunctionCalled when user logs out from the checkout widget

OpenCredits.open(options?)

Open the checkout modal.

OptionTypeDescription
amountnumberPreset dollar/euro amount. If omitted, user picks from $5 / $10 / $25 / $50 / $100 or enters a custom amount.

OpenCredits.close()

Programmatically close the checkout modal.

OpenCredits.getUserKey()

Returns the current user key (oc_sk_...) or null if no user is logged in. The SDK persists this in localStorage automatically.

Checkout modes

ModeBehavior
embeddedStripe checkout renders inside the modal (default, recommended)
new_tabOpens Stripe checkout in a new tab. Modal shows a waiting state.
manualReturns the checkout_url in onCheckoutOpened — you handle opening it yourself.

Full example

HTML
<script src="https://opencredits.ai/assets/sdk.js"></script>
<script>
  OpenCredits.init({
    publishableKey: 'oc_pk_your_key',
    onPurchaseCompleted(data) {
      // Store the key server-side for this user
      fetch('/api/save-credits-key', {
        method: 'POST',
        body: JSON.stringify({ userKey: data.user_key }),
      });
    },
  });

  document.getElementById('buy-btn').addEventListener('click', () => {
    OpenCredits.open();
  });
</script>

API

Make AI requests on behalf of your users. The API is compatible with both OpenAI and Anthropic SDKs — just change the base URL and use the user's key for auth.

Authentication

Pass the user key in the X-User-Key header. When using the OpenAI SDK, this maps to the apiKey field.

OpenAI-compatible endpoint

POST /v1/chat/completions

Accepts the standard OpenAI chat completions request format. Supports streaming, tools, vision, and all other OpenAI features.

Request
{
  "model": "openai/gpt-4o",
  "messages": [
    { "role": "user", "content": "Explain quantum computing" }
  ],
  "stream": true
}

Anthropic-compatible endpoint

POST /v1/messages

Accepts the standard Anthropic messages request format. Supports streaming, thinking, vision, and all other Anthropic features.

Request
{
  "model": "anthropic/claude-sonnet-4-20250514",
  "max_tokens": 1024,
  "messages": [
    { "role": "user", "content": "Explain quantum computing" }
  ]
}

Model IDs

Models are namespaced by provider. Use the full ID in your requests:

ProviderExample model ID
Anthropicanthropic/claude-sonnet-4-20250514
OpenAIopenai/gpt-4o
Googlegoogle/gemini-2.5-pro
xAIxai/grok-3

See Balance & Models for how to list all available models programmatically.

Streaming: Both endpoints support server-sent events (SSE) for real-time responses.

Server-side requests

You can also make requests from your backend. Store the user key after checkout and attach it when making requests:

Node.js (Express)
app.post('/api/chat', async (req, res) => {
  const userKey = getUserKeyFromSession(req);  // your auth logic

  const response = await fetch('https://api.opencredits.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-User-Key': userKey,
    },
    body: JSON.stringify(req.body),
  });

  res.status(response.status).send(await response.json());
});

Balance & Models

Check balance

GET /v1/credits/balance

Returns the user's current credit balance. Requires the X-User-Key header.

Response
{
  "balance": 4850.5,
  "currency": "credits"
}
Tip: Show the credit balance in your UI so users know when to top up.

Usage history

GET /v1/credits/history

Returns the user's transaction and usage history. Requires the X-User-Key header.

ParamTypeDescription
limitnumberNumber of entries to return (default 50)
offsetnumberPagination offset (default 0)

List models

GET /v1/models

Returns all available models. No authentication required.

Response
{
  "data": [
    {
      "id": "anthropic/claude-sonnet-4-20250514",
      "name": "Claude Sonnet 4",
      "type": "language",
      "context_window": 200000,
      "max_tokens": 8192
    },
    ...
  ]
}

Credit pricing estimates

POST /v1/credits/pricing

Returns models with estimated credits per request. Useful for showing users "how many requests will my credits buy?" Results are filtered to your allowed models and include your partner commission. Also available as GET with query params.

FieldTypeDescription
publishable_keystringRequired. Your partner publishable key.
modelsstring[]Optional. Filter to specific model IDs.
input_tokensnumberOptional. Assumed input tokens per request (default 2500).
output_tokensnumberOptional. Assumed output tokens per request (default 2500).
Request
curl -X POST https://api.opencredits.ai/v1/credits/pricing \
  -H "Content-Type: application/json" \
  -d '{
    "publishable_key": "oc_pk_...",
    "models": ["anthropic/claude-opus-4.6", "openai/gpt-4o"],
    "input_tokens": 1000,
    "output_tokens": 500
  }'
Response
{
  "token_assumption": { "input": 2500, "output": 2500 },
  "models": [
    {
      "id": "anthropic/claude-sonnet-4-20250514",
      "name": "Claude Sonnet 4",
      "credits_per_request": 1.44,

    },
    {
      "id": "openai/gpt-4o",
      "name": "GPT-4o",
      "credits_per_request": 0.94,

    },
    ...
  ]
}

Errors

The API returns errors in the format matching the endpoint you're using (OpenAI or Anthropic format).

OpenAI format

Returned from /v1/chat/completions:

{
  "error": {
    "message": "Insufficient credits. Please top up your balance.",
    "type": "insufficient_credits",
    "param": null,
    "code": "402"
  }
}

Anthropic format

Returned from /v1/messages:

{
  "type": "error",
  "error": {
    "type": "insufficient_credits",
    "message": "Insufficient credits. Please top up your balance."
  }
}

Error codes

StatusCodeDescription
400invalid_requestMalformed request body or missing required fields
401missing_api_keyNo X-User-Key header provided
401invalid_user_keyThe user key is invalid or has been revoked
402insufficient_creditsUser doesn't have enough credits. Open the checkout to top up.
403model_not_allowedYour partner account doesn't have access to this model
404model_not_foundThe requested model ID doesn't exist
429rate_limitedToo many requests. Back off and retry.
502upstream_errorThe AI provider returned an error
Handle 402: When you get insufficient_credits, prompt the user to buy more credits by calling OpenCredits.open().

Referrals

You earn a referral share on every AI request your users make through OpenCredits. This is automatic — no extra integration needed.

How it works

Each AI request deducts credits from the user based on token price, plus a referral share that goes to you. Your referral rate is set on your partner account (e.g. 10%). You can see per-request breakdowns in your usage logs.

Example

With a 10% referral rate and a request that costs $5 in provider fees:

Amount
Provider cost for request$5.00
Your referral share (10%)$0.50
Total charged to user$5.50

The more your users use AI features in your app, the more you earn. At scale this adds up — 1,000 requests/month at this rate = $500/month in referral revenue.

By bringing users to OpenCredits, you're rewarded every time they use AI — better features mean more usage and more revenue for you.