array('Content-Type' => 'application/json'), 'timeout' => 20, 'body' => wp_json_encode(array( 'login' => $email, 'password' => $password, 'ecommerce' => Consts::ECOMMERCE_WOOCOMMERCE, 'ecommerceData' => array( 'siteUrl' => home_url(), 'pluginVersion' => RTBPC_VERSION, 'wooCommerceVersion' => WC_VERSION, 'apiVersions' => self::restApiVersions(), 'currency' => get_woocommerce_currency(), ), )), )); if (is_wp_error($response)) { /** @var WP_Error $response */ throw new \RuntimeException('Authentication request failed.'); } $code = (int) wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); $advertiserData = isset($data['advertiser']) && is_array($data['advertiser']) ? $data['advertiser'] : array(); if ($code < 200 || $code >= 300 || !is_array($advertiserData)) { throw new \RuntimeException('Invalid API response.'); } $taggingHash = isset($advertiserData['taggingHash']) ? (string) $advertiserData['taggingHash'] : ''; $dc = isset($advertiserData['dataCenter']) ? (string) $advertiserData['dataCenter'] : Consts::DATA_CENTER_AMS; if ($taggingHash === '') { throw new \RuntimeException('Missing taggingHash in response.'); } return array( 'taggingHash' => $taggingHash, 'dc' => $dc, 'authToken' => isset($data['authToken']) ? (string) $data['authToken'] : '', ); } /** * WooCommerce REST API versions enabled in this shop, newest first; RTB House reads the products through the newest. * * @return string[] */ private static function restApiVersions(): array { $namespaces = rest_get_server()->get_namespaces(); return array_values(array_filter( Consts::WC_REST_API_VERSIONS, static function (string $version) use ($namespaces): bool { return in_array('wc/' . $version, $namespaces, true); } )); } /** * The shop's /wc-auth/v1/authorize link that grants RTB House a read-only REST API key. */ public static function productsAuthorizeUrl(string $authToken, string $returnUrl): string { $url = rtrim(Config::API_DOMAIN, '/') . Config::ENDPOINT_WOOCOMMERCE_REDIRECT . '?' . http_build_query(array( 'returnUrl' => $returnUrl, )); $response = wp_remote_get($url, array( 'headers' => array( 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $authToken, ), 'timeout' => 20, )); if (is_wp_error($response)) { throw new \RuntimeException('Products authorization request failed.'); } $data = json_decode(wp_remote_retrieve_body($response), true); $code = (int) wp_remote_retrieve_response_code($response); if ($code < 200 || $code >= 300 || !is_array($data) || !isset($data['redirectUrl']) || !is_string($data['redirectUrl'])) { throw new \RuntimeException(is_array($data) && isset($data['error']) ? (string) $data['error'] : 'Invalid API response.'); } return $data['redirectUrl']; } }