billing-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Credyt Integrate

Credyt 集成指南

Prefer the official SDKs (
@credyt/api-client
for TypeScript,
credyt-api
for Python) over hand-rolling HTTP calls — they handle auth, retries, and field mapping for you. If neither SDK suits your stack (e.g. a language other than TypeScript or Python), HTTP direct calls are also covered below. If you arrived here without running
billing-setup
first, stop and ask the user to run that skill before proceeding.
Help the user wire Credyt into their application code. This skill works with the user's actual codebase — reading their existing code and adding Credyt integration in the right places.
The full integration guide is at docs.credyt.ai/ai-integration.md. Each section below links to its dedicated docs page, which includes HTTP, TypeScript, and Python examples — consult these if you need more detail on any integration area.
Field naming: The Credyt API uses
snake_case
for all fields. The TypeScript SDK maps these to
camelCase
automatically. The Python SDK keeps
snake_case
. Code samples in the linked docs show all three.
优先使用官方SDK(TypeScript对应
@credyt/api-client
,Python对应
credyt-api
),而非手动编写HTTP调用——SDK会为您处理身份验证、重试以及字段映射。如果这两款SDK都不适合您的技术栈(例如使用TypeScript或Python之外的语言),下文也会介绍直接调用HTTP的方法。如果您还未先执行
billing-setup
,请暂停操作,先让用户运行该技能后再继续。
帮助用户将Credyt接入其应用代码。此技能可对接用户的实际代码库——读取现有代码并在合适位置添加Credyt集成逻辑。
完整集成指南请查看docs.credyt.ai/ai-integration.md。下文每个章节都链接到对应的专属文档页面,包含HTTP、TypeScript和Python示例——如果需要了解任何集成领域的详细信息,请参考这些文档。
字段命名规则:Credyt API所有字段均使用
snake_case
命名。TypeScript SDK会自动将其映射为
camelCase
,Python SDK则保留
snake_case
。链接文档中的代码示例会展示这三种格式。

Understand the codebase first

先了解代码库

Before writing any code, understand what the user has:
"Let me look at your project to understand your stack and where billing should plug in."
Check for:
  • Language and framework (Node/Express, Next.js, Python/FastAPI, etc.)
  • Authentication setup (how users sign up and log in)
  • Where the billable activities happen in their code
  • Existing environment variable patterns
在编写任何代码之前,先了解用户的现有情况:
"让我查看您的项目,了解技术栈以及计费功能的接入位置。"
检查以下内容:
  • 编程语言与框架(Node/Express、Next.js、Python/FastAPI等)
  • 身份验证设置(用户注册和登录的方式)
  • 代码中产生计费活动的位置
  • 现有的环境变量使用模式

Choose the integration approach

选择集成方式

Determine the right approach from context — only ask the user if you genuinely cannot tell.
Auto-detect (in order):
  1. Known AI platform — Lovable, Bolt, Replit, and V0 all default to TypeScript. If running in one of these, use the TypeScript SDK.
  2. Existing tech stack — check the codebase scanned above.
    package.json
    → TypeScript/Node.js SDK.
    requirements.txt
    or
    pyproject.toml
    → Python SDK.
  3. Unclear → ask: "Are you working in TypeScript/Node.js, Python, or another language?" and lead with SDK options for the first two.
Once determined, state the recommendation and give the user the option to override before writing any code:
"Based on your stack, I'll use the TypeScript SDK (
@credyt/api-client
). Let me know if you'd prefer Python or direct HTTP calls."
SDK packages:
  • TypeScript/Node.js
    @credyt/api-client
    (
    npm install @credyt/api-client
    )
  • Python
    credyt-api
    (
    pip install credyt-api
    )
  • Other language or preference for raw HTTP → direct API calls with the
    X-CREDYT-API-KEY
    header
The full SDK reference with examples for all three approaches is at docs.credyt.ai/sdk.
根据上下文确定合适的集成方式——只有在确实无法判断时才询问用户。
自动检测顺序
  1. 已知AI平台——Lovable、Bolt、Replit均默认使用TypeScript。如果在这些平台上运行,使用TypeScript SDK。
  2. 现有技术栈——参考上述扫描的代码库。存在
    package.json
    →使用TypeScript/Node.js SDK;存在
    requirements.txt
    pyproject.toml
    →使用Python SDK。
  3. 无法确定→询问:"您使用的是TypeScript/Node.js、Python还是其他语言?" 前两种优先推荐SDK选项。
