Skip to content

Commit

Permalink
Move V3 logic to api wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanleslie committed Sep 19, 2023
1 parent 92375ee commit db7973d
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 77 deletions.
46 changes: 9 additions & 37 deletions Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,44 +59,16 @@ public function unsetObserverAtcPayload()

public function getKlaviyoLists($api_key = null)
{
if (!$api_key) {
$api_key = $this->_klaviyoScopeSetting->getPrivateApiKey();
}
$v3_list_api = self::KLAVIYO_HOST . self::LIST_V3_API . '?api_key=' . $api_key;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $v3_list_api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


$output = json_decode(curl_exec($ch));
$statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($statusCode !== 200) {
if ($statusCode === 403) {
$reason = self::ERROR_INVALID_API_KEY;
} elseif ($statusCode === 401) {
$reason = self::ERROR_INVALID_API_KEY;
} else {
$reason = self::ERROR_NON_200_STATUS;
}

$result = [
'success' => false,
'reason' => $reason
];
} else {
usort($output, function ($a, $b) {
return strtolower($a->list_name) > strtolower($b->list_name) ? 1 : -1;
});

$result = [
'success' => true,
'lists' => $output
];
}
$response = $this->getLists();

usort($response, function ($a, $b) {
return strtolower($a->list_name) > strtolower($b->list_name) ? 1 : -1;
});

return $result;
return [
'success' => true,
'lists' => $response
];
}

/**
Expand Down
2 changes: 1 addition & 1 deletion KlaviyoV3Sdk/Exception/KlaviyoApiException.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace KlaviyoV3Sdk\Exception;
namespace Klaviyo\Reclaim\KlaviyoV3Sdk\Exception;

class KlaviyoApiException extends KlaviyoException
{
Expand Down
2 changes: 1 addition & 1 deletion KlaviyoV3Sdk/Exception/KlaviyoAuthenticationException.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace KlaviyoV3Sdk\KlaviyoApiException;
namespace Klaviyo\Reclaim\KlaviyoV3Sdk\Exception;

class KlaviyoAuthenticationException extends KlaviyoApiException
{
Expand Down
4 changes: 2 additions & 2 deletions KlaviyoV3Sdk/Exception/KlaviyoException.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php

namespace KlaviyoV3Sdk\Exception;
namespace Klaviyo\Reclaim\KlaviyoV3Sdk\Exception;

class KlaviyoResourceNotFoundException extends KlaviyoApiException
class KlaviyoException extends \Exception
{
}
2 changes: 1 addition & 1 deletion KlaviyoV3Sdk/Exception/KlaviyoRateLimitException.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace KlaviyoV3Sdk\Exception;
namespace Klaviyo\Reclaim\KlaviyoV3Sdk\Exception;

class KlaviyoRateLimitException extends KlaviyoApiException
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace KlaviyoV3Sdk\Exception;
namespace Klaviyo\Reclaim\KlaviyoV3Sdk\Exception;

class KlaviyoResourceNotFoundException extends KlaviyoApiException
{
Expand Down
67 changes: 33 additions & 34 deletions KlaviyoV3Sdk/KlaviyoV3Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
namespace KlaviyoV3Sdk;

use Klaviyo\Reclaim\Helper\ScopeSetting;
use KlaviyoV3Sdk\Exception\KlaviyoAuthenticationException;
use KlaviyoV3Sdk\Exception\KlaviyoRateLimitException;
use KlaviyoV3Sdk\Exception\KlaviyoApiException;
use Klaviyo\Reclaim\KlaviyoV3Sdk\Exception\KlaviyoAuthenticationException;
use Klaviyo\Reclaim\KlaviyoV3Sdk\Exception\KlaviyoException;
use Klaviyo\Reclaim\KlaviyoV3Sdk\Exception\KlaviyoRateLimitException;
use Klaviyo\Reclaim\KlaviyoV3Sdk\Exception\KlaviyoApiException;
use DateTime;
use Klaviyo\Reclaim\Model\Reclaim;
use KlaviyoPs;

class KlaviyoV3Api
Expand All @@ -18,6 +20,7 @@ class KlaviyoV3Api
const KLAVIYO_V3_REVISION = '2023-08-15';
const USER_AGENT = 'Klaviyo/1.0';
const LIST_V3_API = 'api/list/';
const EVENT_V3_API = 'client/event/';
/**
* Request methods
*/
Expand All @@ -30,7 +33,7 @@ class KlaviyoV3Api
const ERROR_EXPIRED_API_KEY = 'The Private Klaviyo API key you have set is no longer valid.';
const ERROR_UNVERIFIABLE_API_KEY = 'Unable to verify Klaviyo Private API Key.';
const ERROR_NON_200_STATUS = 'Request Failed with HTTP Status Code: %s';

