cocodot
← Back to guides
Local card declined for overseas AI? cocodot: one card + one key
AI APIUpdated 2026-10

OpenAI-Compatible API Gateway for SaaS: Tenant Metering and Model Routing

Build a server-side Claude, GPT and Gemini integration with tenant metering, explicit fallback rules and bounded retries.

TL;DR: A SaaS can put Claude, GPT and Gemini behind one OpenAI-compatible server-side integration, while keeping tenant authorization and spending controls in its own backend. Start with explicit task routes, a validator for each route, and a record for every model attempt. A shared endpoint simplifies credentials and protocol handling; it does not define which customer may spend money or what counts as a usable result. With cocodot, the OpenAI-compatible base URL is https://cocodot.co/api/ai/v1 and one key can call different listed models, billed by tokens. For an Anthropic-compatible integration, use https://cocodot.co/api/ai as the base URL. New users must complete identity verification before calling the API, and free trial credit covers only selected budget models. Before sending sustained traffic, test output validation, interrupted requests, key rotation and your fallback policy. The architecture below is a suggested implementation in your application. It gives a product engineer a concrete way to connect usage to tenants without placing a gateway credential in a browser or treating a shared balance as a customer budget.

1. Keep the model credential behind your product API

Design the path as customer request, application authorization, budget admission, task routing, model attempt, validation and delivery. Your public endpoint should accept business inputs such as a product identifier and target language. It should not let an untrusted caller choose arbitrary models, output limits or executable tools. The backend translates an allowed task into a model request. This keeps the access check close to the resource being processed and makes usage attributable to a paying tenant. Store the gateway key in server-side configuration and avoid logging authorization headers, including in error reports. Start with one narrow feature that has a clear output contract. Adding a second provider family is easier once you can explain why the first request was allowed and what happened to its result.

2. Use a route table that an engineer can explain

For each task, store a model identifier, an input contract, an output budget, a validator version and an optional fallback route. Begin with deterministic rules based on the feature the customer selected. A product-description route and a support-draft route need different acceptance conditions even if they use the same model. Claude Sonnet 5.5 (mcs-7), GPT-5.6 Sol (mog-8-s) and Gemini 3.6 Flash (mgg-12) are listed candidates you can evaluate against your own examples; this is not a ranking of their performance. Run the same sanitized cases through every candidate, including missing fields and unusual languages. Keep the route version with the result so a later model change does not erase the explanation for an earlier customer outcome.

3. Verify the protocol your application actually uses

For an OpenAI-compatible client, set the base URL to https://cocodot.co/api/ai/v1 and authenticate with Authorization: Bearer. An Anthropic-compatible client uses the base URL https://cocodot.co/api/ai and the /v1/messages path; x-api-key is also accepted for authentication. Begin with a minimal text request and add streaming, tools and optional parameters separately. Compatibility needs testing at the features you use, including completion handling and usage collection. Only function tools are accepted. Search, inventory lookup and code execution should run in your own controlled application, with their results returned to the model through your tool loop. Do not assume a provider-hosted tool becomes available because the client accepts its name. Check https://cocodot.co/docs for the integration surface before carrying an entire legacy request object across.

Minimal server request; read the key from configuration and do not print it
const response = await fetch("https://cocodot.co/api/ai/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.COCODOT_API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "mcs-7", // Claude Sonnet 5.5
    max_tokens: 1000,
    messages: [{ role: "user", content: "Draft a short product title." }]
  })
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const result = await response.json();
// Validate result and record usage inside your application.

4. Make fallback an explicit product decision

A useful fallback preserves the minimum promise of a feature. A content tool might offer a shorter draft, whereas a support tool handling an order dispute might stop automatic delivery and request human review. Test the alternative route independently against the same schema and business rules. Save the requested model, the route version and the reason for switching. If a streaming answer has already been shown to the customer, finish that attempt clearly instead of silently appending text from a different model. A depleted tenant budget should not trigger a more expensive alternative. These rules belong in your backend and should be exercised before an outage. For error classification, see /hub/ai-api-errors-china-fix; use those categories as inputs to a bounded policy rather than treating every error as permission to try again.

5. Separate credential ownership from tenant attribution

cocodot keys can be named at creation and individually revoked, with at most 10 active keys per account. Names such as prod-content, prod-support and staging help identify the service using a credential. Keep tenant identity in your own request records rather than allocating a gateway key to every customer. Suggested fields are tenant_id, job_id, attempt_id, route_version, requested model, usage and validation state. A named credential does not establish a separate tenant balance or a tenant authorization policy. For a planned rotation, validate the replacement in staging, deploy the dependent service, confirm the old credential is no longer required and revoke it. If a key leaks, revoke the compromised credential promptly and investigate its dependencies. Store only configuration aliases in ordinary logs, never key fragments or full values.

