【发布时间】:2020-12-13 09:06:21
【问题描述】:
我正在尝试做最简单的事情:将用户发送到带有 1 个产品的 Stripe 托管结帐页面。
Stripe 的示例似乎都不起作用,到目前为止我得到的是:
PHP create-checkout-session.php
require_once 'shared.php';
// ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain . '/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain . '/canceled.html',
'payment_method_types' => ['card'], //, 'alipay'
'mode' => 'payment',
'line_items' => [[
'amount' => $price,
'currency' => 'usd',
'name' => $product,
'quantity' => 1,
]]
]);
echo json_encode(['sessionId' => $checkout_session['id']]);
那个 PHP 页面正确地返回了一个会话 ID。
HTML
<html>
<head>
<title>Buy cool new product</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<button id="checkout-button">Checkout</button>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe('pk_test_key'); // removed for Stackoverflow post
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function() {
// Create a new Checkout Session using the server-side endpoint you
// created in step 3.
fetch('create-checkout-session.php', {
method: 'POST',
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
</script>
</body>
</html>
当我单击该按钮时,什么也没有发生,我在 Chrome 开发工具上收到此错误:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new t (https://js.stripe.com/v3/:1:11100)
at Lu (https://js.stripe.com/v3/:1:152624)
at qu (https://js.stripe.com/v3/:1:152923)
at Fu (https://js.stripe.com/v3/:1:153599)
at Bu (https://js.stripe.com/v3/:1:153713)
at e.redirectToCheckout (https://js.stripe.com/v3/:1:154128)
at https://emu.net/stripetest/test.html:24:25
我不明白这个错误。似乎 sessionId 没有正确传递。 HTML 代码直接来自 Stripe 文档: https://stripe.com/docs/payments/checkout/accept-a-payment
说实话,在这一点上我不知道我应该看哪里。 Stripe 的示例似乎都不起作用。有人知道我做错了什么吗?
【问题讨论】:
-
在
.then(function(session) {回调中,如果你console.log(session)会得到什么? -
好主意。我得到的是:{sessionId: "cs_test_blahblahblahblah"}
-
那么看起来你需要
{ sessionId: session.sessionId }而不是{ sessionId: session.id }。 -
是的,就是这样。想将其发布为答案以便我接受吗?
-
懒惰的错别字曾经是旧计算机编程书籍中常见的事情。挑战读者
标签: javascript php stripe-payments