@dodopayments/opencode-plugin 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,942 @@
1
+ ---
2
+ name: credit-based-billing
3
+ description: Guide for implementing credit-based billing with Dodo Payments - credit entitlements, balances, ledger management, rollover, overage, and meter-based deduction.
4
+ ---
5
+
6
+ # Dodo Payments Credit-Based Billing
7
+
8
+ **Reference: [docs.dodopayments.com/features/credit-based-billing](https://docs.dodopayments.com/features/credit-based-billing)**
9
+
10
+ Grant customers a balance of credits (API calls, tokens, compute units, or any custom metric) and deduct from that balance as they consume your service.
11
+
12
+ ---
13
+
14
+ ## Overview
15
+
16
+ Credit-based billing lets you:
17
+ - **Issue credits** with subscriptions, one-time purchases, or via API
18
+ - **Deduct automatically** via usage meters or manually via API
19
+ - **Configure rollover** to carry unused credits forward
20
+ - **Handle overage** when credits run out mid-cycle
21
+ - **Set expiration** rules per credit entitlement
22
+ - **Track everything** via a full audit ledger
23
+
24
+ Credits work across all product types: subscriptions, one-time purchases, and usage-based billing.
25
+
26
+ ---
27
+
28
+ ## Core Concepts
29
+
30
+ ### Credit Types
31
+
32
+ | Type | Description | Best For |
33
+ |------|-------------|----------|
34
+ | **Custom Unit** | Your own metric (tokens, API calls, compute hours) with configurable precision (0–3 decimals) | API calls, AI tokens, compute hours, messages |
35
+ | **Fiat Credits** | Real currency value (USD, EUR, etc.) that depletes as customers use your service | Prepaid balances, promotional credits, compensation |
36
+
37
+ ### Credit Lifecycle
38
+
39
+ 1. **Credits Issued** — Granted on purchase (subscription cycle or one-time) or via API
40
+ 2. **Credits Consumed** — Deducted via meter events or manual API calls
41
+ 3. **Credits Expire or Roll Over** — At cycle end, unused credits expire or carry forward
42
+ 4. **Overage Handling** — If balance hits zero, overage is forgiven, billed, or carried as deficit
43
+
44
+ ### Grant Sources
45
+
46
+ | Source | Description |
47
+ |--------|-------------|
48
+ | **Subscription** | Credits issued each billing cycle |
49
+ | **One-Time** | Credits issued with a one-time payment |
50
+ | **API** | Credits granted manually via API or dashboard |
51
+ | **Rollover** | Credits carried over from a previous billing cycle |
52
+
53
+ ---
54
+
55
+ ## Quick Start
56
+
57
+ ### 1. Create a Credit Entitlement
58
+
59
+ ```typescript
60
+ import DodoPayments from 'dodopayments';
61
+
62
+ const client = new DodoPayments({
63
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY,
64
+ });
65
+
66
+ const credit = await client.creditEntitlements.create({
67
+ name: 'API Credits',
68
+ credit_type: 'custom_unit',
69
+ unit_name: 'API Calls',
70
+ precision: 0,
71
+ expiry_duration: 30, // days
72
+ rollover_enabled: false,
73
+ allow_overage: false,
74
+ });
75
+ ```
76
+
77
+ ### 2. Attach Credits to a Product
78
+
79
+ In Dashboard → Products → Create/Edit Product → Entitlements → Attach Credits:
80
+ - Select the credit entitlement
81
+ - Set credits issued per billing cycle (subscriptions) or total (one-time)
82
+ - Configure trial credits, proration, low balance threshold
83
+
84
+ ### 3. Create Checkout with Credit Product
85
+
86
+ ```typescript
87
+ const session = await client.checkoutSessions.create({
88
+ product_cart: [
89
+ {
90
+ product_id: 'prod_ai_pro_plan', // Product with credits attached
91
+ quantity: 1,
92
+ }
93
+ ],
94
+ customer: { email: 'customer@example.com' },
95
+ return_url: 'https://yourapp.com/success',
96
+ });
97
+
98
+ // Redirect to session.checkout_url
99
+ ```
100
+
101
+ ### 4. Deduct Credits via Usage Events
102
+
103
+ ```typescript
104
+ // Meter linked to credit entitlement deducts automatically
105
+ await client.usageEvents.ingest({
106
+ events: [{
107
+ event_id: `gen_${Date.now()}_${crypto.randomUUID()}`,
108
+ customer_id: 'cus_abc123',
109
+ event_name: 'ai.generation',
110
+ timestamp: new Date().toISOString(),
111
+ metadata: { model: 'gpt-4', tokens: '1500' }
112
+ }]
113
+ });
114
+ ```
115
+
116
+ ### 5. Check Balance
117
+
118
+ ```typescript
119
+ const balance = await client.creditEntitlements.balances.get(
120
+ 'cent_credit_id',
121
+ 'cus_abc123'
122
+ );
123
+
124
+ console.log(`Available: ${balance.available_balance}`);
125
+ console.log(`Overage: ${balance.overage_balance}`);
126
+ ```
127
+
128
+ ---
129
+
130
+ ## API Reference
131
+
132
+ ### Credit Entitlement CRUD
133
+
134
+ | Operation | Method | Endpoint |
135
+ |-----------|--------|----------|
136
+ | Create | `POST` | `/credit-entitlements` |
137
+ | List | `GET` | `/credit-entitlements` |
138
+ | Get | `GET` | `/credit-entitlements/{id}` |
139
+ | Update | `PATCH` | `/credit-entitlements/{id}` |
140
+ | Delete | `DELETE` | `/credit-entitlements/{id}` |
141
+ | Undelete | `POST` | `/credit-entitlements/{id}/undelete` |
142
+
143
+ ### Balance & Ledger Operations
144
+
145
+ | Operation | Method | Endpoint |
146
+ |-----------|--------|----------|
147
+ | List All Balances | `GET` | `/credit-entitlements/{id}/balances` |
148
+ | Get Customer Balance | `GET` | `/credit-entitlements/{id}/balances/{customer_id}` |
149
+ | Create Ledger Entry | `POST` | `/credit-entitlements/{id}/balances/{customer_id}/ledger-entries` |
150
+ | List Customer Ledger | `GET` | `/credit-entitlements/{id}/balances/{customer_id}/ledger` |
151
+ | List Customer Grants | `GET` | `/credit-entitlements/{id}/balances/{customer_id}/grants` |
152
+
153
+ ---
154
+
155
+ ## Implementation Examples
156
+
157
+ ### TypeScript/Node.js
158
+
159
+ #### Create Credit Entitlement
160
+
161
+ ```typescript
162
+ import DodoPayments from 'dodopayments';
163
+
164
+ const client = new DodoPayments({
165
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
166
+ });
167
+
168
+ // Custom unit credit (AI tokens)
169
+ const tokenCredit = await client.creditEntitlements.create({
170
+ name: 'AI Tokens',
171
+ credit_type: 'custom_unit',
172
+ unit_name: 'tokens',
173
+ precision: 0,
174
+ expiry_duration: 30,
175
+ rollover_enabled: true,
176
+ max_rollover_percentage: 25,
177
+ rollover_timeframe: 'month',
178
+ max_rollover_count: 3,
179
+ allow_overage: true,
180
+ overage_limit: 50000,
181
+ price_per_unit: 0.001,
182
+ overage_behavior: 'bill_overage_at_billing',
183
+ });
184
+
185
+ // Fiat credit (USD balance)
186
+ const usdCredit = await client.creditEntitlements.create({
187
+ name: 'Platform Credits',
188
+ credit_type: 'fiat',
189
+ unit_currency: 'USD',
190
+ expiry_duration: 90,
191
+ rollover_enabled: false,
192
+ allow_overage: false,
193
+ });
194
+ ```
195
+
196
+ #### Manual Credit/Debit via Ledger Entry
197
+
198
+ ```typescript
199
+ // Grant credits manually (e.g., promotional bonus)
200
+ await client.creditEntitlements.balances.createLedgerEntry(
201
+ 'cent_credit_id',
202
+ 'cus_abc123',
203
+ {
204
+ type: 'credit',
205
+ amount: '500',
206
+ description: 'Welcome bonus - 500 free API credits',
207
+ idempotency_key: `welcome_bonus_${customerId}`,
208
+ }
209
+ );
210
+
211
+ // Debit credits manually (e.g., service compensation deduction)
212
+ await client.creditEntitlements.balances.createLedgerEntry(
213
+ 'cent_credit_id',
214
+ 'cus_abc123',
215
+ {
216
+ type: 'debit',
217
+ amount: '100',
218
+ description: 'Manual deduction for premium support',
219
+ idempotency_key: `support_deduction_${Date.now()}`,
220
+ }
221
+ );
222
+ ```
223
+
224
+ #### Query Customer Balance and Ledger
225
+
226
+ ```typescript
227
+ // Get current balance
228
+ const balance = await client.creditEntitlements.balances.get(
229
+ 'cent_credit_id',
230
+ 'cus_abc123'
231
+ );
232
+ console.log(`Balance: ${balance.available_balance}`);
233
+
234
+ // List all balances for a credit entitlement
235
+ const allBalances = await client.creditEntitlements.balances.list(
236
+ 'cent_credit_id'
237
+ );
238
+
239
+ // Get full transaction history
240
+ const ledger = await client.creditEntitlements.balances.listLedger(
241
+ 'cent_credit_id',
242
+ 'cus_abc123'
243
+ );
244
+
245
+ for (const entry of ledger.items) {
246
+ console.log(`${entry.type}: ${entry.amount} | Balance: ${entry.balance_after}`);
247
+ }
248
+
249
+ // List credit grants
250
+ const grants = await client.creditEntitlements.balances.listGrants(
251
+ 'cent_credit_id',
252
+ 'cus_abc123'
253
+ );
254
+ ```
255
+
256
+ #### Update Credit Entitlement Settings
257
+
258
+ ```typescript
259
+ await client.creditEntitlements.update('cent_credit_id', {
260
+ rollover_enabled: true,
261
+ max_rollover_percentage: 50,
262
+ allow_overage: true,
263
+ overage_limit: 10000,
264
+ price_per_unit: 0.002,
265
+ overage_behavior: 'bill_overage_at_billing',
266
+ });
267
+ ```
268
+
269
+ ### Python
270
+
271
+ ```python
272
+ from dodopayments import DodoPayments
273
+ import os
274
+ import uuid
275
+ from datetime import datetime
276
+
277
+ client = DodoPayments(bearer_token=os.environ["DODO_PAYMENTS_API_KEY"])
278
+
279
+ # Create credit entitlement
280
+ credit = client.credit_entitlements.create(
281
+ name="AI Tokens",
282
+ credit_type="custom_unit",
283
+ unit_name="tokens",
284
+ precision=0,
285
+ expiry_duration=30,
286
+ rollover_enabled=True,
287
+ max_rollover_percentage=25,
288
+ allow_overage=True,
289
+ overage_limit=50000,
290
+ price_per_unit=0.001,
291
+ overage_behavior="bill_overage_at_billing",
292
+ )
293
+
294
+ # Grant credits manually
295
+ client.credit_entitlements.balances.create_ledger_entry(
296
+ credit_entitlement_id="cent_credit_id",
297
+ customer_id="cus_abc123",
298
+ type="credit",
299
+ amount="500",
300
+ description="Promotional bonus",
301
+ idempotency_key=f"promo_{uuid.uuid4()}",
302
+ )
303
+
304
+ # Check balance
305
+ balance = client.credit_entitlements.balances.get(
306
+ credit_entitlement_id="cent_credit_id",
307
+ customer_id="cus_abc123",
308
+ )
309
+ print(f"Available: {balance.available_balance}")
310
+
311
+ # Send usage events that deduct credits
312
+ client.usage_events.ingest(events=[{
313
+ "event_id": f"api_{datetime.now().timestamp()}_{uuid.uuid4()}",
314
+ "customer_id": "cus_abc123",
315
+ "event_name": "ai.tokens",
316
+ "timestamp": datetime.now().isoformat(),
317
+ "metadata": {"tokens": "1500", "model": "gpt-4"}
318
+ }])
319
+ ```
320
+
321
+ ### Go
322
+
323
+ ```go
324
+ package main
325
+
326
+ import (
327
+ "context"
328
+ "fmt"
329
+ "os"
330
+ "time"
331
+
332
+ "github.com/dodopayments/dodopayments-go"
333
+ "github.com/google/uuid"
334
+ )
335
+
336
+ func main() {
337
+ client := dodopayments.NewClient(
338
+ option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")),
339
+ )
340
+
341
+ ctx := context.Background()
342
+
343
+ // Create credit entitlement
344
+ credit, err := client.CreditEntitlements.Create(ctx, &dodopayments.CreditEntitlementCreateParams{
345
+ Name: "AI Tokens",
346
+ CreditType: "custom_unit",
347
+ UnitName: "tokens",
348
+ Precision: 0,
349
+ })
350
+ if err != nil {
351
+ panic(err)
352
+ }
353
+
354
+ // Get customer balance
355
+ balance, err := client.CreditEntitlements.Balances.Get(ctx, credit.ID, "cus_abc123")
356
+ if err != nil {
357
+ panic(err)
358
+ }
359
+ fmt.Printf("Balance: %s\n", balance.AvailableBalance)
360
+
361
+ // Send usage events
362
+ _, err = client.UsageEvents.Ingest(ctx, &dodopayments.UsageEventIngestParams{
363
+ Events: []dodopayments.UsageEvent{{
364
+ EventID: fmt.Sprintf("api_%d_%s", time.Now().Unix(), uuid.New().String()),
365
+ CustomerID: "cus_abc123",
366
+ EventName: "ai.tokens",
367
+ Timestamp: time.Now().Format(time.RFC3339),
368
+ Metadata: map[string]string{
369
+ "tokens": "1500",
370
+ "model": "gpt-4",
371
+ },
372
+ }},
373
+ })
374
+ if err != nil {
375
+ panic(err)
376
+ }
377
+ }
378
+ ```
379
+
380
+ ---
381
+
382
+ ## Credit Settings
383
+
384
+ ### Rollover
385
+
386
+ Carry unused credits forward to the next billing cycle:
387
+
388
+ | Setting | Description |
389
+ |---------|-------------|
390
+ | **Rollover Enabled** | Toggle to allow unused credits to carry forward |
391
+ | **Max Rollover Percentage** | Limit how much carries over (0–100%) |
392
+ | **Rollover Timeframe** | How long rolled-over credits remain valid (day, week, month, year) |
393
+ | **Max Rollover Count** | Maximum consecutive rollovers before credits are forfeited |
394
+
395
+ **Example**: 200 unused credits at cycle end, 75% rollover → 150 credits carry forward, 50 forfeited.
396
+
397
+ ### Overage
398
+
399
+ Controls what happens when a customer's balance reaches zero mid-cycle:
400
+
401
+ | Setting | Description |
402
+ |---------|-------------|
403
+ | **Allow Overage** | Let customers continue past zero balance |
404
+ | **Overage Limit** | Max credits consumable beyond balance |
405
+ | **Price Per Unit** | Cost per additional credit (with currency) |
406
+ | **Overage Behavior** | How overage is handled at cycle end |
407
+
408
+ **Overage Behaviors:**
409
+
410
+ | Behavior | Description |
411
+ |----------|-------------|
412
+ | **Forgive overage at reset** | Overage tracked but not billed (default) |
413
+ | **Bill overage at billing** | Overage charged on next invoice |
414
+ | **Carry over deficit** | Negative balance carries into next cycle |
415
+ | **Carry over deficit (auto-repay)** | Deficit auto-repaid from new credits next cycle |
416
+
417
+ ### Expiration
418
+
419
+ | Setting | Description |
420
+ |---------|-------------|
421
+ | **Credit Expiry** | Duration after issuance: 7, 30, 60, 90, custom days, or never |
422
+ | **Trial Credits Expire After Trial** | Whether trial-specific credits expire when trial ends |
423
+
424
+ ---
425
+
426
+ ## Webhook Events
427
+
428
+ Credit-based billing fires these webhook events:
429
+
430
+ | Event | Description |
431
+ |-------|-------------|
432
+ | `credit.added` | Credits granted to a customer |
433
+ | `credit.deducted` | Credits consumed through usage or manual debit |
434
+ | `credit.expired` | Unused credits expired |
435
+ | `credit.rolled_over` | Credits carried forward to a new grant |
436
+ | `credit.rollover_forfeited` | Credits forfeited at max rollover count |
437
+ | `credit.overage_charged` | Overage charges applied |
438
+ | `credit.manual_adjustment` | Manual credit/debit adjustment made |
439
+ | `credit.balance_low` | Balance dropped below configured threshold |
440
+
441
+ ### Webhook Handler Example
442
+
443
+ ```typescript
444
+ // app/api/webhooks/dodo/route.ts
445
+ import { NextRequest, NextResponse } from 'next/server';
446
+
447
+ export async function POST(req: NextRequest) {
448
+ const event = await req.json();
449
+
450
+ switch (event.type) {
451
+ case 'credit.added':
452
+ await handleCreditAdded(event.data);
453
+ break;
454
+ case 'credit.deducted':
455
+ await handleCreditDeducted(event.data);
456
+ break;
457
+ case 'credit.balance_low':
458
+ await handleBalanceLow(event.data);
459
+ break;
460
+ case 'credit.expired':
461
+ await handleCreditExpired(event.data);
462
+ break;
463
+ case 'credit.overage_charged':
464
+ await handleOverageCharged(event.data);
465
+ break;
466
+ }
467
+
468
+ return NextResponse.json({ received: true });
469
+ }
470
+
471
+ async function handleCreditAdded(data: any) {
472
+ const { customer_id, credit_entitlement_id, amount, balance_after } = data;
473
+
474
+ // Update internal records
475
+ await prisma.creditBalance.upsert({
476
+ where: { customerId_creditId: { customerId: customer_id, creditId: credit_entitlement_id } },
477
+ create: { customerId: customer_id, creditId: credit_entitlement_id, balance: balance_after },
478
+ update: { balance: balance_after },
479
+ });
480
+ }
481
+
482
+ async function handleCreditDeducted(data: any) {
483
+ const { customer_id, credit_entitlement_id, amount, balance_after } = data;
484
+
485
+ await prisma.creditBalance.update({
486
+ where: { customerId_creditId: { customerId: customer_id, creditId: credit_entitlement_id } },
487
+ data: { balance: balance_after },
488
+ });
489
+ }
490
+
491
+ async function handleBalanceLow(data: any) {
492
+ const {
493
+ customer_id,
494
+ credit_entitlement_name,
495
+ available_balance,
496
+ threshold_percent,
497
+ } = data;
498
+
499
+ // Notify the customer
500
+ await sendEmail(customer_id, {
501
+ subject: `Your ${credit_entitlement_name} balance is running low`,
502
+ body: `You have ${available_balance} credits remaining (${threshold_percent}% threshold reached). Consider upgrading your plan or purchasing additional credits.`,
503
+ });
504
+ }
505
+
506
+ async function handleCreditExpired(data: any) {
507
+ const { customer_id, credit_entitlement_id, amount, balance_after } = data;
508
+
509
+ await prisma.creditBalance.update({
510
+ where: { customerId_creditId: { customerId: customer_id, creditId: credit_entitlement_id } },
511
+ data: { balance: balance_after },
512
+ });
513
+
514
+ // Optionally notify customer
515
+ await sendCreditExpiryNotification(customer_id, amount);
516
+ }
517
+
518
+ async function handleOverageCharged(data: any) {
519
+ const { customer_id, credit_entitlement_id, amount, overage_after } = data;
520
+
521
+ // Track overage for billing
522
+ await prisma.overageRecord.create({
523
+ data: {
524
+ customerId: customer_id,
525
+ creditId: credit_entitlement_id,
526
+ amount,
527
+ overageBalance: overage_after,
528
+ },
529
+ });
530
+ }
531
+ ```
532
+
533
+ ### Balance Low Payload
534
+
535
+ The `credit.balance_low` event has a distinct payload:
536
+
537
+ ```json
538
+ {
539
+ "business_id": "bus_xxxxx",
540
+ "type": "credit.balance_low",
541
+ "timestamp": "2025-08-04T06:15:00.000000Z",
542
+ "data": {
543
+ "payload_type": "CreditBalanceLow",
544
+ "customer_id": "cus_xxxxx",
545
+ "subscription_id": "sub_xxxxx",
546
+ "credit_entitlement_id": "cent_xxxxx",
547
+ "credit_entitlement_name": "API Credits",
548
+ "available_balance": "15",
549
+ "subscription_credits_amount": "100",
550
+ "threshold_percent": 20,
551
+ "threshold_amount": "20"
552
+ }
553
+ }
554
+ ```
555
+
556
+ ---
557
+
558
+ ## Usage Billing with Credits
559
+
560
+ When credits are linked to usage meters, meter events automatically deduct credits. A background worker processes events every minute, converts meter units to credits using your configured rate, and deducts using FIFO ordering (oldest grants first).
561
+
562
+ ### How It Works
563
+
564
+ 1. **Your app sends usage events** — Each event includes customer ID, event name, and metadata
565
+ 2. **Meters aggregate events** — Using Count, Sum, Max, Last, or Unique Count
566
+ 3. **Credits are deducted automatically** — Converted at your configured `meter_units_per_credit` rate
567
+ 4. **Overage is tracked** — If balance reaches zero and overage is enabled, usage continues
568
+
569
+ ### Meter-Credit Configuration
570
+
571
+ In Dashboard → Products → Usage-Based Product → Select Meter:
572
+ 1. Toggle **Bill usage in Credits**
573
+ 2. Select the credit entitlement
574
+ 3. Set **Meter units per credit** (e.g., 1000 API calls = 1 credit)
575
+ 4. Set **Free Threshold** (units free before credit deduction begins)
576
+
577
+ ### AI Token Billing Example
578
+
579
+ ```typescript
580
+ import DodoPayments from 'dodopayments';
581
+
582
+ const client = new DodoPayments({
583
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
584
+ });
585
+
586
+ // Track AI token usage — meter auto-deducts credits
587
+ async function trackAIUsage(
588
+ customerId: string,
589
+ promptTokens: number,
590
+ completionTokens: number,
591
+ model: string
592
+ ) {
593
+ const totalTokens = promptTokens + completionTokens;
594
+
595
+ await client.usageEvents.ingest({
596
+ events: [{
597
+ event_id: `ai_${Date.now()}_${crypto.randomUUID()}`,
598
+ customer_id: customerId,
599
+ event_name: 'ai.tokens',
600
+ timestamp: new Date().toISOString(),
601
+ metadata: {
602
+ tokens: totalTokens.toString(),
603
+ prompt_tokens: promptTokens.toString(),
604
+ completion_tokens: completionTokens.toString(),
605
+ model,
606
+ }
607
+ }]
608
+ });
609
+ }
610
+
611
+ // After AI completion
612
+ await trackAIUsage('cus_abc123', 500, 1200, 'gpt-4');
613
+ ```
614
+
615
+ ### API Rate Tracking Example
616
+
617
+ ```typescript
618
+ // Middleware to track and deduct API credits
619
+ async function trackAPICredit(customerId: string, req: Request) {
620
+ await client.usageEvents.ingest({
621
+ events: [{
622
+ event_id: `api_${Date.now()}_${crypto.randomUUID()}`,
623
+ customer_id: customerId,
624
+ event_name: 'api.call',
625
+ timestamp: new Date().toISOString(),
626
+ metadata: {
627
+ endpoint: new URL(req.url).pathname,
628
+ method: req.method,
629
+ }
630
+ }]
631
+ });
632
+ }
633
+ ```
634
+
635
+ ---
636
+
637
+ ## Next.js Integration
638
+
639
+ ### Credit Balance API Route
640
+
641
+ ```typescript
642
+ // app/api/credits/balance/route.ts
643
+ import { NextRequest, NextResponse } from 'next/server';
644
+ import DodoPayments from 'dodopayments';
645
+
646
+ const client = new DodoPayments({
647
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
648
+ });
649
+
650
+ export async function GET(req: NextRequest) {
651
+ const customerId = req.nextUrl.searchParams.get('customer_id');
652
+ const creditId = req.nextUrl.searchParams.get('credit_id');
653
+
654
+ if (!customerId || !creditId) {
655
+ return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
656
+ }
657
+
658
+ try {
659
+ const balance = await client.creditEntitlements.balances.get(creditId, customerId);
660
+
661
+ return NextResponse.json({
662
+ available: balance.available_balance,
663
+ overage: balance.overage_balance,
664
+ });
665
+ } catch (error: any) {
666
+ return NextResponse.json({ error: error.message }, { status: 500 });
667
+ }
668
+ }
669
+ ```
670
+
671
+ ### Manual Credit Grant API Route
672
+
673
+ ```typescript
674
+ // app/api/credits/grant/route.ts
675
+ import { NextRequest, NextResponse } from 'next/server';
676
+ import DodoPayments from 'dodopayments';
677
+
678
+ const client = new DodoPayments({
679
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
680
+ });
681
+
682
+ export async function POST(req: NextRequest) {
683
+ const { customerId, creditId, amount, description } = await req.json();
684
+
685
+ try {
686
+ const entry = await client.creditEntitlements.balances.createLedgerEntry(
687
+ creditId,
688
+ customerId,
689
+ {
690
+ type: 'credit',
691
+ amount: amount.toString(),
692
+ description,
693
+ idempotency_key: `grant_${customerId}_${Date.now()}`,
694
+ }
695
+ );
696
+
697
+ return NextResponse.json({ success: true, balance_after: entry.balance_after });
698
+ } catch (error: any) {
699
+ return NextResponse.json({ error: error.message }, { status: 500 });
700
+ }
701
+ }
702
+ ```
703
+
704
+ ### Credit Balance Hook
705
+
706
+ ```typescript
707
+ // hooks/useCreditBalance.ts
708
+ import useSWR from 'swr';
709
+
710
+ const fetcher = (url: string) => fetch(url).then(r => r.json());
711
+
712
+ export function useCreditBalance(customerId: string, creditId: string) {
713
+ const { data, error, mutate } = useSWR(
714
+ `/api/credits/balance?customer_id=${customerId}&credit_id=${creditId}`,
715
+ fetcher,
716
+ { refreshInterval: 30000 } // Refresh every 30s
717
+ );
718
+
719
+ return {
720
+ available: data?.available,
721
+ overage: data?.overage,
722
+ isLoading: !error && !data,
723
+ isError: error,
724
+ refresh: mutate,
725
+ };
726
+ }
727
+
728
+ // Usage in component
729
+ function CreditDisplay() {
730
+ const { available, isLoading } = useCreditBalance('cus_abc123', 'cent_xxxxx');
731
+
732
+ if (isLoading) return <div>Loading...</div>;
733
+
734
+ return (
735
+ <div>
736
+ <h3>Credits Remaining</h3>
737
+ <p className="text-3xl font-bold">{available}</p>
738
+ </div>
739
+ );
740
+ }
741
+ ```
742
+
743
+ ---
744
+
745
+ ## Common Patterns
746
+
747
+ ### Credit Top-Up (One-Time Purchase)
748
+
749
+ Sell credit packs as one-time products:
750
+
751
+ ```typescript
752
+ // Product: "500 API Credit Pack" with 500 credits attached
753
+ const session = await client.checkoutSessions.create({
754
+ product_cart: [
755
+ { product_id: 'prod_credit_pack_500', quantity: 1 }
756
+ ],
757
+ customer: { email: 'customer@example.com' },
758
+ return_url: 'https://yourapp.com/credits/success',
759
+ });
760
+ ```
761
+
762
+ ### Subscription with Credits + Overage
763
+
764
+ ```typescript
765
+ // Product: Pro Plan - $49/month, 10,000 tokens included, $0.002/token overage
766
+ // Credits attached in dashboard with:
767
+ // - Credits per cycle: 10000
768
+ // - Allow overage: true
769
+ // - Price per unit: $0.002
770
+ // - Overage behavior: Bill overage at billing
771
+
772
+ const session = await client.checkoutSessions.create({
773
+ product_cart: [
774
+ { product_id: 'prod_pro_with_credits', quantity: 1 }
775
+ ],
776
+ subscription_data: { trial_period_days: 14 },
777
+ customer: { email: 'customer@example.com' },
778
+ return_url: 'https://yourapp.com/success',
779
+ });
780
+ ```
781
+
782
+ ### Access Control Based on Credits
783
+
784
+ ```typescript
785
+ // Middleware to check credit balance before allowing API access
786
+ async function requireCredits(customerId: string, creditId: string): Promise<boolean> {
787
+ try {
788
+ const balance = await client.creditEntitlements.balances.get(creditId, customerId);
789
+ const available = parseFloat(balance.available_balance);
790
+ return available > 0;
791
+ } catch {
792
+ return false;
793
+ }
794
+ }
795
+
796
+ // Express middleware
797
+ async function creditGate(req: Request, res: Response, next: Function) {
798
+ const customerId = req.headers['x-customer-id'] as string;
799
+ const hasCredits = await requireCredits(customerId, 'cent_api_credits');
800
+
801
+ if (!hasCredits) {
802
+ return res.status(402).json({
803
+ error: 'Insufficient credits',
804
+ message: 'Your credit balance is exhausted. Please upgrade your plan or purchase more credits.',
805
+ });
806
+ }
807
+
808
+ next();
809
+ }
810
+ ```
811
+
812
+ ### Promotional Credit Grants
813
+
814
+ ```typescript
815
+ // Grant promotional credits with idempotency
816
+ async function grantPromoCredits(
817
+ customerId: string,
818
+ creditId: string,
819
+ amount: number,
820
+ promoCode: string
821
+ ) {
822
+ await client.creditEntitlements.balances.createLedgerEntry(
823
+ creditId,
824
+ customerId,
825
+ {
826
+ type: 'credit',
827
+ amount: amount.toString(),
828
+ description: `Promotional credit: ${promoCode}`,
829
+ idempotency_key: `promo_${promoCode}_${customerId}`, // Prevents double-granting
830
+ }
831
+ );
832
+ }
833
+ ```
834
+
835
+ ---
836
+
837
+ ## Real-World Pricing Examples
838
+
839
+ ### AI SaaS Platform
840
+
841
+ ```
842
+ Plan | Price | Credits/Month | Overage
843
+ ----------|----------|----------------|----------
844
+ Starter | $29/mo | 10,000 tokens | $0.003/token
845
+ Pro | $99/mo | 100,000 tokens | $0.002/token
846
+ Enterprise| $499/mo | 1,000,000 tokens| $0.001/token
847
+
848
+ Credit Config:
849
+ Type: Custom Unit ("AI Tokens"), Precision: 0
850
+ Rollover: 25% max, 1-month timeframe
851
+ Overage: Bill overage at billing
852
+ Meter: ai.generation (Sum on tokens)
853
+ ```
854
+
855
+ ### API Gateway
856
+
857
+ ```
858
+ Plan | Price | Credits/Month | Overage
859
+ ----------|----------|----------------|----------
860
+ Free | $0/mo | 1,000 calls | Blocked
861
+ Developer | $19/mo | 50,000 calls | $0.001/call
862
+ Business | $99/mo | 500,000 calls | $0.0005/call
863
+
864
+ Credit Config:
865
+ Type: Custom Unit ("API Calls"), Precision: 0
866
+ Rollover: Disabled
867
+ Overage: Free=disabled, Dev+=forgive at reset
868
+ Meter: api.request (Count)
869
+ ```
870
+
871
+ ### Cloud Storage
872
+
873
+ ```
874
+ Plan | Price | Credits/Month | Overage
875
+ ----------|----------|----------------|----------
876
+ Personal | $9/mo | 100 GB-hours | $0.05/GB-hour
877
+ Team | $49/mo | 1,000 GB-hours | $0.03/GB-hour
878
+
879
+ Credit Config:
880
+ Type: Custom Unit ("GB-hours"), Precision: 2
881
+ Rollover: 50% max, carries over once
882
+ Overage: Enabled with 200% limit
883
+ Meter: storage.usage (Sum)
884
+ ```
885
+
886
+ ---
887
+
888
+ ## Credit Ledger
889
+
890
+ Every credit operation is recorded with full audit trail:
891
+
892
+ | Transaction Type | Description |
893
+ |-----------------|-------------|
894
+ | **Credit Added** | Credits granted (subscription, one-time, or API) |
895
+ | **Credit Deducted** | Credits consumed through usage or manual debit |
896
+ | **Credit Expired** | Credits expired without rollover |
897
+ | **Credit Rolled Over** | Credits carried forward to the next period |
898
+ | **Rollover Forfeited** | Rolled credits forfeited after max count reached |
899
+ | **Overage Charged** | Usage beyond credit balance with overage enabled |
900
+ | **Auto Top-Up** | Automatic credit replenishment at low balance |
901
+ | **Manual Adjustment** | Credit or debit applied manually by merchant |
902
+ | **Refund** | Credits refunded |
903
+
904
+ Each ledger entry records balance before/after, overage before/after, description, and reference to the source.
905
+
906
+ ---
907
+
908
+ ## Best Practices
909
+
910
+ ### 1. Start Simple
911
+ Begin with a single credit type and no rollover. Add complexity based on customer usage patterns.
912
+
913
+ ### 2. Use Meaningful Units
914
+ Name credits after what they represent ("API Calls", "AI Tokens") not generic terms.
915
+
916
+ ### 3. Set Low Balance Thresholds
917
+ Configure thresholds and subscribe to `credit.balance_low` to alert customers before they run out.
918
+
919
+ ### 4. Use Idempotency Keys
920
+ Always include idempotency keys for manual ledger entries to prevent double-granting:
921
+ ```typescript
922
+ idempotency_key: `promo_${promoCode}_${customerId}`
923
+ ```
924
+
925
+ ### 5. Configure Expiry Thoughtfully
926
+ Short expiry (7 days) drives urgency but may frustrate. 30–90 days is customer-friendly for most SaaS.
927
+
928
+ ### 6. Test the Full Cycle
929
+ In test mode: create credits → attach to product → purchase → send usage events → verify deduction → test expiration and rollover.
930
+
931
+ ### 7. Monitor Overage
932
+ If using "Bill overage at billing", monitor overage amounts to avoid unexpected charges for customers.
933
+
934
+ ---
935
+
936
+ ## Resources
937
+
938
+ - [Credit-Based Billing Guide](https://docs.dodopayments.com/features/credit-based-billing)
939
+ - [Credit Entitlements API](https://docs.dodopayments.com/api-reference/credit-entitlements/create-credit-entitlement)
940
+ - [Credit Webhook Events](https://docs.dodopayments.com/developer-resources/webhooks/intents/credit)
941
+ - [Usage-Based Billing](https://docs.dodopayments.com/features/usage-based-billing/introduction)
942
+ - [Subscription Integration](https://docs.dodopayments.com/developer-resources/subscription-integration-guide)