Wednesday, 13 January 2021

How to add multiple stripe button in one page?

I'm following this guide to add stripe checkout to my home-made website. https://stripe.com/docs/checkout/integration-builder

I've a database and a PHP page. In this page I loop a mysql table with products and for each product I display information and add a 'Buy Now' stripe button. I call each button with a unique name (tag id and name). Follow example:

<?php
  <button id="checkout-button-<?php $row['productid']; ?>">Buy <?php echo $row['productname']; ?> </button>
?>

My problem is with javascript:

<!-- Start Stripe Integration -->
    <script type="text/javascript">
        // Create an instance of the Stripe object with your publishable API key
        var stripe = Stripe("<?php echo $stripe_key_public ?>");
        var checkoutButton = document.getElementById("checkout-button **$$Here is the problem$$**");
        checkoutButton.addEventListener("click", function () {
            fetch("my-stripe-checkout.php", {
                method: "POST",
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function (session) {
                    return stripe.redirectToCheckout({ sessionId: session.id });
                })
                .then(function (result) {
                    // If redirectToCheckout fails due to a browser or network
                    // error, you should display the localized error message to your
                    // customer using error.message.
                    if (result.error) {
                        alert(result.error.message);
                    }
                })
                .catch(function (error) {
                    console.error("Error:", error);
                });
        });
    </script>
    <!-- End Stripe Integration -->

How can I add custom eventListener or, parametrize javascript function (with item description, price/amount etc), for each button outside my PHP loop?

Or am I wrong approach solution? Is there a better way to add stripe checkout button for a list of products?

Thanks



from How to add multiple stripe button in one page?

No comments:

Post a Comment