Enviar uma mensagem sobre um único produto

Neste trecho de código, você aprenderá a enviar uma mensagem de produto contendo um único item para o chat do WhatsApp usando a Messages API. Você pode ler mais sobre Mensagens sobre produtos para obter mais informações sobre como usar este trecho de código.

Esse tipo de mensagem utiliza o serviço da Vonage Objeto personalizado recurso. Mais informações sobre o formato específico da mensagem podem ser encontradas na documentação para desenvolvedores do WhatsApp Mensagens sobre produtos documentação.

Exemplo

Veja a seguir a descrição de todas as variáveis utilizadas em cada trecho de código:

ChaveDescrição
VONAGE_APPLICATION_ID

The Vonage Application ID.

VONAGE_APPLICATION_PRIVATE_KEY_PATH

Private key path.

VONAGE_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

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-single-product.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": "interactive",
      "interactive": {
        "type": "product",
        "body": {
          "text": "Check out this cool product"
        },
        "footer": {
          "text": "Sale now on!"
        },
        "action": {
          "catalog_id": "'${WHATSAPP_CATALOG_ID}'",
          "product_retailer_id": "'${WHATSAPP_PRODUCT_ID_1}'"
        }
      }
    }

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

bash send-single-product.sh

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 ` SendWhatsappSingleProduct ` 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 ` SendWhatsappSingleProduct `:

val messageId = client.messages.send(
    whatsappSingleProduct {
        to(MESSAGES_TO_NUMBER)
        from(WHATSAPP_SENDER_ID)
        catalogId(WHATSAPP_CATALOG_ID)
        productRetailerId(WHATSAPP_PRODUCT_ID)
        bodyText("Check out this cool product")
        footerText("Sale now on!")
    }
)

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 ` SendWhatsappSingleProduct`:

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

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 ` SendWhatsappSingleProduct ` 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 ` SendWhatsappSingleProduct `:

var response = client.getMessagesClient().sendMessage(
		WhatsappSingleProductRequest.builder()
			.from(WHATSAPP_SENDER_ID).to(MESSAGES_TO_NUMBER)
			.catalogId(WHATSAPP_CATALOG_ID)
			.productRetailerId(WHATSAPP_PRODUCT_ID)
			.bodyText("Check out this cool product")
			.footerText("Sale now on!")
			.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 ` SendWhatsappSingleProduct`:

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

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 ` SendWhatsAppSingleProduct.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 = "interactive",
        interactive = new
        {
            type = "product",
            body = new
            {
                text = "Check out this cool product"
            },
            footer = new
            {
                text = "Sale now on!"
            },
            action = new
            {
                catalog_id = WHATSAPP_CATALOG_ID,
                product_retailer_id = WHATSAPP_PRODUCT_ID
            }
        }
    }
};
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-single-product.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-single-product.php`:

$custom = [
    "to" => TO_NUMBER,
    "from" => WHATSAPP_NUMBER,
    "channel" => "whatsapp",
    "message_type" => "custom",
    "custom" => [
        "type" => "interactive",
        "interactive" => [
            "type" => "product",
            "body" => [
                "text" => "Check out this cool product"
            ],
            "footer" => [
                "text" => "Sale now on!"
            ],
            "action" => [
                "catalog_id" => CATALOG_ID,
                "product_retailer_id" => PRODUCT_ID
            ]
        ]
    ]
];

$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-single-product.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-product-message-single-item.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': 'interactive',
        'interactive': {
            'type': 'product',
            'body': {'text' 'Check out this cool product'},
            'footer': {'text': 'Sale now on!'},
            'action': {
                'catalog_id': WHATSAPP_CATALOG_ID,
                'product_retailer_id': WHATSAPP_PRODUCT_ID_1,
            },
        },
    },
)

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-product-message-single-item.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-single-product.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-single-product.rb`:

message = client.messaging.whatsapp(
  type: 'custom',
  message: {
    type: "interactive",
    interactive: {
      type: "product",
      body: {
        text: "Check out this cool product"
      },
      footer: {
        text: "Sale now on!"
      },
      action: {
        catalog_id: WHATSAPP_CATALOG_ID,
        product_retailer_id: WHATSAPP_PRODUCT_ID_1
      }
    }
  }
)

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-single-product.rb

Experimente

Ao executar o código, uma mensagem do WhatsApp com um único produto é enviada para o número de destino.

Mais informações