![nodejs 中的 stripe 订阅集成 [终极指南]](https://img.php.cn/upload/article/001/246/273/173220068350758.jpg)
让 stripe 订阅与后端服务配合使用可能会很棘手,并且常常会导致开发人员所谓的可怕的“大脑分裂”——同步管理 stripe 的逻辑和您自己的后端数据。
在 vratix,我们在构建开源 stripe 订阅 api 模块时正面解决了这个问题。以下是我们如何在 node.js 中处理 stripe 订阅计费,以保持事情简单、可扩展且对开发人员友好。
关键是将尽可能多的逻辑转移到stripe,同时保持数据库最小化。我们只存储:
这样,我们就可以避免:
通过这种方法,您仍然拥有功能齐全的订阅计费系统,同时依赖 stripe 作为唯一的事实来源。
在本指南结束时,您将拥有一个基于订阅的应用程序,支持:
我们首先设计一个干净、最小的数据库表:
create table user_subscriptions (
"id" serial primary key,
"plan" varchar not null,
"user_id" integer not null references users(id) on delete cascade,
"customer_id" varchar,
"subscription_id" varchar not null,
"is_owner" boolean not null default true,
"created_at" timestamp not null default now(),
unique (user_id, subscription_id)
);
要点:
我们使用工厂函数来保持业务逻辑模块化和可测试。以下是我们的 stripe 订阅控制器的片段:
async getsubscriptions() {
const stripeprices = await stripe.prices.list({
active: true,
type: "recurring",
expand: ["data.product"],
});
return stripeprices.data.map((price) => {
const product = price.product as stripe.product;
return {
plan: price.lookup_key || product.name.tolowercase().replaceall(" ", "_"),
name: product.name,
priceid: price.id,
interval: price.recurring!.interval,
price: { currency: price.currency, amount: price.unit_amount },
};
});
}
主要亮点:
我们的 createcheckout 函数设置订阅结账会话:
const checkout = await stripe.checkout.sessions.create({
line_items: [
{
price: priceid,
adjustable_quantity: { enabled: true },
quantity: seats || 1,
},
],
mode: "subscription",
subscription_data: { metadata: { userid } },
success_url: checkout_success_url,
cancel_url: checkout_cancel_url,
});
return { url: checkout.url! };
我们已将所有内容打包到一个现成的开源模块中。 不到 30 秒,您可以设置:
运行这个:
npx vratix init
查看我们的 stripe 订阅模块文档以了解更多详细信息。
完整代码可在我们的 github 存储库中获取。
在此处观看演示视频,了解如何使用工作 ui 完成所有这些操作。
我很想听听您的想法 - 这是否会让构建订阅 api 变得更容易?让我们知道您接下来想看到哪些功能!
以上就是Nodejs 中的 Stripe 订阅集成 [终极指南]的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号