modelslab-billing-subscriptions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ModelsLab Billing & Subscriptions

ModelsLab 账单与订阅

Manage billing, wallet funding, payment methods, subscriptions, and coupons via the Agent Control Plane API.
通过Agent Control Plane API管理账单、钱包充值、支付方式、订阅和优惠券。

When to Use This Skill

何时使用此技能

  • Check wallet balance and fund it
  • Set up auto-recharge for wallets
  • Manage payment methods (add, set default, remove)
  • Create payment links for human-assisted checkout
  • Confirm Stripe Checkout sessions (wallet funding or subscriptions)
  • View and download invoices
  • Create, upgrade, pause, or resume subscriptions
  • Validate and redeem coupons
  • Update billing information (address, tax ID)
  • 查询钱包余额并进行充值
  • 设置钱包自动充值功能
  • 管理支付方式(添加、设置默认、移除)
  • 创建支付链接供人工完成结账
  • 确认Stripe结账会话(钱包充值或订阅)
  • 查看并下载发票
  • 创建、升级、暂停或恢复订阅
  • 验证并兑换优惠券
  • 更新账单信息(地址、税号)

Authentication

身份验证

All billing endpoints require a bearer token.
Base URL: https://modelslab.com/api/agents/v1
Authorization: Bearer <agent_access_token>
Get a token via the
modelslab-account-management
skill or
POST /auth/login
.
所有账单相关接口均需要Bearer令牌。
Base URL: https://modelslab.com/api/agents/v1
Authorization: Bearer <agent_access_token>
可通过
modelslab-account-management
技能或
POST /auth/login
获取令牌。

Helper

辅助代码

python
import requests

BASE = "https://modelslab.com/api/agents/v1"

def headers(token):
    return {"Authorization": f"Bearer {token}"}
python
import requests

BASE = "https://modelslab.com/api/agents/v1"

def headers(token):
    return {"Authorization": f"Bearer {token}"}

Billing Overview

账单概览

python
def get_billing_overview(token):
    """Get billing overview — balance, active subscriptions, recent charges."""
    resp = requests.get(f"{BASE}/billing/overview", headers=headers(token))
    return resp.json()["data"]
python
def get_billing_overview(token):
    """获取账单概览——余额、活跃订阅、近期消费记录。"""
    resp = requests.get(f"{BASE}/billing/overview", headers=headers(token))
    return resp.json()["data"]

Usage

使用示例

overview = get_billing_overview(token) print(f"Wallet balance: ${overview.get('wallet_balance', 0)}")
undefined
overview = get_billing_overview(token) print(f"钱包余额: ${overview.get('wallet_balance', 0)}")
undefined

Three Payment Paths

三种支付路径

ModelsLab supports three ways for agents to handle payments:
PathBest ForFlow
HeadlessAutonomous agents with card data
GET /billing/stripe-config
-> tokenize via Stripe API -> pass
payment_method_id
to fund/subscribe
Setup IntentSave a card for reuse without immediate charge
POST /billing/setup-intent
-> confirm with Stripe -> reuse
payment_method_id
for future fund/subscribe
Human-AssistedAgents that cannot handle card data directly
POST /billing/payment-link
-> forward URL to human -> human pays on Stripe Checkout -> poll
confirm-checkout
ModelsLab支持三种供Agent处理支付的方式:
路径适用场景流程
无界面模式拥有卡片数据的自主Agent
GET /billing/stripe-config
-> 通过Stripe API生成令牌 -> 将
payment_method_id
传入充值/订阅接口
设置意向流保存卡片以便后续使用,无需立即扣费
POST /billing/setup-intent
-> 通过Stripe确认 -> 后续充值/订阅时复用
payment_method_id
人工协助模式无法直接处理卡片数据的Agent(如聊天机器人、语音助手)
POST /billing/payment-link
-> 将URL转发给人工用户 -> 用户在Stripe结账页面完成支付 -> 调用
confirm-checkout
轮询确认

Stripe Config

Stripe配置

Fetch the Stripe publishable key dynamically instead of hardcoding it. Useful for agents that need to tokenize cards client-side.
python
def get_stripe_config(token):
    """Get the Stripe publishable key for client-side card tokenization.

    Returns:
        publishable_key: Stripe publishable key (pk_...)
        instructions: Usage guidance from the API
    """
    resp = requests.get(f"{BASE}/billing/stripe-config", headers=headers(token))
    return resp.json()["data"]
动态获取Stripe公钥,而非硬编码。适用于需要在客户端生成卡片令牌的Agent。
python
def get_stripe_config(token):
    """获取Stripe公钥用于客户端卡片令牌生成。

    返回:
        publishable_key: Stripe公钥(pk_...)
        instructions: API提供的使用指南
    """
    resp = requests.get(f"{BASE}/billing/stripe-config", headers=headers(token))
    return resp.json()["data"]

Usage

使用示例

config = get_stripe_config(token) stripe_pk = config["publishable_key"] # e.g., "pk_live_..."

> **Tip:** The publishable key is safe to embed in agent code — it can only create tokens, never charge directly. You can either fetch it dynamically via this endpoint or use the hardcoded key below.
config = get_stripe_config(token) stripe_pk = config["publishable_key"] # 例如: "pk_live_..."

> **提示:** 公钥可以安全地嵌入Agent代码中——它仅能生成令牌,无法直接扣费。你可以通过此接口动态获取,也可以使用下方的硬编码密钥。

Headless Card Tokenization (Recommended)

无界面卡片令牌生成(推荐)

Agents create PaymentMethods directly via the Stripe API using the ModelsLab publishable key. Card data goes to Stripe only — ModelsLab never sees raw card numbers.
Fetch the Stripe publishable key dynamically via
GET /billing/stripe-config
. This ensures your agent always uses the current key without redeploying when it rotates.
python
import requests
Agent使用ModelsLab提供的Stripe公钥,直接通过Stripe API创建PaymentMethod。卡片数据仅会发送至Stripe——ModelsLab不会接触原始卡号。
通过
GET /billing/stripe-config
动态获取Stripe公钥,确保Agent始终使用当前有效密钥,无需在密钥轮换时重新部署。
python
import requests

Fetch publishable key from API

从API获取公钥

