跳转到内容

将商务功能集成到我的应用中

使用 Proyecta SDK 在您的应用代码中创建客户、发起结账、限制功能访问以及取消订阅。

连接 Stripe 并创建产品后,您可以通过 proyecta.commerce SDK 资源将商务功能接入您的应用。最常见的四种操作是:创建客户、发起结账、检查功能访问权限以及取消订阅。

import Proyecta from '@proyecta-ai/sdk';
const proyecta = new Proyecta({ apiKey: process.env.PROYECTA_API_KEY });

客户是您应用中的计费实体——通常是用户、组织或项目。请在数据库中创建对应实体的同时创建客户,并存储返回的 id,以便在结账和访问权限检查中引用该客户。

const customer = await proyecta.commerce.customers.create({
email: 'alice@example.com',
name: 'Alice Liddell',
});
await db.users.update({ id: userId, proyectaCustomerId: customer.id });

您也可以在创建时或通过 customers.update() 传入账单地址(line1、line2、city、state、postal_code、country)。

commerce.checkout() 会创建一个由 Stripe 托管的结账会话,并返回一个将客户重定向到的 URL。付款完成后,Stripe 会将客户重定向到您的 success_url

const { url } = await proyecta.commerce.checkout({
customer_id: customer.id,
line_items: [{ variant_id: 'var_pro_monthly', quantity: 1 }],
success_url: 'https://myapp.com/welcome',
cancel_url: 'https://myapp.com/pricing',
});
return Response.redirect(url);

支持传入多个 line_items。对于订阅类产品,quantity 代表席位数量。

在允许客户使用付费功能之前,调用 commerce.check() 来验证其是否拥有访问权限:

const { has_access } = await proyecta.commerce.check({
customer_id: customer.id,
resource_id: 'feat_pro_features',
});
if (!has_access) {
return Response.json({ error: 'Upgrade required' }, { status: 402 });
}

这是限制付费内容访问的推荐方式。有关功能与权益模型的详细说明,请参阅产品与功能

await proyecta.commerce.cancel({
customer_id: customer.id,
subscription_id: 'sub_123',
cancellation_timing: 'at_billing_period_end', // 或 'immediate'
});

默认情况下,客户可继续使用服务直至当前计费周期结束。

您无需手动编写这些代码。常用的提示语示例:

  • "Create a Proyecta customer when a user signs up. Store the proyecta_customer_id on the user record."
  • "Build a /pricing page that shows my Proyecta products and starts a checkout when a button is clicked."
  • "Gate the /admin route — only allow users whose Proyecta customer has access to feat_admin."
  • "When a user clicks Cancel Subscription, call proyecta.commerce.cancel with at_billing_period_end."