Shopify: Automatically assign coupon to user

If you have users that all have different coupon codes pointed to their account, you could add these to the cart automatically using hidden input and metafields.

Metafields

The metafields object allows you to store additional information for products, collections, customers, orders, blogs, pages and your shop. You can output metafields on your storefront using Liquid.

This means we could assign data to a customer, what later we could feed to the hidden input. This example has the following metafield structure: customer.metafields.wholesale.key

Also Shopify only allows one coupon per checkout.

You could add data using the Shopify rest API, but for convenience I used this handy free App.

File: sections/cart-template.liquid

The code goes as follows:

  1. Feed the hidden input the user’s dedicated/assign coupon code that we receive from the metadata.
  2. When the user clicks the final checkout button, that triggers the script to run that makes the URL structure as follows: shop.com/checkout?discount=
  3. The coupon code inside the hidden input will be fed to the URL ex: shop.com/checkout?discount=”mycouponcode”
$(document).ready(function(){
  //listen to the promo button click
  $('#code').on('click', function(event){
    //disable the button event
    event.preventDefault();
    //write the url format
    var theUrl = '/checkout?discount=';
    //grab the discount code from the input
    var theDiscount = $('#customer_wholesale').val();
    //full url to redirect to checkout with promo code
    var toRedirect = theUrl+theDiscount;
    //console.log(toRedirect);
    //redirect
    window.location.href = toRedirect;
  });
});
File: snippets/cartpage-design1.liquid
<input type="hidden" id="customer_wholesale" value="{{customer.metafields.wholesale.key}}">
<form action="/cart" method="post" novalidate id="updateform">
  <a href="/checkout?discount=none" id="code">
    <button type="submit" class="btn btn-lg" id="final_checkout" name="checkout">
      <span class="icon icon-check_circle"></span>
      {{ 'cart.general.checkout' | t }}
    </button>
  </a>
</form>

Leave a Reply