Skip to main content
To have your coding agent write the integration, install the Dodo Agent Plugin. It adds the Dodo Payments skills and MCP servers to Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Kiro, and OpenCode.
You’ll build NeuralAPI, a tiered AI API where each subscription plan includes a monthly allowance of token credits. Customers who run low buy a top-up pack, and your backend reports the tokens each OpenAI request uses so Dodo Payments deducts them from the customer’s balance.
This tutorial uses Node.js, Express, and the OpenAI SDK. The Dodo Payments concepts (credits, meters, and webhooks) work the same with any framework or AI provider.
When you finish, you’ll know how to:
  • Create a custom credit entitlement for tokens, and a meter that deducts from it.
  • Attach credits to subscription plans, with and without overage, and to a one-time top-up product.
  • Call OpenAI from an endpoint that bills tokens through Dodo Payments.
  • Read a customer’s live credit balance with the SDK.
  • Verify webhook signatures and route Dodo Payments credit events.

What We’re Building

NeuralAPI sells three products: Before you start, you need:
  • A Dodo Payments account. Build everything in test mode.
  • An OpenAI API key.
  • Node.js 22 or later, and working knowledge of TypeScript and Node.js.

Step 1: Create Your Token Credit Entitlement

Create the credit entitlement that both plans and the top-up pack share. It defines the token unit NeuralAPI sells.
Credits listing page showing created credit entitlements

The Credits tab under Products shows all your credit entitlements.

1

Navigate to Credits

  1. Log in to the Dodo Payments dashboard.
  2. Click Products in the sidebar.
  3. Select the Credits tab.
  4. Click Create Credit.
2

Configure the Credit Unit

Enter these values:Credit Name: API TokensCredit Type: Custom UnitUnit Name: tokenDefine Precision: 0. Token counts are whole numbers.Credit Expiry: 30 days. Credits expire 30 days after they’re issued, which matches the monthly billing cycle.
Precision can’t be changed after you create the credit. For token counts, use 0.
3

Skip Overage at the Credit Level

Leave overage disabled on the credit. You configure it per plan when you attach the credit to each product, so the Starter plan can block usage at zero while the Pro plan allows overage.
Overage settings on the credit are defaults. Each product attachment can override them, which Step 3 does for the Pro plan.
4

Save and Copy the Credit ID

Click Create Credit. Open the saved credit and copy its ID, which starts with cde_.
The API Tokens credit entitlement is ready. Next, create a meter so that usage events deduct credits.

Step 2: Create a Meter for Token Usage

A meter aggregates incoming usage events. When you link it to a credit, the aggregated usage is deducted from the customer’s credit balance. Create the meter before the plan products, because you attach it while you create them in Step 3.
1

Open the Meters Section

  1. In the dashboard sidebar, go to Products → Meters.
  2. Click Create Meter.
2

Configure the Meter

Enter these values:Meter Name: Token Usage MeterEvent Name: api.tokens_used. This must match the event_name your app sends.Aggregation Type: Sum, to add up the token count from each event.Over Property: tokens, the metadata key whose value is summed.Measurement Unit: tokens
Event names are case-sensitive: api.tokens_used and Api.Tokens.Used are different events. You can’t edit a meter after you create it, so check every value before you confirm.
Create the meter. You select it by name when you attach it to products.
The meter is created. Next, link it to the credit on each plan product.

Step 3: Create the Plan Products

Create both plans with the Usage Based Billing pricing type, not plain Subscription. Meters attach to Usage Based Billing products, and the meter is what deducts credits as customers call your API. A Usage Based Billing product still charges a recurring base fee ($29 or $99), and usage on top of it is billed in credits.
Usage Based Billing pricing configuration

Usage Based Billing pricing type with meter configuration.

Starter Plan ($29/month — 10M Tokens, No Overage)

1

Create the Starter Product

  1. Go to Products and click Add Product.
  2. Under Pricing Type, select Usage Based Billing.
  3. Enter these values:
Product Name: NeuralAPI StarterDescription: 10 million API tokens per month. Perfect for individual developers and small projects.Price: 29.00. This is the recurring base fee, charged every month even before any usage.Repeat payment every: 1 monthCurrency: USD
2

Attach the Meter

