$max ) { $text = rtrim( mb_substr( $text, 0, $max - 1 ) ) . '…'; } return '' === $text ? '-' : $text; } public static function text_param( $text ) { return array( 'type' => 'text', 'text' => self::clean_param( $text ), ); } /** * Send an approved template. * * @param string $to Digits with country code. * @param string $template Template name. * @param string $lang Template language code, e.g. en_US. * @param array $components Cloud API components (header / body / button). * @return string|WP_Error Message id (wamid) or error with Meta's reason. */ public static function send_template( $to, $template, $lang, array $components ) { $number_id = AFPP_Settings::get( 'afpp_phone_number_id' ); $token = AFPP_Settings::get( 'afpp_access_token' ); if ( ! $number_id || ! $token ) { return new WP_Error( 'not_configured', __( 'WhatsApp API is not set up yet.', 'afojet-new-post-alerts' ) ); } $payload = array( 'messaging_product' => 'whatsapp', 'to' => $to, 'type' => 'template', 'template' => array( 'name' => $template, 'language' => array( 'code' => $lang ), ), ); if ( $components ) { $payload['template']['components'] = array_values( $components ); } $payload = apply_filters( 'afpp_whatsapp_payload', $payload, $to ); $response = wp_remote_post( 'https://graph.facebook.com/' . rawurlencode( AFPP_Settings::get( 'afpp_graph_version' ) ) . '/' . rawurlencode( $number_id ) . '/messages', array( 'timeout' => 20, 'headers' => array( 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( $payload ), ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'network', $response->get_error_message() ); } $status = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $status < 200 || $status > 299 ) { $reason = isset( $body['error']['message'] ) ? $body['error']['message'] : 'HTTP ' . $status; if ( ! empty( $body['error']['error_data']['details'] ) ) { $reason .= ' – ' . $body['error']['error_data']['details']; } $code = isset( $body['error']['code'] ) ? (int) $body['error']['code'] : 0; if ( $code && false === strpos( $reason, (string) $code ) ) { $reason = '(#' . $code . ') ' . $reason; } return new WP_Error( 'api_' . $code, $reason, array( 'code' => $code ) ); } return isset( $body['messages'][0]['id'] ) ? (string) $body['messages'][0]['id'] : 'ok'; } /** * Is this error caused by the recipient (bad number, not on WhatsApp, opted out) * rather than our setup? Used to stop retrying such numbers. */ public static function is_recipient_error( WP_Error $error ) { $data = $error->get_error_data(); $code = is_array( $data ) && isset( $data['code'] ) ? (int) $data['code'] : 0; // 131026 undeliverable, 131050 user stopped marketing messages, 131021 sending to self, 100 invalid param on "to". return in_array( $code, array( 131026, 131050, 131021 ), true ); } }