确定方式后,告知用户推荐方案,并在编写代码前给予用户选择其他方式的权限:
"根据您的技术栈,我将使用TypeScript SDK
@credyt/api-client
)。如果您偏好Python或直接HTTP调用,请告知我。"
SDK包信息:
  • TypeScript/Node.js
    @credyt/api-client
    (执行
    npm install @credyt/api-client
    安装)
  • Python
    credyt-api
    (执行
    pip install credyt-api
    安装)
  • 其他语言或偏好原生HTTP → 直接调用API,需携带
    X-CREDYT-API-KEY
    请求头
包含三种方式示例的完整SDK参考文档请查看docs.credyt.ai/sdk

Integration areas

集成领域

Walk through each area. Not all will apply to every user — ask which ones they need.
逐一介绍各集成领域。并非所有领域都适用于每位用户——询问用户需要哪些功能。

1. API key setup

1. API密钥设置

The Credyt API key must be stored securely on the server side — never in code that runs in the browser.
Add
CREDYT_API_KEY
to their environment variables alongside their other secrets, then initialise the client once and reuse it across requests.
TypeScript:
typescript
import { CredytApiClient } from "@credyt/api-client";
const client = new CredytApiClient({ key: process.env.CREDYT_API_KEY! });
Python:
python
from corehttp.credentials import ServiceKeyCredential
from credytapi import CredytApiClient

client = CredytApiClient(
    credential=ServiceKeyCredential(key=os.getenv("CREDYT_API_KEY")),
)
Direct HTTP: Attach
X-CREDYT-API-KEY: <key>
to every request. Create a helper function or configured HTTP client instance that sets this header automatically.
Credyt API密钥必须安全存储在服务器端——绝不能存放在浏览器运行的代码中。
CREDYT_API_KEY
添加到环境变量中与其他密钥放在一起,然后初始化客户端实例并在所有请求中复用。
TypeScript示例:
typescript
import { CredytApiClient } from "@credyt/api-client";
const client = new CredytApiClient({ key: process.env.CREDYT_API_KEY! });
Python示例:
python
from corehttp.credentials import ServiceKeyCredential
from credytapi import CredytApiClient

client = CredytApiClient(
    credential=ServiceKeyCredential(key=os.getenv("CREDYT_API_KEY")),
)
直接HTTP调用: 为每个请求附加
X-CREDYT-API-KEY: <key>
请求头。创建一个辅助函数或配置好的HTTP客户端实例,自动设置该请求头。

2. Customer creation — docs

2. 客户创建——文档

When a new user signs up in their app, create a matching Credyt customer. Find their registration/signup handler and add customer creation after successful account creation.
Key points:
  • Use
    external_id
    to link the Credyt customer to their app's user ID
  • Subscribe the customer to the relevant products during creation
  • Store the Credyt customer ID in their database alongside the user record
  • Handle the case where the customer already exists (409/422 — look up by
    external_id
    instead)
SDK method:
client.customers.create(...)
Recurring fixed fees — pending subscriptions
If the product uses a recurring fixed fee (e.g. $20/month), the customer must pay upfront before their subscription activates. In this case the API returns a
pending
status rather than activating immediately.
Set
return_url
,
failure_url
, and
redirect_to
on the subscription so Credyt knows where to send the customer after payment:
  • return_url
    — where to send the customer after successful payment (e.g.
    https://yourapp.com/account
    )
  • failure_url
    — where to send them if payment fails (e.g.
    https://yourapp.com/callbacks/payment-failed
    )
  • redirect_to
    — set to
    "return_url"
    so the customer lands back on your site instead of staying in the Credyt billing portal (this is the default, but set it explicitly)
When the response status is
pending
:
  • Check the
    required_actions
    array for an action with
    type: "payment"
    and extract its
    redirect_url
  • Redirect the customer to that URL — Credyt will handle the payment form and route them to your
    return_url
    or
    failure_url
    automatically
  • Do not activate the user's account yet — store it as pending in your database until payment is confirmed
  • If the redirect link expires before the customer completes payment, fetch the customer by their Credyt ID to get a refreshed link
Once the customer pays, Credyt fires a
subscription.activated
webhook. Listen for this event on your backend and use it to activate the user's account.
Promotional or bundled signup credits
If the user's plan includes promotional credits (e.g. "start with $10 free") or bundled credits (e.g. 1,000 free API calls on signup), there are two ways to apply them:
  1. One-off adjustment after customer creation — credit the customer's wallet directly post-signup. Use this for simple, one-time promotional amounts. See docs.credyt.ai/advanced-topics/adjustments-charges-gifts.
  2. Entitlements — configure promotional credit as part of the product definition so it applies automatically on every new subscription. Use this for credits that are part of the standard plan offering. See docs.credyt.ai/features/product-catalog/entitlements.
