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:


namespace Innovationm\CreditCoupon\Controller\Index;

use Magento\Framework\App\Action\Action;

use Magento\Framework\App\Action\Context;

use Magento\Framework\Controller\ResultFactory;

use Magento\SalesRule\Model\Rule;

class Index extends Action



     * @var PageFactory


    protected $_resultPageFactory;


     * @param Context     $context

     * @param Rule $rule

     * @param PageFactory $resultPageFactory


    public function __construct(

        Context $context,

        ResultFactory $resultFactory,

        Rule $rule

    ) {

        $this->resultFactory = $resultFactory;

        $this->shoppingCartPriceRule = $rule;



    public function execute()


        $coupon = [] ;

        $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //random string to generate the code

        $ranStr = substr(str_shuffle($str_result), 0, 5); 

        $coupon['name'] = "coupon ".$ranStr; //Generate a rule name

        $coupon['desc'] = "Discount amount coupon";

        $coupon['start'] = date('Y-m-d'); //Coupon use start date

        $coupon['end'] = ''; //coupon use end date

        $coupon['max_redemptions'] = 1; //Uses per Customer

        $coupon['discount_type'] ='cart_fixed'; //for discount type

        $coupon['discount_amount'] = 100; //discount amount/percentage

        $coupon['redemptions'] = 1;

        $coupon['code'] = 'CR'."_".$ranStr; //generate a random coupon code






        ->setCustomerGroupIds(array('0','1','2','3')) //select customer group












        $this->shoppingCartPriceRule->save(); //Coupon code will be generated;



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