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

PHP集成Stripe多产品异常:仅处理首个产品购买

问题分析与解决方案

核心问题

你的代码里**createProducts和createProductPrice函数存在提前返回的错误**:函数内第一个return语句会直接终止函数执行,后面的代码永远不会被运行,所以系统只会创建第一个产品和对应的第一个价格,第二个产品/价格完全没被创建。

修正后的StripeHelper代码

require 'vendor/autoload.php';
include_once "constants.php";
class StripeHelper
{
    /**
     * @var \Stripe\StripeClient
     */
    public $stripeClient;

    public function __construct()
    {
        $this->stripeClient = new \Stripe\StripeClient(STRIPE_API_SECRET_KEY);
    }

    /**
     * 创建多个产品
     * @return \Stripe\Product[]
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function createProducts()
    {
        $products = [];
        // 创建产品1
        $products[] = $this->stripeClient->products->create([
            'name' => 'Product 1',
            'description' => 'Product 1.',
        ]);
        // 创建产品2
        $products[] = $this->stripeClient->products->create([
            'name' => 'Product 2',
            'description' => 'Product 2.',
        ]);
        return $products;
    }

    /**
     * 为单个产品创建价格
     * @param \Stripe\Product $product
     * @param int $productPrice 单位:便士(Stripe使用最小货币单位)
     * @return \Stripe\Price
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function createProductPrice($product, $productPrice)
    {
        return $this->stripeClient->prices->create([
            'unit_amount' => $productPrice,
            'currency' => 'GBP',
            'product' => $product->id,
        ]);
    }

    /**
     * 创建对应产品的结账会话
     * @param \Stripe\Price $price
     * @param string $successUrl
     * @param string $cancelUrl
     * @return \Stripe\Checkout\Session
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function createCheckoutSession($price, $successUrl, $cancelUrl)
    {
        return $this->stripeClient->checkout->sessions->create([
            'payment_method_types' => ['card'],
            'line_items' => [
                [
                    'price' => $price->id,
                    'quantity' => 1,
                ],
            ],
            'mode' => 'payment',
            'success_url' => $successUrl,
            'cancel_url' => $cancelUrl,
        ]);
    }

    /**
     * Get session detail
     * @param $sessionId
     * @return \Stripe\Checkout\Session
     * @throws \Stripe\Exception\ApiErrorException
     */
    public function getSession($sessionId)
    {
        return $this->stripeClient->checkout->sessions->retrieve($sessionId);
    }
}

实现首页展示与结账流程的步骤

  1. 预创建产品和价格:
    运行一次创建产品的代码,把返回的产品ID和价格ID存储到你的数据库(不要每次请求都创建,否则会重复生成产品):

    $stripeHelper = new StripeHelper();
    $products = $stripeHelper->createProducts();
    // 为每个产品创建价格并存储
    foreach ($products as $product) {
        // 假设Product1价格是10英镑(1000便士),Product2是20英镑(2000便士)
        $price = $stripeHelper->createProductPrice($product, $product->name === 'Product 1' ? 1000 : 2000);
        // 把$product->id、$product->name、$price->id存入数据库
    }
    
  2. 首页展示产品:
    从数据库读取所有产品信息,渲染到页面,每个产品对应一个结账按钮:

    // 从数据库获取产品和价格列表
    $products = [
        ['name' => 'Product 1', 'price_id' => 'price_xxx'],
        ['name' => 'Product 2', 'price_id' => 'price_yyy'],
        // 更多产品...
    ];
    ?>
    <!-- 前端HTML -->
    <?php foreach ($products as $item): ?>
        <div class="product">
            <h3><?= $item['name'] ?></h3>
            <form action="/create-checkout-session" method="POST">
                <input type="hidden" name="price_id" value="<?= $item['price_id'] ?>">
                <button type="submit">立即购买</button>
            </form>
        </div>
    <?php endforeach; ?>
    
  3. 处理结账会话请求:
    创建/create-checkout-session接口,接收价格ID,生成Stripe结账链接并跳转:

    require 'StripeHelper.php';
    $stripeHelper = new StripeHelper();
    $priceId = $_POST['price_id'];
    // 先从数据库验证price_id的合法性(防止恶意请求)
    // 创建会话
    $session = $stripeHelper->createCheckoutSession(
        $stripeHelper->stripeClient->prices->retrieve($priceId),
        'https://your-domain.com/success', // 支付成功跳转地址
        'https://your-domain.com/cancel'   // 支付取消跳转地址
    );
    // 跳转到Stripe结账页面
    header("Location: " . $session->url);
    exit;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:31:31