bool, 'status' => int, 'body' => array|null, 'retry' => bool). * $key: 'secret' (server calls), 'publishable' (what a buyer's browser sends) or 'none' (the code exchange). */ public static function post($path, array $body, $key = 'secret', $timeout = 10) { $s = Adly_Shop_Settings::get(); $base = !empty($s['api_base']) ? $s['api_base'] : ADLY_SHOP_API_BASE; $headers = array('Content-Type' => 'application/json', 'User-Agent' => 'ADLY-Shop-WooCommerce/' . ADLY_SHOP_VERSION); if ($key !== 'none') { $k = $key === 'publishable' ? 'pk' : 'sk'; if (empty($s[$k])) { return array('ok' => false, 'status' => 0, 'body' => null, 'retry' => false); } $headers['Authorization'] = 'Bearer ' . $s[$k]; } $res = wp_remote_post(rtrim($base, '/') . $path, array( 'headers' => $headers, // An empty body is still a JSON object ({}), never a list ([]) 'body' => $body ? wp_json_encode($body) : '{}', 'timeout' => $timeout, )); return self::result($res); } public static function get_ping() { $s = Adly_Shop_Settings::get(); if (empty($s['sk'])) { return array('ok' => false, 'status' => 0, 'body' => null, 'retry' => false); } $base = !empty($s['api_base']) ? $s['api_base'] : ADLY_SHOP_API_BASE; $res = wp_remote_get(rtrim($base, '/') . '/ping', array( 'headers' => array('Authorization' => 'Bearer ' . $s['sk'], 'User-Agent' => 'ADLY-Shop-WooCommerce/' . ADLY_SHOP_VERSION), 'timeout' => 10, )); return self::result($res); } private static function result($res) { if (is_wp_error($res)) { return array('ok' => false, 'status' => 0, 'body' => null, 'retry' => true, 'error' => $res->get_error_message()); } $status = (int) wp_remote_retrieve_response_code($res); $body = json_decode(wp_remote_retrieve_body($res), true); // 429, a 5xx or no answer: try again later; any other 4xx: the request needs fixing $retry = $status === 429 || $status >= 500 || $status === 0; return array('ok' => $status >= 200 && $status < 300 && is_array($body) && !empty($body['ok']), 'status' => $status, 'body' => is_array($body) ? $body : null, 'retry' => $retry); } /** Money as ADLY takes it: a number rounded to 2 decimals. */ public static function money($v) { return round((float) $v, 2); } /** An ISO date in UTC. */ public static function iso($date) { if (!$date) { return null; } $d = clone $date; $d->setTimezone(new DateTimeZone('UTC')); return $d->format('Y-m-d\TH:i:s\Z'); } }