diff --git a/Block/Adminhtml/System/Config/Fieldset/Hint.php b/Block/Adminhtml/System/Config/Fieldset/Hint.php index f9a3f325..e74562d7 100644 --- a/Block/Adminhtml/System/Config/Fieldset/Hint.php +++ b/Block/Adminhtml/System/Config/Fieldset/Hint.php @@ -100,4 +100,11 @@ public function getScopeId() } return $scopeId; } + public function getRegisterToken() + { + $scopeId = $this->getScopeId(); + $scope = $this->getScope(); + $token = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_STATISTICS_TOKEN, $scopeId, $scope); + return $token; + } } diff --git a/Controller/Adminhtml/Ecommerce/Getaccountdetails.php b/Controller/Adminhtml/Ecommerce/Getaccountdetails.php index 73fc66e2..2b7ba3ed 100644 --- a/Controller/Adminhtml/Ecommerce/Getaccountdetails.php +++ b/Controller/Adminhtml/Ecommerce/Getaccountdetails.php @@ -16,11 +16,12 @@ use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\Controller\ResultFactory; +use \Ebizmarts\MailChimp\Helper\Data as MailChimpHelper; class Getaccountdetails extends Action { /** - * @var \Ebizmarts\MailChimp\Helper\Data + * @var MailChimpHelper */ protected $_helper; /** @@ -33,15 +34,14 @@ class Getaccountdetails extends Action protected $_storeManager; /** - * Getaccountdetails constructor. * @param Context $context * @param \Magento\Store\Model\StoreManager $storeManager - * @param \Ebizmarts\MailChimp\Helper\Data $helper + * @param MailChimpHelper $helper */ public function __construct( Context $context, \Magento\Store\Model\StoreManager $storeManager, - \Ebizmarts\MailChimp\Helper\Data $helper + MailChimpHelper $helper ) { parent::__construct($context); @@ -55,6 +55,8 @@ public function execute() $apiKey = $param['apikey']; $store = $param['store']; $encrypt = $param['encrypt']; + $scope = $param['scope']; + $scopeId = $param['scopeId']; try { if ($encrypt == 3) { $api = $this->_helper->getApi($this->_storeManager->getStore()->getId()); @@ -64,14 +66,22 @@ public function execute() $apiInfo = $api->root->info(); $options = []; if (isset($apiInfo['account_name'])) { - $options['username'] = ['label' => __('User name:'), 'value' => $apiInfo['account_name']]; + $options['account_name'] = ['code' => 'account_name','html' => __('Account Name'),'value' => $apiInfo['account_name']]; + $options['email'] = ['code' => 'email','html' => __('email'),'value' => $apiInfo['email']]; + $options['first_name'] = ['code'=> 'first_name','html' => __('First Name'),'value' => $apiInfo['first_name']]; + $options['last_name'] = ['code'=>'last_name','html' => __('Last Name'),'value' => $apiInfo['last_name']]; + $options['pricing_plan_type'] = ['code'=>'pricing_plan_type','html' => __('Pricing Plan'),'value' => $apiInfo['pricing_plan_type']]; + $options['username'] = ['code'=>'username','html' => __('User name:'), 'value' => $apiInfo['account_name']]; + $options['account_id'] = ['code'=> 'account_id','html' => __('Account id:'), 'value' => $apiInfo['account_id']]; $options['total_subscribers'] = ['label' => __('Total Account Subscribers:'), 'value' => $apiInfo['total_subscribers']]; + $token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope); if ($store != -1) { $storeData = $api->ecommerce->stores->get($store); $options['list_id'] = $storeData['list_id']; $list = $api->lists->getLists($storeData['list_id']); $options['list_name'] = $list['name']; $options['total_list_subscribers'] = ['label' => __('Total List Subscribers:'), 'value' => $list['stats']['member_count']]; + $options['token'] = ['label' => __('Registration ID:'), 'value' => $token]; $options['subtitle'] = ['label' => __('Ecommerce Data uploaded to MailChimp:'), 'value' => '']; $totalCustomers = $api->ecommerce->customers->getAll($store, 'total_items'); $options['total_customers'] = ['label' => __('Total customers:'), 'value' => $totalCustomers['total_items']]; diff --git a/Controller/Adminhtml/Ecommerce/Register.php b/Controller/Adminhtml/Ecommerce/Register.php new file mode 100644 index 00000000..f1af1d99 --- /dev/null +++ b/Controller/Adminhtml/Ecommerce/Register.php @@ -0,0 +1,98 @@ +_resultFactory = $context->getResultFactory(); + $this->_helper = $helper; + $this->_http = $http; + $this->_http->setUrl($helper->getConfigValue(Helper::XML_REGISTER_URL).'/register'); + $this->_config = $config; + $this->_storeManager = $storeManager; + } + public function execute() + { + $params = $this->getRequest()->getParams(); + $scope = $params['scope']; + $scopeId = $params['scopeId']; + $registerData = []; + $error = true; + $token = $this->_helper->getConfigValue(Helper::XML_STATISTICS_TOKEN,$scopeId, $scope); + foreach ($params['data'] as $index => $value) { + $registerData[$index] = $value['value']; + } + $registerData['store_url'] = stripslashes($this->_storeManager->getStore($scopeId)->getBaseUrl()); + $registerDataJson = json_encode($registerData); + $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON); + if ($token) { + $ret = $this->_http->patch($token, $registerDataJson); + } else { + $ret = $this->_http->post($registerDataJson); + } + $ret = json_decode($ret,true); + if ( !$ret['error']) { + $error = false; + $token = $ret['token']; + $this->_helper->saveConfigValue(Helper::XML_STATISTICS_TOKEN, $token, $scopeId, $scope); + } + $resultJson->setData(['error' => $error, 'token' => $token]); + return $resultJson; + + } + /** + * @return mixed + */ + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp'); + } + +} diff --git a/Controller/Adminhtml/Ecommerce/SyncLog.php b/Controller/Adminhtml/Ecommerce/SyncLog.php new file mode 100644 index 00000000..e0969dcf --- /dev/null +++ b/Controller/Adminhtml/Ecommerce/SyncLog.php @@ -0,0 +1,67 @@ +_resultFactory = $context->getResultFactory(); + $this->_helper = $mailchimpHelper; + $this->_http = $mailchimpHttp; + $this->_url = $mailchimpHelper->getConfigValue(MailchimpHelper::XML_REGISTER_URL); + } + public function execute() + { + $error = 0; + $message = ''; + $params = $this->getRequest()->getParams(); + $scope = $params['scope']; + $scopeId = $params['scopeId']; + $onoff = $params['onoff']; + $token = $this->_helper->getConfigValue(MailchimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope); + if ($token) { + if ($onoff) { + $this->_http->setUrl($this->_url . '/switchon'); + } else { + $this->_http->setUrl($this->_url . '/switchoff'); + } + $response = $this->_http->put($token, null); + $res = json_decode($response, true); + if (key_exists('error',$res)) { + $error = $res['error']; + $message = $res['message']; + } + } else { + $error = 1; + $message = 'First register your copy'; + } + $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON); + $resultJson->setData(['error' => $error, 'message' => $message]); + return $resultJson; + } +} diff --git a/Cron/SyncStatistics.php b/Cron/SyncStatistics.php index eac9cf14..b3df7ac3 100644 --- a/Cron/SyncStatistics.php +++ b/Cron/SyncStatistics.php @@ -2,11 +2,11 @@ namespace Ebizmarts\MailChimp\Cron; +use Magento\Store\Model\StoreManager; use Ebizmarts\MailChimp\Helper\Data as MailChimpHelper; use Ebizmarts\MailChimp\Model\ResourceModel\MailchimpNotification\CollectionFactory as MailchimpNotificationCollectionFactory; use Ebizmarts\MailChimp\Model\ResourceModel\MailchimpNotification; use Ebizmarts\MailChimp\Helper\Http as MailChimpHttp; -use const _PHPStan_7c8075089\__; class SyncStatistics { @@ -26,19 +26,23 @@ class SyncStatistics * @var MailChimpHttp */ private $mailchimpHttp; + private $storeManager; const MAX_NOTIFICATIONS = 100; public function __construct( MailChimpHelper $helper, MailchimpNotificationCollectionFactory $mailchimpNotificationCollectionFactory, MailchimpNotification $mailchimpNotification, - MailchimpHttp $mailchimpHttp + MailchimpHttp $mailchimpHttp, + StoreManager $storeManager ) { $this->helper = $helper; $this->mailchimpNotificationCollectionFactory = $mailchimpNotificationCollectionFactory; $this->mailchimpNotification = $mailchimpNotification; $this->mailchimpHttp = $mailchimpHttp; + $mailchimpHttp->setUrl($helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL)); + $this->storeManager = $storeManager; } public function execute() { @@ -46,18 +50,39 @@ public function execute() $this->helper->log("SyncStatistics"); if ($this->helper->isSupportEnabled()) { + $scopeId = $this->storeManager->getDefaultStoreView()->getId(); + $scope = 'default'; + $token = $this->helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope); + if (!$token) { + $this->helper->log("You must first register your copy to sync statistics"); + return; + } + $this->mailchimpHttp->setUrl($this->helper->getConfigValue(MailChimpHelper::XML_REGISTER_URL).'/logenabled'); + $response = $this->mailchimpHttp->get($token); + $res = json_decode($response, true); + if (key_exists('error',$res) && $res['error']) { + $this->helper->log("Something went wrong while syncing statistics"); + return; + } elseif (key_exists('enabled',$res) && !$res['enabled']) { + $this->helper->log("You are not authorized to sync statistics"); + return; + } $this->helper->log("Processing sync statistics"); + $this->mailchimpHttp->setUrl($this->helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL)."/$token"); $collection = $this->getCollection(); /** * @var $collectionItem \Ebizmarts\MailChimp\Model\MailChimpNotification */ foreach ($collection as $collectionItem) { - $this->syncData($collectionItem->getNotificationData()); - $collectionItem->setProcessed(true); - $collectionItem->setSyncedAt($this->helper->getGmtDate()); - $collectionItem->getResource()->save($collectionItem); - $count++; + if($this->syncData($collectionItem->getNotificationData())) { + $collectionItem->setProcessed(true); + $collectionItem->setSyncedAt($this->helper->getGmtDate()); + $collectionItem->getResource()->save($collectionItem); + $count++; + } else { + break; + } } $this->helper->log("Sync statistics $count registers processed"); } else { @@ -76,10 +101,19 @@ private function getCollection() } private function syncData($data) { + $continue = true; $response = $this->mailchimpHttp->post($data); - if (!$this->mailchimpHttp->extractResponse($response)) { - $this->helper->log("Invalid JSON, syncing process will continue regardless"); + switch($this->mailchimpHttp->extractResponse($response)) { + case MailchimpHttp::ERROR_GENERIC: + break; + case MailChimpHttp::ERROR_AUTH: + $continue = false; + break; + case MailChimpHttp::ERROR_JSON: + $this->helper->log("Invalid JSON, syncing process will continue regardless"); + break; } + return $continue; } private function cleanData() { diff --git a/Helper/Data.php b/Helper/Data.php index cd2b05fe..c7b028cd 100755 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -59,6 +59,8 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper const SYNC_TOKEN = 'mailchimp/statistics/token'; const SYNC_NOTIFICATION_URL = 'mailchimp/statistics/notification_url'; const XML_CLEAN_SUPPORT_PERIOD = 'mailchimp/general/clean_support_period'; + const XML_REGISTER_URL = 'mailchimp/statistics/register_url'; + const XML_STATISTICS_TOKEN = 'mailchimp/register/token'; const ORDER_STATE_OK = 'complete'; @@ -1248,6 +1250,12 @@ public function buttonPressed($button, $result) $data['button']['action'] = $button; $data['button']['result'] = $result; $this->saveNotification($data); + } + public function switchLog($on) + { + $storeId = $this->_storeManager->getDefaultStoreView()->getId(); + $scope = 'default'; + $token = $this->getConfigValue(self::XML_STATISTICS_TOKEN, $storeId, $scope); } } diff --git a/Helper/Http.php b/Helper/Http.php index 772e51c6..2d0ddf4d 100644 --- a/Helper/Http.php +++ b/Helper/Http.php @@ -2,11 +2,17 @@ namespace Ebizmarts\MailChimp\Helper; -use Magento\Framework\HTTP\Client\Curl; +use Ebizmarts\MailChimp\Model\HTTP\Client\Curl; use Ebizmarts\MailChimp\Helper\Data as MailChimpHelper; class Http { + const NO_ERROR = 0; + const ERROR_JSON = 1; + const ERROR_AUTH = 2; + const ERROR_GENERIC = 3; + + /** * @var Curl */ @@ -30,26 +36,59 @@ public function __construct( $this->curl->setHeaders($headers); $this->helper = $helper; } + public function setUrl($url) + { + $this->url = $url; + $token = $this->helper->getConfigValue(MailChimpHelper::SYNC_TOKEN); + $headers = ['Authorization' => 'Bearer ' . $token, + 'Content-Type' => 'application/json' + ]; + $this->curl->setOption(CURLOPT_RETURNTRANSFER, true); + $this->curl->setHeaders($headers); + } public function post($body) { $this->curl->post($this->url , $body); $response = $this->curl->getBody(); return $response; } + public function patch($id,$body) + { + $this->curl->patch($this->url .'/'. $id , $body); + $response = $this->curl->getBody(); + return $response; + } + public function get($id) + { + $this->curl->get($this->url .'/'. $id); + $response = $this->curl->getBody(); + return $response; + } + public function put($id,$body) + { + $this->curl->put($this->url .'/'. $id , $body); + $response = $this->curl->getBody(); + return $response; + } public function extractResponse($response) { try { $data = json_decode($response, true); if (is_null($data) || json_last_error() !== JSON_ERROR_NONE) { - return false; + return self::ERROR_JSON; } - if (key_exists('error', $data) && !$data['error']) { - return true; + if (key_exists('error', $data)) { + if (!$data['error']) { + return self::NO_ERROR; + } else { + $this->helper->log($data['message']); + return self::ERROR_AUTH; + } } } catch (\Exception $e) { $this->helper->log($e->getMessage()); - return false; + return self::ERROR_GENERIC; } - return false; + return self::ERROR_GENERIC; } } diff --git a/Model/Config/Source/Details.php b/Model/Config/Source/Details.php index 832a807d..5f70e21e 100644 --- a/Model/Config/Source/Details.php +++ b/Model/Config/Source/Details.php @@ -12,6 +12,8 @@ namespace Ebizmarts\MailChimp\Model\Config\Source; +use Ebizmarts\MailChimp\Helper\Data as MailChimpHelper; + class Details implements \Magento\Framework\Option\ArrayInterface { /** @@ -55,7 +57,6 @@ public function __construct( } else { $scope = 'default'; } - if ($this->_helper->getApiKey($storeId, $scope)) { $api = $this->_helper->getApi($storeId, $scope); try { @@ -99,6 +100,9 @@ public function __construct( } else { $this->_options['store_exists'] = false; } + $token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $storeId, $scope); + $this->_options['token'] = $token; + } catch (\Mailchimp_Error | \Mailchimp_HttpError $e) { $this->_helper->log($e->getFriendlyMessage()); $this->_error = $e->getMessage(); @@ -126,6 +130,7 @@ public function toOptionArray() [['label' => 'Total List Subscribers', 'value' => $this->_options['list_subscribers']]] ); } + $ret = array_merge($ret, [['label'=> __('Registration ID'), 'value' => $this->_options['token']]]); if (isset($this->_options['store_exists']) && $this->_options['store_exists']) { $ret = array_merge($ret, [ ['label' => 'Ecommerce Data uploaded to MailChimp', 'value' => ''], diff --git a/Model/HTTP/Client/Curl.php b/Model/HTTP/Client/Curl.php new file mode 100644 index 00000000..78e271c6 --- /dev/null +++ b/Model/HTTP/Client/Curl.php @@ -0,0 +1,518 @@ + + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) + * @api + */ +class Curl implements \Magento\Framework\HTTP\ClientInterface +{ + /** + * Max supported protocol by curl CURL_SSLVERSION_TLSv1_2 + * @var int + */ + private $sslVersion; + + /** + * Hostname + * @var string + */ + protected $_host = 'localhost'; + + /** + * @var int + */ + protected $_port = 80; + + /** + * Stream resource + * @var object + */ + protected $_sock = null; + + /** + * Request headers + * @var array + */ + protected $_headers = []; + + /** + * Fields for POST method - hash + * @var array + */ + protected $_postFields = []; + + /** + * Request cookies + * @var array + */ + protected $_cookies = []; + + /** + * @var array + */ + protected $_responseHeaders = []; + + /** + * @var string + */ + protected $_responseBody = ''; + + /** + * @var int + */ + protected $_responseStatus = 0; + + /** + * Request timeout + * @var int type + */ + protected $_timeout = 300; + + /** + * TODO + * @var int + */ + protected $_redirectCount = 0; + + /** + * Curl + * @var resource + */ + protected $_ch; + + /** + * User overrides options hash + * Are applied before curl_exec + * + * @var array + */ + protected $_curlUserOptions = []; + + /** + * Header count, used while parsing headers + * in CURL callback function + * @var int + */ + protected $_headerCount = 0; + + /** + * Set request timeout + * + * @param int $value value in seconds + * @return void + */ + public function setTimeout($value) + { + $this->_timeout = (int)$value; + } + + /** + * @param int|null $sslVersion + */ + public function __construct($sslVersion = null) + { + $this->sslVersion = $sslVersion; + } + + /** + * Set headers from hash + * + * @param array $headers + * @return void + */ + public function setHeaders($headers) + { + $this->_headers = $headers; + } + + /** + * Add header + * + * @param string $name name, ex. "Location" + * @param string $value value ex. "http://google.com" + * @return void + */ + public function addHeader($name, $value) + { + $this->_headers[$name] = $value; + } + + /** + * Remove specified header + * + * @param string $name + * @return void + */ + public function removeHeader($name) + { + unset($this->_headers[$name]); + } + + /** + * Authorization: Basic header + * + * Login credentials support + * + * @param string $login username + * @param string $pass password + * @return void + */ + public function setCredentials($login, $pass) + { + $val = base64_encode("{$login}:{$pass}"); + $this->addHeader("Authorization", "Basic {$val}"); + } + + /** + * Add cookie + * + * @param string $name + * @param string $value + * @return void + */ + public function addCookie($name, $value) + { + $this->_cookies[$name] = $value; + } + + /** + * Remove cookie + * + * @param string $name + * @return void + */ + public function removeCookie($name) + { + unset($this->_cookies[$name]); + } + + /** + * Set cookies array + * + * @param array $cookies + * @return void + */ + public function setCookies($cookies) + { + $this->_cookies = $cookies; + } + + /** + * Clear cookies + * + * @return void + */ + public function removeCookies() + { + $this->setCookies([]); + } + + /** + * Make GET request + * + * @param string $uri uri relative to host, ex. "/index.php" + * @return void + */ + public function get($uri) + { + $this->makeRequest("GET", $uri); + } + + /** + * Make POST request + * + * String type was added to parameter $param in order to support sending JSON or XML requests. + * This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373 + * + * @param string $uri + * @param array|string $params + * @return void + * + * @see \Magento\Framework\HTTP\Client#post($uri, $params) + */ + public function post($uri, $params) + { + $this->makeRequest("POST", $uri, $params); + } + public function patch($uri, $params) + { + $this->makeRequest("PATCH", $uri, $params); + } + public function put($uri, $params) + { + $this->makeRequest("PUT", $uri, $params); + } + /** + * Get response headers + * + * @return array + */ + public function getHeaders() + { + return $this->_responseHeaders; + } + + /** + * Get response body + * + * @return string + */ + public function getBody() + { + return $this->_responseBody; + } + + /** + * Get cookies response hash + * + * @return array + */ + public function getCookies() + { + if (empty($this->_responseHeaders['Set-Cookie'])) { + return []; + } + $out = []; + foreach ($this->_responseHeaders['Set-Cookie'] as $row) { + $values = explode("; ", $row ?? ''); + $c = count($values); + if (!$c) { + continue; + } + list($key, $val) = explode("=", $values[0]); + if ($val === null) { + continue; + } + $out[trim($key)] = trim($val); + } + return $out; + } + + /** + * Get cookies array with details + * (domain, expire time etc) + * + * @return array + */ + public function getCookiesFull() + { + if (empty($this->_responseHeaders['Set-Cookie'])) { + return []; + } + $out = []; + foreach ($this->_responseHeaders['Set-Cookie'] as $row) { + $values = explode("; ", $row ?? ''); + $c = count($values); + if (!$c) { + continue; + } + list($key, $val) = explode("=", $values[0]); + if ($val === null) { + continue; + } + $out[trim($key)] = ['value' => trim($val)]; + array_shift($values); + $c--; + if (!$c) { + continue; + } + for ($i = 0; $i < $c; $i++) { + list($subkey, $val) = explode("=", $values[$i]); + $out[trim($key)][trim($subkey)] = $val !== null ? trim($val) : ''; + } + } + return $out; + } + + /** + * Get response status code + * + * @see lib\Magento\Framework\HTTP\Client#getStatus() + * + * @return int + */ + public function getStatus() + { + return $this->_responseStatus; + } + + /** + * Make request + * + * String type was added to parameter $param in order to support sending JSON or XML requests. + * This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373 + * + * @param string $method + * @param string $uri + * @param array|string $params - use $params as a string in case of JSON or XML POST request. + * + * @return void + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + */ + protected function makeRequest($method, $uri, $params = []) + { + $this->_ch = curl_init(); + $this->curlOption(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS); + $this->curlOption(CURLOPT_URL, $uri); + if ($method == 'POST') { + $this->curlOption(CURLOPT_POST, 1); + $this->curlOption(CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params); + } elseif ($method == "GET") { + $this->curlOption(CURLOPT_HTTPGET, 1); + } else { + $this->curlOption(CURLOPT_CUSTOMREQUEST, $method); + $this->curlOption(CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params); + } + + if (count($this->_headers)) { + $heads = []; + foreach ($this->_headers as $k => $v) { + $heads[] = $k . ': ' . $v; + } + $this->curlOption(CURLOPT_HTTPHEADER, $heads); + } + + if (count($this->_cookies)) { + $cookies = []; + foreach ($this->_cookies as $k => $v) { + $cookies[] = "{$k}={$v}"; + } + $this->curlOption(CURLOPT_COOKIE, implode(";", $cookies)); + } + + if ($this->_timeout) { + $this->curlOption(CURLOPT_TIMEOUT, $this->_timeout); + } + + if ($this->_port != 80) { + $this->curlOption(CURLOPT_PORT, $this->_port); + } + + $this->curlOption(CURLOPT_RETURNTRANSFER, 1); + $this->curlOption(CURLOPT_HEADERFUNCTION, [$this, 'parseHeaders']); + if ($this->sslVersion !== null) { + $this->curlOption(CURLOPT_SSLVERSION, $this->sslVersion); + } + + if (count($this->_curlUserOptions)) { + foreach ($this->_curlUserOptions as $k => $v) { + $this->curlOption($k, $v); + } + } + + $this->_headerCount = 0; + $this->_responseHeaders = []; + $this->_responseBody = curl_exec($this->_ch); + $err = curl_errno($this->_ch); + if ($err) { + $this->doError(curl_error($this->_ch)); + } + curl_close($this->_ch); + } + + /** + * Throw error exception + * + * @param string $string + * @return void + * @throws \Exception + */ + public function doError($string) + { + // phpcs:ignore Magento2.Exceptions.DirectThrow + throw new \Exception($string); + } + + /** + * Parse headers - CURL callback function + * + * @param resource $ch curl handle, not needed + * @param string $data + * @return int + * @throws \Exception + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + protected function parseHeaders($ch, $data) + { + $data = $data !== null ? $data : ''; + if ($this->_headerCount == 0) { + $line = explode(" ", trim($data), 3); + if (count($line) < 2) { + $this->doError("Invalid response line returned from server: " . $data); + } + $this->_responseStatus = (int)$line[1]; + } else { + $name = $value = ''; + $out = explode(": ", trim($data), 2); + if (count($out) == 2) { + $name = $out[0]; + $value = $out[1]; + } + + if (strlen($name)) { + if ('set-cookie' === strtolower($name)) { + $this->_responseHeaders['Set-Cookie'][] = $value; + } else { + $this->_responseHeaders[$name] = $value; + } + } + } + $this->_headerCount++; + + return strlen($data); + } + + /** + * Set curl option directly + * + * @param string $name + * @param mixed $value + * @return void + */ + protected function curlOption($name, $value) + { + curl_setopt($this->_ch, $name, $value); + } + + /** + * Set curl options array directly + * + * @param array $arr + * @return void + */ + protected function curlOptions($arr) + { + curl_setopt_array($this->_ch, $arr); + } + + /** + * Set CURL options overrides array + * + * @param array $arr + * @return void + */ + public function setOptions($arr) + { + $this->_curlUserOptions = $arr; + } + + /** + * Set curl option + * + * @param string $name + * @param mixed $value + * @return void + */ + public function setOption($name, $value) + { + $this->_curlUserOptions[$name] = $value; + } +} diff --git a/etc/config.xml b/etc/config.xml index 8328deb0..901484f5 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -12,7 +12,8 @@ f71334c7039eb7f6574676bd5f43b6bc - https://notifications-mc4mage.ebizmarts.com/notify + https://tvdqcoea6a.execute-api.us-east-2.amazonaws.com/test/notify + https://9jbdttu0m8.execute-api.us-east-2.amazonaws.com/test diff --git a/view/adminhtml/templates/system/config/fieldset/hint.phtml b/view/adminhtml/templates/system/config/fieldset/hint.phtml index ec5b4189..7c82c4c0 100755 --- a/view/adminhtml/templates/system/config/fieldset/hint.phtml +++ b/view/adminhtml/templates/system/config/fieldset/hint.phtml @@ -23,8 +23,11 @@ "resyncSubscribersUrl": "escapeUrl($block->getUrl('mailchimp/ecommerce/resyncSubscribers'));?>", "resyncProductsUrl": "escapeUrl($block->getUrl('mailchimp/ecommerce/resyncProducts'));?>", "fixMailchimpjsUrl": "escapeUrl($block->getUrl('mailchimp/ecommerce/fixMailchimpJS'));?>", + "registerUrl": "escapeUrl($block->getUrl('mailchimp/ecommerce/register'));?>", "scope": "escapeHtml($block->getScope());?>", - "scopeId": "escapeUrl($block->getScopeId()); ?>" + "scopeId": "escapeUrl($block->getScopeId()); ?>", + "registerToken": "escapeUrl($block->getRegisterToken()); ?>", + "switchurl": "escapeUrl($block->getUrl('mailchimp/ecommerce/SyncLog'));?>" }}'>
diff --git a/view/adminhtml/web/js/configapikey.js b/view/adminhtml/web/js/configapikey.js index 26521fa5..c42da693 100644 --- a/view/adminhtml/web/js/configapikey.js +++ b/view/adminhtml/web/js/configapikey.js @@ -26,12 +26,18 @@ define( "resyncSubscribersUrl": "", "resyncProductsUrl": "", "fixMailchimpjsUrl": "", + "registerUrl": "", "scope": "", - "scopeId": "" + "scopeId": "", + "registerToken": "", + "switchurl": "" }, _init: function () { var self = this; + if(!this.options.registerToken) { + self._showRegistationDetails(); + } $('#mailchimp_general_apikey').change(function () { var apiKey = $('#mailchimp_general_apikey').val(); self._loadStores(apiKey); @@ -74,6 +80,10 @@ define( self._changeAbandonedCart(); } }); + $('#mailchimp_general_enable_support').change(function () { + var supportenabled = $('#mailchimp_general_enable_support').find(':selected').val(); + self._switchsupport(supportenabled); + }); $('#mailchimp_support').click(function () { self._showSupport(); }); @@ -313,12 +323,103 @@ define( _showSupport: function () { alert({content: "By leveraging remote diagnostics for the Mailchimp for Magento plugin, our technical team can pinpoint and resolve syncing issues while ensuring that no sensitive data is involved in the troubleshooting process."}); }, + _showRegistationDetails: function () { + var registerUrl = this.options.registerUrl; + var detailsUrl = this.options.detailsUrl; + var accountdata = {}; + var apiKey = $('#mailchimp_general_apikey').val(); + var scope = this.options.scope; + var scopeId = this.options.scopeId; + var selectedStore = $('#mailchimp_general_monkeystore').find(':selected').val(); + var encrypt = 0; + if (apiKey == '******') { + encrypt = 3; + } + + $.ajax({ + url: detailsUrl, + data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "store": selectedStore, 'encrypt': encrypt, "scope": scope, "scopeId": scopeId}, + type: 'GET', + dataType: 'json', + showLoader: true + }).done(function (data) { + $.each(data, function (i, item) { + if (item.hasOwnProperty('label')) { + $('#mailchimp_general_account_details_ul').append('
  • ' + item.label + ' ' + item.value + '
  • '); + } else if (item.hasOwnProperty('code')) { + accountdata[item.code] = {'value': item.value, 'html': item.html}; + } + }); + var outputtext = "" + for (const key in accountdata) { + if (accountdata.hasOwnProperty(key)) { + outputtext += ''; + } + } + outputtext += '
    ' + accountdata[key]['html'] + '' + accountdata[key]['value'] + '
    '; + confirmation({ + content: "Confirm your data

    " + outputtext, + actions: { + confirm: function () { + $.ajax({ + url: registerUrl, + dataType: 'json', + data: { + 'form_key': window.FORM_KEY, + 'apikey': apiKey, + "data": accountdata, + 'scope': scope, + 'scopeId': scopeId + }, + type: 'POST', + showLoader: true + }).done(function (data) { + if (data.error == 0) { + alert({content: 'You confirm, thanks ' + data.token}); + } else { + alert({content: "Something went wrong!"}); + } + }); + }, + cancel: function () { + $('#mailchimp_general_monkeystore option[value="-1"]').attr('selected', 'selected'); + $('#mailchimp_general_monkeylist').empty(); + } + } + } + ); + } + ) + }, + _switchsupport: function (supportenabled) { + var scope = this.options.scope; + var scopeId = this.options.scopeId; + var switchurl = this.options.switchurl; + + $.ajax({ + url: switchurl, + data: {'form_key': window.FORM_KEY, 'scope': scope, 'scopeId': scopeId,'onoff': supportenabled}, + dataType: 'json', + type: 'POST', + showLoader: true + }).done(function (data) { + if (data.error == 1) { + alert({content: data.message}); + $('#mailchimp_general_enable_support option[value="0"]').prop('selected', 'selected'); + } + }) + }, _loadDetails: function () { + var registerUrl = this.options.registerUrl; var detailsUrl = this.options.detailsUrl; var interestUrl = this.options.getInterestUrl; var apiKey = $('#mailchimp_general_apikey').val(); var selectedStore = $('#mailchimp_general_monkeystore').find(':selected').val(); var encrypt = 0; + var accountdata = {}; + var scope = this.options.scope; + var scopeId = this.options.scopeId; + if (apiKey == '******') { encrypt = 3; } @@ -326,7 +427,7 @@ define( $('#mailchimp_general_monkeylist').empty(); $.ajax({ url: detailsUrl, - data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "store": selectedStore, 'encrypt': encrypt}, + data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "store": selectedStore, 'encrypt': encrypt, 'scope': scope, 'scopeId': scopeId}, type: 'GET', dataType: 'json', showLoader: true @@ -334,6 +435,8 @@ define( $.each(data, function (i, item) { if (item.hasOwnProperty('label')) { $('#mailchimp_general_account_details_ul').append('
  • ' + item.label + ' ' + item.value + '
  • '); + } else if (item.hasOwnProperty('code')) { + accountdata[item.code] = {'value': item.value,'html':item.html}; } }); if (data.list_id) { @@ -367,6 +470,38 @@ define( } } }); + var outputtext = "" + for (const key in accountdata) { + if (accountdata.hasOwnProperty(key)) { + outputtext += ''; + } + } + outputtext += '
    '+accountdata[key]['html'] + '' + accountdata[key]['value']+'
    '; + confirmation( { + content: "Confirm your data

    "+outputtext, + actions: { + confirm: function () { + $.ajax({ + url: registerUrl, + dataType: 'json', + data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "data": accountdata,'scope': scope, 'scopeId': scopeId}, + type: 'POST', + showLoader: true + }).done(function (data) { + if (data.error == 0) { + alert({content: 'You confirm, thanks '+data.token}); + } else { + alert({content: "Something went wrong!"}); + } + }); + }, + cancel: function () { + $('#mailchimp_general_monkeystore option[value="-1"]').attr('selected', 'selected'); + $('#mailchimp_general_monkeylist').empty(); + } + } + } + ); }); } });