Botão “Enviar um link”

Neste trecho de código, você aprenderá a enviar um botão no estilo de link pelo WhatsApp. Isso utiliza o serviço da Vonage objeto personalizado recurso. Você pode consultar a documentação para desenvolvedores do WhatsApp para obter detalhes sobre o formato da mensagem.

Quando o destinatário da mensagem clicar no botão do link, será solicitada sua permissão para acessar o link de destino.

Exemplo

Certifique-se de que as seguintes variáveis estejam definidas com os valores desejados, utilizando qualquer método conveniente:

ChaveDescrição
VONAGE_APPLICATION_ID

The Vonage Application ID.

VONAGE_APPLICATION_PRIVATE_KEY_PATH

Private key path.

BASE_URL

For production use the base URL is https://api.nexmo.com/. For sandbox testing the base URL is https://messages-sandbox.nexmo.com/.

MESSAGES_API_URL

There are two versions of the API, each with their own endpoints. For production the previous Messages API endpoint was https://api.nexmo.com/v0.1/messages, the new one is https://api.nexmo.com/v1/messages. For sandbox testing the Messages API endpoint is https://messages-sandbox.nexmo.com/v0.1/messages or https://messages-sandbox.nexmo.com/v1/messages, depending on which version you have set in the sandbox dashboard.

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 WHATSAPP_NUMBER above.

VONAGE_NUMBER

Refer to WHATSAPP_NUMBER above.

TO_NUMBER

Replace with the number you are sending to. E.g. 447700900001

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.

HEADER_IMAGE_URL

The URL of the image to display in the template message header.

NOTA: Não use um espaço à esquerda + ou 00 Ao digitar um número de telefone, comece com o código do país; por exemplo, 447700900000.

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Escreva o código

Adicione o seguinte ao arquivo ` send-button-link.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",
                "text": "Joe Bloggs"
              },
              {
                "type": "text",
                "text": "AB123456"
              }
            ]
          },
          {
            "type": "button",
            "index": "0",
            "sub_type": "url",
            "parameters": [
              {
                "type": "text",
                "text": "AB123456"
              }
            ]
          }
        ]
      }
    }
  }'

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

bash send-button-link.sh

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

npm install @vonage/server-sdk @vonage/messages

Crie um arquivo chamado ` send-button-link.js ` e insira o seguinte 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} : {}),
  },
);

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` send-button-link.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',
              text: 'Joe Bloggs',
            },
            {
              type: 'text',
              text: 'AB123456',
            },
          ],
        },
        {
          type: 'button',
          index: '0',
          sub_type: 'url',
          parameters: [
            {
              type: 'text',
              text: 'AB123456',
            },
          ],
        },
      ],
    },
  },
})
  .then(({ messageUUID }) => console.log(messageUUID))
  .catch((error) => console.error(error));

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

node send-button-link.js

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Adicione o seguinte ao arquivo ` build.gradle`:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'

Crie um arquivo chamado ` SendWhatsappLinkButton ` e adicione o código a seguir ao método ` main `:

val client = Vonage {
    applicationId(VONAGE_APPLICATION_ID)
    privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
}

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao método ` main ` do arquivo ` SendWhatsappLinkButton `:

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.IMAGE,
                                "image" to mapOf(
                                    "link" to WHATSAPP_HEADER_IMAGE_URL
                                )
                            )
                        )
                    ),
                    mapOf(
                        "type" to "body",
                        "parameters" to listOf(
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "Anand"
                            ),
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "Quest"
                            ),
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "113-0921387"
                            ),
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "23rd Nov 2019"
                            )
                        )
                    ),
                    mapOf(
                        "type" to MessageType.BUTTON,
                        "index" to 0,
                        "sub_type" to "url",
                        "parameters" to listOf(
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "1Z999AA10123456784"
                            )
                        )
                    )
                )
            )
        ))
    }
)

Ver código-fonte completo

Execute seu código

Podemos usar o plugin “ aplicativo ” para o Gradle a fim de simplificar a execução do nosso aplicativo. Atualize seu arquivo ` build.gradle ` com o seguinte:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Execute o seguinte comando ` gradle ` para rodar seu aplicativo, substituindo ` com.vonage.quickstart.kt.messages.whatsapp ` pelo pacote que contém ` SendWhatsappLinkButton`:

gradle run -Pmain=com.vonage.quickstart.kt.messages.whatsapp.SendWhatsappLinkButton

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Adicione o seguinte ao arquivo ` build.gradle`:

implementation 'com.vonage:server-sdk:9.3.1'

Crie um arquivo chamado ` SendWhatsappLinkButton ` e adicione o código a seguir ao método ` main `:

VonageClient client = VonageClient.builder()
		.applicationId(VONAGE_APPLICATION_ID)
		.privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
		.build();

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao método ` main ` do arquivo ` SendWhatsappLinkButton `:

var response = client.getMessagesClient().sendMessage(
	WhatsappCustomRequest.builder()
		.from(WHATSAPP_SENDER_ID).to(MESSAGES_TO_NUMBER)
		.custom(Map.of(
			"type", "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", "image",
								"image", Map.of(
									"link", WHATSAPP_HEADER_IMAGE_URL
								)
							)
						)
					),
					Map.of(
						"type", "body",
						"parameters", List.of(
							Map.of(
								"type", "text",
								"text", "Anand"
							),
							Map.of(
								"type", "text",
								"text", "Quest"
							),
							Map.of(
								"type", "text",
								"text", "113-0921387"
							),
							Map.of(
								"type", "text",
								"text", "23rd Nov 2019"
							)
						)
					),
					Map.of(
						"type", "button",
						"index", "0",
						"sub_type", "url",
						"parameters", List.of(
							Map.of(
								"type", "text",
								"text", "1Z999AA10123456784"
							)
						)
					)
				)
			)
		))
		.build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Ver código-fonte completo

