WhatsApp Template Message
Send a pre-approved WhatsApp template message with optional dynamic variables to a contact
This endpoint allows you to send WhatsApp template messages with dynamic variables to contacts through your registered WhatsApp Business account.
Prerequisites
- An active premium subscription
- A configured WhatsApp Business account integration
- Agent configured with the WhatsApp channel
- Template must be pre-approved on WhatsApp Business Manager
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| phoneNumberId | string | Yes | The WhatsApp Business phone number ID |
Request Body
Sending Media Templates
To send a template with a media header (image, video, or document), provide the header_type and the corresponding media source (header_link or header_id).
- Using a URL: Set
header_typeand provide the public URL inheader_link. - Using a Media ID: Set
header_typeand provide the ID of a previously uploaded media file inheader_id. - Text Header: Set
header_typeto"text"and provide the text inheader_text.
Body Variables
You can include dynamic variables in your template body by adding fields with the var_ prefix to your request body. These will be automatically mapped to the template parameters.
You can include dynamic variables in your template by adding fields with the var_ prefix to your request body. These will be automatically mapped to the template parameters.
Format: var_[parameter_name]: "value"
Examples:
var_customer_name: "John Doe"→ maps to parametercustomer_namevar_order_id: "12345"→ maps to parameterorder_idvar_delivery_date: "2024-01-15"→ maps to parameterdelivery_date
Response
Returns the created conversation object, including details about the message sent, contact, agent, and conversation metadata.
Example Response:
Example JS Code
Basic Template (No Variables)
Template with Variables
Template with Image Header
Template Variable Mapping
The API automatically converts var_ prefixed fields into WhatsApp Cloud API template components:
Request Body:
Generated WhatsApp Components:
Error Responses
| Status Code | Description | Details |
|---|---|---|
| 400 | Bad Request - Missing required parameters | Ocorre se algum campo obrigatório estiver ausente (to, templateName, templateLangCode, phoneNumberId ou agentId). Significado: A requisição está malformada devido a parâmetros obrigatórios faltando. Verifique se todos os campos requeridos foram enviados. |
| 401 | Unauthorized - Invalid token or access | Ocorre se o agente não pertencer à organização do usuário logado. Significado: O usuário não tem permissão para usar este agente. Verifique autenticação e permissões. |
| 402 | Payment Required - Premium subscription required | Ocorre se a organização não tiver uma assinatura ativa (premium). Significado: Recurso requer assinatura premium. Atualize a assinatura para continuar. |
| 404 | Not Found - Phone number ID, agent or organization not found | Ocorre se credenciais do phoneNumberId não forem encontradas, organização não existir ou campos requeridos estiverem ausentes (mapeado como 404, mas pode ser 400 na prática). Significado: Recurso não encontrado (phone number ID, agente ou organização). Verifique se o phoneNumberId está correto e configurado. |
| 500 | Internal Server Error | Ocorre se o envio da mensagem WhatsApp falhar (!result), erros na sincronização com CRM (loggado mas não lança erro), ou outros erros não tratados (e.g., Prisma, sendWhatsAppMessage). Significado: Erro interno do servidor. Pode ser problema na integração WhatsApp (rede, credenciais inválidas, template rejeitado pelo WhatsApp), ou falha no banco/CRM. Verifique logs do servidor para detalhes. Para templates, verifique se o template está aprovado no WhatsApp Business Manager e se os componentes estão corretos. |
CRM Integration
The API supports optional CRM (Customer Relationship Management) integration. If crmScenarioId and crmStepId are provided, the conversation will be automatically synchronized with the specified CRM scenario and step after the template message is sent.
- Default Synchronization: If only the agent is provided, the conversation will be synchronized with the default CRM scenario associated with the agent.
- Error Handling: Failures during CRM synchronization are logged but do not prevent the template message from being sent successfully.
- Related Fields:
crmScenarioId,crmStepId(optional) in the request body.
Webhooks
After sending a template message, a webhook with the event type AGENT_MESSAGE_SENDED is triggered asynchronously. It includes details about the message sent, conversation, agent, and contact.
Example Webhook Payload:
Notes:
- The webhook is sent via
WebhookFactory.sendAgentMessageSendedif the agent has an external URL configured (agent.configUrlExternal.url). - It occurs after the message is successfully created and sent (or simulated in development).
Authorizations
Bearer authentication header of the form Bearer <token>, where <token> is your auth token.
Path Parameters
ID of the WhatsApp Business phone number
Body
Recipient's phone number with country code
Message text to store in conversation history
ID of the agent to associate with this message
Name of the pre-approved WhatsApp template
Language code for the template
The default status to set for the conversation.
RESOLVED, UNRESOLVED, HUMAN_REQUESTED Dynamic template variables with 'var_' prefix (e.g., var_customer_name, var_order_id)
Response
Conversation ID
External ID for the channel
Conversation channel
whatsapp Messages in the conversation
Was this page helpful?

