Client Only Dashboard: Choose How Many.

Stripe's JavaScript Snippet

In the last section we copied some autogenerated code from the Prices section of one of the Products we created in our Stripe account. This was pasted into a webpage resulting in a Checkout button appearing on that page. On clicking that button we are taken to a Stripe hosted checkout page which enables the user to pay, through a variety of methods, for one of the Product being sold at the price specified for that product in the Stripe account.

Here we will additionally have an input element on the page so that the user can enter the number of units of the product they want to buy. First lets look at Stripe's autogenerated code before we modify it:


    <!-- 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_1H2Lq1GmidqBA55lPdTu3pQt"
      role="link"
      type="button"
    >
      Buy Me a Coffee!!
    </button>

    <div id="error-message"></div>

    <script>
    (function() {
      var stripe = Stripe('pk_live_...redacted...');

      var checkoutButton = document.getElementById('checkout-button-price_1H2Lq1GmidqBA55lPdTu3pQt');
      checkoutButton.addEventListener('click', function () {
        // When the customer clicks on the button, redirect
        // them to Checkout.
        stripe.redirectToCheckout({
          lineItems: [{price: 'price_1H2Lq1GmidqBA55lPdTu3pQt', quantity: 1}],
          mode: 'payment',
          // 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: window.location.protocol + '//stevespages.org.uk/code-examples/stripe-payment/?session_id={CHECKOUT_SESSION_ID}',
          cancelUrl: window.location.protocol + '//stevespages.org.uk/code-examples/stripe-payment',
        })
        .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>
    

OK I did modify the button by replacing the value "Checkout" with "Buy Me a Coffee!" and I redacted my API Publishable key (pk_live_...) before displaying it on this website. The Stripe JavaScript code has a function which runs in response to the user clicking the "Buy Me a Coffee!" button. That function has a key value pair in it with the key being quantity and the value equal to 1. We need the user to be able to change that value by inputing the number of the product they want to buy into an input element.

We need to change the value of quantity from the integer, 1, to a variable name of our choosing (numberOfCoffees. That can be seen here:


          // ***Change Three*** I change the value 1 to the variable "numberOfCoffees"
          lineItems: [{price: 'price_1H2Lq1GmidqBA55lPdTu3pQt', quantity: numberOfCoffees}],
          // ***End of Change Three***
    

We need to provide an input element on the page that the user can enter a number into


    // ***Change One***
    <input type="number" id="how-many-coffees>
    // ***End of Change One***
    

We need to add a line of code to the JavaScript function so that when it runs it puts the value the user put into the input element into the variable we choose for the value of the quantitiy key (or property as it is often called).


        // ***Change Two***
        numberOfCoffees = parseInt(document.getElementById('steve-number-tickets').value);
        // ***End of Change Two***
    

The parseInt() function wraps the getElementById() function because the latter will get the integer the user has entered as a string. The parseInt() function converts the string type to number type which is required for Strip JavaScript code to work. See this question on Stackoverflow.

The next block of code contains the changes to the code which enable the user to choose how many units of the product they want to buy. I have indicated the three additions noted above in comments on the page.



    <!-- ***Change One*** -->
    <input type="number" id="how-many-coffees>
    <!-- ***End of change One*** -->

    <!-- 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_1H2Lq1GmidqBA55lPdTu3pQt"
      role="link"
      type="button"
    >
      Buy Me a Coffee!!
    </button>

    <div id="error-message"></div>

    <script>
    (function() {
      var stripe = Stripe('pk_live_...redacted...');

      var checkoutButton = document.getElementById('checkout-button-price_1H2Lq1GmidqBA55lPdTu3pQt');
      checkoutButton.addEventListener('click', function () {

        // ***Change Two***
numberOfCoffees = parseInt(document.getElementById('steve-number-tickets').value);
        // ***End of Change Two***

        // When the customer clicks on the button, redirect
        // them to Checkout.
        stripe.redirectToCheckout({
                  
          // ***Change Three*** I change the value 1 to the variable "numberOfCoffees"
          lineItems: [{price: 'price_1H2Lq1GmidqBA55lPdTu3pQt', quantity: numberOfCoffees}],
          // ***End of Change Three***

          mode: 'payment',
          // 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: window.location.protocol + '//stevespages.org.uk/code-examples/stripe-payment/?session_id={CHECKOUT_SESSION_ID}',
          cancelUrl: window.location.protocol + '//stevespages.org.uk/code-examples/stripe-payment',
        })
        .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>
    

As well as displaying the code in this web page I have also included it in the page (without putting it inside pre and code and replacing the less than character with its html entity referencene) so you can see the actual result:

How many coffees do you want to buy me?