Magento provides the Cart Price Rules marketing feature, which allows applying discounts on items/cart, based on various conditions. The discount can be applied automatically as soon as the conditions are met, or when the customer enters a valid coupon code. The coupon codes can be generated per cart price rule via admin panel in Marketing -> Cart Price Rules section. However, sometimes we need to automate this process. Let’s find out how to create a cart price rule and generate coupon codes programmatically in Magento 2.
Let’s find out how to create a cart price rule and generate coupon codes programmatically in Magento 2.
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //random string to generate the code $ranCode = substr(str_shuffle($str_result), 0, 8); $ranStr = substr(str_shuffle($str_result), 0, 5); $coupon['name'] = 'TEST-'.$ranStr.''; //Generate a rule name $coupon['desc'] = 'Discount on First Shopping'; $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'] = 20; //discount amount/percentage $coupon['flag_is_free_shipping'] = 'no'; $coupon['redemptions'] = 1; $coupon['code'] = $ranCode; //generate a random coupon code $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('1','2','3')) //select customer group ->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(1); $shoppingCartPriceRule->save();
Now you are able to check the results in the admin panel under Marketing -> Cart Price Rules.
Don’t hesitate to share your ideas in the comments. Thanks for reading!