From 72d6b17b69e5312971e2650cc0528ae2ab3a2e10 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Tue, 17 Nov 2020 11:28:51 -0300 Subject: [PATCH] closes #1078 for magento 2.1 --- Observer/Subscriber/SaveBefore.php | 35 +++++++++++++++++++++++++++++- etc/events.xml | 3 +++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Observer/Subscriber/SaveBefore.php b/Observer/Subscriber/SaveBefore.php index 405e905b..4494b3f3 100644 --- a/Observer/Subscriber/SaveBefore.php +++ b/Observer/Subscriber/SaveBefore.php @@ -28,22 +28,29 @@ class SaveBefore implements \Magento\Framework\Event\ObserverInterface * @var \Ebizmarts\MailChimp\Model\Api\Subscriber */ protected $_subscriberApi; + /** + * @var \Magento\Newsletter\Model\SubscriberFactory + */ + protected $_subscriberFactory; /** * SaveBefore constructor. * @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce * @param \Ebizmarts\MailChimp\Helper\Data $helper * @param \Ebizmarts\MailChimp\Model\Api\Subscriber $subscriberApi + * @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory */ public function __construct( \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce, \Ebizmarts\MailChimp\Helper\Data $helper, - \Ebizmarts\MailChimp\Model\Api\Subscriber $subscriberApi + \Ebizmarts\MailChimp\Model\Api\Subscriber $subscriberApi, + \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory ) { $this->_ecommerce = $ecommerce; $this->_helper = $helper; $this->_subscriberApi = $subscriberApi; + $this->_subscriberFactory = $subscriberFactory; } public function execute(\Magento\Framework\Event\Observer $observer) @@ -51,8 +58,34 @@ public function execute(\Magento\Framework\Event\Observer $observer) /** * @var $subscriber \Magento\Newsletter\Model\Subscriber */ + $factory = $this->_subscriberFactory->create(); $subscriber = $observer->getSubscriber(); + $subscriberOld = $factory->loadByCustomerId($subscriber->getCustomerId()); + + if ($this->_helper->isMailChimpEnabled($subscriberOld->getStoreId())&&$subscriber->getEmail()!=$subscriberOld->getEmail()) { + $api = $this->_helper->getApi($subscriberOld->getStoreId()); + $mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriberOld, $subscriberOld->getEmail()); + $status = 'unsubscribed'; + try { + $md5HashEmail = hash('md5', strtolower($subscriberOld->getEmail())); + $return = $api->lists->members->addOrUpdate( + $this->_helper->getDefaultList($subscriberOld->getStoreId()), + $md5HashEmail, + null, + $status, + $mergeVars, + null, + null, + null, + null, + $subscriberOld->getEmail(), + $status + ); + } catch (\Mailchimp_Error $e) { + $this->_helper->log($e->getFriendlyMessage()); + } + } $this->_subscriberApi->update($subscriber); } } diff --git a/etc/events.xml b/etc/events.xml index bc7d78ef..22a0b0a9 100644 --- a/etc/events.xml +++ b/etc/events.xml @@ -23,4 +23,7 @@ + + + \ No newline at end of file