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

如何使用flutter_stripe实现订阅类型支付?

使用flutter_stripe实现订阅支付

前置准备

  • 先在Stripe Dashboard创建产品和对应的定期订阅价格(价格类型选recurring,比如月度/年度),记下价格ID(格式类似price_xxxxxx)。
  • 后端必须集成Stripe Server SDK,负责创建客户、生成订阅、处理webhook事件(订阅状态更新、支付成功/失败通知)。

步骤1:前端收集支付方式

用flutter_stripe的CardField组件收集用户支付信息,生成支付方式ID:

import 'package:flutter_stripe/flutter_stripe.dart';

// 初始化Stripe(已完成一次性支付的话这步应该已经做过)
await Stripe.instance.applySettings();

// 创建支付方式
final paymentMethod = await Stripe.instance.createPaymentMethod(
  params: PaymentMethodParams.card(
    paymentMethodData: PaymentMethodData(
      billingDetails: BillingDetails(
        email: 'user@example.com',
        name: '用户姓名',
      ),
    ),
  ),
);
final paymentMethodId = paymentMethod.id;

步骤2:后端创建订阅并返回支付秘钥

把前端拿到的paymentMethodId和用户标识传给后端,后端通过Stripe SDK创建订阅:
(以Node.js后端为例)

const stripe = require('stripe')('你的Stripe Secret Key');

async function createUserSubscription(userExternalId, paymentMethodId, priceId) {
  // 查找或创建Stripe客户
  let customer;
  const existingCustomers = await stripe.customers.list({email: userExternalId});
  if (existingCustomers.data.length > 0) {
    customer = existingCustomers.data[0];
    // 将支付方式关联到已有客户
    await stripe.paymentMethods.attach(paymentMethodId, {customer: customer.id});
    await stripe.customers.update(customer.id, {
      invoice_settings: {default_payment_method: paymentMethodId},
    });
  } else {
    // 创建新客户并绑定支付方式
    customer = await stripe.customers.create({
      email: userExternalId,
      payment_method: paymentMethodId,
      invoice_settings: {default_payment_method: paymentMethodId},
    });
  }

  // 创建订阅
  const subscription = await stripe.subscriptions.create({
    customer: customer.id,
    items: [{price: priceId}],
    payment_behavior: 'default_incomplete',
    expand: ['latest_invoice.payment_intent'],
  });

  // 返回前端需要的支付秘钥和订阅ID
  return {
    clientSecret: subscription.latest_invoice.payment_intent.client_secret,
    subscriptionId: subscription.id,
  };
}

步骤3:前端确认支付完成

后端返回clientSecret后,调用flutter_stripe的确认支付方法完成订阅:

final paymentResult = await Stripe.instance.confirmPayment(
  clientSecret: '后端返回的clientSecret',
  data: PaymentMethodParams.cardFromMethodId(
    paymentMethodId: paymentMethodId,
  ),
);

if (paymentResult.status == PaymentIntentsStatus.succeeded) {
  // 订阅创建成功,更新本地用户状态或跳转成功页面
} else {
  // 支付失败,提示用户检查支付信息或重试
}

关键注意事项

  • 必须配置Stripe Webhook,监听customer.subscription.created、invoice.paid、invoice.payment_failed等事件,用于同步后端的用户订阅状态(比如到期提醒、取消订阅处理)。
  • 如果使用PaymentSheet替代CardField,流程类似:后端生成对应的支付秘钥后,初始化PaymentSheet并展示,用户确认后完成支付。
  • 确保Stripe账户已开启订阅功能,且创建的价格为定期类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:10:58