Skip to content
Advertisement

Add Multiple Stripe Checkout Buttons on one page using Ajax

I have three Stripe buttons for three different products that submit using AJAX, as shown below in the portion of the page below:

<!-- 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>

One button works, but having trouble finding a way send each button to its own form for processing by stripe using a similar AJAX approach.

           <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>

I am struggling a bit to find am an approach in AJAX to run this script for each corresponding ID – for example a first script attached to id=”payButton”, the next to id=”payButton2″ and the last to id=”payButton3″

Advertisement

Answer

One option would be to add 3 different click handlers, one for each button. Then, when a button is clicked, you can pass some reference to that button and an ID to the server which would help create the correct type of Checkout Session.

Here’s what a very basic version might look like:

// 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,
      });
    }
  });
};

You could technically “dry” this up a bit, but I think this should be a little more straightforward.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement