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

使用flutter_stripe^8.0.0+1集成Stripe支付时遇StripeConfigException错误求助

Flutter Stripe集成报错StripeConfigException解决方案(flutter_stripe ^8.0.0+1)

这个StripeConfigException是因为Stripe初始化配置不正确导致的,结合你的代码和报错栈,主要有几个地方得修正:

1. 改用正确的Stripe初始化方式

新版本flutter_stripe已不推荐直接设置Stripe.publishableKey,得用Stripe.instance.initialize方法完成初始化,而且要确保在调用任何Stripe接口前完成这一步。

修改main函数:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 替换成你的真实publishable key
  await Stripe.instance.initialize(
    publishableKey: 'pk_你的公钥',
  );
  runApp(const MaterialApp(
    home: stripe(),
  ));
}

另外你手动添加的MediaQuery是多余的,MaterialApp本身会处理媒体查询,删掉即可。

2. 修复Payment Intent的字段错误&安全问题

你直接在客户端调用Stripe API还暴露了Secret Key,这绝对不行——Secret Key不能出现在客户端代码里,会被盗用造成损失!必须通过自己的后端服务来创建Payment Intent,客户端只调用后端接口获取参数。

同时你从API响应中取的字段名也错误:

  • 支付意图的client secret应该是jsonresponse['client_secret'],不是paymentIntent
  • 如果使用Payment Sheet需要客户ID和临时密钥,也得从后端接口获取,不是当前的customer和ephemeralKey字段

3. 完善异常捕获逻辑

现在的捕获逻辑没处理StripeConfigException,得加上才能看到具体的配置错误信息:

catch(e){
  String errorMsg = '支付失败';
  if (e is StripeConfigException) {
    errorMsg = '配置出错:${e.message}';
  } else if (e is StripeException) {
    errorMsg = '支付出错:${e.error.localizedMessage}';
  } else {
    errorMsg = '未知错误:$e';
  }
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text(errorMsg)),
  );
  print(errorMsg);
}

4. 检查平台基础配置

确保你已经按flutter_stripe文档完成了平台配置:

  • Android:在android/app/src/main/res/values/strings.xml中添加Stripe publishable key
  • iOS:在Info.plist中添加相关配置
    新版本用initialize设置后可以覆盖基础配置,但还是建议完成基础配置步骤。

修改后的完整代码示例

import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 替换为你的真实publishable key
  await Stripe.instance.initialize(
    publishableKey: 'pk_test_你的公钥',
  );
  runApp(const MaterialApp(
    home: stripe(),
  ));
}

class stripe extends StatefulWidget {
  const stripe({Key? key}) : super(key: key);
  @override
  State<stripe> createState() => _stripeState();
}

class _stripeState extends State<stripe> {

  Future<void> intpayment({required String email, required double amount})async{
    try{
      // 这里调用你自己的后端接口,不要直接调用Stripe API
      final response= await http.post(Uri.parse("https://你的后端地址.com/create-payment-intent")
          ,body: jsonEncode({
            "receipt_email": email,
            "amount": (amount * 100).toInt(), // Stripe金额以分为单位
            "currency": "usd"
          }),
          headers: {
            'Content-Type': 'application/json'
          }
      );
      final jsonresponse=jsonDecode(response.body);
      print(jsonresponse.toString());

      await Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: jsonresponse['client_secret'],
        merchantDisplayName: 'Grocery Flutter course',
        customerId: jsonresponse['customer_id'], // 从后端获取
        customerEphemeralKeySecret: jsonresponse['ephemeral_key'], // 从后端获取
      ));
      await Stripe.instance.presentPaymentSheet();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("支付成功")),
      );
    }
    catch(e){
      String errorMsg = '支付失败';
      if (e is StripeConfigException) {
        errorMsg = '配置出错:${e.message}';
      } else if (e is StripeException) {
        errorMsg = '支付出错:${e.error.localizedMessage}';
      } else {
        errorMsg = '未知错误:$e';
      }
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(errorMsg)),
      );
      print(errorMsg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Payment Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            intpayment(email: "zohaib6778@gmail.com", amount: 50.0);
          },
          child: const Text("Pay 50\$"), // 按钮文本和金额保持一致
        ),
      ),
    );
  }
}

内容的提问来源于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 22:35:19