config_resp = requests.get( f"{BASE}/billing/stripe-config", headers={"Authorization": f"Bearer {TOKEN}"} ) STRIPE_PK = config_resp.json()["publishable_key"]
def create_payment_method(card_number, exp_month, exp_year, cvc): """Create a Stripe PaymentMethod directly — card data never touches ModelsLab.
Args:
    card_number: Card number (e.g., "4242424242424242")
    exp_month: Expiry month (e.g., 12)
    exp_year: Expiry year (e.g., 2027)
    cvc: CVC code (e.g., "123")

Returns:
    Stripe PaymentMethod ID (pm_...) for use with ModelsLab endpoints.
"""
resp = requests.post(
    "https://api.stripe.com/v1/payment_methods",
    auth=(STRIPE_PK, ""),
    data={
        "type": "card",
        "card[number]": card_number,
        "card[exp_month]": exp_month,
        "card[exp_year]": exp_year,
        "card[cvc]": cvc,
    }
)
return resp.json()["id"]  # e.g., "pm_1Xyz..."
config_resp = requests.get( f"{BASE}/billing/stripe-config", headers={"Authorization": f"Bearer {TOKEN}"} ) STRIPE_PK = config_resp.json()["publishable_key"]
def create_payment_method(card_number, exp_month, exp_year, cvc): """直接创建Stripe PaymentMethod——卡片数据不会传入ModelsLab。
参数:
    card_number: 卡号(例如: "4242424242424242")
    exp_month: 到期月份(例如: 12)
    exp_year: 到期年份(例如: 2027)
    cvc: CVC码(例如: "123")

返回:
    可用于ModelsLab接口的Stripe PaymentMethod ID(pm_...)。
"""
resp = requests.post(
    "https://api.stripe.com/v1/payment_methods",
    auth=(STRIPE_PK, ""),
    data={
        "type": "card",
        "card[number]": card_number,
        "card[exp_month]": exp_month,
        "card[exp_year]": exp_year,
        "card[cvc]": cvc,
    }
)
return resp.json()["id"]  # 例如: "pm_1Xyz..."

Usage — complete headless payment flow:

使用示例——完整无界面支付流程:

pm_id = create_payment_method("4242424242424242", 12, 2027, "123") fund_wallet(token, 25, payment_method_id=pm_id) # or create_subscription(...)
undefined
pm_id = create_payment_method("4242424242424242", 12, 2027, "123") fund_wallet(token, 25, payment_method_id=pm_id) # 或调用create_subscription(...)
undefined

Setup Intent Flow

设置意向流

Use a SetupIntent to save a card for future use without an immediate charge. The confirmed PaymentMethod can then be reused for wallet funding or subscriptions.
python
def create_setup_intent(token):
    """Create a Stripe SetupIntent to save a card for future use.

    Returns:
        client_secret: Use with Stripe.js or Stripe API to confirm the SetupIntent
        setup_intent_id: The SetupIntent ID (seti_...)
    """
    resp = requests.post(f"{BASE}/billing/setup-intent", headers=headers(token))
    return resp.json()["data"]
使用SetupIntent保存卡片以便后续使用,无需立即扣费。确认后的PaymentMethod可用于钱包充值或订阅。
python
def create_setup_intent(token):
    """创建Stripe SetupIntent以保存卡片供后续使用。

    返回:
        client_secret: 用于Stripe.js或Stripe API确认SetupIntent
        setup_intent_id: SetupIntent ID(seti_...)
    """
    resp = requests.post(f"{BASE}/billing/setup-intent", headers=headers(token))
    return resp.json()["data"]

Usage — save a card for reuse

使用示例——保存卡片以便复用

setup = create_setup_intent(token) client_secret = setup["client_secret"]
setup = create_setup_intent(token) client_secret = setup["client_secret"]

Confirm the SetupIntent via Stripe API with card details

通过Stripe API使用卡片详情确认SetupIntent

stripe_pk = get_stripe_config(token)["publishable_key"] confirm_resp = requests.post( f"https://api.stripe.com/v1/setup_intents/{setup['setup_intent_id']}/confirm", auth=(stripe_pk, ""), data={ "payment_method_data[type]": "card", "payment_method_data[card][number]": "4242424242424242", "payment_method_data[card][exp_month]": 12, "payment_method_data[card][exp_year]": 2027, "payment_method_data[card][cvc]": "123", } ) pm_id = confirm_resp.json()["payment_method"] # e.g., "pm_..."
stripe_pk = get_stripe_config(token)["publishable_key"] confirm_resp = requests.post( f"https://api.stripe.com/v1/setup_intents/{setup['setup_intent_id']}/confirm", auth=(stripe_pk, ""), data={ "payment_method_data[type]": "card", "payment_method_data[card][number]": "4242424242424242", "payment_method_data[card][exp_month]": 12, "payment_method_data[card][exp_year]": 2027, "payment_method_data[card][cvc]": "123", } ) pm_id = confirm_resp.json()["payment_method"] # 例如: "pm_..."

Now attach and reuse the payment method

现在绑定并复用该支付方式

add_payment_method(token, pm_id, make_default=True) fund_wallet(token, 50, payment_method_id=pm_id)
undefined
add_payment_method(token, pm_id, make_default=True) fund_wallet(token, 50, payment_method_id=pm_id)
undefined

Human-Assisted Payment (Payment Links)

人工协助支付(支付链接)

For agents that cannot handle card data directly (e.g., chatbots, voice assistants), create a Stripe-hosted payment URL and forward it to a human user. ModelsLab controls the
success_url
— agents cannot override it.
python
def create_payment_link(token, purpose, amount=None, plan_id=None):
    """Create a Stripe-hosted payment URL for a human to complete.

    Args:
        purpose: "fund" for wallet funding, "subscribe" for subscription
        amount: Required if purpose is "fund" — amount in USD (min $10)
        plan_id: Required if purpose is "subscribe" — plan ID from list_plans()

    Returns:
        payment_url: Stripe Checkout URL to forward to the human
        session_id: Checkout session ID (cs_...) for confirming later
        purpose: Echoed back
        amount: Echoed back (for fund)
        expires_at: When the payment link expires
        instructions: Guidance for the agent

    Note:
        success_url is NOT accepted — ModelsLab controls redirects.
        After payment, the human sees ModelsLab's success page with the session_id
        to copy back to the agent.
    """
    payload = {"purpose": purpose}
    if amount is not None:
        payload["amount"] = amount
    if plan_id is not None:
        payload["plan_id"] = plan_id

    resp = requests.post(
        f"{BASE}/billing/payment-link",
        headers=headers(token),
        json=payload
    )
    return resp.json()["data"]
对于无法直接处理卡片数据的Agent(如聊天机器人、语音助手),可创建Stripe托管的支付URL并转发给人工用户。ModelsLab会控制
success_url
——Agent无法修改该参数。
python
def create_payment_link(token, purpose, amount=None, plan_id=None):
    """创建Stripe托管的支付URL,供人工用户完成支付。

    参数:
        purpose: "fund"表示钱包充值,"subscribe"表示订阅
        amount: 当purpose为"fund"时必填——美元金额(最低10美元)
        plan_id: 当purpose为"subscribe"时必填——来自list_plans()的套餐ID

    返回:
        payment_url: 需转发给用户的Stripe结账URL
        session_id: 用于后续确认的结账会话ID(cs_...)
        purpose: 原样返回的用途参数
        amount: 原样返回的金额(仅充值场景)
        expires_at: 支付链接的过期时间
        instructions: 给Agent的操作指南

    注意:
        不接受success_url参数——ModelsLab控制跳转地址。
        支付完成后,用户会看到ModelsLab的成功页面,上面有需要复制给Agent的session_id
    """
    payload = {"purpose": purpose}
    if amount is not None:
        payload["amount"] = amount
    if plan_id is not None:
        payload["plan_id"] = plan_id

    resp = requests.post(
        f"{BASE}/billing/payment-link",
        headers=headers(token),
        json=payload
    )
    return resp.json()["data"]

