Vonage / vonage-node-sdk

Vonage API client for Node.js. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.
Apache License 2.0
375 stars 178 forks source link

How Do I: send this whatsapp template #902

Closed JaimeCasillasBluu closed 3 months ago

JaimeCasillasBluu commented 5 months ago

How do I

How do I send a whatsapp template that has the {{1}} variable in the body? What do i need to put in the components

API/Product

Messages

Code Sample

template Its a template in spanish.

This is the code: const axios = require('axios'); require('dotenv').config();

const WHATSAPP_NUMBER = process.env.WHATSAPP_NUMBER; const WHATSAPP_TEMPLATE_NAMESPACE = process.env.WHATSAPP_TEMPLATE_NAMESPACE; const WHATSAPP_TEMPLATE_NAME = process.env.WHATSAPP_TEMPLATE_NAME; let JWT_TOKEN = ""; // Initialize the variable without token

// Function to obtain the JWT token async function obtenerJWTToken() { try { const response = await axios.get('https://studio-api-eu.ai.vonage.com/agents/$AGENTID', { headers: { 'X-Vgai-Key': '$APIKEY' } }); JWT_TOKEN = response.data.token; // Update the JWT_TOKEN with the new value console.log("Token actualizado: ", JWT_TOKEN); } catch (error) { console.error("Error al obtener el JWT Token: ", error); } }

// Function to send the message async function enviarMensaje() { const toNumber = $NUMBER;

try { const response = await axios.post('https://api.nexmo.com/v1/messages', { template: { name: ${WHATSAPP_TEMPLATE_NAMESPACE}:${WHATSAPP_TEMPLATE_NAME}, // Use the correct template name }, to: toNumber, from: WHATSAPP_NUMBER, channel: 'whatsapp', message_type: 'template', whatsapp: { policy: 'deterministic', locale: 'es', } }, { headers: { 'Authorization': Bearer ${JWT_TOKEN}, 'X-Vgai-Key': '$APIKEY' // Api key of the bot application } });

console.log(`Mensaje enviado a ${toNumber}:`, response.data.message_uuid);

} catch (error) { console.error(Error al enviar mensaje a ${toNumber}:, error); } }

// Call obtenerJWTToken and then send the message obtenerJWTToken().then(enviarMensaje).catch(error => { console.error("Error durante el proceso: ", error); });

manchuck commented 5 months ago

@JaimeCasillasBluu The @vonage/messages package can help you out with this. There is a built in class which (when using the messages client) will format the request properly for you. Here is an example taken from our code snippets repository:


const { Vonage } = require('@vonage/server-sdk');
const { WhatsAppTemplate } = require('@vonage/messages');

const vonage = new Vonage({
  apiKey: VONAGE_API_KEY,
  apiSecret: VONAGE_API_SECRET,
  applicationId: VONAGE_APPLICATION_ID,
  privateKey: VONAGE_PRIVATE_KEY,
});

vonage.messages.send(
  new WhatsAppTemplate({
    template: {
      name: `${WHATSAPP_TEMPLATE_NAMESPACE}:${WHATSAPP_TEMPLATE_NAME}`,
      parameters: [
        'Vonage Verification',
        '64873',
        '10',
      ],
    },
    to: TO_NUMBER,
    from: WHATSAPP_NUMBER,
    locale: 'en',
  }),
)
  .then(resp => console.log(resp.messageUUID))
  .catch(err => console.error(err));

Let me know if that helps. If you run into issues I can take a look over and help figure out what the issue could be

JaimeCasillasBluu commented 5 months ago

I'm trying to use this for a whatsapp agent that is running in AI, studio. I can't get the private key because that will make the bot crash. I'm getting a 401 error. How do i authenticate in this case?, Like the previous code i had show you? Can you show me how please?

manchuck commented 5 months ago

@JaimeCasillasBluu I ran into a similar issue with AI studio. I wanted to be able to send WhatsApp messages from my telephony agent. What I wound up doing was create a new application in my dashboard. I then used the wehook node to call my own express server to send me a WhatsApp message. You can see an example of this here https://github.com/Vonage-Community/blog-vonage-ai-robocall-honeypot/blob/main/src/server.js#L59-L101

I call /add from AI studio, send the message, then listen for the response I setup in the application.