如何在Stripe中指定订阅时长并关联Subscription Schedule避免重复订阅
问题原因
你当前的代码逻辑存在两个独立的订阅创建流程,因此会生成重复订阅:
- 提前调用
stripe.subscriptionSchedules.create创建了绑定目标客户的24个月订阅计划,该计划本身会对应生成一个订阅 - 后续创建的
mode: 'subscription'类型Checkout会话,付款成功后默认会生成一个全新的独立订阅
解决方案
推荐直接在创建Checkout会话时传入订阅计划配置,无需提前单独创建Subscription Schedule,避免重复生成订阅:
修正后代码示例
const customer = await stripe.customers.create({ description: "My First Test Customer (created for API docs)", email: "some.email@gmail.com", address: { city: 'Toronto', country: 'CA', line1: "Some Address", line2: "Some unit number", postal_code: "M5G0V1", state: "ON", }, name: "Some Name", phone: "Some Number", }); const price = await stripe.prices.create({ unit_amount: 599, currency: 'cad', recurring: {interval: 'month', interval_count: '1'}, product: 'prod_KZfHFK4nfCqlGS', }); const session = await stripe.checkout.sessions.create({ success_url: 'http://localhost:8080/stripeSessionSuccessHook', cancel_url: 'http://localhost:8080/stripeSessionCancelHook', payment_method_types: ['card'], customer: customer.id, line_items: [ {price: price.id, quantity: 1}, ], mode: 'subscription', // 新增订阅计划配置 subscription_schedule_data: { end_behavior: 'cancel', phases: [ { items: [ { price: price.id, quantity: 1, }, ], iterations: 24, }, ] } });
以上配置会让Checkout付款成功后自动生成符合24个月按月付费要求的订阅,到期后自动取消,不会出现重复订阅的问题。
内容的提问来源于stack exchange,提问作者Elvin Jafali
相关产品推荐
相关产品推荐

