我试图模仿Stripe在他们的Github中的功能,通过我的网站创建一个新的订阅会话。 当我点击触发事件处理程序的按钮时,我在Google Chrome的控制台中收到以下错误:
script.js:3 POST http://127.0.0.1:3000/create-checkout-session net::ERR_CONNECTION_REFEUND createCheckoutSession@script.js:3(匿名)@script.js:39
和
未捕获(在promise中)TypeError:无法获取promise.Then(async)
(anonymous)@Script.js:39
VS代码中的终端向我显示了这个错误(显示了消息的一部分):
{错误:缺少必需的参数:line_items[0][currency].
我假设script.js文件中有什么不正确的地方,但我不确定是什么地方? 下面是该文件的代码:
// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function (priceId) {
return fetch('/create-checkout-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
priceId: priceId,
}),
}).then(function (result) {
return result.json();
});
};
// Handle any errors returned from Checkout
var handleResult = function (result) {
if (result.error) {
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
};
/* Get your Stripe publishable key to initialize Stripe.js */
fetch('/setup')
.then(function (result) {
return result.json();
})
.then(function (json) {
var publishableKey = json.publishableKey;
var basicPriceId = json.basicPrice;
var stripe = Stripe(publishableKey);
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById('basic-plan-btn')
.addEventListener('click', function (evt) {
console.log('This is working');
createCheckoutSession(basicPriceId).then(function (data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId,
})
.then(handleResult);
});
});
});
如有任何帮助,我们将不胜感激!
接收前端请求以实际创建会话的服务器端处理程序看起来是什么样子的? 这将在您的后端使用秘密密钥完成。
如果我假设您的fetch大致映射到那个create调用,根据您如何使用pass参数,您可能需要添加一些层。 例如,确保您的价格ID位于line_items
数组的行项目对象中:
stripe.checkout.sessions.create(
{
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/cancel',
payment_method_types: ['card'],
line_items: [
{
price: priceId,
quantity: 2,
},
],
mode: 'payment',
},
)