Flutter调用Stripe POST API时List<String>被转为单个字符串问题求助
问题解决思路
根因说明
你遇到的参数异常是Dart HTTP库默认x-www-form-urlencoded编码逻辑导致的:直接将包含数组的Dart Map作为请求body传输时,数组类型会被自动调用toString()方法转为"[card]"格式的单个字符串,不符合Stripe API的参数规范。
可行解决方案
方案1:使用JSON格式发送请求(最简单)
Stripe API支持JSON格式的请求体,只需主动指定请求头的Content-Type为application/json,并将请求Map序列化为JSON字符串即可,原有参数结构无需调整:
import 'dart:convert'; import 'package:http/http.dart' as http; // 原有body定义不变 final body = { 'payment_method_types': [ 'card', ], 'line_items': [ { 'amount': price, 'quantity': 1, 'currency': 'usd', 'name': 'Some Name here' }, ], 'mode': 'payment', 'success_url': 'https://success.com/{CHECKOUT_SESSION_ID}', 'cancel_url': 'https://cancel.com/', }; // 发送请求部分调整为如下写法 final response = await http.post( Uri.parse('https://api.stripe.com/v1/checkout/sessions'), headers: { 'Authorization': 'Bearer 你的Stripe私钥', 'Content-Type': 'application/json', }, body: jsonEncode(body), );
方案2:适配Form编码的参数格式
如果需要沿用x-www-form-urlencoded格式,需要按照Stripe的form参数规则调整结构:数组类型参数的键名后加[],嵌套对象用[下标][字段名]的格式声明:
final body = { 'payment_method_types[]': 'card', 'line_items[0][amount]': price.toString(), 'line_items[0][quantity]': '1', 'line_items[0][currency]': 'usd', 'line_items[0][name]': 'Some Name here', 'mode': 'payment', 'success_url': 'https://success.com/{CHECKOUT_SESSION_ID}', 'cancel_url': 'https://cancel.com/', }; // 发送请求时无需额外序列化,直接传入body即可,注意参数值都需为字符串类型 final response = await http.post( Uri.parse('https://api.stripe.com/v1/checkout/sessions'), headers: { 'Authorization': 'Bearer 你的Stripe私钥', }, body: body, );
方案3:使用官方Stripe Flutter SDK(最推荐)
直接使用官方维护的Stripe Flutter SDK发起请求,SDK内部已经处理了所有参数编码逻辑,无需手动调整参数结构,避免格式错误。
注意事项
- 发送请求前请确认Stripe私钥权限正确,没有路径、拼写错误
- 使用Form编码时所有参数值必须转为字符串类型,禁止直接传入int、double等数值类型
内容的提问来源于stack exchange,提问作者Hamza
相关产品推荐
相关产品推荐

