一页上的多个条纹签出按钮

时间:2019-03-31 18:21:53

标签: javascript html stripe-payments

for循环中的一页上,我有可变数量的Stripe Checkout按钮,可以是不同的数量/标题。不幸的是,这些按钮无法通过第一个按钮。这就是渲染的样子。

<a class="btn btn-primary text-white mt-3 btn-sm" id="purchaseButton">Add (£20)</a>

<a class="btn btn-primary text-white mt-3 btn-sm" id="purchaseButton">Add (£35)</a>

<a class="btn btn-primary text-white mt-3 btn-sm" id="purchaseButton">Add (£42)</a>

然后我的脚本名为:

<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
  key: 'pk_test_TYooMQauvdEDq54NiTphI7jx',
  locale: 'auto',
  token: function(token) {
    // You can access the token ID with `token.id`.
    // Get the token ID to your server-side code for use.
  }
});

document.getElementById('purchaseButton').addEventListener('click', function(e) {
  // Open Checkout with further options:
  handler.open({
    name: 'Stripe.com',
    src: "https://checkout.stripe.com/checkout.js",
    class: "stripe-button",
    key: "pk_test_6pRNASCoBOKtIshFeQd4XMUh",
    name: "Demo Site",
    email: "{{ currentUser.email }}",
    currency: "gbp",
    description: "{{ entry.title }} - {{ entry.author.username }}",
    amount: "{{ entry.cost * 100 }}"
  });
  e.preventDefault();
});

// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
  handler.close();
});
</script>

有没有办法只调用一次脚本并通过按钮动态发送amount

1 个答案:

答案 0 :(得分:0)

这是将Stripe侦听器分配给多个签出按钮的正确过程。这个例子也使用计划,根据您的问题更改产品。

首先,使用每个具有唯一ID的结帐按钮创建标记。

在示例中,PHP被用作服务器端语言来生成标记。更改为JavaScript,或者在您认为合适的情况下使用任何可用的方法。

<?php foreach ($planData as $plan) { ?>
    <form method="GET" onsubmit="return false;">
        <?php echo $plan['Title']; ?>
            <button id="checkout-button-<?php echo $plan['Id']; ?>">
                Subscribe
            </button>
    </form>
<?php } ?>

然后,在客户端的每个计划条目的入口,将侦听器分配给相应的按钮:

$(plans).each(function (index, plan) {
    var checkoutButton = document.querySelector('#checkout-button-' + plan.Id);
    checkoutButton.addEventListener('click', function () {
    stripe.redirectToCheckout({
        items: [{
             // Define the product and plan in the Dashboard first, and use the plan
             // ID in your client-side code.
             plan: plan.StripePlanId,
             quantity: 1
             }],
          successUrl: plan.UrlSubscribeSuccess,
          cancelUrl: plan.UrlSubscribeCancel,
          customerEmail: userEmail
     });
   });
 });