如何解决为每个用户的不同项目添加stipe stripe订阅
我正在处理的用例很常见,但我需要一些建议来对其进行可视化。 每个用户可以拥有多个可以订阅的项目。
例如,用户名下有两个项目,项目 X 和项目 Y。现在每个项目都有自己的订阅。
对于每个项目特定的付款,我如何标记客户 -> 项目 -> 订阅?
我在想类似的事情
我看到这个有问题,如果我改变价格计划,我将不得不在所有地方更新。 :(
实现这一目标的最佳/其他替代方法是什么? 为此,我将 Nextjs 与 Supabase 一起使用。按照这个例子。 https://github.com/vercel/nextjs-subscription-payments
解决方法
您可以使用 metadata 在 Stripe 中“标记”事物以映射到数据模型中的事物。
如果您想更改价格,是的,您必须更新所有订阅。相反,您可能想要查看使用数量或计量计费。 https://stripe.com/docs/billing/subscriptions/model
,首先,您应该为订阅计划创建一个 product
和一些 prices
。 price
代表订阅计划的实体。
lookup_key
用于从静态字符串动态检索价格,如果 transfer_lookup_key
设置为 true,将从现有价格中自动删除查找键,并将其分配给该价格。因此,您始终可以通过使用 lookup_key
并将 transfer_lookup_key
设置为 true 来检索计划的最新价格。
const product = await stripe.products.create({
name: 'MyService',// your service name
});
const beginnerPrice = await stripe.prices.create({
unit_amount: 5,currency: 'usd',recurring: {interval: 'month'},product: product.id,lookup_key: 'beginner',transfer_lookup_key: true,});
const proPrice = await stripe.prices.create({
unit_amount: 20,lookup_key: 'pro',});
这是我假设的数据库架构。
// db schema
interface IUser{
id: string
stripeCustomerId: string
}
interface IProject{
id: string
userId: string
}
interface IProjectSubscription{
id: string
projectId: string
stripeSubscriptionId: string // or/and stripeCheckoutSessionId,it's up to your use case
}
当用户创建新项目并选择他/她的订阅计划时,您将创建新的 checkout.session
并使用 price
传递相应的行项目。您可以使用 price
获取所选计划的当前 lookup_key
。
const prices = await stripe.prices.list({
lookup_keys: ['pro'],type: 'recurring',limit: 1,});
const session = await stripe.checkout.sessions.create({
success_url: 'https://example.com/success',cancel_url: 'https://example.com/cancel',payment_method_types: ['card'],line_items: [
{price: prices[0].id,quantity: 1},],mode: 'subscription',});
然后在 checkout.session.completed
上,您可以接收 checkout.session
对象并在 webhook 中迁移您的数据库。
接下来,假设您要将“专业”计划的价格从 20 美元更改为 30 美元。在这种情况下,您将使用相同的 price
创建新的 lookup_key
。通过这样做,您可以更改新订阅者的订阅价格,而无需更改向现有订阅者收取的费用。
const newProPrice = await stripe.prices.create({
unit_amount: 30,});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。