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

Flutter应用Stripe支付Web端适配故障求助(移动端已正常)

解决Flutter Stripe Web端适配问题

1. 移除客户端直接调用Stripe API的逻辑(核心修复)

当前代码中createPaymentIntent直接在客户端使用Secret Key调用Stripe API,这在Web端会引发两个致命问题:

  • Secret Key泄露,导致账号安全风险
  • 浏览器CORS策略拦截请求,Stripe不允许前端直接创建Payment Intent

修复方案:将Payment Intent创建逻辑移至后端
搭建一个后端接口(如Firebase Functions、Node.js服务),由后端安全调用Stripe API生成Payment Intent,再将client_secret返回给客户端。

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

const stripe = require('stripe')('你的Stripe Secret Key');
const express = require('express');
const app = express();
app.use(express.json());

app.post('/create-payment-intent', async (req, res) => {
  const { amount, currency } = req.body;

  const paymentIntent = await stripe.paymentIntents.create({
    amount: amount * 100, // 转换为分单位
    currency: currency,
    payment_method_types: ['card'],
  });

  res.json({ clientSecret: paymentIntent.client_secret });
});

app.listen(3000, () => console.log('服务运行在3000端口'));

修改客户端createPaymentIntent方法,改为调用自有后端接口:

Future<Map<String, dynamic>> createPaymentIntent(String amount, String currency) async {
  try {
    var response = await http.post(
      Uri.parse('https://你的后端域名/create-payment-intent'), // 替换为实际后端地址
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'amount': int.parse(amount),
        'currency': currency,
      }),
    );
    print('Payment Intent响应: ${response.body.toString()}');
    return jsonDecode(response.body.toString());
  } catch (err) {
    print('获取Payment Intent失败: ${err.toString()}');
    rethrow;
  }
}

2. 配置Web端Stripe初始化

flutter_stripe在Web端需要额外配置:

  • 在web/index.html的<head>标签内添加stripe.js加载脚本:
<script src="https://js.stripe.com/v3/"></script>
  • 在main.dart中区分平台初始化Stripe,Web端需传入Publishable Key:
import 'package:flutter/foundation.dart';
import 'package:stripe_stripe.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  const String publishableKey = '你的Stripe Publishable Key';
  if (kIsWeb) {
    await Stripe.instance.initialize(
      publishableKey: publishableKey,
      stripeAccountId: null,
    );
  } else {
    // 移动端保持原有初始化逻辑
    await Stripe.instance.initialize();
  }
  
  runApp(const MyApp());
}

3. 调整Payment Sheet的跨平台适配

Web端不需要配置Google Pay参数,移除或按需区分平台:

await Stripe.instance.initPaymentSheet(
  paymentSheetParameters: SetupPaymentSheetParameters(
    paymentIntentClientSecret: paymentIntent!['clientSecret'],
    merchantDisplayName: 'Deal Diligence',
    // 仅在非Web平台启用Google Pay
    googlePay: kIsWeb 
        ? null 
        : const PaymentSheetGooglePay(
            testEnv: true,
            currencyCode: "USD",
            merchantCountryCode: "US"),
  ),
);

4. 优化支付后的状态验证(可选)

Web端建议通过Stripe Webhook监听payment_intent.succeeded事件,在后端确认支付成功后再执行用户注册逻辑,避免出现支付失败但用户被创建的异常情况。

5. Web端测试

使用Stripe官方测试卡号验证支付流程:

  • 卡号:4242 4242 4242 4242(任意有效期、CVV)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:37:33