Usage — wallet funding via human

使用示例——人工协助钱包充值

link = create_payment_link(token, purpose="fund", amount=50) print(f"Please complete payment at: {link['payment_url']}") print(f"Session ID: {link['session_id']} (expires {link['expires_at']})")
link = create_payment_link(token, purpose="fund", amount=50) print(f"请在此完成支付: {link['payment_url']}") print(f"会话ID: {link['session_id']}(过期时间 {link['expires_at']})")

Usage — subscription via human

使用示例——人工协助订阅

plans = list_plans(token) chosen_plan = plans["subscription_plans"][0] link = create_payment_link(token, purpose="subscribe", plan_id=chosen_plan["id"]) print(f"Please subscribe at: {link['payment_url']}")
undefined
plans = list_plans(token) chosen_plan = plans["subscription_plans"][0] link = create_payment_link(token, purpose="subscribe", plan_id=chosen_plan["id"]) print(f"请在此完成订阅: {link['payment_url']}")
undefined

Confirming Checkout Sessions

确认结账会话

After the human completes payment on the Stripe Checkout page, confirm the session to finalize the transaction. Use the
session_id
from
create_payment_link()
or from the human after they see the success page.
python
def confirm_wallet_checkout(token, session_id):
    """Confirm a Stripe Checkout session for wallet funding.

    Call this after the human completes payment on the Stripe Checkout page.

    Args:
        session_id: The Checkout session ID (cs_...) from create_payment_link()
    """
    resp = requests.post(
        f"{BASE}/wallet/confirm-checkout",
        headers=headers(token),
        json={"session_id": session_id}
    )
    return resp.json()["data"]

def confirm_subscription_checkout(token, session_id):
    """Confirm a Stripe Checkout session for subscription.

    Call this after the human completes payment on the Stripe Checkout page.

    Args:
        session_id: The Checkout session ID (cs_...) from create_payment_link()
    """
    resp = requests.post(
        f"{BASE}/subscriptions/confirm-checkout",
        headers=headers(token),
        json={"session_id": session_id}
    )
    return resp.json()["data"]
用户在Stripe结账页面完成支付后,需确认会话以完成交易。使用
create_payment_link()
返回的
session_id
,或用户从成功页面复制的会话ID。
python
def confirm_wallet_checkout(token, session_id):
    """确认钱包充值的Stripe结账会话。

    用户在Stripe结账页面完成支付后调用此接口。

    参数:
        session_id: 来自create_payment_link()的结账会话ID(cs_...)
    """
    resp = requests.post(
        f"{BASE}/wallet/confirm-checkout",
        headers=headers(token),
        json={"session_id": session_id}
    )
    return resp.json()["data"]

def confirm_subscription_checkout(token, session_id):
    """确认订阅的Stripe结账会话。

    用户在Stripe结账页面完成支付后调用此接口。

    参数:
        session_id: 来自create_payment_link()的结账会话ID(cs_...)
    """
    resp = requests.post(
        f"{BASE}/subscriptions/confirm-checkout",
        headers=headers(token),
        json={"session_id": session_id}
    )
    return resp.json()["data"]

Usage — complete human-assisted wallet funding flow

使用示例——完成人工协助钱包充值流程

link = create_payment_link(token, purpose="fund", amount=50) print(f"Pay here: {link['payment_url']}")
link = create_payment_link(token, purpose="fund", amount=50) print(f"请在此支付: {link['payment_url']}")

... human pays ...

... 用户完成支付 ...

session_id = link["session_id"] # or human copies it from success page result = confirm_wallet_checkout(token, session_id) print(f"Wallet funded! New balance: ${result.get('balance')}")
session_id = link["session_id"] # 或用户从成功页面复制的会话ID result = confirm_wallet_checkout(token, session_id) print(f"钱包充值成功! 新余额: ${result.get('balance')}")

Usage — complete human-assisted subscription flow

使用示例——完成人工协助订阅流程

link = create_payment_link(token, purpose="subscribe", plan_id=42) print(f"Subscribe here: {link['payment_url']}")
link = create_payment_link(token, purpose="subscribe", plan_id=42) print(f"请在此完成订阅: {link['payment_url']}")

... human pays ...

... 用户完成支付 ...

result = confirm_subscription_checkout(token, link["session_id"]) print(f"Subscription active! Status: {result.get('status')}")
undefined
result = confirm_subscription_checkout(token, link["session_id"]) print(f"订阅已激活! 状态: {result.get('status')}")
undefined

Payment Methods

支付方式

List Payment Methods

列出支付方式

python
def list_payment_methods(token):
    """List all saved payment methods."""
    resp = requests.get(f"{BASE}/billing/payment-methods", headers=headers(token))
    return resp.json()["data"]
python
def list_payment_methods(token):
    """列出所有已保存的支付方式。"""
    resp = requests.get(f"{BASE}/billing/payment-methods", headers=headers(token))
    return resp.json()["data"]

Add Payment Method

添加支付方式

python
def add_payment_method(token, payment_method_id, make_default=True):
    """Add a Stripe payment method.

    Args:
        payment_method_id: Stripe PaymentMethod ID (pm_...)
        make_default: Set as default payment method
    """
    resp = requests.post(
        f"{BASE}/billing/payment-methods",
        headers=headers(token),
        json={
            "payment_method_id": payment_method_id,
            "make_default": make_default
        }
    )
    return resp.json()["data"]
python
def add_payment_method(token, payment_method_id, make_default=True):
    """添加Stripe支付方式。

    参数:
        payment_method_id: Stripe PaymentMethod ID(pm_...)
        make_default: 是否设置为默认支付方式
    """
    resp = requests.post(
        f"{BASE}/billing/payment-methods",
        headers=headers(token),
        json={
            "payment_method_id": payment_method_id,
            "make_default": make_default
        }
    )
    return resp.json()["data"]

Set Default & Remove

设置默认与移除

python
def set_default_payment_method(token, payment_method_id):
    """Set a payment method as the default."""
    requests.put(
        f"{BASE}/billing/payment-methods/{payment_method_id}/default",
        headers=headers(token)
    )

def remove_payment_method(token, payment_method_id):
    """Remove a payment method."""
    requests.delete(
        f"{BASE}/billing/payment-methods/{payment_method_id}",
        headers=headers(token)
    )
