$args Optional keys: headers (array), body (array|string), json (array), timeout (int). * @return array{ok: bool, status: int, body: string, json: array|null, error: string} */ public static function request( $method, $url, array $args = array() ) { $headers = isset( $args['headers'] ) ? (array) $args['headers'] : array(); $body = isset( $args['body'] ) ? $args['body'] : null; if ( isset( $args['json'] ) ) { $headers['Content-Type'] = 'application/json'; $body = wp_json_encode( $args['json'] ); } $response = wp_remote_request( $url, array( 'method' => strtoupper( $method ), 'headers' => $headers, 'body' => $body, 'timeout' => isset( $args['timeout'] ) ? (int) $args['timeout'] : 15, 'redirection' => 0, 'sslverify' => true, ) ); if ( is_wp_error( $response ) ) { return array( 'ok' => false, 'status' => 0, 'body' => '', 'json' => null, 'error' => $response->get_error_message(), ); } $status = (int) wp_remote_retrieve_response_code( $response ); $raw = (string) wp_remote_retrieve_body( $response ); $json = json_decode( $raw, true ); return array( 'ok' => $status >= 200 && $status < 300, 'status' => $status, 'body' => $raw, 'json' => is_array( $json ) ? $json : null, 'error' => '', ); } /** * Shortens a provider response so it is safe to store in a log. * * @param string $body Raw response body. * @return string */ public static function excerpt( $body ) { $clean = sanitize_text_field( (string) $body ); return strlen( $clean ) > 200 ? substr( $clean, 0, 200 ) . '…' : $clean; } }