'GET', 'timeout' => 15, 'redirection' => 10, 'blocking' => true, 'headers' => [ 'Accept-Charset' => 'charset=utf-8', 'Content-Type' => 'application/json', ], 'body' => null, 'cookies' => [], 'sslverify' => false, // Equivalent to CURLOPT_SSL_VERIFYPEER => false ]; // Merge provided options with defaults $this->options = wp_parse_args( $options, $default_options ); } /** * Execute the HTTP request. * * @return array ['headers_raw', 'body_raw', 'body', 'error', 'http_code', 'last_url'] */ public function exec( $url ) { $response = wp_remote_request( $url, $this->options ); $result = [ 'headers_raw' => '', 'body_raw' => '', 'body' => '', 'error' => '', 'http_code' => '', 'last_url' => $url, ]; if ( is_wp_error( $response ) ) { $result['error'] = $response->get_error_message(); return $result; } // Retrieve headers $result['headers_raw'] = wp_remote_retrieve_headers( $response ); // Retrieve body $result['body_raw'] = wp_remote_retrieve_body( $response ); $result['body'] = self::may_be_json( $result['body_raw'] ); // Retrieve HTTP status code $result['http_code'] = wp_remote_retrieve_response_code( $response ); Logger::log( $result, 'response >>', 'api_request' ); return $result; } /** * Check if the string is a valid JSON and optionally return decoded data. * * @param string $string * @param bool $return_decoded * * @return mixed */ public static function may_be_json( $string, $return_decoded = true ) { $decoded = json_decode( $string, true ); if ( $return_decoded ) { return ( json_last_error() === JSON_ERROR_NONE ) ? $decoded : $string; } return json_last_error() === JSON_ERROR_NONE; } }