首页 > 解决方案 > stripe.redirectToCheckout:您必须提供 lineItems、items 或 sessionId 之一

问题描述

几周以来,我一直在将 Stripe checout 集成到我的网站中。内容将是动态的,并在结帐过程中设置名称/描述和价格。

我目前正在运行以下内容:

创建-checkout-session.php

<?php
require('../config.php');
require_once('../includes/stripe-php/init.php');

// Set your secret key. Remember to switch to your live secret key in production!
// See your keys here: https://dashboard.stripe.com/account/apikeys
 \Stripe\Stripe::setApiKey('sk_test_lF...');

 $checkout_session = \Stripe\Checkout\Session::create([
 'payment_method_types' => ['card'],
 'line_items' => [[
'name' => 'T-shirt',
'description' => 'Description of item',
'images' => ['https://example.com/t-shirt.png'],
'amount' => 500,
'currency' => 'gbp',
'quantity' => 1,
]],
'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'https://example.com/cancel',
]);


?>

结帐会话 ID 可以使用

    <?php echo json_encode($checkout_session['id']) ?>

在脚本中,我有触发此功能的购买照片按钮

$( document ).ready(function() {
$('#buyingPhoto').on('click', function() {

    var stripe = Stripe('pk_test_CX...');
         console.log("Can a button be depressed?")
            stripe.redirectToCheckout({
                // Make the id field from the Checkout Session creation API response
                // available to this file, so you can provide it as parameter here
                // instead of the {{CHECKOUT_SESSION_ID}} placeholder.
                sessionId: document.$checkout_session
            }).then(function (result) {
                // If `redirectToCheckout` fails due to a browser or network
                // error, display the localized error message to your customer
                // using `result.error.message`.
            });
});
});

但是我得到参考错误。除了更改域以成功/取消我还缺少什么?

标签: javascriptphpstripe-payments

解决方案


为了让您的代码在客户端工作,您需要在参数中传递 Checkout Sessionidcs_test_123456客户端sessionId

目前,您的代码正在传递sessionId: document.$checkout_session此变量可能未初始化的位置。我的猜测是您正在尝试访问 Javascript 中的 PHP 变量,因为它们是独立的环境,所以无法以这种方式工作。相反,您需要修复您的 JS 代码以正确获取 PHP 变量中的值。

如果您将 JS 和 PHP 混合在一个文件中,最简单的方法是:

sessionId: '<?php echo $checkout_session->id; >?',

如果您不是并且已经分离了 PHP 和 JS,那么您需要找到一种从 PHP 变量加载值的方法,就像从服务器加载其他信息一样。


推荐阅读