From ac91b6d6e65cfbbff38d21b4bb6c48cfc0f6164d Mon Sep 17 00:00:00 2001 From: Jordan Vasconcelos Date: Wed, 25 Mar 2026 15:53:26 -0300 Subject: [PATCH 1/2] docs: add custom headers and JWT documentation for webhook endpoints Document the `headers` field in webhook configuration, including support for static tokens (Bearer, API Key, Basic Auth) and automatic JWT generation via the special `jwt_key` property. Updated PT and EN docs and OpenAPI v2 spec for webhook/set, webhook/find, and instance/create. --- openapi/openapi-v2.json | 50 ++++++++-- v2/en/configuration/webhooks.mdx | 159 ++++++++++++++++++++++++++++++- v2/pt/configuration/webhooks.mdx | 157 +++++++++++++++++++++++++++++- 3 files changed, 351 insertions(+), 15 deletions(-) diff --git a/openapi/openapi-v2.json b/openapi/openapi-v2.json index 72a92ae..ff45177 100644 --- a/openapi/openapi-v2.json +++ b/openapi/openapi-v2.json @@ -130,16 +130,14 @@ }, "headers": { "type": "object", - "description": "Headers for send the API from webhook", - "properties": { - "authorization": { - "type": "string", - "description": "Your authorization key header" - }, - "Content-Type": { - "type": "string", - "description": "content-type" - } + "description": "Custom HTTP headers sent with every webhook request. Accepts any key-value string pairs such as Authorization, X-Api-Key, or any other valid HTTP header. Special key 'jwt_key': instead of being sent as a header, its value is used as a secret to sign a JWT token (HS256, 10min expiry) that is automatically injected as 'Authorization: Bearer ' on each request.", + "additionalProperties": { + "type": "string" + }, + "example": { + "Authorization": "Bearer your-token-here", + "X-Api-Key": "your-api-key", + "jwt_key": "your-secret-for-auto-jwt-signing" } }, "events": { @@ -1228,6 +1226,18 @@ "type": "string", "description": "Webhook URL" }, + "headers": { + "type": "object", + "description": "Custom HTTP headers sent with every webhook request. Accepts any key-value string pairs such as Authorization, X-Api-Key, or any other valid HTTP header. Special key 'jwt_key': instead of being sent as a header, its value is used as a secret to sign a JWT token (HS256, 10min expiry) that is automatically injected as 'Authorization: Bearer ' on each request.", + "additionalProperties": { + "type": "string" + }, + "example": { + "Authorization": "Bearer your-token-here", + "X-Api-Key": "your-api-key", + "jwt_key": "your-secret-for-auto-jwt-signing" + } + }, "webhookByEvents": { "type": "boolean", "description": "Enables Webhook by events" @@ -1296,6 +1306,13 @@ "type": "string", "description": "The URL of the webhook." }, + "headers": { + "type": "object", + "description": "Custom HTTP headers configured for this webhook.", + "additionalProperties": { + "type": "string" + } + }, "events": { "type": "array", "items": { @@ -1317,6 +1334,9 @@ "instanceName": "teste-docs", "webhook": { "url": "https://example.com", + "headers": { + "Authorization": "Bearer your-token-here" + }, "events": [ "APPLICATION_STARTUP" ], @@ -1372,6 +1392,13 @@ "type": "string", "description": "The URL of the webhook." }, + "headers": { + "type": "object", + "description": "Custom HTTP headers configured for this webhook.", + "additionalProperties": { + "type": "string" + } + }, "events": { "type": "array", "items": { @@ -1383,6 +1410,9 @@ "example": { "enabled": true, "url": "https://example.com", + "headers": { + "Authorization": "Bearer your-token-here" + }, "events": [ "APPLICATION_STARTUP" ] diff --git a/v2/en/configuration/webhooks.mdx b/v2/en/configuration/webhooks.mdx index 5618aab..a832b09 100644 --- a/v2/en/configuration/webhooks.mdx +++ b/v2/en/configuration/webhooks.mdx @@ -33,7 +33,7 @@ Here is an example with some common events being listened to: "CONNECTION_UPDATE", "TYPEBOT_START", "TYPEBOT_CHANGE_STATUS" - ] + ] } ``` ### Parameters @@ -42,7 +42,9 @@ Here is an example with some common events being listened to: | ----------------- | ------- | --------- | ----------------------------------------------------------------------------------------------------------------- | | enabled | boolean | Yes | Enter "true" to create or change Webhook data, or "false" if you want to stop using it. | | url | string | Yes | Webhook URL to receive event data. | +| headers | object | No | Custom HTTP headers sent with every webhook request. See [Custom Headers](#custom-headers). | | webhook_by_events | boolean | No | Whether to generate a specific Webhook URL for each of your events. | +| base64 | boolean | No | Encode media as base64 in the webhook payload. | | events | array | No | List of events to be processed. If you don't want to use some of these events, simply remove them from the list. | @@ -50,6 +52,149 @@ It is extremely necessary that the payload follows the rules to create a JSON fi Before consuming the endpoint, if you have doubts about the JSON formatting, go to https://jsonlint.com/ and validate. +## Custom Headers + +You can configure custom HTTP headers that will be sent with **every webhook request** for the instance. This is useful for authentication, identification, and integration with external systems that require tokens or API keys. + +The `headers` field accepts any JSON object with string key-value pairs. + +### Configuring Headers + +```json POST /event/webhook/set/{instanceName} +{ + "webhook": { + "enabled": true, + "url": "https://your-endpoint.com/webhook", + "headers": { + "Authorization": "Bearer your-token-here", + "X-Api-Key": "your-secret-key" + }, + "events": [ + "MESSAGES_UPSERT", + "CONNECTION_UPDATE" + ], + "byEvents": false, + "base64": false + } +} +``` + +### Supported Authentication Types + +Any valid HTTP header can be used. Below are the most common patterns: + +#### Bearer Token + +```json +"headers": { + "Authorization": "Bearer eyJhbGciOiJIUzI1NiIs..." +} +``` + +#### API Key + +```json +"headers": { + "X-Api-Key": "your-key-here" +} +``` + +#### Basic Auth + +```json +"headers": { + "Authorization": "Basic dXNlcjpwYXNzd29yZA==" +} +``` + + +For Basic Auth, the value must be the `username:password` string encoded in base64. + + +#### Multiple Headers + +You can combine as many headers as needed: + +```json +"headers": { + "Authorization": "Bearer token", + "X-Tenant-Id": "company-123", + "X-Source": "evolution-api" +} +``` + +### Automatic JWT (jwt_key) + +Evolution API has a special feature for automatic JWT token generation. When you set the `jwt_key` key in the headers, the API will: + +1. Use the value as a secret key to sign a JWT token (HS256 algorithm) +2. Generate a new token for each event with the following payload: + ```json + { + "iat": 1711367040, + "exp": 1711367640, + "app": "evolution", + "action": "webhook" + } + ``` +3. Send the token in the `Authorization: Bearer ` header +4. The `jwt_key` itself is **not** sent as a header — it is removed before sending + +#### Configuration + +```json +"headers": { + "jwt_key": "your-secret-signing-key" +} +``` + +#### Result on each request + +Every webhook request will be sent with the header: +``` +Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... +``` + + +The JWT token expires in **10 minutes** and is **automatically regenerated** with each event sent, ensuring your server always receives a valid token. + + +#### Validating on your server + +On your server, validate the token using the same secret key configured in `jwt_key` with the HS256 algorithm. + +You can combine `jwt_key` with other custom headers: + +```json +"headers": { + "jwt_key": "secret-key", + "X-Tenant-Id": "company-123" +} +``` + +In this case, the request will be sent with `Authorization: Bearer ` and `X-Tenant-Id: company-123`. + +### Headers on instance creation + +You can also configure headers directly when creating an instance: + +```json POST /instance/create +{ + "instanceName": "my-instance", + "integration": "WHATSAPP-BAILEYS", + "qrcode": true, + "webhook": { + "url": "https://your-endpoint.com/webhook", + "headers": { + "Authorization": "Bearer my-token" + }, + "events": ["MESSAGES_UPSERT", "CONNECTION_UPDATE"], + "byEvents": false, + "base64": false + } +} +``` + ### Global Webhook Events Each instance's Webhook URL and events will be requested when they are created. @@ -70,6 +215,11 @@ WEBHOOK_EVENTS_QRCODE_UPDATED=true WEBHOOK_EVENTS_ERRORS=false WEBHOOK_EVENTS_ERRORS_WEBHOOK= ``` + + +The global webhook configured via environment variables **does not support custom headers**. To use headers, configure the webhook per instance via the API. + + ## Supported Events These are the available and supported webhook events: @@ -104,7 +254,7 @@ When enabling the WEBHOOK_BY_EVENTS options in both global and local webhooks, t Add the event name at the end of the URL with a hyphen (-) between the words that make up the event. - + ### Example Suppose your webhook URL is `https://sub.domain.com/webhook/`. Evolution will automatically add the event name to the end of the URL when `webhook_by_events` is set to true. @@ -149,9 +299,12 @@ Calling the endpoint will return all information about the webhook being used by { "enabled": true, "url": "[url]", + "headers": { + "Authorization": "Bearer configured-token" + }, "webhookByEvents": false, "events": [ [events] ] } -``` \ No newline at end of file +``` diff --git a/v2/pt/configuration/webhooks.mdx b/v2/pt/configuration/webhooks.mdx index 37b6f75..d7e92bb 100644 --- a/v2/pt/configuration/webhooks.mdx +++ b/v2/pt/configuration/webhooks.mdx @@ -34,7 +34,7 @@ Aqui está um exemplo com alguns eventos comuns ouvidos: "CONNECTION_UPDATE", "TYPEBOT_START", "TYPEBOT_CHANGE_STATUS" - ] + ] } ``` ### Parâmetros @@ -43,7 +43,9 @@ Aqui está um exemplo com alguns eventos comuns ouvidos: | ----------------- | ------- | ------------ | --------------------------------------------------------------------------------------------------------------- | | enabled | boolean | Sim | Insira "true" para criar ou alterar dados do Webhook, ou "false" se quiser parar de usá-lo. | | url | string | Sim | URL do Webhook para receber dados do evento. | +| headers | object | Não | Headers HTTP customizados enviados em cada requisição do webhook. Veja [Headers Customizados](#headers-customizados). | | webhook_by_events | boolean | Não | Deseja gerar uma URL específica do Webhook para cada um dos seus eventos. | +| base64 | boolean | Não | Codifica mídias em base64 no payload do webhook. | | events | array | Não | Lista de eventos a serem processados. Se você não quiser usar alguns desses eventos, apenas remova-os da lista. | @@ -51,6 +53,149 @@ Aqui está um exemplo com alguns eventos comuns ouvidos: Antes de consumir o endpoint, se tiver dúvidas sobre a formatação JSON, vá para https://jsonlint.com/ e valide. +## Headers Customizados + +Você pode configurar headers HTTP customizados que serão enviados em **todas as requisições de webhook** da instância. Isso é útil para autenticação, identificação e integração com sistemas externos que exigem tokens ou chaves de API. + +O campo `headers` aceita qualquer objeto JSON com pares chave-valor string. + +### Configurando Headers + +```json POST /event/webhook/set/{instanceName} +{ + "webhook": { + "enabled": true, + "url": "https://seu-endpoint.com/webhook", + "headers": { + "Authorization": "Bearer seu-token-aqui", + "X-Api-Key": "sua-chave-secreta" + }, + "events": [ + "MESSAGES_UPSERT", + "CONNECTION_UPDATE" + ], + "byEvents": false, + "base64": false + } +} +``` + +### Tipos de Autenticação Suportados + +Qualquer header HTTP válido pode ser utilizado. Abaixo estão os padrões mais comuns: + +#### Bearer Token + +```json +"headers": { + "Authorization": "Bearer eyJhbGciOiJIUzI1NiIs..." +} +``` + +#### API Key + +```json +"headers": { + "X-Api-Key": "sua-chave-aqui" +} +``` + +#### Basic Auth + +```json +"headers": { + "Authorization": "Basic dXNlcjpwYXNzd29yZA==" +} +``` + + +Para Basic Auth, o valor deve ser a string `usuario:senha` codificada em base64. + + +#### Múltiplos Headers + +Você pode combinar quantos headers forem necessários: + +```json +"headers": { + "Authorization": "Bearer token", + "X-Tenant-Id": "empresa-123", + "X-Source": "evolution-api" +} +``` + +### JWT Automático (jwt_key) + +A Evolution API possui um recurso especial para geração automática de tokens JWT. Ao configurar a chave `jwt_key` nos headers, a API irá: + +1. Usar o valor como chave secreta para assinar um token JWT (algoritmo HS256) +2. Gerar um novo token a cada envio de evento com o payload: + ```json + { + "iat": 1711367040, + "exp": 1711367640, + "app": "evolution", + "action": "webhook" + } + ``` +3. Enviar o token no header `Authorization: Bearer ` +4. O `jwt_key` **não** é enviado como header — ele é removido antes do envio + +#### Configuração + +```json +"headers": { + "jwt_key": "sua-chave-secreta-para-assinatura" +} +``` + +#### Resultado no envio + +Cada requisição de webhook será enviada com o header: +``` +Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... +``` + + +O token JWT expira em **10 minutos** e é **regenerado automaticamente** a cada evento enviado, garantindo que seu servidor sempre receba um token válido. + + +#### Validação no seu servidor + +No seu servidor, valide o token usando a mesma chave secreta configurada em `jwt_key` com o algoritmo HS256. + +Você pode combinar `jwt_key` com outros headers customizados: + +```json +"headers": { + "jwt_key": "chave-secreta", + "X-Tenant-Id": "empresa-123" +} +``` + +Neste caso, a requisição será enviada com `Authorization: Bearer ` e `X-Tenant-Id: empresa-123`. + +### Headers na criação da instância + +Também é possível configurar os headers diretamente ao criar uma instância: + +```json POST /instance/create +{ + "instanceName": "minha-instancia", + "integration": "WHATSAPP-BAILEYS", + "qrcode": true, + "webhook": { + "url": "https://seu-endpoint.com/webhook", + "headers": { + "Authorization": "Bearer meu-token" + }, + "events": ["MESSAGES_UPSERT", "CONNECTION_UPDATE"], + "byEvents": false, + "base64": false + } +} +``` + ### Eventos Globais de Webhook Cada URL e eventos de Webhook da instância serão solicitados no momento em que forem criados @@ -71,6 +216,11 @@ WEBHOOK_EVENTS_QRCODE_UPDATED=true WEBHOOK_EVENTS_ERRORS=false WEBHOOK_EVENTS_ERRORS_WEBHOOK= ``` + + +O webhook global configurado via variáveis de ambiente **não suporta headers customizados**. Para utilizar headers, configure o webhook por instância via API. + + ## Eventos Suportados Estes são os eventos de webhook disponíveis e suportados: @@ -105,7 +255,7 @@ Ao habilitar as opções WEBHOOK_BY_EVENTS nos webhooks globais e locais, os seg Adicione ao final da URL o nome do evento com um traço (-) entre as palavras que compõem o evento. - + ### Exemplo Supondo que sua URL de webhook fosse `https://sub.domain.com/webhook/`. A Evolution adicionará automaticamente ao final da URL o nome do evento quando `webhook_by_events` estiver definido como verdadeiro. @@ -150,6 +300,9 @@ Chamando o endpoint retornará todas as informações sobre o webhook que está { "enabled": true, "url": "[url]", + "headers": { + "Authorization": "Bearer token-configurado" + }, "webhookByEvents": false, "events": [ [eventos] From bcd12f4ed04c9e5bcdb89202215b57691d7bea5d Mon Sep 17 00:00:00 2001 From: Jordan Vasconcelos Date: Wed, 25 Mar 2026 16:12:21 -0300 Subject: [PATCH 2/2] docs: address review feedback - standardize param names and add jwt_key security warning - Standardize parameter names in tables to match actual API request fields (byEvents, base64) - Note that response fields use different names (webhookByEvents, webhookBase64) - Add security warning about treating jwt_key as a secret --- v2/en/configuration/webhooks.mdx | 20 ++++++++++++-------- v2/pt/configuration/webhooks.mdx | 20 ++++++++++++-------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/v2/en/configuration/webhooks.mdx b/v2/en/configuration/webhooks.mdx index a832b09..b38bff9 100644 --- a/v2/en/configuration/webhooks.mdx +++ b/v2/en/configuration/webhooks.mdx @@ -38,14 +38,14 @@ Here is an example with some common events being listened to: ``` ### Parameters -| Parameter | Type | Required | Description | -| ----------------- | ------- | --------- | ----------------------------------------------------------------------------------------------------------------- | -| enabled | boolean | Yes | Enter "true" to create or change Webhook data, or "false" if you want to stop using it. | -| url | string | Yes | Webhook URL to receive event data. | -| headers | object | No | Custom HTTP headers sent with every webhook request. See [Custom Headers](#custom-headers). | -| webhook_by_events | boolean | No | Whether to generate a specific Webhook URL for each of your events. | -| base64 | boolean | No | Encode media as base64 in the webhook payload. | -| events | array | No | List of events to be processed. If you don't want to use some of these events, simply remove them from the list. | +| Parameter | Type | Required | Description | +| --------- | ------- | --------- | ----------------------------------------------------------------------------------------------------------------- | +| enabled | boolean | Yes | Enter "true" to create or change Webhook data, or "false" if you want to stop using it. | +| url | string | Yes | Webhook URL to receive event data. | +| headers | object | No | Custom HTTP headers sent with every webhook request. See [Custom Headers](#custom-headers). | +| byEvents | boolean | No | Whether to generate a specific Webhook URL for each of your events. Returned as `webhookByEvents` in API responses. | +| base64 | boolean | No | Encode media as base64 in the webhook payload. Returned as `webhookBase64` in API responses. | +| events | array | No | List of events to be processed. If you don't want to use some of these events, simply remove them from the list. | It is extremely necessary that the payload follows the rules to create a JSON file, considering the correct arrangement of items, formatting, brackets, braces, commas, etc. @@ -140,6 +140,10 @@ Evolution API has a special feature for automatic JWT token generation. When you 3. Send the token in the `Authorization: Bearer ` header 4. The `jwt_key` itself is **not** sent as a header — it is removed before sending + +The `jwt_key` value is a secret key used to sign JWT tokens. Treat it like a password: never expose it in frontend code, public repositories, or share it publicly. + + #### Configuration ```json diff --git a/v2/pt/configuration/webhooks.mdx b/v2/pt/configuration/webhooks.mdx index d7e92bb..7d53536 100644 --- a/v2/pt/configuration/webhooks.mdx +++ b/v2/pt/configuration/webhooks.mdx @@ -39,14 +39,14 @@ Aqui está um exemplo com alguns eventos comuns ouvidos: ``` ### Parâmetros -| Parâmetro | Tipo | Obrigatório | Descrição | -| ----------------- | ------- | ------------ | --------------------------------------------------------------------------------------------------------------- | -| enabled | boolean | Sim | Insira "true" para criar ou alterar dados do Webhook, ou "false" se quiser parar de usá-lo. | -| url | string | Sim | URL do Webhook para receber dados do evento. | -| headers | object | Não | Headers HTTP customizados enviados em cada requisição do webhook. Veja [Headers Customizados](#headers-customizados). | -| webhook_by_events | boolean | Não | Deseja gerar uma URL específica do Webhook para cada um dos seus eventos. | -| base64 | boolean | Não | Codifica mídias em base64 no payload do webhook. | -| events | array | Não | Lista de eventos a serem processados. Se você não quiser usar alguns desses eventos, apenas remova-os da lista. | +| Parâmetro | Tipo | Obrigatório | Descrição | +| --------- | ------- | ------------ | --------------------------------------------------------------------------------------------------------------- | +| enabled | boolean | Sim | Insira "true" para criar ou alterar dados do Webhook, ou "false" se quiser parar de usá-lo. | +| url | string | Sim | URL do Webhook para receber dados do evento. | +| headers | object | Não | Headers HTTP customizados enviados em cada requisição do webhook. Veja [Headers Customizados](#headers-customizados). | +| byEvents | boolean | Não | Deseja gerar uma URL específica do Webhook para cada um dos seus eventos. Retornado como `webhookByEvents` nas respostas da API. | +| base64 | boolean | Não | Codifica mídias em base64 no payload do webhook. Retornado como `webhookBase64` nas respostas da API. | +| events | array | Não | Lista de eventos a serem processados. Se você não quiser usar alguns desses eventos, apenas remova-os da lista. | É extremamente necessário que o payload obedeça às regras para criar um arquivo JSON, considerando o arranjo correto de itens, formatação, colchetes, chaves e vírgulas, etc. @@ -141,6 +141,10 @@ A Evolution API possui um recurso especial para geração automática de tokens 3. Enviar o token no header `Authorization: Bearer ` 4. O `jwt_key` **não** é enviado como header — ele é removido antes do envio + +O valor de `jwt_key` é uma chave secreta usada para assinar tokens JWT. Trate-o como uma senha: nunca exponha em código frontend, repositorios publicos ou compartilhe publicamente. + + #### Configuração ```json