Hello guys. I’m trying to integrate recurring Stripe subscription payments via “Stripe Checkout”. Looks like this.
Payment is done on stripe rather than on the website server. It’s secure and offers me business protection.
I’ve looked over some Stripe Guides. Though for subscription payments they don’t list ready to go snippets as an option to copy/paste into an html element, it does seem to work.
One Time Payment: https://stripe.com/docs/payments/checkout/client
Subscription: https://stripe.com/docs/payments/checkout/set-up-a-subscription
An issue with the snippets, is that I can’t use html elements as I need dynamic buttons. I also can’t figure out how to to make it work in Javascript either, but I hope it’s possible.
Anyone know how this could be best done to connect a dynamic button to redirect to stripe checkout? I’m thinking adding the product ID into database, then having an array in javascript that imports it.
Product Snippet:
<!-- Load Stripe.js on your website. -->
<script src="https://js.stripe.com/v3"></script>
<!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. -->
<button
style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
id="checkout-button-price_1HASL5IfqBRoEUN03Uo1xelP"
role="link"
type="button"
>
Checkout
</button>
<div id="error-message"></div>
<script>
(function() {
var stripe = Stripe('pk_test_publickey');
var checkoutButton = document.getElementById('checkout-button-price_1HASL5IfqBRoEUN03Uo1xelP');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
lineItems: [{price: 'price_1HASL5IfqBRoEUN03Uo1xelP', quantity: 1}],
mode: 'subscription',
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: 'https://website.com/success',
cancelUrl: 'https://website.com/canceled',
})
.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('error-message');
displayError.textContent = result.error.message;
}
});
});
})();
</script>