MONTHWRAP_VERSION, 'events' => $events, ) ); } /** * Which client and agency a key belongs to. * * @param string|null $key A key to check, or null for the saved one. * @return array See request(). On success, body has client_name and agency_name. */ public static function whoami( $key = null ) { return self::request( 'GET', '/ingest/site', null, $key ); } /** * One request to the API. * * @param string $method HTTP method. * @param string $path Path, starting with a slash. * @param array|null $body JSON body, if any. * @param string|null $key Site key, or null for the saved one. * @return array { * @type int $code HTTP status, or 0 when the API couldn't be reached. * @type array|null $body The decoded JSON reply. * @type string $error What went wrong, when it couldn't be reached. * } */ public static function request( $method, $path, $body = null, $key = null ) { $args = array( 'method' => $method, 'timeout' => 15, 'user-agent' => 'Monthwrap-WordPress/' . MONTHWRAP_VERSION . '; ' . home_url( '/' ), 'headers' => array( 'Authorization' => 'Bearer ' . ( null === $key ? self::site_key() : $key ), 'Accept' => 'application/json', ), ); if ( null !== $body ) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode( $body ); $args['data_format'] = 'body'; } $response = wp_remote_request( self::base_url() . $path, $args ); if ( is_wp_error( $response ) ) { return array( 'code' => 0, 'body' => null, 'error' => $response->get_error_message(), ); } $decoded = json_decode( wp_remote_retrieve_body( $response ), true ); return array( 'code' => (int) wp_remote_retrieve_response_code( $response ), 'body' => is_array( $decoded ) ? $decoded : null, 'error' => '', ); } }