How can we create coupon or discount codes programmatically in magento 2 ?


As we know coupon codes are the combination of letters and digits which are given to the customer to avail a special discount offer at the checkout page of an online store. Nowadays it’s the basic technique to attract customers to online stores.

In this blog, we will create coupon codes programmatically. 

For this we need a model class Magento\SalesRule\Model\Rule, With the help of this class, we will create coupon code programmatically.

In this, we will create our own coupon code with the ‘CR’ prefix and then some random suffix.

The coupon name will have the prefix “coupon”.

Let’s start with the code:

Explanation of methods used:

  • setName() Method used for set  Rule Name.
  • setDescription() is used for set rule Description
  • setFromDate() is used to set coupon start dates.
  • setToDate() is used to set coupon expiry dates.
  • setUsesPerCustomer() is used to set the maximum number of uses of coupons per customer.
  • setIsActive() is used for Enabled disabled Rules. Its value is true or false
  • setCustomerGroupIds() Method used for  Customer Groups field value. Parameters type Should Array-like [0, 1]. 
  • setCouponType(), Using this method you can set Coupon type It value will be 
    • 1 (No Coupon) or
    • 2 (Specific Coupon).
  • setSimpleAction() is used for set Coupon discount type means Value of  Apply field at Action tab. Its value may be 
    • by_percent (i.e Percent of product price discount), 
    • by_fixed(i.e Fixed amount discount) oR 
    • cart_fixed(i.e Fixed amount discount for the whole cart)Or 
    • buy_x_get_y(i.e Buy X get Y free (discount amount is Y))
  • setDiscountAmount() is used for set field Discount Amount value.
  • setDiscountQty() is used for set  Maximum Qty Discount is Applied To field value. Its value will be an integer.
  • setSimpleFreeShipping() is used to set the Free Shipping field.Its value should be string and value will be 
    • 0 (I.e No),
    • 1 (I.e For matching items only),
    • 2 ( I.e For shipment with matching items).

This coupon code can be created in many scenarios like in refund process, offer section, audience gather to plan, promotions, etc

 

Leave a Reply