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

如何在订阅场景中使用Stripe Payment Element?

使用Stripe Payment Element实现无预先客户信息的注册+订阅流程

核心逻辑

订阅场景下无需单独创建Payment Intent,而是直接通过创建待激活的Subscription生成Payment Element所需的客户端密钥,用户完成支付后Stripe会自动创建客户并激活订阅,完全适配你的单页注册+支付流程。

具体步骤

1. 后端:创建待激活的Subscription

当用户选定套餐进入页面后,调用Stripe API创建Subscription,关键参数设置如下:

  • customer: 留空(后续由Stripe自动生成客户)
  • items: 指定用户选择的订阅套餐价格ID(格式为price_xxx)
  • payment_behavior: 'default_incomplete'(标记订阅为待支付状态)
  • expand: ['latest_invoice.payment_intent'](获取关联的Payment Intent信息,用于前端初始化Payment Element)
  • 可选:提前传入用户输入的邮箱到customer_email参数,后续会自动关联到生成的客户

示例代码(Node.js):

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

const createPendingSubscription = async (priceId, userEmail) => {
  const subscription = await stripe.subscriptions.create({
    customer: '',
    items: [{ price: priceId }],
    payment_behavior: 'default_incomplete',
    expand: ['latest_invoice.payment_intent'],
    customer_email: userEmail,
  });

  return {
    clientSecret: subscription.latest_invoice.payment_intent.client_secret,
    subscriptionId: subscription.id,
  };
};

2. 前端:初始化Payment Element并完成支付

拿到后端返回的clientSecret后,初始化Stripe实例和Payment Element,同时收集用户姓名、邮箱信息,最后发起支付确认:

示例代码(React):

import { loadStripe } from '@stripe/stripe-js';
import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { useState } from 'react';

const stripePromise = loadStripe('你的Stripe公钥');

const CheckoutPage = ({ clientSecret, selectedPlan }) => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!stripe || !elements) return;

    // 确认支付,触发订阅激活与客户创建
    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        return_url: window.location.href, // 单页应用可直接用当前页面
      },
    });

    if (error) {
      // 处理支付失败逻辑
      alert(`支付失败:${error.message}`);
    } else {
      // 支付成功,订阅已激活,客户已创建
      // 可调用后端接口同步本地用户数据或跳转至成功页
      alert('订阅成功!');
    }
  };

  return (
    <form onSubmit={handleSubmit} className="checkout-form">
      <h2>订阅套餐:{selectedPlan.name}</h2>
      <div className="form-group">
        <label>姓名</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
        />
      </div>
      <div className="form-group">
        <label>邮箱</label>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
      </div>
      <div className="payment-element-container">
        <PaymentElement />
      </div>
      <button type="submit" disabled={!stripe} className="submit-btn">
        完成订阅并支付
      </button>
    </form>
  );
};

export default ({ clientSecret, selectedPlan }) => (
  <Elements stripe={stripePromise} options={{ clientSecret }}>
    <CheckoutPage clientSecret={clientSecret} selectedPlan={selectedPlan} />
  </Elements>
);

3. 后端:监听Stripe Webhook完成数据同步

支付成功后,Stripe会发送customer.created和subscription.updated(状态变为active)的Webhook事件,你可以在后端监听这些事件:

  • 从customer.created事件中提取客户ID、邮箱等信息
  • 将客户数据同步到你的数据库,关联到本地用户账号

关于“先获取令牌再创建客户”的疑问

Payment Element不返回传统的支付令牌(如Card Element的token),它通过Stripe安全通道直接完成支付确认,无需手动处理令牌。上述流程中,Stripe会自动完成客户创建、支付验证和订阅激活的全链路,同时原生支持Apple/Google Pay等支付方式,完全覆盖你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:30:28