python
def set_default_payment_method(token, payment_method_id):
    """将指定支付方式设置为默认。"""
    requests.put(
        f"{BASE}/billing/payment-methods/{payment_method_id}/default",
        headers=headers(token)
    )

def remove_payment_method(token, payment_method_id):
    """移除指定支付方式。"""
    requests.delete(
        f"{BASE}/billing/payment-methods/{payment_method_id}",
        headers=headers(token)
    )

Billing Info

账单信息

python
def get_billing_info(token):
    """Get billing name, address, and tax ID."""
    resp = requests.get(f"{BASE}/billing/info", headers=headers(token))
    return resp.json()["data"]

def update_billing_info(token, **kwargs):
    """Update billing information.

    Kwargs: name, email, tax_id, tax_id_type,
            address_line1, address_line2, address_city,
            address_state, address_postal_code, address_country
    """
    resp = requests.put(
        f"{BASE}/billing/info",
        headers=headers(token),
        json=kwargs
    )
    return resp.json()["data"]
python
def get_billing_info(token):
    """获取账单姓名、地址和税号。"""
    resp = requests.get(f"{BASE}/billing/info", headers=headers(token))
    return resp.json()["data"]

def update_billing_info(token, **kwargs):
    """更新账单信息。

    关键字参数: name, email, tax_id, tax_id_type,
            address_line1, address_line2, address_city,
            address_state, address_postal_code, address_country
    """
    resp = requests.put(
        f"{BASE}/billing/info",
        headers=headers(token),
        json=kwargs
    )
    return resp.json()["data"]

Usage

使用示例

update_billing_info( token, name="Acme Corp", email="billing@acme.com", tax_id="EU123456789", tax_id_type="eu_vat", address_line1="123 AI Street", address_city="San Francisco", address_state="CA", address_postal_code="94105", address_country="US" )
undefined
update_billing_info( token, name="Acme Corp", email="billing@acme.com", tax_id="EU123456789", tax_id_type="eu_vat", address_line1="123 AI Street", address_city="San Francisco", address_state="CA", address_postal_code="94105", address_country="US" )
undefined

Invoices

发票

python
def list_invoices(token):
    """List all invoices."""
    resp = requests.get(f"{BASE}/billing/invoices", headers=headers(token))
    return resp.json()["data"]

def get_invoice(token, invoice_id):
    """Get invoice details."""
    resp = requests.get(
        f"{BASE}/billing/invoices/{invoice_id}",
        headers=headers(token)
    )
    return resp.json()["data"]

def get_invoice_pdf(token, invoice_id):
    """Get invoice PDF download URL."""
    resp = requests.get(
        f"{BASE}/billing/invoices/{invoice_id}/pdf",
        headers=headers(token)
    )
    return resp.json()["data"]
python
def list_invoices(token):
    """列出所有发票。"""
    resp = requests.get(f"{BASE}/billing/invoices", headers=headers(token))
    return resp.json()["data"]

def get_invoice(token, invoice_id):
    """获取发票详情。"""
    resp = requests.get(
        f"{BASE}/billing/invoices/{invoice_id}",
        headers=headers(token)
    )
    return resp.json()["data"]

def get_invoice_pdf(token, invoice_id):
    """获取发票PDF下载链接。"""
    resp = requests.get(
        f"{BASE}/billing/invoices/{invoice_id}/pdf",
        headers=headers(token)
    )
    return resp.json()["data"]

Wallet

钱包

Wallet Balance

钱包余额

python
def get_wallet_balance(token):
    """Quick wallet balance check."""
    resp = requests.get(f"{BASE}/wallet/balance", headers=headers(token))
    return resp.json()["data"]
python
def get_wallet_balance(token):
    """快速查询钱包余额。"""
    resp = requests.get(f"{BASE}/wallet/balance", headers=headers(token))
    return resp.json()["data"]

Usage

使用示例

balance = get_wallet_balance(token) print(f"Balance: ${balance['balance']} {balance['currency']}")
undefined
balance = get_wallet_balance(token) print(f"余额: ${balance['balance']} {balance['currency']}")
undefined

Wallet Transactions

钱包交易记录

python
def get_wallet_transactions(token, type=None, limit=50, offset=0):
    """Get wallet transaction ledger (deposits, charges, refunds).

    Args:
        type: Filter by "credit" or "debit" (optional)
        limit: Max items 1-200 (default 50)
        offset: Pagination offset (default 0)
    """
    params = {"limit": limit, "offset": offset}
    if type: params["type"] = type

    resp = requests.get(
        f"{BASE}/wallet/transactions",
        headers=headers(token),
        params=params
    )
    return resp.json()["data"]
python
def get_wallet_transactions(token, type=None, limit=50, offset=0):
    """获取钱包交易明细(充值、消费、退款)。

    参数:
        type: 按"credit"(入账)或"debit"(出账)筛选(可选)
        limit: 最大条目数1-200(默认50)
        offset: 分页偏移量(默认0)
    """
    params = {"limit": limit, "offset": offset}
    if type: params["type"] = type

    resp = requests.get(
        f"{BASE}/wallet/transactions",
        headers=headers(token),
        params=params
    )
    return resp.json()["data"]

Usage

使用示例

txns = get_wallet_transactions(token, type="debit", limit=20) for txn in txns["items"]: print(f"{txn['created_at']}: {txn['type']} ${txn['amount']} — {txn['usecase']}") print(f"Wallet balance: ${txns['wallet']['balance']}")
undefined
txns = get_wallet_transactions(token, type="debit", limit=20) for txn in txns["items"]: print(f"{txn['created_at']}: {txn['type']} ${txn['amount']} — {txn['usecase']}") print(f"钱包余额: ${txns['wallet']['balance']}")
undefined

Fund Wallet

钱包充值

python
def fund_wallet(token, amount, payment_method_id=None, idempotency_key=None):
    """Add funds to wallet.

    Args:
        amount: Amount in USD (min $10)
        payment_method_id: Stripe PM ID from create_payment_method() (recommended)
        idempotency_key: Prevent duplicate charges on retries (optional)
    """
    payload = {"amount": amount}
    if payment_method_id:
        payload["payment_method_id"] = payment_method_id

    h = headers(token)
    if idempotency_key:
        h["Idempotency-Key"] = idempotency_key

    resp = requests.post(f"{BASE}/wallet/fund", headers=h, json=payload)
    return resp.json()["data"]
python
def fund_wallet(token, amount, payment_method_id=None, idempotency_key=None):
    """为钱包充值。

    参数:
        amount: 美元金额(最低10美元)
        payment_method_id: 来自create_payment_method()的Stripe PM ID(推荐)
        idempotency_key: 重试时防止重复扣费的幂等键(可选)
    """
    payload = {"amount": amount}
    if payment_method_id:
        payload["payment_method_id"] = payment_method_id

    h = headers(token)
    if idempotency_key:
        h["Idempotency-Key"] = idempotency_key

    resp = requests.post(f"{BASE}/wallet/fund", headers=h, json=payload)
    return resp.json()["data"]

