Flutter集成Stripe支付遇FormatException错误求助
Flutter Stripe集成:FormatException问题解决思路
你遇到的FormatException: Unexpected character确实是因为jsonDecode(response.body)解析失败——服务器返回的内容并非合法JSON格式。以下是具体排查和解决步骤:
先确认服务器返回的原始内容
在调用jsonDecode之前,先打印服务器返回的完整内容,明确是不是合法JSON:final response = await http.post(...); // 新增打印步骤,查看真实返回内容 debugPrint('Server response body: ${response.body}'); final jsonResponse = jsonDecode(response.body);如果打印结果是HTML代码、纯文本错误信息(比如"Internal Server Error"),或者带有多余换行/空格的内容,那就是问题核心——云函数没有返回标准JSON。
修正Cloud Functions的返回逻辑
确保你的Firebase云函数返回标准JSON格式,并且设置正确的响应头:
(以Node.js云函数为例)exports.stripePaymentIntentRequest = functions.https.onRequest(async (req, res) => { try { // 生成Payment Intent、Customer、Ephemeral Key的业务逻辑 const paymentIntent = await stripe.paymentIntents.create(...); const customer = await stripe.customers.create(...); const ephemeralKey = await stripe.ephemeralKeys.create( {customer: customer.id}, {apiVersion: '2024-06-20'} ); // 必须用res.json返回,自动设置Content-Type为application/json res.json({ paymentIntent: paymentIntent.client_secret, customer: customer.id, ephemeralKey: ephemeralKey.secret }); } catch (error) { // 出错时也要返回JSON格式的错误信息 res.status(500).json({error: error.message}); } });同时去Firebase控制台查看云函数日志,确认是否有执行报错(比如Stripe密钥错误、参数缺失)。
添加HTTP状态码校验
在解析JSON前先判断请求是否成功,避免服务器返回错误状态码时强行解析:final response = await http.post(...); if (response.statusCode < 200 || response.statusCode >= 300) { debugPrint('Request failed: ${response.statusCode} - ${response.body}'); return PaymentHandler( isError: true, message: '请求失败:${response.statusCode}', ); } // 再执行JSON解析 final jsonResponse = jsonDecode(response.body);验证请求参数合法性
确认传给云函数的参数没有问题:- 检查
user.email是否为非空字符串,空邮箱会导致云函数处理出错; - 确保
totalAmount是有效数值,避免传入null或NaN,否则(totalAmount * 100).toString()会生成无效字符串,触发云函数错误。
- 检查
内容的提问来源于stack exchange,提问作者Jacques
相关产品推荐
相关产品推荐

