Suppose you have a Stripe Checkout page setup to sell a product.
To link to your payment page, you must generate a Checkout button HTML snippet for display on your site. However, the default snippet only supports one Checkout button. You cannot have several Checkout buttons for the same product on the same page.
This gist modifies Stripe's generated snippet to support several buttons.
-
Setup Stripe Checkout's client-only integration
-
Assemble the data you'll need:
- Your account publishable API key (Over here then "Publishable key")
- Your product plan ID or SKU
- Product Quantity
- Success and cancel landing page URLS
- Include the following snippet on your page
<!-- Paste this anywhere you want a checkout button-->
<!-- You can use as many as you like -->
<div id="stripe-error-message"></div>
<button data-stripe-checkout-button role="link">Checkout</button>
<!-- Include this somewhere on the page-->
<script src="https://js.stripe.com/v3"></script>
<script>
(function() {
const STRIPE_PUBLISHABLE_API_KEY = 'pk_live_***************' // Get this from your Stripe dashboard
const STRIPE_PRODUCT_PLAN_ID = 'plan_*************';
const STRIPE_PRODUCT_QUANTITY = 1;
const SUCCESS_URL = window.location.protocol + "mysite.com/purchase-success";
const CANCEL_URL = window.location.protocol + "mysite.com/store";
var stripe = Stripe(STRIPE_PUBLISHABLE_API_KEY);
function redirectToCheckout (event) {
event.preventDefault(); // Prevent button click from refershing the page in some browsers
stripe.redirectToCheckout({
items: [{plan: STRIPE_PRODUCT_PLAN_ID, quantity: STRIPE_PRODUCT_QUANTITY}],
successUrl: SUCCESS_URL,
cancelUrl: CANCEL_URL,
})
.then(function (result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('stripe-error-message');
displayError.textContent = result.error.message;
}
});
}
// Locate all elements with the `data-stripe-checkout-button` attribute and attach a listener
// Clicking any of these elements will now redirect the user to Stripe Checkout
document.querySelectorAll("*[data-stripe-checkout-button]").forEach(function(element) {
checkoutButton.addEventListener('click', redirectToCheckout);
});
})();
</script>