marketing scripts | | contact us handler | Search

This code sets up a simple online checkout system using Stripe.js, allowing users to purchase products by clicking a button and securely handling payment processing.

Run example

npm run import -- "make a purchase with stripe"

make a purchase with stripe

var head = document.getElementsByTagName('head')[0];
var newScript = document.createElement("script");
newScript.src = 'https://js.stripe.com/v3';
head.appendChild(newScript);

var stripe;
newScript.onload = function () {
    stripe = Stripe('pk_live_4LdeNXQQ1sm3SECaJRr5lMg9000RQ4FXDa');
}

function checkout(evt) {
    var sku = evt.value;
    // When the customer clicks on the button, redirect
    // them to Checkout.
    stripe.redirectToCheckout({
        items: [{sku: sku, quantity: 1}],
        billingAddressCollection: 'required',
        successUrl: window.location.protocol + '//' + window.location.host + '/success',
        cancelUrl: window.location.protocol + '//' + window.location.host + '/canceled',
    })
    .then(function (result) {
        if (result.error) {
            // error, display the localized error message to your customer.
            var displayError = document.getElementById('error-message');
            displayError.textContent = result.error.message;
        }
    });
}

What the code could have been:

// Get the head element from the document
const head = document.querySelector('head');

// Create a new script element to load Stripe library
const stripeScript = document.createElement('script');
stripeScript.src = 'https://js.stripe.com/v3';

// Append the script to the head element
head.appendChild(stripeScript);

// Initialize Stripe object when script is loaded
let stripe;

// Define stripeKey for better code organization
const stripeKey = 'pk_live_4LdeNXQQ1sm3SECaJRr5lMg9000RQ4FXDa';

// Wait for script to load before initializing Stripe object
stripeScript.onload = function () {
  // Initialize Stripe object with public key
  stripe = Stripe(stripeKey);
}

// Function to handle checkout button click event
function checkout(evt) {
  // Get the selected sku from the event
  const sku = evt.target.value;

  // Check if the script is loaded before proceeding
  if (stripe) {
    // Redirect to Checkout with required items and success URL
    stripe.redirectToCheckout({
      items: [{ sku, quantity: 1 }],
      billingAddressCollection:'required',
      successUrl: `${window.location.protocol}://${window.location.host}/success`,
      cancelUrl: `${window.location.protocol}://${window.location.host}/canceled`,
    })
   .then(result => {
      // Check for any errors
      if (result.error) {
        // Display the error message to the user
        const errorMessage = document.getElementById('error-message');
        errorMessage.textContent = result.error.message;
      }
    });
  } else {
    // Display error message if Stripe object is not initialized
    const errorMessage = document.getElementById('error-message');
    errorMessage.textContent = 'Stripe script is not loaded yet.';
  }
}

This code snippet sets up Stripe.js for a simple checkout process on a webpage.

Here's a breakdown:

  1. Include Stripe.js:

  2. Initialize Stripe:

  3. Checkout Function:

Overall Purpose:

This code integrates Stripe's payment processing into a webpage, allowing users to purchase products by clicking a button. It handles the checkout flow, collects billing information, and redirects the user to success or cancel pages based on the outcome.