skip to Main Content

I have a rule created in Magento 2, e.g. 10% OFF, this rule uses auto generated coupon code, instead of a pre-assigned code.

I’d like to know how I can generate codes based on the rule programmatically.

NOTE: This is not about creating a new rule programmatically. I want to generate codes based on a existing rule, so I can add more codes when needed but doesn’t have to create a new rule every time, e.g. when a customer subscribes our mailing list, I can execute the code to generate a new code under the same rule and send it to the subscriber.

I found this post, but this is about creating a new rule;

https://magento.stackexchange.com/questions/207311/magento2-2-programmatically-create-coupon

I found the solution for Magento 1:

https://mage2-blog.com/magento-1-programmatically-create-promotion-coupon-codes/

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    It is actually easier than I thought. Code below worked for me:

    $couponGenerator = $objectManager->create('MagentoSalesRuleModelCouponGenerator');
    
        $data = array(
          'rule_id' => $rule->getId(),
          'qty' => '1',
          'length' => '12',
          'format' => 'alphanum',
          'prefix' => 'pre',
          'suffix' => 'suf',
        );
    
        $codes = $couponGenerator->generateCodes($data);
    

  2. You can create a Coupon based on the Sales rule id.
    You first need to Sales rule with basic details like Rule name, description, Rule type, website ids and Customer type.

    Create Coupon Rule Programmatically Magento 2

    Refer above tutorials for more details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search