How to Create Coupon (Discount) code Programmatically Magento 2?

Create Coupon Programmatically in Magento 2 is the process of first create a Sales rule with basic details, next get rule id and apply rule id to the generate the new coupon.

Create Sales Rule using Magento\SalesRule\Api\Data\RuleInterfaceFactory and Coupon using Magento\SalesRule\Api\Data\CouponInterface.

We will create a coupon code with 20FIXED, When you applied this coupon from the cart page, It will be given a discount of $20 for the whole cart.

Coupon code

Now When you check the admin panel, Marketing -> Promotions -> Cart Price rules,

You have displayed a new Shopping cart rule with the sales rule grid.

You can set Coupon type as per your needs. In the above demo, We have used action type is Fixed amount discount for whole cart (cart_fixed).

You can see a list of all the actions apply conditions from the Magento\SalesRule\Api\Data\RuleInterface.

You can Create Coupon Dynamically using the above code approach with required changes on the code.

coupon action