Ask the user whether they want to include signup credits, and if so which approach fits their use case.
当应用中有新用户注册时,创建对应的Credyt客户。找到注册/ signup处理程序,在成功创建账户后添加客户创建逻辑。
关键点:
  • 使用
    external_id
    将Credyt客户与应用的用户ID关联
  • 在创建客户时订阅相关产品
  • 将Credyt客户ID与用户记录一起存储在数据库中
  • 处理客户已存在的情况(409/422错误——改用
    external_id
    查询)
SDK方法:
client.customers.create(...)
定期固定费用——待处理订阅
如果产品采用定期固定费用(例如每月20美元),客户必须预先支付费用,订阅才会激活。这种情况下API会返回
pending
状态,而非立即激活。
在订阅中设置
return_url
failure_url
redirect_to
,让Credyt知道支付完成后将用户导向何处:
  • return_url
    ——支付成功后用户的跳转地址(例如
    https://yourapp.com/account
  • failure_url
    ——支付失败后用户的跳转地址(例如
    https://yourapp.com/callbacks/payment-failed
  • redirect_to
    ——设置为
    "return_url"
    ,让用户支付完成后返回您的站点,而非停留在Credyt计费门户(这是默认设置,但建议显式配置)
当响应状态为
pending
时:
  • 检查
    required_actions
    数组中
    type: "payment"
    的操作,提取其
    redirect_url
  • 将用户重定向到该URL——Credyt会处理支付表单,并自动将用户导向您设置的
    return_url
    failure_url
  • 暂不激活用户账户——在数据库中将其标记为待处理,直到支付确认
  • 如果用户完成支付前重定向链接过期,通过Credyt客户ID查询客户信息获取新的链接
客户完成支付后,Credyt会触发
subscription.activated
webhook。在后端监听此事件,并用它激活用户账户。
注册赠送或捆绑信用额度
如果用户的套餐包含赠送信用额度(例如“注册即送10美元”)或捆绑信用额度(例如注册即享1000次免费API调用),有两种应用方式:
  1. 客户创建后一次性调整——在注册完成后直接为客户钱包充值。适用于简单的一次性赠送金额。查看docs.credyt.ai/advanced-topics/adjustments-charges-gifts
  2. 权益配置——将赠送信用额度配置为产品定义的一部分,使其在每次新订阅时自动应用。适用于作为标准套餐一部分的信用额度。查看docs.credyt.ai/features/product-catalog/entitlements
询问用户是否需要添加注册信用额度,以及哪种方式更符合其使用场景。

3. Usage event tracking — docs

3. 使用事件跟踪——文档

Find where the billable activities happen in their code and add event submission after each one. Each event needs:
  • A unique ID (UUID) so the same event can't be billed twice
  • The correct
    event_type
    matching the product configuration
  • A timestamp of when it happened (
    occurred_at
    )
  • Any data fields needed for pricing (volume fields, dimensions)
SDK method:
client.events.sendUsage(...)
(TS) or
client.events.send_usage(...)
(Python).
For volume-based products, the event data must include the volume field (e.g.,
total_tokens: 1500
). For dimensional products, include the dimension values (e.g.,
model: "gpt-4"
).
找到代码中产生计费活动的位置,在每次活动完成后添加事件提交逻辑。每个事件需要包含:
  • 唯一ID(UUID),避免同一事件被重复计费
  • 与产品配置匹配的正确
    event_type
  • 事件发生的时间戳(
    occurred_at
  • 定价所需的所有数据字段(数量字段、维度信息)
SDK方法: TypeScript为
client.events.sendUsage(...)
,Python为
client.events.send_usage(...)
对于基于数量的产品,事件数据必须包含数量字段(例如
total_tokens: 1500
)。 对于基于维度的产品,需包含维度值(例如
model: "gpt-4"
)。

4. Cost tracking — docs

4. 成本追踪——文档

If the user set up vendors in
/credyt:billing-setup
, add cost data to usage events. Each event can include a
costs
array with the vendor ID, the amount it cost, and the currency.
This is typically added right after the billable action completes, when the cost is known (e.g., after receiving the response from an AI API that includes token counts).
"Even if you're not charging users yet, attaching costs to every event lets Credyt calculate your unit economics so you can make pricing decisions based on real data."
如果用户在
/credyt:billing-setup
中配置了供应商,需在使用事件中添加成本数据。每个事件可包含
costs
数组,包含供应商ID、成本金额和货币类型。
通常在计费操作完成后、成本已知时添加此信息(例如在收到包含令牌数量的AI API响应后)。
"即使您尚未向用户收费,为每个事件附加成本信息也能让Credyt计算您的单位经济效益,帮助您基于真实数据制定定价策略。"

5. Balance checks — docs

5. 余额查询——文档

Before expensive operations, check the customer's wallet balance. If insufficient, block the action and prompt the user to top up.
SDK method:
client.wallets.customerWalletOps.getCustomerWallet(customerId)
to fetch the full wallet, or
client.wallets.customerWalletOps.getAccount(customerId, "accountName:ASSET")
to check a specific account balance.
Find where billable actions are initiated (API routes, button handlers, etc.) and add a balance check before the action runs. Return a clear message if the balance is too low.
Estimate the cost of the upcoming action and compare it against the available balance.
在执行高成本操作前,检查客户的钱包余额。如果余额不足,阻止操作并提示用户充值。
SDK方法: 使用
client.wallets.customerWalletOps.getCustomerWallet(customerId)
获取完整钱包信息,或使用
client.wallets.customerWalletOps.getAccount(customerId, "accountName:ASSET")
查询特定账户余额。
找到计费操作的发起位置(API路由、按钮处理程序等),在操作执行前添加余额检查逻辑。如果余额不足,返回清晰提示信息。
估算即将执行操作的成本,并与可用余额进行比较。

6. Billing portal / top-up UI — docs

6. 计费门户/充值UI——文档

Help users add funds through Credyt's billing portal. This is the simplest way to handle payments — Credyt hosts the page, handles Stripe, and redirects back to their app.
Add a "Billing" or "Add funds" link/button in their app's settings or account page. When clicked, the backend creates a billing portal session and redirects the user to the URL.
SDK method:
client.billingPortal.createPortalSession(...)
Key points:
  • Portal sessions expire after 10 minutes
  • Set
    return_url
    for where to send users after they're done
  • Set
    failure_url
    for payment failures
帮助用户通过Credyt计费门户添加资金。这是处理支付的最简单方式——Credyt托管页面、对接Stripe,并在完成后将用户重定向回您的应用。
在应用的设置页面或账户页面添加“计费”或“充值”链接/按钮。用户点击时,后端创建计费门户会话并将用户重定向到对应的URL。
SDK方法:
client.billingPortal.createPortalSession(...)
关键点:
  • 门户会话10分钟后过期
  • 设置
    return_url
    ,指定用户操作完成后的跳转地址
  • 设置
    failure_url
    ,指定支付失败后的跳转地址

7. Balance display — docs

7. 余额展示——文档

Show the user's current balance in the app UI. Fetch from the wallet endpoint and display the available amount.
SDK method:
client.wallets.customerWalletOps.getCustomerWallet(customerId)
.
Decide where this fits in their app — sidebar, header, account page — and add it there.
在应用UI中展示用户当前余额。从钱包接口获取数据并显示可用金额。
SDK方法:
client.wallets.customerWalletOps.getCustomerWallet(customerId)
确定余额展示在应用中的位置——侧边栏、页眉、账户页面等,并添加对应的展示逻辑。

Implementation approach

实施步骤

Don't dump all the code at once. Work through each area one at a time:
  1. Start with API key setup and customer creation — these are foundational
  2. Then add usage event tracking — this is the core billing integration
  3. Add balance checks to gate expensive operations
  4. Add billing portal and balance display for the user-facing pieces
  5. Add cost tracking last if applicable
After each piece, suggest they test it:
"Try creating a new account in your app and check the Credyt dashboard — you should see a new customer appear. Then we'll move on to usage tracking."
不要一次性提供所有代码。逐个领域逐步推进:
  1. 从API密钥设置和客户创建开始——这些是基础功能
  2. 然后添加使用事件跟踪——这是计费集成的核心
  3. 添加余额检查,限制高成本操作
  4. 添加计费门户和余额展示,完善用户端功能
  5. 如果适用,最后添加成本追踪
完成每个部分后,建议用户进行测试:
"尝试在您的应用中创建一个新账户,然后查看Credyt控制台——您应该能看到一个新客户。之后我们再进行使用事件跟踪的集成。"

Reference

参考资源

For detailed code examples, error handling patterns, and advanced topics (hybrid billing, refunds, auto top-up), point the user to:
如需详细代码示例、错误处理模式和高级主题(混合计费、退款、自动充值),请引导用户查看: