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

集成Stripe支付遇FlowController初始化错误,支付卡片不显示如何解决?

Stripe支付集成错误解决:FlowController未初始化及卡片不显示问题

错误原因分析

你遇到的FlowController must be successfully initialized...错误,以及支付卡片不显示的问题,主要由以下几个原因导致:

  1. 未异步等待initPaymentSheet()完成就调用presentPaymentSheet(),导致支付流程控制器未正确初始化
  2. 错误获取Payment Intent的客户端密钥(误用paymentIntent字段,而非Stripe返回的client_secret)
  3. 金额格式不符合Stripe要求(未转换为最小货币单位)
  4. 按钮调用时存在语法错误

分步解决方法

1. 确保Stripe全局初始化

在App启动时先完成Stripe SDK的初始化,将以下代码添加到main()函数:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 替换为你的Stripe公钥
  await Stripe.instance.initialize(publishableKey: 'pk_your_publishable_key');
  runApp(MyApp());
}

2. 修正Payment Intent密钥获取逻辑

Stripe API返回的支付意图中,客户端密钥对应的字段是client_secret,修改初始化代码:

paymentIntentClientSecret: jsonresponse['client_secret'],

3. 等待Payment Sheet初始化完成

initPaymentSheet()是异步方法,必须用await等待执行完成后,再调用presentPaymentSheet():

// 等待Payment Sheet初始化完成
await Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
  paymentIntentClientSecret: jsonresponse['client_secret'],
  merchantDisplayName: 'Zohaib',
));
// 再弹出支付表单
await Stripe.instance.presentPaymentSheet();

4. 修正金额格式

Stripe要求金额为最小货币单位(例如美元需用分表示),所以需要把输入的美元金额乘以100:

"amount": (amount * 100).toInt().toString(),

5. 修复按钮调用的语法错误

按钮中调用intpayment时,email字符串未闭合,修正为:

onPressed: () {
  intpayment(email: "example@email.com", amount: 50.0);
},

修正后的完整支付函数

Future<void> intpayment({required String email, required double amount}) async {
  try {
    final response = await http.post(
      Uri.parse("https://api.stripe.com/v1/payment_intents"),
      body: {
        "receipt_email": email,
        "amount": (amount * 100).toInt().toString(), // 转换为最小货币单位(分)
        "currency": "usd"
      },
      headers: {
        // 替换为你的Stripe私钥
        'Authorization': 'Bearer ' + 'sk_your_secret_key',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
    );

    // 检查API请求是否成功
    if (response.statusCode != 200) {
      throw Exception('创建支付意图失败:${jsonDecode(response.body)['error']['message']}');
    }

    final jsonresponse = jsonDecode(response.body);
    
    // 等待Payment Sheet初始化
    await Stripe.instance.initPaymentSheet(
      paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: jsonresponse['client_secret'],
        merchantDisplayName: 'Zohaib',
      ),
    );

    // 弹出支付表单
    await Stripe.instance.presentPaymentSheet();
    Fluttertoast.showToast(msg: "支付成功");
  } catch (e) {
    if (e is StripeException) {
      Fluttertoast.showToast(msg: "Stripe错误:${e.error.message}");
    } else {
      Fluttertoast.showToast(msg: "错误:$e", toastLength: Toast.LENGTH_SHORT);
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:31:01