Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Klaviyo user creation #54

Merged
merged 6 commits into from
Jan 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 69 additions & 12 deletions Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper
protected $_request;
protected $_state;
protected $_moduleList;
protected $_configWriter;

const ENABLE = 'klaviyo_reclaim_general/general/enable';
const PUBLIC_API_KEY = 'klaviyo_reclaim_general/general/public_api_key';
Expand All @@ -20,46 +21,72 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper
const NEWSLETTER = 'klaviyo_reclaim_newsletter/newsletter/newsletter';
const USING_KLAVIYO_LIST_OPT_IN = 'klaviyo_reclaim_newsletter/newsletter/using_klaviyo_list_opt_in';

const KLAVIYO_NAME_DEFAULT = 'klaviyo';
const KLAVIYO_USERNAME = 'klaviyo_reclaim_user/klaviyo_user/username';
const KLAVIYO_PASSWORD = 'klaviyo_reclaim_user/klaviyo_user/password';
const KLAVIYO_EMAIL = 'klaviyo_reclaim_user/klaviyo_user/email';

const API_MEMBERS = '/members';
const API_SUBSCRIBE = '/subscribe';

public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\App\State $state,
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\Module\ModuleListInterface $moduleList
\Magento\Framework\Module\ModuleListInterface $moduleList,
\Magento\Framework\App\Config\Storage\WriterInterface $configWriter
) {
parent::__construct($context);
$this->_scopeConfig = $context->getScopeConfig();
$this->_request = $context->getRequest();
$this->_state = $state;
$this->_storeId = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
$this->_moduleList = $moduleList;
$this->_configWriter = $configWriter;
}