6. Give retries the same deadline and budget as the job

Put a tenant concurrency limit and a service-wide concurrency limit at the dispatch boundary. Queue background jobs so a large import cannot occupy every interactive slot. Each business job needs a total deadline, an attempt limit and a cumulative spending allowance. Temporary failures may justify delayed retries with jitter; authentication, invalid parameters and insufficient funds need their causes addressed. Check whether both your SDK and your application retry, because stacked loops can multiply attempts. With several workers, reading a budget and then sending a request is insufficient: they can all read the same remaining amount. Reserve an estimated allowance atomically in your own store before dispatch, then reconcile it after completion. This is an application safeguard based on estimates, not a promise of exact model charges. Concurrency troubleshooting is covered in /hub/api-429-rate-limit-concurrency-china.

7. Join attempts into the customer-visible unit of work

One customer action may require a summary, a draft and a validator, plus a fallback attempt. Record each attempt separately and aggregate them under one job identifier. Retain the usage fields you actually receive, the validation result and whether an artifact was delivered. Missing usage should create an unresolved accounting state instead of a zero-cost record. Your tenant budget should consider incurred charges, active reservations and unresolved attempts. When the cocodot balance runs out, new requests are refused and requests already in flight may still incur charges, with fallback estimates used when usage is missing. That behavior is why a shared prepaid balance cannot replace per-tenant admission in your product. Avoid estimating charges from visible answer length. For longer autonomous workflows, /hub/agent-api-cost-runaway provides related application guardrails. For unit economics, see /hub/team-ai-api-cost-per-task. Track delivered jobs as well as attempted requests so a retry improvement cannot conceal a decline in customer outcomes.

8. Launch a narrow workflow and verify its recovery path

Use a small sanitized set that includes ordinary requests, long input, invalid tool arguments, insufficient funds and an unavailable preferred route. Define acceptance before the run: required fields are present, interrupted jobs remain identifiable, completed results are not duplicated and each tenant receives a clear state. To start with cocodot, register, verify email, complete identity verification, prepare a balance for the intended models and create a server-side key. Free trial credit is limited to selected budget models. Funding options are Alipay / WeChat Pay (RMB), USDT / USDC. Listed Claude / GPT / Gemini rates are at or below the official list price; check the pricing page for each model's current rate. Review https://cocodot.co/pricing before budgeting. Expand traffic only after your own queue-age, validation and cost-per-delivery checks pass; keep an operator responsible for stopping dispatch when those checks fail.

BoundaryYour application should recordAcceptance check
Tenant entryTenant and job identifiersCaller owns the requested resource
Model routeModel and route versionRequired capabilities tested
AttemptUsage, status and attempt numberUnknown cost remains unresolved
DeliveryValidated artifact and completion stateDuplicate delivery is prevented

FAQ

Do I need an API key for every SaaS tenant?

Keep gateway credentials on the server and authorize tenants through your own product. Named keys are useful for services and environments; cocodot permits at most 10 active keys per account. Tenant usage and spending policies belong in your application records.

Does one OpenAI-compatible API key include automatic routing?

One cocodot key can request different listed models. The task routing, validation, fallback and tenant controls described here are implementation suggestions for your backend. Decide and test those policies explicitly.

Can I pay for Claude API usage with USDT?

cocodot funding options are Alipay / WeChat Pay (RMB), USDT / USDC. Your application calls the cocodot endpoint and usage is billed by tokens; this describes gateway funding, not funding a direct Anthropic account.

How should I meter a request that timed out?

Retain an attempt record with an unresolved outcome and reconcile available usage and charges. A client timeout alone is not proof that no processing occurred. Apply the job deadline and budget before considering another attempt.

Can a new account test every model with free credit?

No. New users must complete identity verification before calling the API, and free trial credit covers only selected budget models. Prepare the appropriate balance before evaluating your production candidates.

About cocodot

cocodot is a payment and AI access service for developers and cross-border teams in mainland China. It provides US-BIN virtual cards issued by a licensed institution — used to pay for overseas subscriptions and ad accounts — and an OpenAI-compatible AI API gateway for calling Claude, GPT and Gemini from within mainland China. Both share one wallet, funded by Alipay / WeChat Pay (RMB), USDT / USDC and accounted in USD. Card: $9.9 to open, 3% to load, $1 per active card per month; spending: $0.60 settlement fee on purchases under $20; a corresponding fee applies when the issuer charges one.

Service scope, pricing and limits →