Execute seu código

Podemos usar o plugin “ aplicativo ” para o Gradle a fim de simplificar a execução do nosso aplicativo. Atualize seu arquivo ` build.gradle ` com o seguinte:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Execute o seguinte comando ` gradle ` para rodar seu aplicativo, substituindo ` com.vonage.quickstart.messages.whatsapp ` pelo pacote que contém ` SendWhatsappLinkButton`:

gradle run -Pmain=com.vonage.quickstart.messages.whatsapp.SendWhatsappLinkButton

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

Install-Package Vonage

Escreva o código

Adicione o seguinte ao arquivo ` SendWhatsAppButtonLink.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 Custom
    {
        type = "template",
        template = new Template
        {
            @namespace = "whatsapp:hsm:technology:nexmo",
            name = WHATSAPP_TEMPLATE_NAME,
            language = new Language
            {
                code = "en",
                policy = "deterministic"
            },
            components = new List<Component>
            {
                new()
                {
                    type = "header",
                    parameters = new List<Parameter>
                    {
                        new()
                        {
                            type = "image",
                            image = new Image
                            {
                                link = MESSAGES_IMAGE_URL
                            }
                        }
                    }
                },
                new()
                {
                    type = "body",
                    parameters = new List<Parameter>
                    {
                        new()
                        {
                            type = "text",
                            text = "Anand"
                        },
                        new()
                        {
                            type = "text",
                            text = "Quest"
                        },
                        new()
                        {
                            type = "text",
                            text = "113-0921387"
                        },
                        new()
                        {
                            type = "text",
                            text = "23rd Nov 2019"
                        }
                    }
                },
                new()
                {
                    type = "button",
                    index = "0",
                    sub_type = "url",
                    parameters = new List<Parameter>
                    {
                        new()
                        {
                            type = "text",
                            text = "1Z999AA10123456784"
                        }
                    }
                }
            }
        }
    }
};
var response = await vonageClient.MessagesClient.SendAsync(request);

Ver código-fonte completo

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

composer require vonage/client

Crie um arquivo chamado ` send-button-link.php ` e insira o seguinte código:

$keypair = new \Vonage\Client\Credentials\Keypair(
    file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
    VONAGE_APPLICATION_ID
);

$client = new \Vonage\Client($keypair);

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` send-button-link.php`:

$custom = [
    "type" => "template",
    "template" => [
        "namespace" => WHATSAPP_TEMPLATE_NAMESPACE,
        "name" => WHATSAPP_TEMPLATE_NAME,
        "language" => ["code" => "en", "policy" => "deterministic"],
        "components" => [
            [
                "type" => "header",
                "parameters" => [
                    [
                        "type" => "image",
                        "image" => ["link" => HEADER_IMAGE_URL],
                    ],
                ],
            ],
            [
                "type" => "body",
                "parameters" => [
                    ["type" => "text", "text" => "Anand"],
                    ["type" => "text", "text" => "Quest"],
                    ["type" => "text", "text" => "113-0921387"],
                    ["type" => "text", "text" => "23rd Nov 2019"],
                ],
            ],
            [
                "type" => "button",
                "index" => "0",
                "sub_type" => "url",
                "parameters" => [
                    ["type" => "text", "text" => "1Z999AA10123456784"],
                ],
            ],
        ],
    ],
];

$whatsApp = new \Vonage\Messages\Channel\WhatsApp\WhatsAppCustom(
    TO_NUMBER,
    FROM_NUMBER,
    $custom
);

$client->messages()->send($whatsApp);

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

php send-button-link.php

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

pip install vonage python-dotenv

Escreva o código

Adicione o seguinte ao arquivo ` send-button-link.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", "text": "Joe Bloggs"},
                        {"type": "text", "text": "AB123456"},
                    ],
                },
                {
                    "type": "button",
                    "index": "0",
                    "sub_type": "url",
                    "parameters": [{"type": "text", "text": "AB123456"}],
                },
            ],
        },
    },
)

response = client.messages.send(message)
print(response)

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

python messages/whatsapp/send-button-link.py

Pré-requisitos

Se você não tiver um aplicativo, acesse criar um. Certifique-se também de acessar configure seus webhooks.

gem install vonage

Crie um arquivo chamado ` send-button-link.rb ` e insira o seguinte código:

client = Vonage::Client.new(
  application_id: VONAGE_APPLICATION_ID,
  private_key: VONAGE_PRIVATE_KEY
)

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` send-button-link.rb`:

message = client.messaging.whatsapp(
  type: 'custom',
  message: {
    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",
              text: "Joe Bloggs"
            },
            {
              type: "text",
              text: "AB123456"
            }
          ]
        },
        {
          type: "button",
          sub_type: "url",
          index: "0",
          parameters: [
            {
              type: "text",
              text: "AB123456"
            }
          ]
        }
      ]
    }
  }
)

client.messaging.send(
  from: WHATSAPP_SENDER_ID,
  to: MESSAGES_TO_NUMBER,
  **message
)

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

ruby send-button-link.rb

Experimente

Ao executar o código, uma mensagem do WhatsApp contendo um botão de link é enviada ao destinatário. Neste exemplo, o botão é um link para as informações de rastreamento da encomenda.

Mais informações