$body * @param array $headers * @return array|WP_Error */ public function post_json( string $url, array $body, array $headers, string $label ): array|WP_Error { $response = wp_remote_post( $url, array( 'timeout' => 120, 'headers' => array_merge( array( 'Content-Type' => 'application/json' ), $headers ), 'body' => (string) wp_json_encode( $body ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $raw = wp_remote_retrieve_body( $response ); $data = json_decode( $raw, true ); if ( $code < 200 || $code >= 300 ) { return new WP_Error( 'blocklingo_mt_http', sprintf( /* translators: 1: provider name, 2: HTTP status, 3: error message. */ __( '%1$s API error (HTTP %2$d): %3$s', 'blocklingo' ), $label, $code, $this->error_message( $data, $raw ) ), array( 'provider_status' => $code ) ); } if ( ! is_array( $data ) ) { return new WP_Error( 'blocklingo_mt_json', $label . ' returned an invalid response.' ); } return $data; } /** * GET and decode JSON. * * @param array $headers * @return array|WP_Error */ public function get_json( string $url, array $headers, string $label ): array|WP_Error { $response = wp_remote_get( $url, array( 'timeout' => 20, 'headers' => $headers, ) ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code < 200 || $code >= 300 || ! is_array( $data ) ) { $msg = is_array( $data ) && isset( $data['error']['message'] ) ? (string) $data['error']['message'] : 'HTTP ' . $code; return new WP_Error( 'blocklingo_mt_http', $label . ': ' . $msg ); } return $data; } /** The message from the shapes Claude, DeepL and others use, else the body text. */ private function error_message( mixed $data, string $raw ): string { if ( is_array( $data ) ) { if ( isset( $data['error']['message'] ) ) { return (string) $data['error']['message']; } if ( isset( $data['message'] ) ) { return (string) $data['message']; } if ( isset( $data['error'] ) && is_string( $data['error'] ) ) { return $data['error']; } } return wp_trim_words( wp_strip_all_tags( $raw ), 30 ); } }