In the Select meter section, click + and add Token Usage Meter. Then configure the meter:
  1. Turn on Bill usage in credits.
  2. Select credit: API Tokens
  3. Meter units per credit: 1. Each token in an event deducts one credit.
  4. Free Threshold: 0. The free threshold applies only when a meter bills in money. When it bills in credits, every unit is deducted from the balance.
Meter with Bill usage in Credits enabled and API Tokens selected

Toggle 'Bill usage in Credits' on the meter and pick the credit entitlement.

This link is what makes incoming api.tokens_used events deduct from the customer’s balance.
3

Configure Credit Issuance for Starter

After you attach a credit-billed meter, the product shows a credit configuration section. Enter:Credits issued per billing cycle: 10000000Import Default Credit Settings: on, so the product uses the 30-day expiry from the credit entitlement.Allow Overage: off. The default from Step 1 keeps overage disabled, so Starter customers stop at zero.
Credit configuration form with per-cycle amount and overage settings

Configure credit issuance per cycle on the UBB product.

Save the product and copy its ID, which starts with pdt_.
Starter Plan: $29/month base fee, 10M tokens per cycle, blocked at zero, and deducted through the meter.

Pro Plan ($99/month — 40M Tokens, Overage Enabled)

1

Create the Pro Product

Follow the Starter flow with these values:Product Name: NeuralAPI ProDescription: 40 million API tokens per month with overage. Built for production applications.Price: 99.00Repeat payment every: 1 monthCurrency: USD
2

Attach the Meter

Configure the meter as you did for Starter: add Token Usage Meter, turn on Bill usage in credits, select API Tokens, and set Meter units per credit to 1 and Free Threshold to 0.
3

Configure Credit Issuance with Overage

Configure credit issuance, this time with overage enabled:Credits issued per billing cycle: 40000000Import Default Credit Settings: off, so you can set overage for this product.Allow Overage: onPrice Per Unit: 0.000005 USD per token. That is $0.005 per 1K tokens, or $5 per 1M tokens, which is above the plan’s effective per-token rate and discourages overage.Overage Behavior: Bill overage at billing. Overage is charged on the next invoice, and then the balance resets.Save the product and copy its ID.
Pro Plan: $99/month base fee, 40M tokens per cycle, overage at $0.005 per 1K tokens, and deducted through the meter.

Step 4: Create the Token Top-Up Pack

The top-up pack is a one-time purchase that adds 5,000,000 tokens to an existing customer’s balance.
Product pricing section with Single Payment selected

One-time pricing selected for a credit product.

1

Create a One-Time Product

  1. Go to Products and click Add Product.
  2. Under Pricing Type, select One Time.
  3. Enter these values:
Product Name: Token Top-Up PackDescription: Add 5 million tokens to your NeuralAPI balance.Price: 19.00Currency: USD
2

Attach the Token Credit

  1. In the Entitlements section, click Attach next to Credits.
  2. Select API Tokens.
  3. Set No of credits issued to 5000000.
  4. Turn off Import Default Credit Settings to override the default 30-day expiry.
  5. Set Credit Expiry to Custom and enter 365 days.
  6. Save the product.
Copy the product ID.
لماذا تكون مدة انتهاء صلاحية عمليات الشحن أطول؟ تنتهي صلاحية أرصدة الاشتراك بعد 30 يومًا لأن هذه هي دورة الفوترة. أما عملية الشحن فهي عملية شراء مسبقة الدفع: دفع العميل $19 مقدمًا ويتوقع أن تستمر الرموز لأكثر من شهر. تتوافق مدة انتهاء الصلاحية البالغة 365 يومًا مع طريقة عمل أرصدة API المدفوعة مسبقًا لدى OpenAI وAnthropic، حيث تنتهي صلاحية الأرصدة المشتراة بعد عام من الشراء، كما أنها تحد من مسؤوليتك بحيث لا يتمكن العملاء من تخزين الأرصدة إلى أجل غير محدود.
The Top-Up Pack is configured. Buying it grants 5,000,000 tokens that stay valid for 365 days.

Step 5: Build the Backend

Build the Express server. It creates subscription and top-up checkouts, calls OpenAI and bills the tokens, reads balances, and receives credit webhook events.
1

Set Up Your Project