Usage — headless payment flow

使用示例——无界面支付流程

pm_id = create_payment_method("4242424242424242", 12, 2027, "123") fund_wallet(token, 50, payment_method_id=pm_id, idempotency_key="fund-50-20260220")
undefined
pm_id = create_payment_method("4242424242424242", 12, 2027, "123") fund_wallet(token, 50, payment_method_id=pm_id, idempotency_key="fund-50-20260220")
undefined

Check Payment Status

支付状态查询

python
def get_payment_status(token, payment_intent_id):
    """Check the status of a Stripe PaymentIntent."""
    resp = requests.get(
        f"{BASE}/payments/{payment_intent_id}/status",
        headers=headers(token)
    )
    return resp.json()["data"]
python
def get_payment_status(token, payment_intent_id):
    """查询Stripe PaymentIntent的状态。"""
    resp = requests.get(
        f"{BASE}/payments/{payment_intent_id}/status",
        headers=headers(token)
    )
    return resp.json()["data"]

Usage

使用示例

status = get_payment_status(token, "pi_xxx") print(f"Payment status: {status['status']}")
undefined
status = get_payment_status(token, "pi_xxx") print(f"支付状态: {status['status']}")
undefined

Auto-Recharge

自动充值

python
def enable_auto_funding(token, auto_charge_amount, charge_threshold):
    """Enable automatic wallet recharge.

    Args:
        auto_charge_amount: Amount to charge (min $5)
        charge_threshold: Balance threshold to trigger charge (min $1)
    """
    resp = requests.put(
        f"{BASE}/wallet/auto-funding",
        headers=headers(token),
        json={
            "auto_charge_amount": auto_charge_amount,
            "charge_threshold": charge_threshold
        }
    )
    return resp.json()["data"]

def disable_auto_funding(token):
    """Disable automatic wallet recharge."""
    requests.delete(f"{BASE}/wallet/auto-funding", headers=headers(token))
python
def enable_auto_funding(token, auto_charge_amount, charge_threshold):
    """启用钱包自动充值功能。

    参数:
        auto_charge_amount: 充值金额(最低5美元)
        charge_threshold: 触发充值的余额阈值(最低1美元)
    """
    resp = requests.put(
        f"{BASE}/wallet/auto-funding",
        headers=headers(token),
        json={
            "auto_charge_amount": auto_charge_amount,
            "charge_threshold": charge_threshold
        }
    )
    return resp.json()["data"]

def disable_auto_funding(token):
    """禁用钱包自动充值功能。"""
    requests.delete(f"{BASE}/wallet/auto-funding", headers=headers(token))

Usage — auto-charge $25 when balance drops below $5

使用示例——当余额低于5美元时自动充值25美元

enable_auto_funding(token, auto_charge_amount=25, charge_threshold=5)
undefined
enable_auto_funding(token, auto_charge_amount=25, charge_threshold=5)
undefined

Withdraw

提现

python
def withdraw(token, amount):
    """Withdraw from wallet balance."""
    resp = requests.post(
        f"{BASE}/wallet/withdraw",
        headers=headers(token),
        json={"amount": amount}
    )
    return resp.json()["data"]
python
def withdraw(token, amount):
    """从钱包余额提现。"""
    resp = requests.post(
        f"{BASE}/wallet/withdraw",
        headers=headers(token),
        json={"amount": amount}
    )
    return resp.json()["data"]

Coupons

优惠券

python
def validate_coupon(token, coupon_code, purchase_amount=None):
    """Validate a coupon code before redeeming (GET request)."""
    params = {"coupon_code": coupon_code}
    if purchase_amount:
        params["purchase_amount"] = purchase_amount

    resp = requests.get(
        f"{BASE}/wallet/coupons/validate",
        headers=headers(token),
        params=params
    )
    return resp.json()["data"]

def redeem_coupon(token, coupon_code, payment_method_id=None, purchase_amount=None):
    """Redeem a coupon code."""
    payload = {"coupon_code": coupon_code}
    if payment_method_id:
        payload["payment_method_id"] = payment_method_id
    if purchase_amount:
        payload["purchase_amount"] = purchase_amount

    resp = requests.post(
        f"{BASE}/wallet/coupons/redeem",
        headers=headers(token),
        json=payload
    )
    return resp.json()["data"]
python
def validate_coupon(token, coupon_code, purchase_amount=None):
    """兑换前验证优惠券代码(GET请求)。"""
    params = {"coupon_code": coupon_code}
    if purchase_amount:
        params["purchase_amount"] = purchase_amount

    resp = requests.get(
        f"{BASE}/wallet/coupons/validate",
        headers=headers(token),
        params=params
    )
    return resp.json()["data"]

def redeem_coupon(token, coupon_code, payment_method_id=None, purchase_amount=None):
    """兑换优惠券代码。"""
    payload = {"coupon_code": coupon_code}
    if payment_method_id:
        payload["payment_method_id"] = payment_method_id
    if purchase_amount:
        payload["purchase_amount"] = purchase_amount

    resp = requests.post(
        f"{BASE}/wallet/coupons/redeem",
        headers=headers(token),
        json=payload
    )
    return resp.json()["data"]

Usage

使用示例

info = validate_coupon(token, "WELCOME50") if not info.get("error"): redeem_coupon(token, "WELCOME50")
undefined
info = validate_coupon(token, "WELCOME50") if not info.get("error"): redeem_coupon(token, "WELCOME50")
undefined

Subscriptions

订阅

Discover Available Plans

查看可用套餐

Before creating a subscription, discover available plans and pay-as-you-go options:
python
def list_plans(token):
    """List all available subscription plans and pay-as-you-go options.

    Returns:
        subscription_plans: Array of plans with id, name, price, features
        pay_as_you_go: Info about wallet-based billing (min $10 topup, auto-payments)
    """
    resp = requests.get(f"{BASE}/subscriptions/plans", headers=headers(token))
    return resp.json()["data"]
创建订阅前,先查看可用的订阅套餐和按需付费选项:
python
def list_plans(token):
    """列出所有可用的订阅套餐和按需付费选项。

    返回:
        subscription_plans: 包含id、名称、价格、功能的套餐数组
        pay_as_you_go: 基于钱包的计费信息(最低10美元充值,自动扣费)
    """
    resp = requests.get(f"{BASE}/subscriptions/plans", headers=headers(token))
    return resp.json()["data"]

Usage

使用示例

plans_data = list_plans(token)
plans_data = list_plans(token)

Show subscription plans

显示订阅套餐

for plan in plans_data["subscription_plans"]: print(f"{plan['name']} - ${plan['price']}/{plan['period']} (ID: {plan['id']})") print(f" Features: {', '.join(plan['features'])}")
for plan in plans_data["subscription_plans"]: print(f"{plan['name']} - ${plan['price']}/{plan['period']}(ID: {plan['id']})") print(f" 功能: {', '.join(plan['features'])}")

