Botón Enviar una respuesta rápida
En este fragmento de código aprenderás a enviar un botón de estilo de respuesta rápida en WhatsApp. Para ello se utiliza objeto personalizado facilidad. Puede consultar la documentación para desarrolladores de WhatsApp para conocer los detalles específicos de la función formato del mensaje.
Cuando el destinatario del mensaje haga clic en el botón de respuesta rápida, Vonage POST datos relevantes a la URL de su webhook de mensajes entrantes.
Ejemplo
A continuación encontrará la descripción de todas las variables utilizadas en cada fragmento de código:
| Clave | Descripción |
|---|---|
VONAGE_APPLICATION_ID | The Vonage Application ID. |
VONAGE_APPLICATION_PRIVATE_KEY_PATH | Private key path. |
BASE_URL | For production use the base URL is |
MESSAGES_API_URL | There are two versions of the API, each with their own endpoints. For production the previous Messages API endpoint was |
WHATSAPP_NUMBER | The WhatsApp number that has been allocated to you by Vonage. For sandbox testing the number is 14157386102. |
VONAGE_WHATSAPP_NUMBER | Refer to |
VONAGE_NUMBER | Refer to |
TO_NUMBER | Replace with the number you are sending to. E.g. |
WHATSAPP_TEMPLATE_NAMESPACE | The namespace ID found in your WhatsApp Business Account. Only templates created in your own namespace will work. Using an template with a namespace outside of your own results in an error code 1022 being returned. |
WHATSAPP_TEMPLATE_NAME | The name of the template created in your WhatsApp Business Account. |
NOTA: No utilice un + o 00 cuando introduzca un número de teléfono, empiece por el prefijo del país, por ejemplo, 447700900000.
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
Escriba el código
Añada lo siguiente a send-button-quick-reply.sh:
curl -X POST "${MESSAGES_API_URL}" \
-H "Authorization: Bearer "$JWT\
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d $'{
"to": "'${MESSAGES_TO_NUMBER}'",
"from": "'${WHATSAPP_SENDER_ID}'",
"channel": "whatsapp",
"message_type": "custom",
"custom": {
"type": "template",
"template": {
"name": "'${WHATSAPP_TEMPLATE_NAME}'",
"language": {
"policy": "deterministic",
"code": "en"
},
"components": [
{
"type": "header",
"parameters": [
{
"type": "image",
"image": {
"link": "'${MESSAGES_IMAGE_URL}'"
}
}
]
},
{
"type": "body",
"parameters": [
{
"type": "text",
"parameter_name": "customer_name",
"text": "Joe Bloggs"
},
{
"type": "text",
"parameter_name": "dentist_name",
"text": "Mr Smith"
},
{
"type": "text",
"parameter_name": "appointment_date",
"text": "2025-02-26"
},
{
"type": "text",
"parameter_name": "appointment_location",
"text": "ACME Dental Practice"
}
]
},
{
"type": "button",
"sub_type": "quick_reply",
"index": 0,
"parameters": [
{
"type": "payload",
"payload": "Yes-Button-Payload"
}
]
},
{
"type": "button",
"sub_type": "quick_reply",
"index": 1,
"parameters": [
{
"type": "payload",
"payload": "No-Button-Payload"
}
]
}
]
}
}
}'Ejecute su código
Guarde este archivo en su máquina y ejecútelo:
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
npm install @vonage/server-sdk @vonage/messagesCrea un archivo llamado send-button-quick-reply.js y añade el siguiente código:
const { Vonage } = require('@vonage/server-sdk');
const { Channels } = require('@vonage/messages');
/**
* It is best to send messages using JWT instead of basic auth. If you leave out
* apiKey and apiSecret, the messages SDK will send requests using JWT tokens
*
* @link https://developer.vonage.com/en/messages/technical-details#authentication
*/
const vonage = new Vonage(
{
applicationId: VONAGE_APPLICATION_ID,
privateKey: VONAGE_PRIVATE_KEY,
},
{
...(MESSAGES_API_URL ? {apiHost: MESSAGES_API_URL} : {}),
},
);Escriba el código
Añada lo siguiente a send-button-quick-reply.js:
vonage.messages.send({
to: MESSAGES_TO_NUMBER,
from: WHATSAPP_SENDER_ID,
channel: Channels.WHATSAPP,
messageType: 'custom',
custom: {
type: 'template',
template: {
name: WHATSAPP_TEMPLATE_NAME,
language: {
policy: 'deterministic',
code: 'en',
},
components: [
{
type: 'header',
parameters: [
{
type: 'image',
image: {
link: MESSAGES_IMAGE_URL,
},
},
],
},
{
type: 'body',
parameters: [
{
type: 'text',
parameter_name: 'customer_name',
text: 'Joe Bloggs',
},
{
type: 'text',
parameter_name: 'dentist_name',
text: 'Mr Smith',
},
{
type: 'text',
parameter_name: 'appointment_date',
text: '2025-02-26',
},
{
type: 'text',
parameter_name: 'appointment_location',
text: 'ACME Dental Practice',
},
],
},
{
type: 'button',
sub_type: 'quick_reply',
index: 0,
parameters: [
{
type: 'payload',
payload: 'Yes-Button-Payload',
},
],
},
{
type: 'button',
sub_type: 'quick_reply',
index: 1,
parameters: [
{
type: 'payload',
payload: 'No-Button-Payload',
},
],
},
],
},
},
})
.then((resp) => console.log(resp.messageUUID))
.catch((error) => console.error(error));Ejecute su código
Guarde este archivo en su máquina y ejecútelo:
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
Añada lo siguiente a build.gradle:
implementation 'com.vonage:server-sdk-kotlin:2.1.1'Crea un archivo llamado SendWhatsappQuickReplyButton y añade el siguiente código al método main:
val client = Vonage {
applicationId(VONAGE_APPLICATION_ID)
privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
}Escriba el código
Añada lo siguiente al método main del archivo SendWhatsappQuickReplyButton:
val messageId = client.messages.send(
whatsappCustom {
to(MESSAGES_TO_NUMBER)
from(WHATSAPP_SENDER_ID)
custom(mapOf(
"type" to MessageType.TEMPLATE,
"template" to mapOf(
"namespace" to WHATSAPP_TEMPLATE_NAMESPACE,
"name" to WHATSAPP_TEMPLATE_NAME,
"language" to mapOf(
"code" to Locale.ENGLISH,
"policy" to Policy.DETERMINISTIC
),
"components" to listOf(
mapOf(
"type" to "header",
"parameters" to listOf(
mapOf(
"type" to MessageType.TEXT,
"text" to "12/26"
)
)
),
mapOf(
"type" to "body",
"parameters" to listOf(
mapOf(
"type" to MessageType.TEXT,
"text" to "*Ski Trip*"
),
mapOf(
"type" to MessageType.TEXT,
"text" to "2019-12-26"
),
mapOf(
"type" to MessageType.TEXT,
"text" to "*Squaw Valley Ski Resort, Tahoe*"
)
)
),
mapOf(
"type" to MessageType.BUTTON,
"sub_type" to "quick_reply",
"index" to 0,
"parameters" to listOf(
mapOf(
"type" to "payload",
"payload" to "Yes-Button-Payload"
)
)
),
mapOf(
"type" to MessageType.BUTTON,
"sub_type" to "quick_reply",
"index" to 1,
"parameters" to listOf(
mapOf(
"type" to "payload",
"payload" to "No-Button-Payload"
)
)
)
)
)
))
}
)Ejecute su código
Podemos utilizar el plugin aplicación para Gradle para simplificar la ejecución de nuestra aplicación. Actualiza tu build.gradle con lo siguiente:
apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''Ejecute el siguiente comando gradle para ejecutar su aplicación, sustituyendo com.vonage.quickstart.kt.messages.whatsapp por el paquete que contiene SendWhatsappQuickReplyButton:
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
Añada lo siguiente a build.gradle:
implementation 'com.vonage:server-sdk:9.3.1'Crea un archivo llamado SendWhatsappQuickReplyButton y añade el siguiente código al método main:
VonageClient client = VonageClient.builder()
.applicationId(VONAGE_APPLICATION_ID)
.privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
.build();Escriba el código
Añada lo siguiente al método main del archivo SendWhatsappQuickReplyButton:
var response = client.getMessagesClient().sendMessage(
WhatsappCustomRequest.builder()
.from(WHATSAPP_SENDER_ID).to(MESSAGES_TO_NUMBER)
.custom(Map.of(
"type", MessageType.TEMPLATE,
"template", Map.of(
"namespace", WHATSAPP_TEMPLATE_NAMESPACE,
"name", WHATSAPP_TEMPLATE_NAME,
"language", Map.of(
"code", Locale.ENGLISH,
"policy", Policy.DETERMINISTIC
),
"components", List.of(
Map.of(
"type", "header",
"parameters", List.of(
Map.of(
"type", MessageType.TEXT,
"text", "12/26"
)
)
),
Map.of(
"type", "body",
"parameters", List.of(
Map.of(
"type", MessageType.TEXT,
"text", "*Ski Trip*"
),
Map.of(
"type", MessageType.TEXT,
"text", "2019-12-26"
),
Map.of(
"type", MessageType.TEXT,
"text", "*Squaw Valley Ski Resort, Tahoe*"
)
)
),
Map.of(
"type", MessageType.BUTTON,
"sub_type", "quick_reply",
"index", 0,
"parameters", List.of(
Map.of(
"type", "payload",
"payload", "Yes-Button-Payload"
)
)
),
Map.of(
"type", MessageType.BUTTON,
"sub_type", "quick_reply",
"index", 1,
"parameters", List.of(
Map.of(
"type", "payload",
"payload", "No-Button-Payload"
)
)
)
)
)
)).build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());Ejecute su código
Podemos utilizar el plugin aplicación para Gradle para simplificar la ejecución de nuestra aplicación. Actualiza tu build.gradle con lo siguiente:
apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''Ejecute el siguiente comando gradle para ejecutar su aplicación, sustituyendo com.vonage.quickstart.messages.whatsapp por el paquete que contiene SendWhatsappQuickReplyButton:
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
Install-Package VonageEscriba el código
Añada lo siguiente a SendWhatsAppQuickReplyButton.cs:
var credentials = Credentials.FromAppIdAndPrivateKeyPath(VONAGE_APPLICATION_ID, VONAGE_PRIVATE_KEY_PATH);
var vonageClient = new VonageClient(credentials);
var request = new WhatsAppCustomRequest
{
To = MESSAGES_TO_NUMBER,
From = WHATSAPP_SENDER_ID,
Custom = new
{
type = "template",
template = new
{
name = WHATSAPP_TEMPLATE_NAME,
language = new
{
code = "en",
policy = "deterministic"
},
components = new object[]
{
new
{
type = "header",
parameters = new[]
{
new
{
type = "text",
text = "12/26"
}
}
},
new
{
type = "body",
parameters = new[]
{
new
{
type = "text",
text = "*Ski Trip*"
},
new
{
type = "text",
text = "2019-12-26"
},
new
{
type = "text",
text = "*Squaw Valley Ski Resort, Tahoe*"
}
}
},
new
{
type = "button",
sub_type = "quick_reply",
index = 0,
parameters = new[]
{
new
{
type = "payload",
text = "Yes-Button-Payload"
}
}
},
new
{
type = "button",
sub_type = "quick_reply",
index = 1,
parameters = new[]
{
new
{
type = "payload",
text = "No-Button-Payload"
}
}
}
}
}
}
};
var response = await vonageClient.MessagesClient.SendAsync(request);Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
composer require vonage/clientCrea un archivo llamado send-button-quick-reply.php y añade el siguiente código:
$keypair = new \Vonage\Client\Credentials\Keypair(
file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
VONAGE_APPLICATION_ID
);
$client = new \Vonage\Client($keypair);Escriba el código
Añada lo siguiente a send-button-quick-reply.php:
$custom = [
"type" => "template",
"template" => [
"namespace" => WHATSAPP_TEMPLATE_NAMESPACE,
"name" => WHATSAPP_TEMPLATE_NAME,
"language" => ["code" => "en", "policy" => "deterministic"],
"components" => [
[
"type" => "header",
"parameters" => [["type" => "text", "text" => "12/26"]],
],
[
"type" => "body",
"parameters" => [
["type" => "text", "text" => "*Ski Trip*"],
["type" => "text", "text" => "2019-12-26"],
[
"type" => "text",
"text" => "*Squaw Valley Ski Resort, Tahoe*",
],
],
],
[
"type" => "button",
"sub_type" => "quick_reply",
"index" => 0,
"parameters" => [
["type" => "payload", "payload" => "Yes-Button-Payload"],
],
],
[
"type" => "button",
"sub_type" => "quick_reply",
"index" => 1,
"parameters" => [
["type" => "payload", "payload" => "No-Button-Payload"],
],
],
],
],
];
$whatsApp = new \Vonage\Messages\Channel\WhatsApp\WhatsAppCustom(
TO_NUMBER,
FROM_NUMBER,
$custom
);
$client->messages()->send($whatsApp);Ejecute su código
Guarde este archivo en su máquina y ejecútelo:
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
pip install vonage python-dotenvEscriba el código
Añada lo siguiente a send-button-quick-reply.py:
from vonage import Auth, Vonage
from vonage_messages import WhatsappCustom
client = Vonage(
Auth(
application_id=VONAGE_APPLICATION_ID,
private_key=VONAGE_PRIVATE_KEY,
)
)
message = WhatsappCustom(
to=MESSAGES_TO_NUMBER,
from_=WHATSAPP_SENDER_ID,
custom={
"type": "template",
"template": {
"name": WHATSAPP_TEMPLATE_NAME,
"language": {"policy": "deterministic", "code": "en"},
"components": [
{
"type": "header",
"parameters": [
{
"type": "image",
"image": {
"link": MESSAGES_IMAGE_URL,
},
},
],
},
{
"type": "body",
"parameters": [
{
"type": "text",
"parameter_name": "customer_name",
"text": "Joe Bloggs",
},
{
"type": "text",
"parameter_name": "dentist_name",
"text": "Mr Smith",
},
{
"type": "text",
"parameter_name": "appointment_date",
"text": "2025-02-26",
},
{
"type": "text",
"parameter_name": "appointment_location",
"text": "ACME Dental Practice",
},
],
},
{
"type": "button",
"sub_type": "quick_reply",
"index": 0,
"parameters": [{"type": "payload", "payload": "Yes-Button-Payload"}],
},
{
"type": "button",
"sub_type": "quick_reply",
"index": 1,
"parameters": [{"type": "payload", "payload": "No-Button-Payload"}],
},
],
},
},
)
response = client.messages.send(message)
print(response)Ejecute su código
Guarde este archivo en su máquina y ejecútelo:
Requisitos previos
Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.
gem install vonageCrea un archivo llamado send-button-quick-reply.rb y añade el siguiente código:
Ejecute su código
Guarde este archivo en su máquina y ejecútelo:
Pruébalo
Al ejecutar el código, se envía un mensaje recordatorio de WhatsApp al número de destino. El mensaje tiene dos botones de respuesta rápida que puedes utilizar para seleccionar si vas al evento o no. Cuando se pulsa un botón, se envían datos similares a los siguientes a tu URL de webhook de entrada:
{
"message_uuid": "28ee5a1c-c4cc-48ec-922c-01520d4d396b",
"to": {
"number": "447700000000",
"type": "whatsapp"
},
"from": {
"number": "447700000001",
"type": "whatsapp"
},
"timestamp": "2019-12-03T12:45:57.929Z",
"direction": "inbound",
"message": {
"content": {
"type": "button",
"button": {
"payload": "Yes-Button-Payload",
"text": "Yes"
}
}
}
}
En este ejemplo, el destinatario hizo clic en el botón Sí.