diff --git a/lib/Services/Bridge.php b/lib/Services/Bridge.php index 03f6578235..6bcc2e9edd 100644 --- a/lib/Services/Bridge.php +++ b/lib/Services/Bridge.php @@ -3,6 +3,7 @@ namespace MailPoet\Services; use MailPoet\Mailer\Mailer; use MailPoet\Models\Setting; +use MailPoet\Models\Subscriber; if(!defined('ABSPATH')) exit; @@ -41,7 +42,9 @@ class Bridge { function checkKey($api_key) { $this->initApi($api_key); $result = $this->api->checkKey(); - return $this->processResult($result); + $result = $this->processResult($result); + $this->updateSubscriberCount($result); + return $result; } function processResult(array $result) { @@ -76,6 +79,16 @@ class Bridge { return $state; } + function updateSubscriberCount($result) { + if(!empty($result['state']) + && ($result['state'] === self::MAILPOET_KEY_VALID + || $result['state'] === self::MAILPOET_KEY_EXPIRING) + ) { + return $this->api->updateSubscriberCount(Subscriber::getTotalSubscribers()); + } + return null; + } + static function invalidateKey() { Setting::setValue( self::API_KEY_STATE_SETTING_NAME, diff --git a/lib/Services/Bridge/API.php b/lib/Services/Bridge/API.php index 9059811dc1..e759f0df0b 100644 --- a/lib/Services/Bridge/API.php +++ b/lib/Services/Bridge/API.php @@ -15,6 +15,7 @@ class API { public $url_me = 'https://bridge.mailpoet.com/api/v0/me'; public $url_messages = 'https://bridge.mailpoet.com/api/v0/messages'; public $url_bounces = 'https://bridge.mailpoet.com/api/v0/bounces/search'; + public $url_stats = 'https://bridge.mailpoet.com/api/v0/stats'; function __construct($api_key) { $this->setKey($api_key); @@ -70,7 +71,7 @@ class API { function checkBounces(array $emails) { $result = wp_remote_post( - $this->url, + $this->url_bounces, $this->request($emails) ); if(wp_remote_retrieve_response_code($result) === 200) { @@ -79,6 +80,17 @@ class API { return false; } + function updateSubscriberCount($count) { + $result = wp_remote_post( + $this->url_stats, + $this->request(array('subscriber_count' => (int)$count), 'PUT') + ); + if(wp_remote_retrieve_response_code($result) === 204) { + return true; + } + return false; + } + function setKey($api_key) { $this->api_key = $api_key; } @@ -91,11 +103,11 @@ class API { return 'Basic ' . base64_encode('api:' . $this->api_key); } - private function request($body) { + private function request($body, $method = 'POST') { return array( 'timeout' => 10, 'httpversion' => '1.0', - 'method' => 'POST', + 'method' => $method, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => $this->auth() diff --git a/tests/unit/Services/BridgeTestMockAPI.php b/tests/unit/Services/BridgeTestMockAPI.php index b75d03135d..ba23d42143 100644 --- a/tests/unit/Services/BridgeTestMockAPI.php +++ b/tests/unit/Services/BridgeTestMockAPI.php @@ -19,6 +19,10 @@ class MockAPI { return $this->processResponse($code); } + function updateSubscriberCount($count) { + return true; + } + function setKey($api_key) { $this->api_key = $api_key; }