Show pay-as-you-go option

显示按需付费选项

payg = plans_data["pay_as_you_go"] if payg["available"]: print(f"\nPay-as-you-go: min ${payg['minimum_topup_usd']} topup") print(f"Auto-payments: {payg['auto_payments']['supported']}")
undefined
payg = plans_data["pay_as_you_go"] if payg["available"]: print(f"\n按需付费: 最低充值{payg['minimum_topup_usd']}美元") print(f"自动扣费: {payg['auto_payments']['supported']}")
undefined

List Subscriptions

列出订阅

python
def list_subscriptions(token):
    """List all active subscriptions."""
    resp = requests.get(f"{BASE}/subscriptions", headers=headers(token))
    return resp.json()["data"]
python
def list_subscriptions(token):
    """列出所有活跃订阅。"""
    resp = requests.get(f"{BASE}/subscriptions", headers=headers(token))
    return resp.json()["data"]

Create Subscription

创建订阅

python
def create_subscription(token, plan_id, success_url=None):
    """Start a new subscription. Returns a Stripe checkout URL.

    Use list_plans() first to discover valid plan IDs.

    Args:
        plan_id: The plan ID from list_plans() response
        success_url: Redirect after successful checkout
    """
    payload = {"plan_id": plan_id}
    if success_url: payload["success_url"] = success_url

    resp = requests.post(
        f"{BASE}/subscriptions",
        headers=headers(token),
        json=payload
    )
    return resp.json()["data"]
python
def create_subscription(token, plan_id, success_url=None):
    """创建新订阅,返回Stripe结账URL。

    请先调用list_plans()获取有效的套餐ID。

    参数:
        plan_id: list_plans()返回的套餐ID
        success_url: 结账成功后的跳转地址
    """
    payload = {"plan_id": plan_id}
    if success_url: payload["success_url"] = success_url

    resp = requests.post(
        f"{BASE}/subscriptions",
        headers=headers(token),
        json=payload
    )
    return resp.json()["data"]

Usage — discover plans, then subscribe

使用示例——先查看套餐,再创建订阅

plans = list_plans(token) chosen_plan = plans["subscription_plans"][0] # Pick a plan result = create_subscription(token, chosen_plan["id"]) print(f"Checkout URL: {result['checkout_url']}")
undefined
plans = list_plans(token) chosen_plan = plans["subscription_plans"][0] # 选择一个套餐 result = create_subscription(token, chosen_plan["id"]) print(f"结账URL: {result['checkout_url']}")
undefined

Create Subscription (Headless — Recommended)

创建订阅(无界面模式——推荐)

Subscribe headlessly with a
payment_method_id
from the Stripe API. No Checkout redirect needed.
python
def create_subscription_headless(token, plan_id, payment_method_id, idempotency_key=None):
    """Create a subscription headlessly with a Stripe PaymentMethod.

    No browser redirect — fully headless.
    Use list_plans() first to discover valid plan IDs.
    Use create_payment_method() to get a pm_id from Stripe.

    Args:
        plan_id: The plan ID from list_plans() response
        payment_method_id: Stripe PM ID from create_payment_method()
        idempotency_key: Prevent duplicate subscriptions on retries (optional)
    """
    h = headers(token)
    if idempotency_key:
        h["Idempotency-Key"] = idempotency_key

    resp = requests.post(
        f"{BASE}/subscriptions",
        headers=h,
        json={
            "plan_id": plan_id,
            "payment_method_id": payment_method_id
        }
    )
    return resp.json()["data"]
使用从Stripe API获取的
payment_method_id
无界面创建订阅,无需跳转结账页面。
python
def create_subscription_headless(token, plan_id, payment_method_id, idempotency_key=None):
    """使用Stripe PaymentMethod无界面创建订阅。

    无需浏览器跳转——完全无界面。
    请先调用list_plans()获取有效的套餐ID。
    请先调用create_payment_method()从Stripe获取pm_id。

    参数:
        plan_id: list_plans()返回的套餐ID
        payment_method_id: 来自create_payment_method()的Stripe PM ID
        idempotency_key: 重试时防止重复创建订阅的幂等键(可选)
    """
    h = headers(token)
    if idempotency_key:
        h["Idempotency-Key"] = idempotency_key

    resp = requests.post(
        f"{BASE}/subscriptions",
        headers=h,
        json={
            "plan_id": plan_id,
            "payment_method_id": payment_method_id
        }
    )
    return resp.json()["data"]

Usage — full headless flow

使用示例——完整无界面流程

pm_id = create_payment_method("4242424242424242", 12, 2027, "123") plans = list_plans(token) chosen_plan = plans["subscription_plans"][0] result = create_subscription_headless(token, chosen_plan["id"], pm_id) print(f"Status: {result['status']}")
undefined
pm_id = create_payment_method("4242424242424242", 12, 2027, "123") plans = list_plans(token) chosen_plan = plans["subscription_plans"][0] result = create_subscription_headless(token, chosen_plan["id"], pm_id) print(f"状态: {result['status']}")
undefined

Check Subscription Status

查询订阅状态

python
def get_subscription_status(token, subscription_id):
    """Check the current status of a subscription."""
    resp = requests.get(
        f"{BASE}/subscriptions/{subscription_id}/status",
        headers=headers(token)
    )
    return resp.json()["data"]
python
def get_subscription_status(token, subscription_id):
    """查询订阅当前状态。"""
    resp = requests.get(
        f"{BASE}/subscriptions/{subscription_id}/status",
        headers=headers(token)
    )
    return resp.json()["data"]

Update (Upgrade/Downgrade)

更新(升级/降级)

python
def update_subscription(token, subscription_id, new_plan_id):
    """Change a subscription to a different plan."""
    resp = requests.put(
        f"{BASE}/subscriptions/{subscription_id}",
        headers=headers(token),
        json={"new_plan_id": new_plan_id}
    )
    return resp.json()["data"]
python
def update_subscription(token, subscription_id, new_plan_id):
    """将订阅更换为其他套餐。"""
    resp = requests.put(
        f"{BASE}/subscriptions/{subscription_id}",
        headers=headers(token),
        json={"new_plan_id": new_plan_id}
    )
    return resp.json()["data"]

Pause & Resume

暂停与恢复

python
def pause_subscription(token, subscription_id):
    """Pause a subscription."""
    resp = requests.post(
        f"{BASE}/subscriptions/{subscription_id}/pause",
        headers=headers(token)
    )
    return resp.json()["data"]

def resume_subscription(token, subscription_id):
    """Resume a paused subscription."""
    resp = requests.post(
        f"{BASE}/subscriptions/{subscription_id}/resume",
        headers=headers(token)
    )
    return resp.json()["data"]
