Magento – Magento2: How to insert dynamic generated coupon code in email templates

email-templatesmagento2

Requirement: every time a customer place an order, a free shipping coupon will be sent which can only be used once.

So I need to insert the dynamic coupon code just like gift card code and abandoned cart rule coupon on normal email template.

Appreciate for any comment and solution.

Best Answer

Yes,it is possible.

  • Create A cart rules from admin>Marketing>Cart Rules.
  • Create a rules which will create dynamic coupon by selecting 'Use Auto Generation' for create multiple couple coupons.

During Creation setting should be :

enter image description here

Now,Add custom data in order email template in Magento 2 and create a coupon of the rule,you should fire run observer at event email_order_set_template_vars_before.

$this->eventManager->dispatch( 'email_order_set_template_vars_before', ['sender' => $this, 'transport' => $transport] );

So, at this event you can add new parameter via transport to template means you can create coupon and send to email.

Just like: events.xml

<?xml version="1.0" encoding="utf-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="email_order_set_template_vars_before">
        <observer name="add_Custom_variable_to_Order" 
            instance="[Vendor]\[ModuleName]\Observer\ObserverforAddCustomVariable" />
    </event>
</config>

And at observer will create coupon and send to to email:

<?php
namespace [Vendor]\[ModuleName]\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;

class ObserverforAddCustomVariable implements ObserverInterface
{

    protected $ruleFactory;
    protected $massgenerator;
    protected $logger;

    public function __construct(\Magento\SalesRule\Model\RuleFactory $ruleFactory,\Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator, \Psr\Log\LoggerInterface $logger ) {
        $this->ruleFactory= $ruleFactory;
        $this->massgenerator = $massgenerator;
        $this->logger = $logger;
    }

    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /** @var \Magento\Framework\App\Action\Action $controller */
        $transport = $observer->getTransport();
        $couponCode = $this->createOneCoupon();
        if($couponCode){
            $transport['free-coupon'] = $couponCode;
        }
    }
    protected function createOneCoupon()
    {
        $ruleModel = $this->ruleFactory->create();
        $ruleModel->load({RulesID});
         try {
                $data = array(
                        'rule_id' => 1,
                        'qty' => 1,
                        'length' => '12',
                        'format' => 'alphanum',
                        'prefix' => 'free-shipping',
                        'suffix' => '',
                        'dash'=>0
                        );


                $generator = $this->massgenerator;
                if (!$generator->validateData($data)) {
                   return false;
                } else {
                    $generator->setData($data);
                    $generator->generatePool();
                    $generated = $generator->getGeneratedCount();
                    $codes = $generator->getGeneratedCodes();
                    return $codes[0];

                }
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->logger->critical($e);
                return false;
            } catch (\Exception $e) {

                $this->logger->critical($e);
                return false;
            }
    }

}

At the email template , you can get this custom variables free-coupon using {{var free-coupon|raw}}.

how to add custom data in order email in magento 2

Related Topic