E-commerce businesses always needs dynamic rules of marketing to attract and lure their customers. The more the customers visits the sites, the more opportunity for the merchants to sell their products and ultimately, in returns a handsome revenue.
Magento-2 a leading E-commerce platform provides a full flexible and customizable architecture to implement any sort of automation that ultimately leads in generating customer traffic and business.
The automated coupons in order email is one of the marketing tactics of many e commerce businesses and in this blog we will cover the implementation of “order email coupons” within Magento-2 system.
The module “order email coupons” will email new coupon in every order email, to lure customer to re-visit site and shop more.
We will try to cover each and every necessary step of module development and configurations.
For reference, we have attached screen-shots for letting it know, how module need to be configured.
Create new module, at following path:
app/code/Folio3/OrderEmailCoupon
Create required module files and folder:
app/code/Folio3/OrderEmailCoupon/registration.php
\Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Folio3_OrderEmailCoupon', __DIR__ );
app/code/Folio3/OrderEmailCoupon/etc/module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Folio3_OrderEmailCoupon" setup_version="1.0.1"> </module> </config>
We will provide new order email templates for logged-in and guest customers. Add templates code in file:
app/code/Folio3/OrderEmailCoupon/etc/email_templates.xml
<template id="sales_email_order_with_coupon" label="New Order With Coupon" file="ordRRQMCM02er_new_with_coupon.html" type="html" module="Folio3_OrderEmailCoupon" area="frontend"/> <template id="sales_email_order_guest_with_coupon" label="New Order Guest With Coupon" file="order_new_guest_with_coupon.html" type="html" module="Folio3_OrderEmailCoupon" area="frontend"/>
In order to show the added emailed templates under admin→stores→configuration…
We need to code the following module file:
app/code/Folio3/OrderEmailCoupon/etc/adminhtml/system.xml
<system> <tab id="folio3" translate="label" sortOrder="200"> <label>Folio3</label> </tab> <section id="coupon" translate="label" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1"> <class>separator-top</class> <label>Gift Coupon</label> <tab>folio3</tab> <resource>Folio3_OrderEmailCoupon::config_orderemailcoupon</resource> <group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Coupon Configuration</label> <field id="id" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="0"> <label>Generate Rule ID</label> <comment>The cart price rule ID must be valid and active.</comment> </field> </group> </section> </system>
Create email templates (html) files:
For Guest Customer(s):
app/code/Folio3/OrderEmailCoupon/view/frontend/email/order_new_guest_with_coupon.html
For Logged-in Customer(s):
app/code/Folio3/OrderEmailCoupon/view/frontend/email/order_new_with_coupon.html
Please insert, the required gift coupon code in each email templates
{{if gift-coupon}} <table class="message-info"> <tr> <td> <h3 style="text-align:center;">{{trans "Gift Coupon"}}</h3> <p style="text-align:center;">{{var gift-coupon}}</p> </td> </tr> </table> {{/if}}
Create need shopping cart rule under admin→marketing→promotions→cart price rules, with following necessary configurations, also highlighted in screen-shots:
Active: Yes
Coupon: Specific Coupon
(Checked) Use Auto Generation
User per Customer: 1
Note:
This rule will be utilized for creating dynamic coupon. The logic will be covered shortly.
Once rule is configured, please save it, copy the rule ID from URL and paste under text field at admin→stores→configuration→folio3→gift coupon→generate rule ID…
We have almost completed the required module files & folders with configurations.
In this step, we will add event “email_order_set_template_vars_before” at following path, that will be responsible for inserting coupon information at the time of sending order email.
app/code/Folio3/OrderEmailCoupon/etc/events.xml
<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="folio3_send_coupon_in_email" instance="Folio3\OrderEmailCoupon\Observer\OrderEmailCoupon" /> </event> </config>
Create observer file:
The observer will check for “Rule ID” and if found, generates dynamic coupon and bind it in order emails.
app/code/Folio3/OrderEmailCoupon/Observer/OrderEmailCoupon.php
namespace Folio3\OrderEmailCoupon\Observer; use Magento\Framework\Event\ObserverInterface; class OrderEmailCoupon implements ObserverInterface { protected $logger; protected $ruleFactory; protected $massgenerator; protected $scopeConfig; public function __construct( \Psr\Log\LoggerInterface $logger, \Magento\SalesRule\Model\RuleFactory $ruleFactory, \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) { $this->logger = $logger; $this->ruleFactory = $ruleFactory; $this->massgenerator = $massgenerator; $this->scopeConfig = $scopeConfig; } /** * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $transport = $observer->getTransport(); $couponApplied = $transport->getOrder()->getCouponCode(); $generatedCoupon = $this->generateOrderEmailCoupon(); if($generatedCoupon) { $transport['gift-coupon'] = $generatedCoupon; } } public function generateOrderEmailCoupon() { $ruleModel = $this->ruleFactory->create(); $ruleId = $this->scopeConfig->getValue('coupon/general/id' ,\Magento\Store\Model\ScopeInterface::SCOPE_STORE); //if ruleId defined under, stores->configuration->Folio3->Gift Coupon->Generate Rule ID if($ruleId) { try { if(!$ruleModel->load($ruleId)->getIsActive()) { return false; } $generateData = array( 'rule_id' => $ruleId, 'qty' => 1, 'length' => '12', 'format' => 'alphanum', 'prefix' => '', 'suffix' => '', 'dash'=> 0 ); /** @var $generator \Magento\SalesRule\Model\Coupon\Massgenerator */ $generator = $this->massgenerator; if (!$generator->validateData($generateData)) { throw new \Magento\Framework\Exception\LocalizedException( __('Coupon generation validation fails.') ); } else { $generator->setData($generateData); $generator->generatePool(); $generated = $generator->getGeneratedCount(); $codes = $generator->getGeneratedCodes(); if(isset($codes[0])) { return $codes[0]; } } } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->logger->critical($e); } catch (\Exception $e) { $this->logger->critical($e); } } return false; }
Please feel free to comment or reach out if you have any questions. If you need any help with customizing your Magento 2 web store, please get in touch with us.
USA408 365 4638
1301 Shoreway Road, Suite 160,
Belmont, CA 94002
Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.
Tel:
+1 408 365 4638
Support:
+1 (408) 512 1812
COMMENTS ()
Tweet