Create a tsconfig.json:
tsconfig.json
Update package.json scripts:
package.json
2

Set Up Environment Variables

Create .env with a test mode API key from Developer → API Keys and the IDs from the previous steps:
.env
Never commit .env to version control. Add it to .gitignore before your first commit.
You fill in DODO_PAYMENTS_WEBHOOK_KEY in Step 7, after you register the webhook endpoint.
3

Implement the Server

أنشئ src/server.ts. تستدعي نقطة نهاية الإكمال نموذج OpenAI gpt-6-luna، وهو مناسب للطلبات كبيرة الحجم. تعرض علامة التبويب package.json قائمة التبعيات الكاملة:
اكتمل الجزء الخلفي: عملية دفع الاشتراك، وعملية دفع الشحن، وإكمال OpenAI مع فوترة الرموز المستندة إلى الاستخدام، وقراءة الرصيد، ومعالج webhook تم التحقق منه.
يوفر @dodopayments/ingestion-blueprints أدوات تتبع تنفذ استدعاء usageEvents.ingest نيابةً عنك، بما في ذلك استخدام LLM Blueprint، وبوابة API، وتخزين الكائنات، والتدفقات، والنطاق الزمني.
4

How Deductions Happen

لا يستدعي الخادم مطلقًا نقطة نهاية من نوع “خصم N من الأرصدة”. يتولى العداد عملية الخصم:
  1. يستدعي معالجك OpenAI ويقرأ usage.total_tokens، مثلًا 1532.
  2. تستوعب حدث استخدام واحدًا باستخدام event_name: api.tokens_used وmetadata: { tokens: 1532 }.
  3. يجمع Token Usage Meter الأحداث لكل عميل. يعالج عامل في الخلفية الأحداث الجديدة كل دقيقة.
  4. بما أن العداد يفوتر API Tokens من الرصيد عبر Bill usage in credits، تخصم Dodo Payments 1532 رصيدًا، بدءًا من المنحة التي تنتهي صلاحيتها أولًا لدى العميل (FIFO).
  5. إذا تم تمكين الاستخدام الزائد ونفد الرصيد، يتم تتبع العجز وفوترته في الفاتورة التالية.
يقتصر دور شفرتك على استيعاب الأحداث.

الخطوة 6: إضافة واجهة أمامية تجريبية

أنشئ public/index.html لاختبار كل تدفق في متصفحك. تحفظ الصفحة معرّف العميل في localStorage، ولذلك تشترك عمليات الاشتراك والتوليد والشحن في هوية واحدة، كما يحدث في تطبيق يسجل المستخدم الدخول إليه:

الخطوة 7: إعداد Webhook

تتيح لك Webhooks أن تجعل خادمك يستجيب لتغييرات الرصيد، مثل إرسال بريد إلكتروني إلى عميل أوشك رصيده على النفاد.
1

Expose Your Local Server

تحتاج Webhooks إلى عنوان URL عامًا. للتطوير المحلي، استخدم ngrok أو نفقًا آخر:
انسخ عنوان URL لإعادة التوجيه عبر HTTPS، الذي ينتهي بـ ngrok-free.app.
2

Register the Webhook in Dodo Payments

  1. في لوحة المعلومات، انتقل إلى Developer → Webhooks وانقر على Add endpoint.
  2. أدخل عنوان URL https://your-tunnel.ngrok-free.app/webhooks/dodo، باستخدام مضيف النفق الخاص بك.
  3. حدد هذه الأحداث على الأقل:
    • credit.added
    • credit.deducted
    • credit.overage_charged
  4. انقر على Create endpoint، ثم انسخ سر التوقيع من علامة التبويب Overview لنقطة النهاية.
  5. الصقه في .env باعتباره DODO_PAYMENTS_WEBHOOK_KEY، ثم أعد تشغيل npm run dev.
يتحقق dodo.webhooks.unwrap() في SDK من رؤوس webhook-id وwebhook-timestamp وwebhook-signature باستخدام سر التوقيع الخاص بك، ثم يحلل الحمولة. لا تكتب فحص HMAC الخاص بك: تتبع Dodo Payments معيار Standard Webhooks، الذي يوقّع id.timestamp.body، وليس نص الطلب وحده.

الخطوة 8: اختبار التدفق الكامل

1

