如何通过API添加Stripe订阅?Python/JS实现求助
我之前也折腾过类似的客户自动化流程,给你分享下用Python和JavaScript实现添加订阅、生成发票的具体方案——假设你用的是Stripe(这类场景最常用的支付平台),如果是其他平台思路也一致,核心就是调用官方API来完成操作:
用Python实现订阅与发票操作
首先得安装对应平台的SDK,以Stripe为例:
pip install stripe
添加订阅
你需要用到Zapier创建客户后返回的customer_id,以及你手里的plan_id,代码示例如下:
import stripe import os # 从环境变量读取API密钥,别硬编码! stripe.api_key = os.getenv("STRIPE_SECRET_KEY") def create_subscription(customer_id, plan_id): try: subscription = stripe.Subscription.create( customer=customer_id, items=[ { "plan": plan_id, # 如果需要自定义金额,这里可以加"quantity"或者用price参数 # "price": "自定义价格ID", } ], # 自动生成发票并收费的话可以加这个参数 payment_behavior="default_incomplete" ) return subscription except stripe.error.StripeError as e: print(f"创建订阅失败: {e.user_message}") return None # 调用函数,传入你的变量 customer_id = "从Zapier获取的客户ID" plan_id = "你的套餐ID" new_subscription = create_subscription(customer_id, plan_id)
生成发票
如果需要单独创建发票(比如一次性收费场景),可以先创建发票项再生成发票:
def create_invoice(customer_id, amount, description): try: # 先创建发票项 invoice_item = stripe.InvoiceItem.create( customer=customer_id, amount=amount, # 单位是分,比如1000就是10美元 currency="usd", description=description ) # 生成发票 invoice = stripe.Invoice.create( customer=customer_id, auto_advance=True # 自动完成发票 ) return invoice except stripe.error.StripeError as e: print(f"创建发票失败: {e.user_message}") return None # 调用函数 invoice = create_invoice(customer_id, 1500, "自定义服务收费")
用JavaScript实现订阅与发票操作
同样以Stripe为例,先安装依赖:
npm install stripe
添加订阅
Node.js环境下的代码示例:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); async function createSubscription(customerId, planId) { try { const subscription = await stripe.subscriptions.create({ customer: customerId, items: [{ plan: planId }], payment_behavior: 'default_incomplete', }); return subscription; } catch (error) { console.error('创建订阅失败:', error.message); return null; } } // 调用函数 const customerId = '从Zapier获取的客户ID'; const planId = '你的套餐ID'; createSubscription(customerId, planId);
生成发票
async function createInvoice(customerId, amount, description) { try { // 创建发票项 await stripe.invoiceItems.create({ customer: customerId, amount: amount, // 单位分 currency: 'usd', description: description, }); // 生成并完成发票 const invoice = await stripe.invoices.create({ customer: customerId, auto_advance: true, }); return invoice; } catch (error) { console.error('创建发票失败:', error.message); return null; } } // 调用函数 createInvoice(customerId, 1500, '自定义服务收费');
额外提示
- 一定要把API密钥放在环境变量里,别直接写在代码里,避免泄露
- 如果是在Zapier里集成这些代码,可以用「Code by Zapier」模块,直接把Python/JS代码放进去,Zapier会自动把流程里的变量(比如客户ID)传递给代码
- 如果用的不是Stripe,比如PayPal或者其他支付工具,只需要替换对应的SDK和API调用参数就行,核心逻辑都是“传入客户ID+套餐/金额参数,调用创建订阅/发票的API”
内容的提问来源于stack exchange,提问作者Nathan Bruning
相关产品推荐
相关产品推荐

