Stripe JavaScript Checkout Example

Stripe JavaScript Checkout Example
Code Snippet:Dynamic Pricing w/ Stripe Checkout
Author: Greg Rickaby
Published: January 9, 2024
Last Updated: January 22, 2024
Downloads: 757
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code example demonstrates Stripe checkout process. It calculates and displays the total price based on the selected quantity, applies discounts, and lets you pay securely via Stripe. This code allows you to create a simple checkout experience on your website.

You can use this code on your e-commerce website to enable a smooth and user-friendly checkout form.

How to Create Stripe Checkout Form Using JavaScript

1. Copy and paste the HTML code into your website where you want the checkout form to appear. Customize the form elements, such as changing the product name, description, and pricing as needed.

<h1>Buy some cool widgets!</h1>

<form class="stripe-checkout">
	<div class="quantity-select">
		<label for="quantity">Select Quantity</label>
		<select name="quantity" class="form-control" id="quantity" onChange="calculatePrice()">
			<option value="1" selected>1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
			<option value="7">7</option>
			<option value="8">8</option>
			<option value="9">9</option>
			<option value="10">10</option>
			<option value="11">11</option>
			<option value="12">12</option>
			<option value="13">13</option>
			<option value="14">14</option>
			<option value="15">15</option>
			<option value="16">16</option>
			<option value="17">17</option>
			<option value="18">18</option>
			<option value="19">19</option>
			<option value="20">20</option>
		</select>
	</div><!-- .quantity-select -->

	<div class="text-content" id="pricingContent">
		<p class="total-price"><strong>Total: $89.99</strong></p>
	</div><!-- .text-content -->

	<button id="buyNow" data-price="8999">Pay <span class="price">$89.99</span></button>
</form>

<p><em>Select a quantity, and the click "Pay" to see this Pen in action!</em></p>

2. Include the CSS code in your website’s stylesheet to style the checkout form as desired.

body {
	font-family: sans-serif;
}

.stripe-checkout {
	background-color: gray;
	padding: 24px;
	width: 300px;
}

table {
	margin: 5px 0;
}

.total td {
	border-top: 2px solid black;
}

3. Now, load the the Stripe Checkout JS by adding the following scripts before closing the body tag:

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

4. Finally, add the following JavaScript code to your website. This code powers the dynamic pricing and Stripe integration. Ensure you have a valid Stripe account and replace the key in the stripeHandler function with your Stripe API key.

/**
 * Calculate price.
 */
function calculatePrice() {
	// Set defaults.
	const normalRetailPrice = 89.99;
	const extraDiscount = 0;
	let quantity = Number(document.querySelector("#quantity").value);
	let discount = 0;

	// First, calculate discount.
	if (quantity < 2) {
		discount = 0;
	} else if (quantity > 1 && quantity < 6) {
		discount = 30;
	} else if (quantity > 5 && quantity < 11) {
		discount = 33;
	} else if (quantity > 10 && quantity < 21) {
		discount = 35;
	} else if (quantity > 20 && quantity < 26) {
		discount = 40;
	}

	// Next, calculate the different prices.
	let price = +(
		quantity * normalRetailPrice -
		(quantity * normalRetailPrice * discount) / 100
	).toFixed(2);
	let pricePerSubscription = +(price / quantity).toFixed(2);
	let discountPrice = +(price - (price * extraDiscount) / 100).toFixed(2);
	let totalSavings = Math.abs(
		+(
			normalRetailPrice * quantity -
			(price - (price * extraDiscount) / 100)
		).toFixed(2)
	);
	let totalRetailPrice = +(normalRetailPrice * quantity).toFixed(2);
	let totalInCents = Math.round(discountPrice * 100);

	// Then, throw pricing into an object.
	let pricingData = {
		quantity: quantity,
		discount: discount,
		extraDiscount: extraDiscount,
		price: price,
		pricePerSubscription: pricePerSubscription,
		discountPrice: discountPrice,
		totalSavings: totalSavings,
		totalRetailPrice: totalRetailPrice,
		totalInCents: totalInCents
	};

	// Finally, update the markup!
	buyNowHandler(pricingData);
	pricingContentHandler(pricingData);
}

/**
 * Buy now button.
 */
function buyNowHandler(pricingData) {
	// Grab the buy now button.
	button = document.querySelector("#buyNow");

	// No button? Bail.
	if ("undefined" === button) {
		console.error("The buy now button is missing!");
	}

	// Update button content.
	button.setAttribute("data-price", pricingData.totalInCents);
	button.innerText = `Pay $${pricingData.discountPrice}`;
}

/**
 * Pricing content.
 */
function pricingContentHandler(pricingData) {
	// Grab the pricing content.
	content = document.querySelector("#pricingContent");

	// No content? Bail.
	if ("undefined" === content) {
		console.error("The pricing content is missing!");
	}

	// Update the markup.
	pricingContent.innerHTML = `
		<div class="text-content">
			<table class="pricing">
				<tr class="retail">
					<td>Retail Price</td>
					<td>$${pricingData.totalRetailPrice}</td>
				</tr>
				<tr class="discount">
					<td>${pricingData.discount}% Discount</td>
					<td>-$${pricingData.totalSavings}</td>
				</tr>
				<tr class="total">
					<td><strong>Total Price</strong></td>
					<td><strong>$${pricingData.discountPrice}</strong></td>
				</tr>
			</table>

			<p class="discount">You're saving ${pricingData.discount}% per subscription!</p>
		</div>
	`;
}

/**
 * Stripe checkout.
 *
 * @link https://stripe.com/docs/checkout#integration-custom
 */
function stripeHandler() {
	// Configure Stripe.
	const handler = StripeCheckout.configure({
		key: "pk_test_TYooMQauvdEDq54NiTphI7jx",
		image: "https://stripe.com/img/documentation/checkout/marketplace.png",
		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.
		}
	});

	// Grab the button.
	let button = document.querySelector("#buyNow");

	// No button? Bail.
	if ("undefined" === button) {
		console.error("The buy now button is missing!");
	}

	// Open checkout on click.
	button.addEventListener("click", function (e) {
		handler.open({
			name: "Cool Widgets",
			description: "The best widgets money can buy!",
			zipCode: true,
			amount: button.dataset.price // Must be in cents!
		});
		e.preventDefault();
	});

	// Close Checkout on page navigation.
	window.addEventListener("popstate", () => handler.close());
}

// Fire checkout after everything has loaded.
document.addEventListener("DOMContentLoaded", stripeHandler());

That’s all! hopefully, you have successfully integrated this JavaScript Stripe Checkout form example into your website. This code empowers you to offer a user-friendly and secure shopping experience for your customers. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X