1 回答

TA貢獻1830條經驗 獲得超3個贊
一種選擇是添加 3 個不同的點擊處理程序,每個按鈕一個。然后,當單擊按鈕時,您可以向服務器傳遞對該按鈕的一些引用和 ID,這將有助于創建正確類型的結賬會話。
一個非?;镜陌姹究赡苋缦滤荆?/p>
// initialize Stripe, first.
var stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');
// grab reference to the buttons
var buyBtn = document.getElementById('payButton');
var buyBtn2 = document.getElementById('payButton2');
var buyBtn3 = document.getElementById('payButton3');
// register click handlers for each button
buyBtn.addEventListener("click", function (evt) {
buyBtn.disabled = true;
buyBtn.textContent = 'Please wait...';
// each click handler will pass some
// ID that will be passed to the server
// which would use that identifier to determine
// what parameters to use to create the
// Checkout Session.
createCheckoutSession(1, buyBtn);
});
buyBtn2.addEventListener("click", function (evt) {
buyBtn2.disabled = true;
buyBtn2.textContent = 'Please wait...';
createCheckoutSession(2, buyBtn2);
});
buyBtn3.addEventListener("click", function (evt) {
buyBtn3.disabled = true;
buyBtn3.textContent = 'Please wait...';
createCheckoutSession(3, buyBtn3);
});
// no need to pass in `stripe` here, as it's
// in the parent scope, instead we're passing
// the identifier down.
function createCheckoutSession(identifier, btn) {
return fetch("stripe_charge.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
checkoutSession: identifier, // passing button identifier to server
}),
}).then(function (result) {
return result.json();
}).then(function (result) {
// if the stripe_charge.php call fails
// re-enable the button.
if (result.error) {
responseContainer.innerHTML = '<p>'+result.error.message+'</p>';
btn.disabled = false;
btn.textContent = 'Buy Now';
} else {
// if the call to server was successful, redirect to Checkout.
stripe.redirectToCheckout({
sessionId: data.sessionId,
});
}
});
};
從技術上講,您可以將其“干燥”一點,但我認為這應該更簡單一些。
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報