home_url() ), 30 ); if ( is_wp_error( $reply ) ) { return $reply; } update_option( self::KEY_OPTION, $reply['key'], false ); return $reply['key']; } private static function send( $method, $path, $body, $timeout, $key = null ) { $args = array( 'method' => $method, 'timeout' => $timeout, 'headers' => array( 'Content-Type' => 'application/json' ), ); if ( $key ) { $args['headers']['Authorization'] = 'Bearer ' . $key; } if ( null !== $body ) { $args['body'] = wp_json_encode( $body ); } $res = wp_remote_request( untrailingslashit( LISTBRIGHT_API ) . $path, $args ); if ( is_wp_error( $res ) ) { return new WP_Error( 'listbright_unreachable', __( 'Could not reach the Listbright service. Try again in a minute.', 'listbright' ) ); } $code = wp_remote_retrieve_response_code( $res ); $data = json_decode( wp_remote_retrieve_body( $res ), true ); if ( 401 === $code && $key ) { // The key was removed on the server; start over with a new one. delete_option( self::KEY_OPTION ); } if ( $code >= 400 || ! is_array( $data ) ) { $message = is_array( $data ) && ! empty( $data['error'] ) ? $data['error'] : __( 'The Listbright service had a problem.', 'listbright' ); return new WP_Error( 'listbright_api', $message, array( 'status' => $code ) ); } return $data; } }