为每个用户的不同项目添加stipe stripe订阅

问题描述

我正在处理的用例很常见,但我需要一些建议来对其进行可视化。 每个用户可以拥有多个可以订阅的项目。

例如,用户名下有两个项目,项目 X 和项目 Y。现在每个项目都有自己的订阅

对于每个项目特定的付款,我如何标记客户 -> 项目 -> 订阅

我可以用订阅标记客户,但不确定如何标记项目订阅

我在想类似的事情

  1. 用户创建时,添加客户。
  2. 在项目创建时添加带有价格的产品。
  3. 结帐
  4. 会话
  5. 订阅/结帐已完成
  6. 更新数据库

我看到这个有问题,如果我改变价格计划,我将不得不在所有地方更新。 :(

实现这一目标的最佳/其他替代方法是什么? 为此,我将 Nextjs 与 Supabase 一起使用。按照这个例子。 https://github.com/vercel/nextjs-subscription-payments

解决方法

您可以使用 metadata 在 Stripe 中“标记”事物以映射到数据模型中的事物。

如果您想更改价格,是的,您必须更新所有订阅。相反,您可能想要查看使用数量或计量计费。 https://stripe.com/docs/billing/subscriptions/model

,

首先,您应该为订阅计划创建一个 product 和一些 pricesprice 代表订阅计划的实体。

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,});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...