protected function getScopeSetting($path){

protected function getScopeSetting($path)
{
if ($this->_state->getAreaCode() == \Magento\Framework\App\Area::AREA_ADMINHTML) {
$storeId = $this->_request->getParam('store');
$websiteId = $this->_request->getParam('website');
$scopedStoreCode = $this->_request->getParam('store');
$scopedWebsiteCode = $this->_request->getParam('website');
} else {
// In frontend area. Only concerned with store for frontend.
$storeId = $this->_storeId;
$scopedStoreCode = $this->_storeId;
}

if (isset($storeId)) {
if (isset($scopedStoreCode)) {
$scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
$value = $storeId;
return $this->_scopeConfig->getValue($path, $scope, $value);
} elseif (isset($websiteId)) {
return $this->_scopeConfig->getValue($path, $scope, $scopedStoreCode);
} elseif (isset($scopedWebsiteCode)) {
$scope = \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE;
$value = $websiteId;
return $this->_scopeConfig->getValue($path, $scope, $value);
return $this->_scopeConfig->getValue($path, $scope, $scopedWebsiteCode);
} else {
return $this->_scopeConfig->getValue($path);
};
}

protected function setScopeSetting($path, $value)
{
if ($this->_state->getAreaCode() == \Magento\Framework\App\Area::AREA_ADMINHTML) {
$scopedStoreCode = $this->_request->getParam('store');
$scopedWebsiteCode = $this->_request->getParam('website');
} else {
// In frontend area. Only concerned with store for frontend.
$scopedStoreCode = $this->_storeId;
}

if (isset($scopedStoreCode)) {
$scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
return $this->_configWriter->save($path, $value, $scope, $scopedStoreCode);
} elseif (isset($scopedWebsiteCode)) {
$scope = \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE;
return $this->_configWriter->save($path, $value, $scope, $scopedWebsiteCode);
} else {
return $this->_configWriter->save($path, $value);
};
}

public function getVersion()
{
return $this->_moduleList
Expand All @@ -81,6 +108,36 @@ public function getPrivateApiKey()
return $this->getScopeSetting(self::PRIVATE_API_KEY);
}

public function getKlaviyoUsername()
{
return $this->getScopeSetting(self::KLAVIYO_USERNAME);
}

public function unsetKlaviyoUsername()
{
return $this->setScopeSetting(self::KLAVIYO_USERNAME, self::KLAVIYO_NAME_DEFAULT);
}

public function getKlaviyoPassword()
{
return $this->getScopeSetting(self::KLAVIYO_PASSWORD);
}

public function unsetKlaviyoPassword()
{
return $this->setScopeSetting(self::KLAVIYO_PASSWORD, "");
}

public function getKlaviyoEmail()
{
return $this->getScopeSetting(self::KLAVIYO_EMAIL);
}

public function unsetKlaviyoEmail()
{
return $this->setScopeSetting(self::KLAVIYO_EMAIL, "");
}

public function getCustomMediaURL()
{
return $this->getScopeSetting(self::CUSTOM_MEDIA_URL);
Expand Down
29 changes: 16 additions & 13 deletions Helper/ListOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
class ListOptions implements \Magento\Framework\Option\ArrayInterface
{

const LABEL = 'label';
const VALUE = 'value';

public function __construct(
\Magento\Framework\Message\ManagerInterface $messageManager,
\Klaviyo\Reclaim\Helper\Data $data_helper
\Klaviyo\Reclaim\Helper\Data $_dataHelper
) {
$this->messageManager = $messageManager;
$this->data_helper = $data_helper;
$this->_dataHelper = $_dataHelper;
}

/**
Expand All @@ -22,35 +25,35 @@ public function toOptionArray()
// field in Klaviyo\Reclaim\Block\System\Config\Form\Field\Newsletter, so we pass
// it over in the options array.

if (!$this->data_helper->getPrivateApiKey()) {
if (!$this->_dataHelper->getPrivateApiKey()) {
return [[
'label' => 'To sync newsletter subscribers to Klaviyo, first save a <strong>Private Klaviyo API Key</strong> on the "General" tab.',
'value' => 0
self::LABEL => 'To sync newsletter subscribers to Klaviyo, first save a <strong>Private Klaviyo API Key</strong> on the "General" tab.',
self::VALUE => 0
]];
}

$result = $this->data_helper->getKlaviyoLists();
$result = $this->_dataHelper->getKlaviyoLists();
if (!$result['success']) {
return [[
'label' => $result['reason'] . ' To sync newsletter subscribers to Klaviyo, update the <strong>Private Klaviyo API Key</strong> on the "General" tab.',
'value' => 0
self::LABEL => $result['reason'] . ' To sync newsletter subscribers to Klaviyo, update the <strong>Private Klaviyo API Key</strong> on the "General" tab.',
self::VALUE => 0
]];
}

if (!count($result['lists'])) {
return [[
'label' => 'You don\\\'t have any Klaviyo lists. Please create one first at <a href="https://www.klaviyo.com/lists/create" target="_blank">https://www.klaviyo.com/lists/create</a> and then return here to select it.',
'value' => 0
self::LABEL => 'You don\\\'t have any Klaviyo lists. Please create one first at <a href="https://www.klaviyo.com/lists/create" target="_blank">https://www.klaviyo.com/lists/create</a> and then return here to select it.',
self::VALUE => 0
]];
}

$options = array_map(function($list) {
return ['label' => $list->name, 'value' => $list->id];
return [self::LABEL => $list->name, self::VALUE => $list->id];
}, $result['lists']);

$default_value = [
'label' => 'Select a list...',
'value' => 0
self::LABEL => 'Select a list...',
self::VALUE => 0
];
array_unshift($options, $default_value);

Expand Down
113 changes: 113 additions & 0 deletions Observer/KlaviyoUserObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

namespace Klaviyo\Reclaim\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Authorization\Model\Acl\Role\Group as RoleGroup;

class KlaviyoUserObserver implements ObserverInterface
{
/**
* DataHelper
*
* @var _dataHelper
*/
protected $_dataHelper;

/**
* ManagerInterface
*
* @var _messageManager
*/
protected $_messageManager;

/**
* RoleCollectionFactory
*
* @var RoleCollectionFactory
*/
protected $_roleCollectionFactory;

/**
* UserFactory
*
* @var _userFactory
*/
protected $_userFactory;

const KLAVIYO_FIRST_NAME = 'klaviyo';
const KLAVIYO_LAST_NAME = 'klaviyo';
const KLAVIYO_ROLE_NAME = 'Klaviyo';
const DEFAULT_LOCALE = 'en_US';

/**
* Init
*
* @param DataHelper $_dataHelper
* @param MessageManager $_messageManager
* @param RoleCollectionFactory $_roleCollectionFactory
* @param UserFactory $_userFactory
*/
public function __construct(
\Klaviyo\Reclaim\Helper\Data $_dataHelper,
\Magento\Framework\Message\ManagerInterface $_messageManager,
\Magento\Authorization\Model\ResourceModel\Role\CollectionFactory $_roleCollectionFactory,
\Magento\User\Model\UserFactory $_userFactory
) {
$this->_dataHelper = $_dataHelper;
$this->_messageManager = $_messageManager;
$this->_roleCollectionFactory = $_roleCollectionFactory;
$this->_userFactory = $_userFactory;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
$apiUsername = $this->_dataHelper->getKlaviyoUsername();
$apiPassword = $this->_dataHelper->getKlaviyoPassword();
$apiEmail = $this->_dataHelper->getKlaviyoEmail();

//
$role = $this->_roleCollectionFactory->create();
$roleCollection = $role->getData();

$adminInfo = [
'role_id' => 1,
'username' => $apiUsername,
'firstname' => self::KLAVIYO_FIRST_NAME,
'lastname' => self::KLAVIYO_LAST_NAME,
'email' => $apiEmail,
'password' => $apiPassword,
'interface_locale' => self::DEFAULT_LOCALE,
'is_active' => 1
];

//try to get the ID of the Klaviyo role
try {
foreach ($roleCollection as $item) {
if ($item['role_name'] == self::KLAVIYO_ROLE_NAME && $item['role_type'] == RoleGroup::ROLE_TYPE) {
$adminInfo['role_id'] = $item['role_id'];
}
}
} catch (\Exception $ex) {
$this->_messageManager->addErrorMessage('Unable to retrieve Klaviyo user role with error: ' . $ex->getMessage() . '\n Default administrator role used instead.');
}

//make the rest API user
$userModel = $this->_userFactory->create();
$userModel->setData($adminInfo);

//try to save the new user
try {
$userModel->save();
$this->_messageManager->addSuccessMessage('Klaviyo User was successfully created');
} catch (\Exception $ex) {
$this->_messageManager->addErrorMessage('Failed to create Klaviyo user with error: ' . $ex->getMessage());
}

//reset the details in the store config
$this->_dataHelper->unsetKlaviyoUsername();
$this->_dataHelper->unsetKlaviyoPassword();
$this->_dataHelper->unsetKlaviyoEmail();
}
}
10 changes: 5 additions & 5 deletions Observer/NewsletterSubscribeObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@

class NewsletterSubscribeObserver implements ObserverInterface
{
protected $data_helper;
protected $_dataHelper;
njparadis marked this conversation as resolved.
Show resolved Hide resolved

public function __construct(
\Klaviyo\Reclaim\Helper\Data $data_helper,
\Klaviyo\Reclaim\Helper\Data $_dataHelper,
\Magento\Framework\App\RequestInterface $request
) {
$this->data_helper = $data_helper;
$this->_dataHelper = $_dataHelper;
$this->request = $request;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
if (!$this->data_helper->getEnabled()) return;
if (!$this->_dataHelper->getEnabled()) return;

$email = $this->request->getParam('email');
$this->data_helper->subscribeEmailToKlaviyoList($email);
$this->_dataHelper->subscribeEmailToKlaviyoList($email);
}
}
8 changes: 4 additions & 4 deletions Observer/PrivateApiKeyObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
class PrivateApiKeyObserver implements ObserverInterface
{
protected $messageManager;
protected $data_helper;
protected $_dataHelper;

public function __construct(
\Magento\Framework\Message\ManagerInterface $messageManager,
\Klaviyo\Reclaim\Helper\Data $data_helper
\Klaviyo\Reclaim\Helper\Data $_dataHelper
) {
$this->messageManager = $messageManager;
$this->data_helper = $data_helper;
$this->_dataHelper = $_dataHelper;
}

public function execute(\Magento\Framework\Event\Observer $observer)
Expand All @@ -27,7 +27,7 @@ public function execute(\Magento\Framework\Event\Observer $observer)
$api_key = $field['value'];
if (!$api_key) return;

$result = $this->data_helper->getKlaviyoLists($api_key);
$result = $this->_dataHelper->getKlaviyoLists($api_key);

if ($result['success']) {
$this->messageManager->addSuccessMessage('Your Private Klaviyo API Key was successfully validated.');
Expand Down
Loading