Subscribe a Test Customer

  1. شغّل npm run dev.
  2. افتح http://localhost:3000.
  3. اختر Pro، وأدخل عنوان بريد إلكتروني واسمًا تجريبيين، ثم انقر على Get Checkout Link. أكمل عملية الدفع باستخدام بيانات بطاقة الاختبار.
  4. في لوحة المعلومات، انتقل إلى Customers، وافتح أحدث عميل، وانسخ معرّفه الذي يبدأ بـ cus_.
  5. الصق المعرّف في حقل Logged-in customer ID في العرض التجريبي، ثم انقر على Save.
لدى العميل 40,000,000 رمز. انقر على Refresh Balance للتأكيد.
2

Generate an AI Response

اكتب مطالبة وانقر على Generate. يستدعي الخادم OpenAI، ويقرأ total_tokens الفعلي، ويستوعب حدث استخدام، ثم يعيد الاستجابة.
يعالج عامل في الخلفية أحداث الاستخدام كل دقيقة، ولذلك لا ينخفض الرصيد فورًا. انتظر دقيقة أو دقيقتين، ثم انقر على Refresh Balance مرة أخرى. عدم تغير الرصيد عند أول تحديث لا يعني فشل القياس.
3

Test the Top-Up Flow

انقر على Buy 5M Tokens — $19 وأكمل عملية الدفع. بعد نجاح الدفع، حدّث الرصيد: سيزداد بمقدار 5,000,000 رمز، وسيعرض سجل الخادم حدثًا من نوع credit.added.

استكشاف الأخطاء وإصلاحها

الأسباب المحتملة:
  • لا يتطابق اسم حدث العداد مع event_name الذي ترسله. api.tokens_used حساس لحالة الأحرف.
  • العداد غير مرتبط برصيد API Tokens في المنتج. افتح إعدادات عداد المنتج وتأكد من تشغيل Bill usage in credits.
  • لا يتطابق مفتاح metadata.tokens مع Over Property للعداد.
  • انتهت صلاحية منحة العميل. تحقق من سجل أرصدة العميل.
ما يجب التحقق منه:
  1. في Products → Meters، افتح العداد وتأكد من أن مرفق المنتج يعرض اسم الرصيد المرتبط.
  2. افتح علامة التبويب Events للعداد. تظهر الأحداث المستوعبة هناك حتى قبل إجراء أي خصم.
  3. افتح العميل في Customers وحدد علامة التبويب Credits. تظهر إدخالات دفتر الأستاذ خلال دقيقة أو دقيقتين.
الأسباب المحتملة:
  • لم يكمل العميل عملية الدفع. لا يتم إصدار الأرصدة إلا بعد نجاح الدفع.
  • تستعلم باستخدام customer_id غير صحيح. استخدم المعرّف الذي يبدأ بـ cus_ من لوحة المعلومات، وليس معرّفًا من قاعدة بياناتك الخاصة.
  • لا يتطابق CREDIT_ENTITLEMENT_ID في .env مع الرصيد المرتبط بالمنتج.
ما يجب التحقق منه: افتح العميل في Customers وحدد علامة التبويب Credits. إذا لم تظهر أي أرصدة، فهذا يعني أن الرصيد لم يُربط بالمنتج أو أن عملية الدفع لم تكتمل.
الأسباب المحتملة:
  • لم يتم تمكين الاستخدام الزائد في مرفق رصيد منتج Pro. الإعداد الموجود على الرصيد هو مجرد إعداد افتراضي.
  • العميل مشترك في Starter وليس Pro.
  • تم تعيين Overage Limit إلى 0.
ما يجب التحقق منه: عدّل منتج Pro، وافتح الرصيد في Entitlements، وتأكد من تشغيل Allow Overage وأن قيمة Price Per Unit هي 0.000005 ($5 لكل مليون رمز). تحقق من الأصفار البادئة: يقبل الحقل سعرًا لكل رمز، وليس لكل 1K رمز.
الأسباب المحتملة:
  • ترتيب تحليل النص: تم تشغيل express.json() على /webhooks/dodo قبل express.raw(). يحتاج SDK إلى البايتات الخام للطلب، وليس JSON الذي تم تحليله.
  • يحتوي DODO_PAYMENTS_WEBHOOK_KEY على سر توقيع غير صحيح.
  • يعيد وكيل عكسي كتابة رؤوس الطلب.