const ERROR_RATE_LIMIT_EXCEEDED = 'Rate limit exceeded';
/**
* Request options
*/
Expand Down Expand Up @@ -93,13 +96,17 @@ public function __construct($public_key, $private_key)
*/
public function getHeaders($clientEvent)
{
$klaviyops = new KlaviyoPs();
$klVersion = $this->_klaviyoScopeSetting->getVersion();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface');
$m2Version = $productMetadata->getVersion();

$headers = array(
CURLOPT_HTTPHEADER => [
self::REVISION_KEY_HEADER . ': ' . self::KLAVIYO_V3_REVISION,
self::ACCEPT_KEY_HEADER . ': ' . self::APPLICATION_JSON_HEADER_VALUE,
self::KLAVIYO_USER_AGENT_KEY . ': ' . 'prestashop-klaviyo/' . $klaviyops->version . 'Prestashop/' . _PS_VERSION_ . 'PHP/' . phpversion()
self::KLAVIYO_USER_AGENT_KEY . ': ' . 'prestashop-klaviyo/' . $klVersion() . 'Magento2/' . $m2Version . 'PHP/' . phpversion()
]
);

Expand All @@ -114,9 +121,9 @@ public function getHeaders($clientEvent)
*
* @return array
*/
public function getLists($api_key)
public function getKlaviyoLists()
{

$this->sendApiRequest(self::LIST_V3_API, false, 'GET');
}

/**
Expand All @@ -137,7 +144,7 @@ public function track($config): array
)
);

return $this->make_request('/client/events/?company_id=' . $this->public_key, true, $body);
return $this->sendApiRequest(self::EVENT_V3_API . '?company_id=' . $this->public_key, true, $body);
}

/**
Expand Down Expand Up @@ -183,7 +190,7 @@ public function unsubscribeEmailFromKlaviyoList($email): array|string|null
'emails' => [(string)$email],
];

return $this->sendApiRequest($path, $fields, 'POST');
return $this->sendApiRequest($path, false, 'POST', $fields);
}

/**
Expand All @@ -206,7 +213,7 @@ protected function sendApiRequest($path, $clientEvent, $method = null, $body = n
$curl = curl_init();
$options = array(
CURLOPT_URL => self::KLAVIYO_HOST . $path,
) + $this->getHeaders($clientEvent) + $this->getDefaultCurlOptions();
) + $this->getHeaders($clientEvent) + $this->getDefaultCurlOptions($method);

if ($body !== null) {
$options[CURLOPT_POSTFIELDS][] = $body;
Expand Down Expand Up @@ -289,7 +296,7 @@ protected function getDefaultCurlOptions($method = null)
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => (!empty($method)) ? $method : 'POST',,
CURLOPT_CUSTOMREQUEST => (!empty($method)) ? $method : 'POST',
CURLOPT_USERAGENT => self::USER_AGENT,
);
}
Expand All @@ -306,29 +313,21 @@ protected function getDefaultCurlOptions($method = null)
* @throws KlaviyoRateLimitException
*/
protected
function handleAPIResponse($response, $statusCode, $clientEvent = false)
function handleAPIResponse($response, $statusCode, $clientEvent = false): array|string|null
{
$decoded_response = $this->decodeJsonResponse($response);
if ($statusCode == 403) {
throw new KlaviyoAuthenticationException(self::ERROR_INVALID_API_KEY, $statusCode);
}

if ($statusCode == 401) {
throw new KlaviyoAuthenticationException(self::ERROR_EXPIRED_API_KEY, $statusCode);
}

if ($statusCode === 429) {
throw new KlaviyoAuthenticationException(self::ERROR_UNVERIFIABLE_API_KEY, $statusCode);
}

if ($statusCode == 429) {
throw new KlaviyoRateLimitException(
$this->returnRateLimit($decoded_response)
);
}

if ($statusCode < 200 || $statusCode >= 300) {
throw new KlaviyoApiException(isset($decoded_response['detail']) ? $decoded_response['detail'] : sprintf(self::ERROR_NON_200_STATUS, $statusCode), $statusCode);
try {
$decoded_response = $this->decodeJsonResponse($response);
} catch (\Exception $error) {
switch ($statusCode) {
case 403:
case 401:
throw new KlaviyoAuthenticationException($error['detail'], $statusCode);
case 429:
throw new KlaviyoRateLimitException($error['detail'], $statusCode);
default:
$errorMessage = isset($decoded_response['detail']) ? $decoded_response['detail'] : sprintf(self::ERROR_NON_200_STATUS, $statusCode);
throw new KlaviyoApiException($errorMessage, $statusCode);
}
}

if ($clientEvent) {
Expand Down

0 comments on commit db7973d

Please sign in to comment.