Create Coupon code Programmatically


By Default Magento Gives us the functionality to create a coupon for cart(Cart Rule) and for catalog (Catalog Rule). But What if we want to create a coupon dynamically as per our conditions without going to admin section.


Example: if we want to create a functionality to send a coupon code on some condition to a customer or if we want to send a gift card value as a coupon code to other customers.

There are also many Extensions available which are performing the same custom coupon code part. Here you can check that too.

So, let get Dig Into this.
But Before this we assume that one should a basic knowledge about Module and its base structure, as its a core of our Work. if not then please go to this Link.

Now as we are aware about base Module structure.

Lets Proceed Further

Here we have created a Cart rule Coupon which will be used at checkout page. we are using a helper function whi123ch could be used any where as per our requirement.

In Our Case It at Excellence/Hello/Helper

Above, we have define a function which will create a coupon code as per the given fields every time its gets trigger.
generateCouponCode( $length, $chars = null ) function return a random string with the given length that we pass as a parameter in it.

Note: Here in $coupon[‘discount_type’] we are setting the type of coupon i.e; either it can be Percentage type or fixed type which will be applied on subtotal of cart depending upon our requirement.

By Default we are setting it to active, all rest of the functionality of coupon code will be working as it made for Magento2.

Well, Its all Done As the Coupon Get Created and get saved into Magento 2 Database Table -> Salesrule Coupon with relevant information as we provided in above code.

One can also check in Admin Section Under
Marketing>Cart Price Rule.
Here will see our Dynamic Coupon code that we created via Above Code.

Well Its all Done for now.
Further one can use this according to there Needs.