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

如何正确初始化PHP数组以匹配Stripe支付line_items语法

解决Stripe Checkout line_items参数解析问题

问题根源

前端传递的是PHP数组格式的字符串,后端直接将其放入数组后,得到的是包含字符串的一维数组,而非Stripe要求的多维关联数组,导致参数验证失败。

正确解决方案

1. 前端正确序列化数据

不要手动拼接PHP数组格式的字符串,改用JSON.stringify()将JS对象序列化为JSON字符串,再编码后传递:

// 构建符合Stripe要求的line_items数组
const lineItems = [
  { price: 'price_xxxx', quantity: 1 },
  { price: 'price_yyyy', quantity: 2 }
];

// 序列化并编码,避免URL参数乱码
const encodedData = encodeURIComponent(JSON.stringify(lineItems));

// 跳转到checkout.php并携带参数
window.location.href = `checkout.php?purchased=${encodedData}`;

2. 后端PHP解析为合法数组

接收参数后,用json_decode()将JSON字符串解析为PHP关联数组(第二个参数传true):

// 安全获取URL参数,避免未定义索引错误
$purchasedStr = $_GET['purchased'] ?? '';

// 解码JSON字符串为关联数组
$lineItems = json_decode(urldecode($purchasedStr), true);

// 验证数据有效性(可选但推荐)
if (!is_array($lineItems) || empty($lineItems)) {
    http_response_code(400);
    exit("无效的商品数据");
}

// 创建Stripe Checkout Session
$session = \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => $lineItems,
    'mode' => 'payment',
    'success_url' => 'https://your-domain.com/success',
    'cancel_url' => 'https://your-domain.com/cancel',
]);

为什么之前的方法失效?

你之前的代码$xarray=array($purchaseData['purchased'])只是把前端传来的字符串当作数组的一个元素,比如前端传的是"[{price:'price_123', quantity:1}]",$xarray最终是:

array(
  0 => "[{price:'price_123', quantity:1}]",
)

这完全不符合Stripe line_items需要的多维关联数组结构,自然会触发"无效对象"错误。

安全提示

绝对不要使用eval()来解析前端传来的PHP格式字符串,这会导致严重的代码注入漏洞,JSON解析是更安全可靠的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:57:41