python
def pause_subscription(token, subscription_id):
    """暂停订阅。"""
    resp = requests.post(
        f"{BASE}/subscriptions/{subscription_id}/pause",
        headers=headers(token)
    )
    return resp.json()["data"]

def resume_subscription(token, subscription_id):
    """恢复已暂停的订阅。"""
    resp = requests.post(
        f"{BASE}/subscriptions/{subscription_id}/resume",
        headers=headers(token)
    )
    return resp.json()["data"]

Other Subscription Actions

其他订阅操作

python
def reset_subscription_cycle(token, subscription_id):
    """Reset the current billing cycle."""
    requests.post(
        f"{BASE}/subscriptions/{subscription_id}/reset-cycle",
        headers=headers(token)
    )

def charge_subscription_amount(token, amount):
    """Charge a custom amount ($5-$10,000)."""
    resp = requests.post(
        f"{BASE}/subscriptions/charge-amount",
        headers=headers(token),
        json={"amount": amount}
    )
    return resp.json()["data"]

def fix_payment(token, subscription_id):
    """Fix a failed subscription payment."""
    requests.post(
        f"{BASE}/subscriptions/{subscription_id}/fix-payment",
        headers=headers(token)
    )
python
def reset_subscription_cycle(token, subscription_id):
    """重置当前计费周期。"""
    requests.post(
        f"{BASE}/subscriptions/{subscription_id}/reset-cycle",
        headers=headers(token)
    )

def charge_subscription_amount(token, amount):
    """收取自定义金额(5-10000美元)。"""
    resp = requests.post(
        f"{BASE}/subscriptions/charge-amount",
        headers=headers(token),
        json={"amount": amount}
    )
    return resp.json()["data"]

def fix_payment(token, subscription_id):
    """修复订阅支付失败问题。"""
    requests.post(
        f"{BASE}/subscriptions/{subscription_id}/fix-payment",
        headers=headers(token)
    )

Common Workflow: Ensure Funded Account

常见工作流:确保账户余额充足

python
def ensure_account_funded(token, min_balance=10, top_up_amount=50):
    """Check wallet balance and fund if low."""
    overview = get_billing_overview(token)
    balance = overview.get("wallet_balance", 0)

    if balance < min_balance:
        print(f"Balance ${balance} below ${min_balance}, funding ${top_up_amount}...")
        fund_wallet(token, top_up_amount)
        print("Wallet funded!")
    else:
        print(f"Balance OK: ${balance}")
python
def ensure_account_funded(token, min_balance=10, top_up_amount=50):
    """检查钱包余额,若余额不足则进行充值。"""
    overview = get_billing_overview(token)
    balance = overview.get("wallet_balance", 0)

    if balance < min_balance:
        print(f"余额${balance}低于${min_balance},正在充值${top_up_amount}...")
        fund_wallet(token, top_up_amount)
        print("钱包充值成功!")
    else:
        print(f"余额充足: ${balance}")

Usage

使用示例

ensure_account_funded(token, min_balance=5, top_up_amount=25)
undefined
ensure_account_funded(token, min_balance=5, top_up_amount=25)
undefined

Common Workflow: Human-Assisted Funding with Polling

常见工作流:带轮询的人工协助充值

python
import time

def fund_via_human(token, amount, poll_interval=5, max_wait=300):
    """Create a payment link and poll until the human completes it.

    Args:
        amount: Amount in USD
        poll_interval: Seconds between balance checks
        max_wait: Maximum seconds to wait before giving up
    """
    # Get initial balance
    initial = get_wallet_balance(token)["balance"]

    # Create payment link
    link = create_payment_link(token, purpose="fund", amount=amount)
    print(f"Please fund your wallet at: {link['payment_url']}")
    print(f"Waiting for payment (expires {link['expires_at']})...")

    # Poll for confirmation
    elapsed = 0
    while elapsed < max_wait:
        time.sleep(poll_interval)
        elapsed += poll_interval
        try:
            result = confirm_wallet_checkout(token, link["session_id"])
            print(f"Payment confirmed! New balance: ${result.get('balance')}")
            return result
        except Exception:
            # Session not yet completed, keep polling
            pass

    print("Payment not completed within timeout.")
    return None
python
import time

def fund_via_human(token, amount, poll_interval=5, max_wait=300):
    """创建支付链接并轮询,直到用户完成支付。

    参数:
        amount: 美元金额
        poll_interval: 余额检查的间隔秒数
        max_wait: 最长等待秒数,超时后放弃
    """
    # 获取初始余额
    initial = get_wallet_balance(token)["balance"]

    # 创建支付链接
    link = create_payment_link(token, purpose="fund", amount=amount)
    print(f"请在此为钱包充值: {link['payment_url']}")
    print(f"等待支付完成(过期时间{link['expires_at']})...")

    # 轮询确认
    elapsed = 0
    while elapsed < max_wait:
        time.sleep(poll_interval)
        elapsed += poll_interval
        try:
            result = confirm_wallet_checkout(token, link["session_id"])
            print(f"支付已确认! 新余额: ${result.get('balance')}")
            return result
        except Exception:
            # 会话尚未完成,继续轮询
            pass

    print("支付未在超时时间内完成。")
    return None

Usage

使用示例

fund_via_human(token, amount=50, max_wait=600)
undefined
fund_via_human(token, amount=50, max_wait=600)
undefined

MCP Server Access

MCP服务器访问

These same capabilities are available via the Agent Control Plane MCP server:
  • URL:
    https://modelslab.com/mcp/agents
  • Tools:
    agent-billing
    ,
    agent-wallet
    ,
    agent-subscriptions
    (use
    list-plans
    action to discover plans)
上述所有功能也可通过Agent Control Plane MCP服务器访问:
  • URL:
    https://modelslab.com/mcp/agents
  • 工具:
    agent-billing
    ,
    agent-wallet
    ,
    agent-subscriptions
    (使用
    list-plans
    操作查看可用套餐)

API Endpoints Reference

API端点参考

