api_key = trim( $api_key ); } /** * Checks whether the client has credentials. */ public function has_api_key(): bool { return '' !== $this->api_key; } /** * Requests the Brevo account endpoint for connection testing. */ public function get_account(): array { return $this->request( 'GET', '/account' ); } /** * Gets contact lists from Brevo. */ public function get_lists(): array { $response = $this->request( 'GET', '/contacts/lists?limit=50&offset=0&sort=desc' ); if ( ! $response['success'] ) { return $response; } $lists = $response['body']['lists'] ?? array(); $response['body'] = is_array( $lists ) ? $lists : array(); return $response; } /** * Creates or updates a Brevo contact. * * @param array $payload Contact API request body. */ public function create_or_update_contact( array $payload ): array { return $this->request( 'POST', '/contacts', $payload ); } /** * Sends an authenticated request to Brevo. * * @param string $method HTTP method. * @param string $path API path. * @param array|null $body Optional JSON request body. */ private function request( string $method, string $path, array $body = null ): array { if ( ! $this->has_api_key() ) { return array( 'success' => false, 'message' => __( 'Brevo API key is missing.', 'abdullahwp-contact-sync-for-brevo-elementor' ), 'code' => 0, 'body' => array(), ); } $args = array( 'method' => $method, 'timeout' => 20, 'headers' => array( 'accept' => 'application/json', 'content-type' => 'application/json', 'api-key' => $this->api_key, ), ); if ( null !== $body ) { $args['body'] = wp_json_encode( $body ); } $response = wp_remote_request( self::BASE_URL . $path, $args ); if ( is_wp_error( $response ) ) { return array( 'success' => false, 'message' => $response->get_error_message(), 'code' => 0, 'body' => array(), ); } $code = (int) wp_remote_retrieve_response_code( $response ); $raw_body = (string) wp_remote_retrieve_body( $response ); $decoded = json_decode( $raw_body, true ); $decoded = is_array( $decoded ) ? $decoded : array(); if ( $code < 200 || $code >= 300 ) { return array( 'success' => false, 'message' => $this->get_error_message( $decoded, $code ), 'code' => $code, 'body' => $decoded, ); } return array( 'success' => true, 'message' => __( 'Brevo request succeeded.', 'abdullahwp-contact-sync-for-brevo-elementor' ), 'code' => $code, 'body' => $decoded, ); } /** * Builds a readable error from a Brevo response. * * @param array $body Decoded response body. * @param int $code HTTP response code. */ private function get_error_message( array $body, int $code ): string { if ( ! empty( $body['message'] ) && is_string( $body['message'] ) ) { return sprintf( /* translators: 1: HTTP status code, 2: Brevo error message. */ __( 'Brevo API error HTTP %1$d: %2$s', 'abdullahwp-contact-sync-for-brevo-elementor' ), $code, $body['message'] ); } return sprintf( /* translators: %d: HTTP status code. */ __( 'Brevo API error HTTP %d.', 'abdullahwp-contact-sync-for-brevo-elementor' ), $code ); } }