Hello Magento Friends,
This blog will help you to learn How to Create Coupon Codes Programmatically in Magento 2.
Magento 2 store owners can encourage customers to make a purchase and increase sales with the help of coupon codes. Coupon codes are created when you want to offer discounts to customers. Coupon Code Manager helps to effortlessly manage coupon codes of your Magento 2 store.
Magento 2 provides the option the create coupon codes through admin panel. However, you can create coupon codes programmatically in Magento 2.
Steps to Create Coupon Codes Programmatically in Magento 2:
Step 1: You need to create a root script file on your Magento root directory.
Path of file: Root Directory\pub\Customcoupon.php
Now add the below code
<?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('adminhtml'); $coupon['name'] = 'custom_coupon'; $coupon['desc'] = ' 10% Off Discount coupon.'; $coupon['start'] = date('Y-m-d'); $coupon['end'] = ''; $coupon['max_redemptions'] = 1; $coupon['discount_type'] ='by_percent'; $coupon['discount_amount'] = 10; $coupon['flag_is_free_shipping'] = 'no'; $coupon['redemptions'] = 1; $coupon['code'] ='10%OFF'; $shoppingCartPriceRule = $obj->create('Magento\SalesRule\Model\Rule'); $shoppingCartPriceRule->setName($coupon['name']) ->setDescription($coupon['desc']) ->setFromDate($coupon['start']) ->setToDate($coupon['end']) ->setUsesPerCustomer($coupon['max_redemptions']) ->setCustomerGroupIds(array('0','1','2','3',)) ->setIsActive(1) ->setSimpleAction($coupon['discount_type']) ->setDiscountAmount($coupon['discount_amount']) ->setDiscountQty(1) ->setApplyToShipping($coupon['flag_is_free_shipping']) ->setTimesUsed($coupon['redemptions']) ->setWebsiteIds(array('1')) ->setCouponType(2) ->setCouponCode($coupon['code']) ->setUsesPerCoupon(NULL); $shoppingCartPriceRule->save();
Now, check the coupon code from the Magento 2 admin panel.
Conclusion:
This way, you can easily create coupon codes programmatically in Magento 2. If you have any doubts, let me know through the comment section. Share the article with your friends and stay updated so that you do not miss out on our latest tutorial.
Happy Coding!