How To Programmatically Create Coupon Code In Magento 2

Discount is one serious hack in online stores and that’s how people do businesses in a competitive market.

People tend to love a good deal, it’s human nature. When you are an online business, sometimes, offering the right coupon code to the right person can push conversion.

For example, if you are a Magento 2 store owner and want to offer a personalized coupon code to a potential customer, you might get lucky.

The post gives the method to programmatically create coupon code in Magento 2 store and attract potential customers to use the coupon code, resulting in conversion!

Method To Programmatically Create Coupon Code In Magento 2:

<?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'] = 'Test Rule';
$coupon['desc'] = 'Test Rule';
$coupon['start'] = date('Y-m-d');
$coupon['end'] = '';
$coupon['max_redemptions'] = 1;
$coupon['discount_type'] ='by_percent';
$coupon['discount_amount'] = 50;
$coupon['flag_is_free_shipping'] = 'no';
$coupon['redemptions'] = 1;
$coupon['code'] ='OFF50'; 

$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();

That’s it.

Generate coupon codes in Magento 2 store and effectively use the discount strategies to benefit the business.

Help Magento store owners manage discounts and coupon codes by sharing this solution via social media.

Thanks.

Table of Contents