the decoded body, for a caller that wants more */ public $body = array(); public function __construct($message, $status, $errorCode = '', $param = null, array $body = array()) { parent::__construct($message, (int) $status); $this->status = (int) $status; $this->errorCode = (string) $errorCode; $this->param = $param; $this->body = $body; } public function isRetryable() { if ($this->status >= 500) { return true; } return $this->status === 429 || $this->status === 409 || $this->status === 408; } } } if (!class_exists('AffiliatantClient', false)) { class AffiliatantClient { const VERSION = '1.0.0'; /** The API revision this client was written against. */ const API_VERSION = '2026-10-20'; /** Signature tolerance in seconds, matching the platform's own. */ const SIGNATURE_TOLERANCE = 300; private static $zeroDecimal = array( 'BIF', 'CLP', 'DJF', 'GNF', 'ISK', 'JPY', 'KMF', 'KRW', 'PYG', 'RWF', 'UGX', 'UYI', 'VND', 'VUV', 'XAF', 'XOF', 'XPF', ); private static $threeDecimal = array('BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'); /** @var string */ private $apiKey; /** @var string */ private $baseUrl; /** @var string */ private $apiVersion; /** @var string|null */ private $signingSecret; /** @var int */ private $timeout; /** @var int */ private $connectTimeout; /** @var bool */ private $verifySsl; /** @var string */ private $userAgent; /** @var callable|null replaces the HTTP call; see setTransport() */ private $transport = null; /** @var array the last raw response, for a status screen */ private $lastResponse = array(); /** * @param string $apiKey a secret or publishable API key from the console * @param array $options base_url, version, signing_secret, timeout, * connect_timeout, verify_ssl, user_agent */ public function __construct($apiKey, array $options = array()) { $this->apiKey = (string) $apiKey; $this->baseUrl = rtrim(isset($options['base_url']) && $options['base_url'] !== '' ? (string) $options['base_url'] : 'https://affiliatant.com', '/'); $this->apiVersion = isset($options['version']) ? (string) $options['version'] : self::API_VERSION; $this->signingSecret = isset($options['signing_secret']) && $options['signing_secret'] !== '' ? (string) $options['signing_secret'] : null; $this->timeout = isset($options['timeout']) ? (int) $options['timeout'] : 5; $this->connectTimeout = isset($options['connect_timeout']) ? (int) $options['connect_timeout'] : 2; $this->verifySsl = isset($options['verify_ssl']) ? (bool) $options['verify_ssl'] : true; $this->userAgent = isset($options['user_agent']) ? (string) $options['user_agent'] : 'affiliatant-php/' . self::VERSION . ' php/' . PHP_VERSION; } /** * @param array $params * @return array */ public function createClick(array $params, $idempotencyKey = null) { return $this->request('POST', '/v1/clicks', $params, $idempotencyKey); } /** * @param array $params * @return array */ public function createLead(array $params, $idempotencyKey = null) { return $this->request('POST', '/v1/leads', $params, $idempotencyKey); } /** * @param array $params * @return array */ public function createConversion(array $params, $idempotencyKey = null) { if ($idempotencyKey === null) { $idempotencyKey = self::deterministicKey(array( 'conversion', isset($params['external_order_id']) ? $params['external_order_id'] : '', isset($params['kind']) ? $params['kind'] : 'sale', isset($params['event_id']) ? $params['event_id'] : '', )); } return $this->request('POST', '/v1/conversions', $params, $idempotencyKey); } /** * @param int|string $conversionId * @param array $params reason, amount_minor (partial), currency * @return array */ public function reverseConversion($conversionId, array $params = array(), $idempotencyKey = null) { $id = rawurlencode((string) $conversionId); return $this->request('POST', '/v1/conversions/' . $id . '/reverse', $params, $idempotencyKey); } /** * @param array $filters extra query parameters, e.g. kind * @return array */ public function findConversion($externalOrderId, array $filters = array()) { $query = array_merge(array('external_order_id' => (string) $externalOrderId), $filters); return $this->request('GET', '/v1/conversions', $query); } /** * @param array $filters conversion_id, affiliate_id, status * @return array */ public function listCommissions(array $filters = array()) { return $this->request('GET', '/v1/commissions', $filters); } /** @return array */ public function ping() { return $this->findConversion('__affiliatant_connection_test__'); } /** @return bool */ public static function verifyWebhookSignature( $header, $rawBody, $secret, $previousSecret = null, $now = null, $tolerance = self::SIGNATURE_TOLERANCE ) { if (!is_string($header) || $header === '' || !is_string($secret) || $secret === '') { return false; } $now = $now === null ? time() : (int) $now; $timestamp = null; $supplied = array(); foreach (explode(',', $header) as $part) { $pair = explode('=', trim($part), 2); if (count($pair) !== 2) { continue; } if ($pair[0] === 't' && ctype_digit($pair[1])) { $timestamp = (int) $pair[1]; } elseif ($pair[0] === 'v1') { $supplied[] = $pair[1]; } } if ($timestamp === null || $supplied === array()) { return false; } if (abs($now - $timestamp) > (int) $tolerance) { return false; } $candidates = array($secret); if (is_string($previousSecret) && $previousSecret !== '') { $candidates[] = $previousSecret; } foreach ($candidates as $candidate) { $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $candidate); foreach ($supplied as $given) { if (is_string($given) && hash_equals($expected, $given)) { return true; } } } return false; } public static function signatureFor($rawBody, $secret, $timestamp = null) { $timestamp = $timestamp === null ? time() : (int) $timestamp; return 't=' . $timestamp . ',v1=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret); } /** * @param array $query * @return string */ public static function canonicalQuery(array $query) { unset($query['t'], $query['sig'], $query['k']); ksort($query); $pairs = array(); foreach ($query as $key => $value) { if (is_array($value)) { continue; } $pairs[] = rawurlencode((string) $key) . '=' . rawurlencode((string) $value); } return implode('&', $pairs); } /** * @param string $endpoint the pixel endpoint URL * @param string $keyPrefix the visible part of the API key (not a secret) * @param string $secret the conversion signing secret from the console * @param array $params order, event_id, amount_minor, currency, ... * @return string */ public static function signedUrl($endpoint, $keyPrefix, $secret, array $params, $timestamp = null) { $timestamp = $timestamp === null ? time() : (int) $timestamp; $clean = array(); foreach ($params as $key => $value) { if ($value === null || $value === '' || is_array($value)) { continue; } if (is_bool($value)) { $value = $value ? '1' : '0'; } $clean[(string) $key] = (string) $value; } $canonical = self::canonicalQuery($clean); $signature = hash_hmac('sha256', $timestamp . '.' . $canonical, $secret); $query = $clean; $query['k'] = $keyPrefix; $query['t'] = $timestamp; $query['sig'] = $signature; return $endpoint . (strpos($endpoint, '?') === false ? '?' : '&') . http_build_query($query, '', '&', PHP_QUERY_RFC3986); } /** * @param array $parts * @return string 40 hex characters */ public static function deterministicKey(array $parts) { $flat = array(); foreach ($parts as $part) { $flat[] = is_scalar($part) ? (string) $part : json_encode($part); } return sha1(implode("\x1f", $flat)); } /** ISO 4217 exponent. 2 unless the currency says otherwise. */ public static function exponent($currency) { $code = strtoupper(trim((string) $currency)); if (in_array($code, self::$zeroDecimal, true)) { return 0; } if (in_array($code, self::$threeDecimal, true)) { return 3; } return 2; } /** * @param string|float|int $amount * @return int */ public static function toMinor($amount, $currency) { $exponent = self::exponent($currency); $value = is_string($amount) ? trim($amount) : $amount; if ($value === '' || $value === null) { return 0; } $formatted = sprintf('%.' . $exponent . 'F', (float) $value); $negative = strpos($formatted, '-') === 0; $digits = preg_replace('/[^0-9]/', '', $formatted); $minor = (int) ltrim($digits, '0'); return $negative ? -$minor : $minor; } /** The last decoded response, for a plugin's status screen. */ public function lastResponse() { return $this->lastResponse; } public function baseUrl() { return $this->baseUrl; } public function isTestKey() { return strpos($this->apiKey, '_test_') !== false; } /** The first characters of the key, safe to show in an admin screen. */ public function keyHint() { if ($this->apiKey === '') { return ''; } return substr($this->apiKey, 0, 11) . str_repeat('.', 6); } /** @param callable $transport fn(string $method, string $url, array $headers, ?string $body): array{status:int,headers:array,body:string} */ public function setTransport($transport) { $this->transport = $transport; return $this; } /** * @param array $params * @return array * @throws AffiliatantException */ public function request($method, $path, array $params = array(), $idempotencyKey = null) { $method = strtoupper($method); $url = $this->baseUrl . $path; $body = ''; if ($method === 'GET' || $method === 'DELETE') { if ($params !== array()) { $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params); } } else { $encoded = json_encode($params, JSON_UNESCAPED_SLASHES); $body = $encoded === false ? '{}' : $encoded; } $headers = array( 'Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'Affiliatant-Version: ' . $this->apiVersion, 'User-Agent: ' . $this->userAgent, ); if ($method !== 'GET' && $method !== 'DELETE') { $headers[] = 'Content-Type: application/json'; if ($idempotencyKey === null) { $idempotencyKey = self::deterministicKey(array($method, $path, $body)); } $headers[] = 'Idempotency-Key: ' . $idempotencyKey; if ($this->signingSecret !== null) { $headers[] = 'Affiliatant-Signature: ' . self::signatureFor($body, $this->signingSecret); } } $response = $this->send($method, $url, $headers, $body); $decoded = array(); if (isset($response['body']) && $response['body'] !== '') { $decoded = json_decode($response['body'], true); if (!is_array($decoded)) { $decoded = array(); } } $this->lastResponse = array( 'status' => isset($response['status']) ? (int) $response['status'] : 0, 'body' => $decoded, 'headers' => isset($response['headers']) ? $response['headers'] : array(), ); $status = $this->lastResponse['status']; if ($status >= 200 && $status < 300) { return $decoded; } $message = 'Affiliatant returned HTTP ' . $status . '.'; $code = ''; $param = null; if (isset($decoded['error']) && is_array($decoded['error'])) { if (isset($decoded['error']['message']) && is_string($decoded['error']['message'])) { $message = $decoded['error']['message']; } if (isset($decoded['error']['code']) && is_string($decoded['error']['code'])) { $code = $decoded['error']['code']; } if (isset($decoded['error']['param']) && is_string($decoded['error']['param'])) { $param = $decoded['error']['param']; } } $exception = new AffiliatantApiException($message, $status, $code, $param, $decoded); if ($status === 429) { $retryAfter = $this->headerValue($this->lastResponse['headers'], 'retry-after'); $exception->retryAfter = $retryAfter === null ? null : (int) $retryAfter; } throw $exception; } /** * @return array{status:int,headers:array,body:string} * @throws AffiliatantTransportException */ private function send($method, $url, array $headers, $body) { if ($this->transport !== null) { $result = call_user_func($this->transport, $method, $url, $headers, $body); if (!is_array($result)) { throw new AffiliatantTransportException('The injected transport returned no response.'); } return array( 'status' => isset($result['status']) ? (int) $result['status'] : 0, 'headers' => isset($result['headers']) && is_array($result['headers']) ? $result['headers'] : array(), 'body' => isset($result['body']) ? (string) $result['body'] : '', ); } throw new AffiliatantTransportException( 'No HTTP transport was injected. Inside WordPress the plugin supplies ' . 'wp_remote_request() through setTransport(); this copy of the SDK makes ' . 'no request of its own.' ); } /** @param array $headers */ private function headerValue(array $headers, $name) { $name = strtolower($name); return isset($headers[$name]) ? $headers[$name] : null; } } }