Denna handledning använder Node.js/Express + OpenAI SDK. Dodo Payments-koncept (krediter, mätare, webhooks) gäller för alla ramverk eller AI-leverantörer — anpassa fritt.
- Skapa ett anpassat kreditberättigande (tokens) och en mätare som automatiskt drar ifrån det
- Fästa krediter på prenumerationsplaner (med och utan överspill) och en engångs topprodukt
- Ansluta en riktig OpenAI-kompletterande slutpunkt som fakturerar tokens genom Dodo Payments
- Fråga en kunds aktuella kreditsaldo via SDK
- Verifiera webhook-signaturer och dirigera Dodo Payments kredithändelser
Vad Vi Bygger
Här är prismodellen för NeuralAPI:Innan du börjar, se till att du har:
- Ett Dodo Payments-konto (testläge är okej)
- En OpenAI API-nyckel
- Node.js 18+
- Grundläggande kunskaper i TypeScript/Node.js
Steg 1: Skapa Ditt Token Krediteringsberättigande
Först skapar du kreditberättigandet som både prenumerationsplanerna och toppningspaketet delar. Tänk på detta som att definiera den “token”-enhet din plattform använder.
The Credits tab under Products shows all your credit entitlements.
1
Navigate to Credits
- Logga in på din Dodo Payments-instrumentpanel
- Klicka på Produkter i den vänstra sidopanelen
- Välj fliken Krediter
- Klicka på Skapa Kredit
2
Configure the credit unit
Fyll i de grundläggande detaljerna för din tokenkredit:Kreditnamn:
API TokensKredittype: Välj Anpassad EnhetEnhetsnamn: tokenPrecision: 0 (tokens är alltid hela nummer)Kredits Utgång: 30 days (krediter återställs varje faktureringscykel)3
Skip overage at the credit level
Lämna överspill avaktiverad här — du kommer att konfigurera det per plan när du fäster krediten på produkter. Detta gör att startplanen blockerar användning vid noll medan Pro-planen tillåter överspill.
4
Test the top-up flow
Click Buy 5M Tokens — $19 and complete checkout. After the payment succeeds, refresh the balance — it should jump by 5,000,000 tokens. Your server log should show a
credit.added event.Troubleshooting
Credits not deducting after usage events
Credits not deducting after usage events
Possible causes:
- The meter’s event name doesn’t match the
event_nameyou’re sending (api.tokens_usedis case-sensitive) - The meter isn’t linked to the
API Tokenscredit on the product — go to the product’s meter configuration and confirm Bill usage in Credits is on - The
metadata.tokenskey doesn’t match the meter’s “Over Property” field - The customer’s grant has expired (check the customer’s credit history)
- Products → Meters: open the meter and confirm it shows the linked credit name on the product attachment
- The Events tab on the meter — ingested events should appear there even before deduction
- Customers → [Customer] → Credits: ledger entries should appear within a minute or two
Balance always shows 0 or 'customer not found'
Balance always shows 0 or 'customer not found'
Possible causes:
- The customer hasn’t completed checkout yet — credits are only issued after a successful payment
- You’re querying with the wrong
customer_id(use thecus_...ID from the dashboard, not your own DB ID) - The
CREDIT_ENTITLEMENT_IDin.envdoesn’t match the credit attached to the product
Overage not working for Pro plan customers
Overage not working for Pro plan customers
Possible causes:
- Overage wasn’t enabled on the Pro product’s credit attachment (the credit-level setting is just a default)
- The customer is actually on Starter, not Pro
- Overage limit was set to 0
0.000005 (= $5 per million tokens; double-check the leading zeros — the field takes per-token price, not per-1K).`Webhook verification failed` in logs
`Webhook verification failed` in logs
Possible causes:
- Body parsing order:
express.json()was applied to/webhooks/dodobeforeexpress.raw()— the SDK needs the raw bytes of the request, not parsed JSON - Wrong signing secret in
DODO_PAYMENTS_WEBHOOK_KEY - Reverse proxy is rewriting headers
app.use('/webhooks/dodo', express.raw(...)) line comes before app.use(express.json()) in server.ts.Need help?
Congratulations! You’ve Built Credit-Based Billing for NeuralAPI
Your platform now has a complete, production-ready credit billing system:Token Credit Entitlement
A reusable
API Tokens credit with 30-day expiry, shared across all plans and the top-up packTiered Plans, One Credit
Starter (10M, hard limit) and Pro (40M + overage) configured per-product without duplicating the credit
One-Time Top-Up Pack
Customers add 5M tokens for $19 without changing their subscription
Auto-Deduction via Meter
Real OpenAI token counts ingested as events; the meter deducts credits FIFO with no manual tracking
Live Balance API
Real-time balance via the SDK to gate access, display usage, or warn customers in-app
Verified Webhook Pipeline
Credit ledger events (
credit.added, credit.deducted, credit.overage_charged) routed through a signature-verified handler using the SDK’s Standard Webhooks helperGoing to production? Tighten these:
- Auth on
/credits/:customerIdand/api/generate— currently anyone can hit these with any customer ID. Authenticate users and look up their customer ID server-side. - Stable
event_ids — the example usesDate.now() + random. In production, use your request ID so retries are idempotent (Dodo Payments deduplicates byevent_id). - Persist the customer↔user mapping — store
customer_idin your DB after the first checkout so you don’t need a manual paste step. - Decide what happens when a subscription ends. Plan credits remain in the customer’s ledger until their natural expiry (30 days from issuance) and top-up credits stay valid for 365 days — but the cookbook’s
/api/generateonly checks balance, not subscription status. So a cancelled customer can still consume their remaining tokens. That’s the consumer-friendly default. If you want stricter access control, either (a) listen to thesubscription.cancelledwebhook and gate/api/generateon subscription status, or (b) call Dodo’s ledger API to debit unused plan credits on cancel while leaving top-up credits intact. - Monitor the Usage Billing dashboard to catch metering anomalies early.
Credit-Based Billing Reference
Full CBB documentation: rollover, overage modes, ledger management, all API endpoints.
Credit Webhook Events
Payload schemas for every credit event your server might receive.