How to add a BUY NOW secondary button with direct checkout on Shopify

In this tutorial we will see how to create a direct checkout system by adding a Buy Now button in addition to the Add to Cart button.

As you know, you can add this type of button in Shopify but it is dynamic! This means that the button adapts to the user’s connected payment methods. Indeed this button will change into a Payment by Paypal button, a Google pay button, etc…

It’s good but many people only want a simple Buy Now button without the additional dynamic system! That is why we will learn how to create one 😀

How to install the code

Create the snippet

Go to your Shopify admin and click on “Online Store“.

Click on the Action button and then on “Edit code“.

Find the Snippets folder and click on Add a new snippet and name it “direct-checkout”.

Open and put in the snippet the whole code below:

<style>
  #dg-go-checkout {
    margin:15px 0; 
    width:100%;  
    color: #111 !important;
    background: #f0c14b !important;
    background: linear-gradient(#ffe6a8, #e2b43f) !important;
    border-color: #a88734 #9c7e31 #846a29 !important;
    border-radius: 4px !important;
  }
  #dg-go-checkout:hover { opacity:0.9;  }
</style>

<button class="btn btn-primary" id="dg-go-checkout">Buy Now</button>

<script>
/**
 * Module to ajaxify all add to cart forms on the page.
 *
 * Copyright (c) 2015 Caroline Schnapp (11heavens.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
$( "#dg-go-checkout" ).click(function() {   

Shopify.AjaxifyCart = (function($) {
  
  // Some configuration options.
  // I have separated what you will never need to change from what
  // you might change.
  
  var _config = {
    
    // What you might want to change    
    addingToCartBtnLabel:          'Processing',
    soldOutBtnLabel:               'Sold Out',
    howLongTillBtnReturnsToNormal: 1000, // in milliseconds.
    cartCountSelector:             '.cart-count, #cart-count a:first, #gocart p a, #cart .checkout em, .item-count',
    cartTotalSelector:             '#cart-price',
    // 'aboveForm' for top of add to cart form, 
    // 'belowForm' for below the add to cart form, and 
    // 'nextButton' for next to add to cart button.
    feedbackPosition:              'nextButton',
    
    // What you will never need to change
    addToCartBtnSelector:          '#dg-go-checkout',
    addToCartFormSelector:         'form',
    shopifyAjaxAddURL:             '/cart/add.js',
    shopifyAjaxCartURL:            '/cart.js'
  };
  
  // We need some feedback when adding an item to the cart.
  // Here it is.  
  var _showFeedback = function(success, html, $addToCartForm) {
    $('.ajaxified-cart-feedback').remove();
    var feedback = '<p class="ajaxified-cart-feedback ' + success + '">' + html + '</p>';
    switch (_config.feedbackPosition) {
      case 'aboveForm':
        $addToCartForm.before(feedback);
        break;
      case 'belowForm':
        $addToCartForm.after(feedback);
        break;
      case 'nextButton':
      default:
        $addToCartForm.find(_config.addToCartBtnSelector).after(feedback);
        break;   
    }
    // If you use animate.css
    // $('.ajaxified-cart-feedback').addClass('animated bounceInDown');
    $('.ajaxified-cart-feedback').slideDown();
  };
  var _setText = function($button, label) {
    if ($button.children().length) {
      $button.children().each(function() {
        if ($.trim($(this).text()) !== '') {
          $(this).text(label);
        }
      });
    }
    else {
      $button.val(label).text(label);
    }
  };
  var _init = function() {   
    $(document).ready(function() { 
      
      $(_config.addToCartFormSelector).submit(function(e) {
        e.preventDefault();
        var $addToCartForm = $(this);
        var $addToCartBtn = $addToCartForm.find(_config.addToCartBtnSelector);
        _setText($addToCartBtn, _config.addingToCartBtnLabel);
        $addToCartBtn.addClass('disabled').prop('disabled', true);
        // Add to cart.
        $.ajax({
          url: _config.shopifyAjaxAddURL,
          dataType: 'json',
          type: 'post',
          data: $addToCartForm.serialize(),
          success: function(itemData) {
            // Re-enable add to cart button.
            $addToCartBtn.addClass('inverted');
            window.location.href = "/checkout";
           window.setTimeout(function(){
              $addToCartBtn.prop('disabled', false).removeClass('disabled').removeClass('inverted');
              
            }, _config.howLongTillBtnReturnsToNormal);
            // Update cart count and show cart link.
            $.getJSON(_config.shopifyAjaxCartURL, function(cart) {
              if (_config.cartCountSelector && $(_config.cartCountSelector).size()) {
                var value = $(_config.cartCountSelector).html() || '0';
                $(_config.cartCountSelector).html(value.replace(/[0-9]+/,cart.item_count)).removeClass('hidden-count');
              }
              if (_config.cartTotalSelector && $(_config.cartTotalSelector).size()) {
                if (typeof Currency !== 'undefined' && typeof Currency.moneyFormats !== 'undefined') {
                  var newCurrency = '';
                  if ($('[name="currencies"]').size()) {
                    newCurrency = $('[name="currencies"]').val();
                  }
                  else if ($('#currencies span.selected').size()) {
                    newCurrency = $('#currencies span.selected').attr('data-currency');
                  }
                  if (newCurrency) {
                    $(_config.cartTotalSelector).html('<span class=money>' + Shopify.formatMoney(Currency.convert(cart.total_price, "{{ shop.currency }}", newCurrency), Currency.money_format[newCurrency]) + '</span>');
                  } 
                  else {
                    $(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
                  }
                }
                else {
                  $(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
                }
              };
            });        
          }, 
          error: function(XMLHttpRequest) {
            var response = eval('(' + XMLHttpRequest.responseText + ')');
            response = response.description;
            if (response.slice(0,4) === 'All ') {
              _showFeedback('error', response.replace('All 1 ', 'All '), $addToCartForm);
              $addToCartBtn.prop('disabled', false);
              _setText($addToCartBtn, _config.soldOutBtnLabel);
              $addToCartBtn.prop('disabled',true);
            }
            else {
              _showFeedback('error', '<i class="fa fa-warning"></i> ' + response, $addToCartForm);
              $addToCartBtn.prop('disabled', false).removeClass('disabled');
              _setText($addToCartBtn, _config.addToCartBtnLabel);
            }
          }
        });   
        return false;    
      });
    });
  };
  return {
    init: function(params) {
        // Configuration
        params = params || {};
        // Merging with defaults.
        $.extend(_config, params);
        // Action
        $(function() {
          _init();
        });
    },    
    getConfig: function() {
      return _config;
    }
  }  
})(jQuery);

Shopify.AjaxifyCart.init();
    
});

</script>

I chose the style of an Amazon button by default but you can take change the style if you want to. I show how in the video at the bottom of the article 😉

Button placement

Find the Sections folder and open the “product-template.liquid” file, if you don’t have it go to Templates – “product.liquid”.

At this point you will need to find your form and more specifically the button tag.

Do a ctrl + F (to open the search bar) and look for the following code : “{% endform %}” or “</form>”. Once you find the form, you will copy/paste the following code just above it.

{% include "direct-checkout" %}

All you have to do now is click on the “Save” button in the top right corner to save your changes!

You now have a new button that will allow you to shorten your sales funnel as much as possible 😉

If you want to replace your add to cart button with a buy now button instead of just adding it, this is the tutorial you need: Replace my add to cart button

This tutorial is also available in video format

Hope you found this tutorial helpful !

You have any ideas for new tutorials ? Any questions about this one ? Leave me a comment 😉

Share this article

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on telegram
Share on whatsapp
Share on email

Leave a Reply

Your email address will not be published. Required fields are marked *