api_key = (string) $api_key; } /** * Base URL: the production API, or the ABS_COURIER_API_BASE constant for staging. * * @return string URL with a trailing slash. * @throws AbsError When the constant is set to a non-HTTPS URL. */ public static function base_url() { if ( ! defined( 'ABS_COURIER_API_BASE' ) ) { return self::DEFAULT_BASE_URL; } $url = (string) constant( 'ABS_COURIER_API_BASE' ); if ( 0 !== stripos( $url, 'https://' ) ) { throw new AbsError( AbsError::CONFIG, __( 'ABS_COURIER_API_BASE must be an https:// URL.', 'abs-courier' ) ); } return rtrim( $url, '/' ) . '/'; } /** * GET request. * * @param string $path Path relative to the base URL, e.g. 'shipments/123'. * @param array $query Query parameters. * @param int|null $timeout Seconds, for endpoints known to be slow; default READ_TIMEOUT. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ public function get( $path, array $query = array(), $timeout = null ) { return $this->send( 'GET', $path, $query, null, '', $timeout ); } /** * POST request with a JSON body. * * @param string $path Path relative to the base URL. * @param array $body Request body. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ public function post( $path, array $body ) { return $this->request( 'POST', $path, array(), $body ); } /** * PATCH request with a JSON body. * * @param string $path Path relative to the base URL. * @param array $body Request body. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ public function patch( $path, array $body ) { return $this->request( 'PATCH', $path, array(), $body ); } /** * POST multipart/form-data with one file, e.g. the NDJSON upload for bulk creation. * * @param string $path Path relative to the base URL. * @param array $fields Text fields, name => value. * @param string $file_field File field name. * @param string $filename File name sent to ABS. * @param string $content File content. * @param string $mime File MIME type. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ public function post_file( $path, array $fields, $file_field, $filename, $content, $mime ) { $boundary = 'abs-courier-' . bin2hex( random_bytes( 12 ) ); $body = ''; foreach ( $fields as $name => $value ) { $body .= "--{$boundary}\r\nContent-Disposition: form-data; name=\"{$name}\"\r\n\r\n{$value}\r\n"; } $body .= "--{$boundary}\r\nContent-Disposition: form-data; name=\"{$file_field}\"; filename=\"{$filename}\"\r\nContent-Type: {$mime}\r\n\r\n{$content}\r\n--{$boundary}--\r\n"; return $this->send( 'POST', $path, array(), $body, 'multipart/form-data; boundary=' . $boundary ); } /** * DELETE request. * * @param string $path Path relative to the base URL. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ public function delete( $path ) { return $this->request( 'DELETE', $path, array(), null ); } /** * Sends a request and interprets the response. * * @param string $method HTTP method. * @param string $path Path relative to the base URL. * @param array $query Query parameters. * @param array|null $body JSON body, or null. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ private function request( $method, $path, array $query, $body ) { return null === $body ? $this->send( $method, $path, $query, null, '' ) : $this->send( $method, $path, $query, wp_json_encode( $body ), 'application/json' ); } /** * Sends a request with a raw body and interprets the response. * * @param string $method HTTP method. * @param string $path Path relative to the base URL. * @param array $query Query parameters. * @param string|null $body Raw body, or null. * @param string $content_type Content-Type of the body. * @param int|null $timeout Seconds; null for the default. * @return mixed Unwrapped `data`. * @throws AbsError On failure. */ private function send( $method, $path, array $query, $body, $content_type, $timeout = null ) { $is_write = 'GET' !== $method; $url = self::base_url() . ltrim( $path, '/' ); if ( ! empty( $query ) ) { $url .= '?' . http_build_query( $query, '', '&', PHP_QUERY_RFC3986 ); } $args = array( 'method' => $method, 'timeout' => null !== $timeout ? (int) $timeout : ( $is_write ? self::WRITE_TIMEOUT : self::READ_TIMEOUT ), 'redirection' => 0, 'user-agent' => self::user_agent(), 'headers' => array( 'x-api-key' => $this->api_key, 'Accept' => 'application/json', ), ); if ( null !== $body ) { $args['headers']['Content-Type'] = $content_type; $args['body'] = $body; } $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { throw new AbsError( $is_write ? AbsError::UNKNOWN_OUTCOME : AbsError::RETRYABLE, __( 'ABS Courier could not be reached. Check the site\'s internet connection and try again.', 'abs-courier' ) ); } return self::interpret( (int) wp_remote_retrieve_response_code( $response ), (string) wp_remote_retrieve_body( $response ), $is_write ); } /** * Turns an HTTP status and body into the unwrapped payload, or an AbsError. * * @param int $status HTTP status. * @param string $body Raw response body. * @param bool $is_write Whether the request changed data at ABS. * @return mixed `data` from the envelope, or the whole decoded body when there is no `data` key. * @throws AbsError On failure. */ public static function interpret( $status, $body, $is_write ) { $decoded = json_decode( $body, true ); $message = self::message_from( $decoded ); if ( $status >= 200 && $status < 300 ) { if ( ! is_array( $decoded ) ) { throw new AbsError( $is_write ? AbsError::UNKNOWN_OUTCOME : AbsError::RETRYABLE, __( 'ABS Courier returned an unexpected response.', 'abs-courier' ), $status ); } if ( array_key_exists( 'success', $decoded ) && false === $decoded['success'] ) { throw new AbsError( AbsError::VALIDATION, '' !== $message ? $message : __( 'ABS Courier rejected the request.', 'abs-courier' ), $status ); } return array_key_exists( 'data', $decoded ) ? $decoded['data'] : $decoded; } if ( 401 === $status ) { throw new AbsError( AbsError::AUTH, __( 'ABS Courier rejected the API key.', 'abs-courier' ), $status ); } if ( 403 === $status ) { throw new AbsError( AbsError::FORBIDDEN, '' !== $message ? $message : __( 'The API key is not allowed to do this.', 'abs-courier' ), $status ); } if ( 404 === $status ) { throw new AbsError( AbsError::NOT_FOUND, '' !== $message ? $message : __( 'Not found at ABS Courier.', 'abs-courier' ), $status ); } if ( 429 === $status || $status >= 500 ) { throw new AbsError( AbsError::RETRYABLE, __( 'ABS Courier is temporarily unavailable. It will be retried.', 'abs-courier' ), $status ); } throw new AbsError( AbsError::VALIDATION, '' !== $message ? $message : __( 'ABS Courier rejected the request.', 'abs-courier' ), $status ); } /** * Extracts the envelope's message, which ABS sends as a string or a list of strings. * * @param mixed $decoded Decoded response body. * @return string Plain text, at most 500 characters. */ private static function message_from( $decoded ) { if ( ! is_array( $decoded ) || ! isset( $decoded['message'] ) ) { return ''; } $message = $decoded['message']; if ( is_array( $message ) ) { $message = implode( '; ', array_filter( array_map( 'strval', array_filter( $message, 'is_scalar' ) ) ) ); } if ( ! is_string( $message ) ) { return ''; } $message = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $message ) ) ); return function_exists( 'mb_substr' ) ? mb_substr( $message, 0, 500 ) : substr( $message, 0, 500 ); } /** * User agent without the site URL that WordPress adds by default. * * @return string */ private static function user_agent() { return sprintf( 'ABS-Courier-WooCommerce/%s (WordPress/%s; WooCommerce/%s)', ABS_COURIER_VERSION, get_bloginfo( 'version' ), defined( 'WC_VERSION' ) ? WC_VERSION : 'unknown' ); } }