Question

I want to generate coupon on order success below is the code i am unsing to generate in Observer

public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\SalesRule\Model\Rule $rule
    )
    {
        $this->logger = $logger;
        $this->rule = $rule;        
    }    
public function execute(\Magento\Framework\Event\Observer $observer)
        {
            $order = $observer->getEvent()->getOrder();
            $orderId = $order->getId();
            $coupon = [];
            $coupon['name'] = 'vip_signup';
            $coupon['desc'] = 'Discount for vip signup coupon.';
            $coupon['start'] = date('Y-m-d');
            $coupon['end'] = '';
            $coupon['max_redemptions'] = 1;
            $coupon['discount_type'] ='by_percent';
            $coupon['discount_amount'] = 15;
            $coupon['flag_is_free_shipping'] = 'no';
            $coupon['redemptions'] = 1;
            $coupon['code'] ='NL01-1234'; 

        //this code will normally be autogenetated but i am hard coding for testing purposes

        $shoppingCartPriceRule =  $this->rule->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();

        }

events.xml

<event name="sales_order_save_after">
        <observer name="vendor_coupon_order_save_after" instance="Vendor\Coupon\Observer\GiftcardSave" />
    </event>
Was it helpful?

Solution

Change

Magento\SalesRule\Model\Rule

to

Magento\SalesRule\Model\RuleFactory

And change

 $this->rule->create('Magento\SalesRule\Model\Rule')

to

 $this->rule->create()

If you want to use Service contact then check out the link.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top