OpenCredits Developer Docs
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:
- User buys credits via the checkout widget you embed in your app
- You make AI requests through our OpenAI/Anthropic-compatible API using the user's key
- 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
https://api.opencredits.ai
Quickstart
Get credits working in your app in under 5 minutes.
1. Add the SDK
<script src="https://opencredits.ai/assets/sdk.js"></script>
2. Initialize
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
// 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:
// 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!' }],
}),
});
// 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!' }],
}),
});
localStorage. For returning users, pass it back via OpenCredits.getUserKey() so they don't have to repurchase.
5. Works with OpenAI SDKs
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!"}],
)
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
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!"}],
)
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
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!',
});
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:
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.
| Option | Type | Description |
|---|---|---|
publishableKey | string | Required. Your partner publishable key (oc_pk_...) |
baseUrl | string | OpenCredits URL. Default: 'https://opencredits.ai' |
currency | string | 'usd' or 'eur'. Default: 'usd' |
checkoutMode | string | 'embedded' (default), 'new_tab', or 'manual' |
onPurchaseCompleted | function | Called when payment succeeds. Receives { user_key, balance, credits_added } |
onLoginCompleted | function | Called when user signs in. Receives { user_key, balance } |
onCheckoutOpened | function | Called when checkout session starts. Receives { session_id, user_key } |
onPurchaseError | function | Called on payment failure. Receives { error } |
onError | function | Called on any error. Receives { error } |
onComplete | function | Called when the user dismisses the success screen after purchase. Receives { user_key, balance, credits_added } |
onLoggedOut | function | Called when user logs out from the checkout widget |
OpenCredits.open(options?)
Open the checkout modal.
| Option | Type | Description |
|---|---|---|
amount | number | Preset 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
| Mode | Behavior |
|---|---|
embedded | Stripe checkout renders inside the modal (default, recommended) |
new_tab | Opens Stripe checkout in a new tab. Modal shows a waiting state. |
manual | Returns the checkout_url in onCheckoutOpened — you handle opening it yourself. |
Full example
<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.
{
"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.
{
"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:
| Provider | Example model ID |
|---|---|
| Anthropic | anthropic/claude-sonnet-4-20250514 |
| OpenAI | openai/gpt-4o |
google/gemini-2.5-pro | |
| xAI | xai/grok-3 |
See Balance & Models for how to list all available models programmatically.
Server-side requests
You can also make requests from your backend. Store the user key after checkout and attach it when making requests:
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.
{
"balance": 4850.5,
"currency": "credits"
}
Usage history
GET /v1/credits/history
Returns the user's transaction and usage history. Requires the X-User-Key header.
| Param | Type | Description |
|---|---|---|
limit | number | Number of entries to return (default 50) |
offset | number | Pagination offset (default 0) |
List models
GET /v1/models
Returns all available models. No authentication required.
{
"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.
| Field | Type | Description |
|---|---|---|
publishable_key | string | Required. Your partner publishable key. |
models | string[] | Optional. Filter to specific model IDs. |
input_tokens | number | Optional. Assumed input tokens per request (default 2500). |
output_tokens | number | Optional. Assumed output tokens per request (default 2500). |
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
}'
{
"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
| Status | Code | Description |
|---|---|---|
| 400 | invalid_request | Malformed request body or missing required fields |
| 401 | missing_api_key | No X-User-Key header provided |
| 401 | invalid_user_key | The user key is invalid or has been revoked |
| 402 | insufficient_credits | User doesn't have enough credits. Open the checkout to top up. |
| 403 | model_not_allowed | Your partner account doesn't have access to this model |
| 404 | model_not_found | The requested model ID doesn't exist |
| 429 | rate_limited | Too many requests. Back off and retry. |
| 502 | upstream_error | The AI provider returned an error |
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.