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

使用PHP为Stripe Checkout添加自定义产品价格时提示无对应产品求助

问题核心原因

  • 语法错误:你使用了{{$product}}/{{$price}}这类前端模板插值语法,PHP服务端代码中不能这么用,需要直接取Stripe接口返回对象的id属性传入
  • 逻辑不匹配:你创建的Price设置了recurring订阅参数,但Checkout Session的mode设为了一次性支付的payment,二者类型不兼容

修正后可运行代码

include './stripe/init.php';
\Stripe\Stripe::setApiKey('API KEY GOES HERE');

$YOUR_DOMAIN = 'https://www.XXXXX.XX.XX';

// 创建产品
$product = \Stripe\Product::create([
  'name' => 'Elearn Product',
]);

// 创建价格:如果需要订阅模式保留recurring参数,一次性支付请删除recurring配置
$price = \Stripe\Price::create([
  'product' => $product->id, // 直接传入产品返回的ID字段
  'unit_amount' => 1100,
  'currency' => 'usd',
  'recurring' => [
    'interval' => 'month',
  ],
]);

$checkout_session = \Stripe\Checkout\Session::create([
  'line_items' => [[
    'price' => $price->id, // 直接传入价格返回的ID字段
    'quantity' => 1,
  ]],
  'payment_method_types' => [
    'card',
   ],
  // 订阅模式对应mode改为subscription,一次性支付保留payment即可
  'mode' => 'subscription',
  'success_url' => $YOUR_DOMAIN . '/enrolment-success',
  'cancel_url' => $YOUR_DOMAIN . '/enrolment-failure',
]);

header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url);

动态价格优化方案

你要实现购物车动态价格,不需要每次都调用接口创建产品和价格实例,可以直接在line_items中用price_data参数动态生成结算项,避免后台产生大量冗余数据:

'line_items' => [[
  'price_data' => [
    'currency' => 'usd',
    'product_data' => [
      'name' => '自定义购物车商品名称',
    ],
    'unit_amount' => 1100, // 直接传入动态计算的商品价格(单位为分)
  ],
  'quantity' => 1,
]],

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:15:02