购买完成后更改条纹签出按钮

时间:2019-04-04 13:41:29

标签: stripe-payments

当用户通过Stripe Checkout支付时,我试图使按钮显示为“已支付”,甚至还返回某种console.log。我当前的代码如下所示,但是在控制台错误中出现错误token is not defined

HTML:

<a class="btn btn-primary text-white mt-3 btn-sm purchaseButton" data-amount="23.99" data-name="test" data-email="test@gmail.com" data-description="test">
    Accept & Pay (£23.99)
</a>

JavaScript:

<script src="https://checkout.stripe.com/checkout.js"></script>

<script>
    var handler = StripeCheckout.configure({
        key: 'pk_test_CF2GDj8RsSNWc23MhUJ9kylU00CkI1AJZ5',
        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.
            chargeStatus(token);
        }
    });

    var buyButtons = document.getElementsByClassName('purchaseButton');
    for (i = 0; i < buyButtons.length; i++) {
        buyButtons[i].addEventListener('click', function(e) {
            // Open Checkout with further options:
            handler.open({
                name: this.dataset.name,
                amount: this.dataset.amount,
                src: "https://checkout.stripe.com/checkout.js",
                class: "stripe-button",
                key: "pk_test_6pRNASCoBOKtIshFeQd4XMUh",
                email: this.dataset.email,
                currency: "gbp",
                description: this.dataset.description,
            });
            e.preventDefault();
        });
    }
    // Close Checkout on page navigation:
    window.addEventListener('popstate', function() {
        handler.close();
    });

    function chargeStatus(theObject) {
        fetch("/charge", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify(theObject.id)
        })
        .then(response => {
            if (!response.ok)
                throw response;
            return response.json();
        })
        .then(output => {
            console.log("Purchase succeeded:", output);
        })
        .catch(err => {
            console.log("Purchase failed:", err);
        })
    }

</script>

1 个答案:

答案 0 :(得分:2)

fetch块正在尝试访问该范围中不存在的变量token。您应该在Stripe Checkouts返回令牌供您使用之后执行获取。将您的fetch代码包装在一个函数中,然后在您的token: function(token) {}处理函数中调用该函数。