How to Create Magento 2 Coupon Code Programmatically

Here’s a step-by-step guide to creating Magento 2 coupon codes programmatically:

  1. Create a New Coupon Rule: To create a new coupon rule programmatically, you need to first create a new instance of the \Magento\SalesRule\Model\Rule class. You can do this using the Magento 2 Object Manager or dependency injection.
php

use Magento\SalesRule\Model\Rule;

$rule = $this->_objectManager->create(Rule::class);

  1. Set the Rule Information: Once you have created a new instance of the Rule class, you need to set the rule information, such as the rule name, description, and discount amount. You can do this using the setData method.
scss
$rule->setName('10% Off Your Order');
$rule->setDescription('Get 10% off your order with this coupon code');
$rule->setDiscountAmount(10);
  1. Set the Coupon Code Information: After setting the rule information, you need to set the coupon code information, such as the code itself, usage limit, and expiration date.
bash
$couponCode = 'NEWCUSTOMER10'; // Replace with your desired coupon code
$rule->setCouponCode($couponCode);
$rule->setUsesPerCoupon(1);
$rule->setUsesPerCustomer(1);
$rule->setFromDate(date('Y-m-d'));
$rule->setToDate(date('Y-m-d', strtotime('+1 week')));
  1. Set the Conditions: Next, you need to set the conditions that must be met for the coupon code to apply. You can do this using the setConditions method and passing in an instance of the \Magento\CatalogRule\Model\Rule\Condition\Combine class.
bash
$conditions = [
[
'type' => 'Magento\SalesRule\Model\Rule\Condition\Address',
'attribute' => 'shipping_method',
'operator' => '==',
'value' => 'flatrate_flatrate',
],
];
$rule->setConditionsSerialized(serialize($conditions));
  1. Save the Rule: Finally, you need to save the rule using the save method.
scss
$rule->save();

That’s it! By following these steps, you can create a new coupon code programmatically in Magento 2. You can customize the coupon code information and conditions to fit your specific needs.