MethodEndpointDescription
GET
/billing/overview
Billing overview
GET
/billing/stripe-config
Get Stripe publishable key
POST
/billing/setup-intent
Create SetupIntent for card saving
POST
/billing/payment-link
Create Stripe Checkout payment URL
GET
/billing/payment-methods
List payment methods
POST
/billing/payment-methods
Add payment method
PUT
/billing/payment-methods/{id}/default
Set default
DELETE
/billing/payment-methods/{id}
Remove payment method
GET
/billing/info
Get billing info
PUT
/billing/info
Update billing info
GET
/billing/invoices
List invoices
GET
/billing/invoices/{id}
Invoice details
GET
/billing/invoices/{id}/pdf
Invoice PDF URL
GET
/wallet/balance
Quick wallet balance check
GET
/wallet/transactions
Wallet transaction ledger
POST
/wallet/fund
Fund wallet (with payment_method_id)
POST
/wallet/confirm-checkout
Confirm Checkout wallet funding
PUT
/wallet/auto-funding
Enable auto-recharge
DELETE
/wallet/auto-funding
Disable auto-recharge
POST
/wallet/withdraw
Withdraw balance
GET
/wallet/coupons/validate
Validate coupon
POST
/wallet/coupons/redeem
Redeem coupon
GET
/payments/{id}/status
Check payment intent status
GET
/subscriptions/plans
List available plans + pay-as-you-go
GET
/subscriptions
List subscriptions (addon, enterprise, normal)
POST
/subscriptions
Create subscription (headless with pm_id, or Checkout)
POST
/subscriptions/confirm-checkout
Confirm Checkout subscription
GET
/subscriptions/{id}/status
Check subscription status
PUT
/subscriptions/{id}
Update subscription
POST
/subscriptions/{id}/pause
Pause
POST
/subscriptions/{id}/resume
Resume
POST
/subscriptions/{id}/reset-cycle
Reset cycle
POST
/subscriptions/charge-amount
Charge amount
POST
/subscriptions/{id}/fix-payment
Fix payment
方法端点描述
GET
/billing/overview
获取账单概览
GET
/billing/stripe-config
获取Stripe公钥
POST
/billing/setup-intent
创建SetupIntent以保存卡片
POST
/billing/payment-link
创建Stripe结账支付URL
GET
/billing/payment-methods
列出支付方式
POST
/billing/payment-methods
添加支付方式
PUT
/billing/payment-methods/{id}/default
设置默认支付方式
DELETE
/billing/payment-methods/{id}
移除支付方式
GET
/billing/info
获取账单信息
PUT
/billing/info
更新账单信息
GET
/billing/invoices
列出发票
GET
/billing/invoices/{id}
获取发票详情
GET
/billing/invoices/{id}/pdf
获取发票PDF下载链接
GET
/wallet/balance
快速查询钱包余额
GET
/wallet/transactions
获取钱包交易明细
POST
/wallet/fund
钱包充值(需传入payment_method_id)
POST
/wallet/confirm-checkout
确认钱包充值的结账会话
PUT
/wallet/auto-funding
启用自动充值
DELETE
/wallet/auto-funding
禁用自动充值
POST
/wallet/withdraw
余额提现
GET
/wallet/coupons/validate
验证优惠券
POST
/wallet/coupons/redeem
兑换优惠券
GET
/payments/{id}/status
查询PaymentIntent状态
GET
/subscriptions/plans
列出可用套餐+按需付费选项
GET
/subscriptions
列出订阅(附加套餐、企业套餐、普通套餐)
POST
/subscriptions
创建订阅(传入pm_id无界面创建,或生成结账链接)
POST
/subscriptions/confirm-checkout
确认订阅的结账会话
GET
/subscriptions/{id}/status
查询订阅状态
PUT
/subscriptions/{id}
更新订阅
POST
/subscriptions/{id}/pause
暂停订阅
POST
/subscriptions/{id}/resume
恢复订阅
POST
/subscriptions/{id}/reset-cycle
重置计费周期
POST
/subscriptions/charge-amount
收取自定义金额
POST
/subscriptions/{id}/fix-payment
修复支付失败问题

Best Practices

最佳实践

1. Choose the Right Payment Path

1. 选择合适的支付路径

python
undefined
python
undefined

Headless — agent has card data, fully autonomous

无界面模式——Agent拥有卡片数据,完全自主

pm_id = create_payment_method("4242424242424242", 12, 2027, "123") fund_wallet(token, 50, payment_method_id=pm_id)
pm_id = create_payment_method("4242424242424242", 12, 2027, "123") fund_wallet(token, 50, payment_method_id=pm_id)

Setup Intent — save card first, charge later

设置意向流——先保存卡片,后续再扣费

setup = create_setup_intent(token)
setup = create_setup_intent(token)

... confirm with Stripe API ...

... 通过Stripe API确认 ...

add_payment_method(token, pm_id, make_default=True)
add_payment_method(token, pm_id, make_default=True)

Human-Assisted — agent cannot handle cards

人工协助模式——Agent无法处理卡片数据

link = create_payment_link(token, purpose="fund", amount=50)
link = create_payment_link(token, purpose="fund", amount=50)

Forward link['payment_url'] to human, then confirm_wallet_checkout()

将link['payment_url']转发给用户,之后调用confirm_wallet_checkout()

undefined
undefined

2. Use Idempotency Keys for Billing

2. 为账单操作使用幂等键

python
undefined
python
undefined

Prevent duplicate charges on retries

重试时防止重复扣费

fund_wallet(token, 50, payment_method_id=pm_id, idempotency_key="fund-50-unique-key")
undefined
fund_wallet(token, 50, payment_method_id=pm_id, idempotency_key="fund-50-unique-key")
undefined

3. Set Up Auto-Recharge

3. 设置自动充值

python
undefined
python
undefined

Avoid running out of credits during generation

避免生成内容时余额不足

enable_auto_funding(token, auto_charge_amount=25, charge_threshold=5)
undefined
enable_auto_funding(token, auto_charge_amount=25, charge_threshold=5)
undefined

4. Check Balance Before Large Jobs

4. 大型任务前检查余额

python
balance = get_wallet_balance(token)
if balance["balance"] < estimated_cost:
    fund_wallet(token, estimated_cost * 1.2)  # 20% buffer
python
balance = get_wallet_balance(token)
if balance["balance"] < estimated_cost:
    fund_wallet(token, estimated_cost * 1.2)  # 预留20%缓冲

5. Validate Coupons Before Redeeming

5. 兑换前验证优惠券

python
info = validate_coupon(token, code)
python
info = validate_coupon(token, code)

Check discount amount, expiry, etc. before committing

确认折扣金额、有效期等信息后再进行兑换

undefined
undefined

6. Handle Card Failures Gracefully

6. 优雅处理卡片支付失败

python
result = fund_wallet(token, 50, payment_method_id=pm_id)
python
result = fund_wallet(token, 50, payment_method_id=pm_id)

Check for errors

检查错误信息

if result.get("error"): if result["error"]["code"] == "payment_declined": print(f"Card declined: {result['error']['details']['decline_code']}") # Try a different card or ask user
undefined
if result.get("error"): if result["error"]["code"] == "payment_declined": print(f"卡片支付失败: {result['error']['details']['decline_code']}") # 尝试使用其他卡片或询问用户
undefined

Resources

相关资源

Related Skills

相关技能

  • modelslab-account-management
    - Account setup and API keys
  • modelslab-model-discovery
    - Check usage and find models
  • modelslab-webhooks
    - Per-request webhook URLs for async results
  • modelslab-account-management
    - 账户设置与API密钥管理
  • modelslab-model-discovery
    - 查看使用情况与查找模型
  • modelslab-webhooks
    - 为异步结果设置单请求Webhook URL