You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

订阅场景下从CardElement切换到PaymentElement时如何获取clientSecret?

创建订阅时获取PaymentElement所需的clientSecret方法

情况1:订阅需要立即扣费(无免费试用)

创建订阅时,通过指定payment_behavior: 'default_incomplete'参数,Stripe会自动为订阅的首张发票生成一个未完成的PaymentIntent。你需要通过expand参数展开关联的PaymentIntent,从中提取clientSecret。

后端代码示例(Node.js):

const stripe = require('stripe')('你的Stripe密钥');

const createSubscription = async (customerId, priceId) => {
  const subscription = await stripe.subscriptions.create({
    customer: customerId,
    items: [{ price: priceId }],
    payment_behavior: 'default_incomplete', // 触发生成未完成的PaymentIntent
    expand: ['latest_invoice.payment_intent'], // 展开获取PaymentIntent详情
  });

  // 提取PaymentIntent的clientSecret返回给前端
  const clientSecret = subscription.latest_invoice.payment_intent.client_secret;
  return { clientSecret };
};

将获取到的clientSecret传给前端的PaymentElement,即可让客户完成支付流程。

情况2:订阅仅需保存支付方式(如免费试用)

如果订阅不需要立即扣费,仅需提前保存客户的支付方式用于后续自动扣费,你需要单独创建SetupIntent来获取clientSecret。

后端代码示例(Node.js):

const stripe = require('stripe')('你的Stripe密钥');

const createSetupIntent = async (customerId) => {
  const setupIntent = await stripe.setupIntents.create({
    customer: customerId,
    payment_method_types: ['card'],
    setup_future_usage: 'off_session', // 标记支付方式将用于后续离线扣费
  });

  const clientSecret = setupIntent.client_secret;
  return { clientSecret };
};

前端用PaymentElement完成SetupIntent的确认后,支付方式会绑定到客户账号,后续创建订阅时直接关联该支付方式即可。

内容的提问来源于stack exchange,提问作者ilyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:25:28