ما يجب التحقق منه: تأكد من أن سطر app.use('/webhooks/dodo', express.raw(...)) يأتي قبل app.use(express.json()) في server.ts.

هل تحتاج إلى مساعدة؟

تهانينا! لقد أنشأت نظام فوترة قائمًا على الأرصدة لـ NeuralAPI

تقوم NeuralAPI الآن بالفوترة بالأرصدة بدءًا من الدفع وحتى الخصم:

Token Credit Entitlement

رصيد API Tokens قابل لإعادة الاستخدام، مع مدة انتهاء صلاحية قدرها 30 يومًا، ومشترك بين كلتا الخطتين وحزمة الشحن.

Tiered Plans, One Credit

Starter (10M رمز، حد صارم) وPro (40M رمزًا بالإضافة إلى الاستخدام الزائد)، مع إعداد كل منتج دون تكرار الرصيد.

One-Time Top-Up Pack

يضيف العملاء 5M رمز مقابل $19 دون تغيير اشتراكهم.

Deduction Through a Meter

يتم استيعاب أعداد رموز OpenAI الفعلية كأحداث، ويخصم العداد الأرصدة وفق FIFO دون تتبع يدوي.

Live Balance API

الرصيد الحالي، الذي تتم قراءته عبر SDK، للتحكم في الوصول أو عرض الاستخدام أو تحذير العملاء في تطبيقك.

Verified Webhook Pipeline

أحداث دفتر أرصدة الائتمان (credit.added، credit.deducted، credit.overage_charged) التي يتم توجيهها عبر معالج يتحقق من التوقيعات باستخدام مساعد Standard Webhooks في SDK.
هل تتجه إلى الإنتاج؟ عزز هذه الجوانب:
  • أضف المصادقة إلى /credits/:customerId و/api/generate. بصيغتهما الحالية، يمكن لأي شخص استدعاؤهما باستخدام أي معرّف عميل. صادق على المستخدمين وابحث عن معرّف العميل على الخادم.
  • استخدم قيم event_id مستقرة. يستخدم المثال Date.now() مع سلسلة عشوائية. في بيئة الإنتاج، استخدم معرّف طلبك حتى تكون عمليات إعادة المحاولة idempotent: تتجاهل Dodo Payments الحدث الذي سبق أن استوعبت قيمة event_id الخاصة به.
  • خزّن الربط بين العميل والمستخدم. احفظ customer_id في قاعدة بياناتك بعد أول عملية دفع، حتى لا يضطر المستخدمون إلى لصقه يدويًا.
  • حدد ما يحدث عند انتهاء الاشتراك. تبقى أرصدة الخطة في دفتر أستاذ العميل حتى تنتهي صلاحيتها بعد 30 يومًا من إصدارها، وتظل أرصدة الشحن صالحة لمدة 365 يومًا. يتحقق /api/generate في البرنامج التعليمي من الرصيد فقط، وليس من حالة الاشتراك، ولذلك يمكن للعميل الملغى الاستمرار في استخدام رموزه المتبقية. هذا هو الإعداد الافتراضي الملائم للعميل. ولتطبيق وصول أكثر صرامة، إما (أ) استمع إلى webhook من نوع subscription.cancelled وقيّد /api/generate بناءً على حالة الاشتراك، أو (ب) عند الإلغاء، اخصم أرصدة الخطة غير المستخدمة باستخدام Ledger API. تُخصم الديبتات من المنحة التي تنتهي صلاحيتها أولًا، ولذلك تُستخدم أرصدة الخطة ذات الصلاحية البالغة 30 يومًا قبل أرصدة الشحن ذات الصلاحية البالغة 365 يومًا.
  • راقب لوحة Usage Billing لاكتشاف حالات الخلل في القياس مبكرًا.

Credit-Based Billing Reference

التدوير، وأنماط الاستخدام الزائد، وإدارة دفتر الأستاذ، وكل نقطة نهاية لـ credit API.

Credit Webhook Events

مخططات الحمولة لكل حدث رصيد يمكن لخادمك استلامه.
آخر تعديل في ٢٦ سبتمبر ٢٠٢٦