$message Message. * @param array $config Channel config. * @return true|WP_Error */ abstract public function send( array $message, array $config ); /** * POST JSON and treat any 2xx as success. * * Uses wp_safe_remote_post(), which refuses local and private network * addresses, so a webhook URL can't be pointed at the server itself. * * @param string $url URL. * @param array $payload Body. * @param array $headers Extra headers. * @return true|WP_Error */ protected function post_json( string $url, array $payload, array $headers = array() ) { $body = (string) wp_json_encode( $payload ); return $this->post_raw( $url, $body, $headers ); } /** * POST an already-encoded JSON body. * * @param string $url URL. * @param string $body JSON body. * @param array $headers Extra headers. * @return true|WP_Error */ protected function post_raw( string $url, string $body, array $headers = array() ) { $response = wp_safe_remote_post( $url, array( 'timeout' => self::TIMEOUT, 'redirection' => 0, 'headers' => array_merge( array( 'Content-Type' => 'application/json; charset=utf-8' ), $headers ), 'body' => $body, ) ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); if ( $code >= 200 && $code < 300 ) { return true; } $detail = trim( wp_strip_all_tags( (string) wp_remote_retrieve_body( $response ) ) ); return new WP_Error( 'profit_engine_notification_http', /* translators: 1: HTTP status code, 2: response text from the service. */ sprintf( __( 'The service answered HTTP %1$d. %2$s', 'profit-engine' ), $code, mb_substr( $detail, 0, 200 ) ), array( 'code' => $code ) ); } /** * The message as plain text lines (for services without rich layouts). * * @param array $message Message. * @return string[] */ protected function item_lines( array $message ): array { $lines = array(); foreach ( (array) ( $message['items'] ?? array() ) as $item ) { $name = (string) ( $item['title'] ?? '' ); $sku = (string) ( $item['subtitle'] ?? '' ); $detail = (string) ( $item['detail'] ?? '' ); $lines[] = $name . ( '' !== $sku ? " ({$sku})" : '' ) . ( '' !== $detail ? " — {$detail}" : '' ); } if ( ! empty( $message['more'] ) ) { /* translators: %d: number of further rows not listed. */ $lines[] = sprintf( __( '…and %d more', 'profit-engine' ), (int) $message['more'] ); } return $lines; } }