我为使用 AJAX 提交的三种不同产品设置了三个 Stripe 按钮,如下页面部分所示:
<!-- key stripe settings such as stripe account and product variables -->
<?php require_once 'config.php'; ?>
<div id="buynow">
<button class="stripe-button stripebutton1" id="payButton">Buy Now</button>
</div>
<div id="buynow2">
<button class="stripe-button stripebutton1" id="payButton2">Buy Now</button>
</div>
<div id="buynow3">
<button class="stripe-button stripebutton1" id="payButton3">Buy Now</button>
</div>
<script src="https://js.stripe.com/v3/"></script>
一个按钮可以工作,但很难找到一种方法将每个按钮发送到自己的表单,以便使用类似的 AJAX 方法通过条带进行处理。
<script>
var buyBtn = document.getElementById('payButton');
var responseContainer = document.getElementById('paymentResponse');
// Create a Checkout Session with the selected product
var createCheckoutSession = function (stripe) {
return fetch("stripe_charge.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
checkoutSession: 1,
}),
}).then(function (result) {
return result.json();
});
};
// Handle any errors returned from Checkout
var handleResult = function (result) {
if (result.error) {
responseContainer.innerHTML = '<p>'+result.error.message+'</p>';
}
buyBtn.disabled = false;
buyBtn.textContent = 'Buy Now';
};
// Specify Stripe publishable key to initialize Stripe.js
var stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');
buyBtn.addEventListener("click", function (evt) {
buyBtn.disabled = true;
buyBtn.textContent = 'Please wait...';
createCheckoutSession().then(function (data) {
if(data.sessionId){
stripe.redirectToCheckout({
sessionId: data.sessionId,
}).then(handleResult);
}else{
handleResult(data);
}
});
});
</script>
我正在努力寻找一种在 AJAX 中为每个相应 ID 运行此脚本的方法 - 例如,第一个脚本附加到 id="payButton",下一个脚本附加到 id="payButton2",最后一个脚本附加到 id="payButton3 ”
牛魔王的故事