WhatsApp official API in Go: net/http and webhook
Integrate the official WhatsApp API in Go via CRPRO Hub with the standard library only: net/http client with timeout, hmac.Equal webhook and a signature test.
In Go, the CRPRO Hub integration fits in the standard library: net/http to call the API, crypto/hmac to check the signature and encoding/json for the bodies. No framework or SDK is needed. This article shows a send client, a webhook server and a test, and points out where Go demands more care than other languages, mainly with timeouts and body reading. For the overall flow, see the quickstart.
How to build the HTTP client
Short answer: create a single http.Client with a Timeout and reuse it across the application. The package's default client has no timeout, and a stuck call holds the goroutine forever.
The net/http package documentation defines the client Timeout as the total time of the request, covering the connection, redirects and reading the response body, and states that zero means no limit. The http.NewRequestWithContext function takes a context.Context, the method, the URL and an io.Reader, and lets you cancel the call from outside. Use both: Timeout on the client and a per-request context.
- Create the API key in the dashboard with the messages:send scope and read it from an environment variable (authentication). It is shown only once.
- Send POST to /api/v1/channels/{id}/messages with Authorization: Bearer, Content-Type: application/json and Idempotency-Key.
- The body carries to (country code, digits only), type and text with body. The Hub answers 202 with status accepted.
- Treat any status other than 202 as an error and read only a short slice of the body for the log.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
// Um unico cliente, reutilizado. O Timeout cobre conexao, redirecionamentos e leitura da resposta.
var cliente = &http.Client{Timeout: 10 * time.Second}
func enviarTexto(ctx context.Context, canal, para, texto, chave string) error {
corpo, err := json.Marshal(map[string]any{
"to": para,
"type": "text",
"text": map[string]string{"body": texto},
})
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://crprohub.com/api/v1/channels/"+canal+"/messages", bytes.NewReader(corpo))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("CRPRO_API_KEY"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", chave)
resp, err := cliente.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted { // 202: aceita, nao entregue
detalhe, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
return fmt.Errorf("crprohub: status %d: %s", resp.StatusCode, detalhe)
}
return nil
}The Idempotency-Key must be stable per logical message. Repeating the call with the same key and the same body returns the original response; with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED. The limits are 60 messages per minute per channel and 120 requests per minute per organization and credential. On a 429 or 5xx, repeat with the same key and growing waits.
How to receive the webhook
Short answer: register a POST route, read the whole body with a size limit, check the HMAC with hmac.Equal, answer 200 and process in a goroutine. The Hub expects a 2xx within 10 seconds.
The "POST /webhooks/crprohub" pattern in ServeMux, with the method inside the pattern, is available from Go 1.22. http.MaxBytesReader caps the body and protects memory; 1 MiB is a limit of our own choosing, since the Hub documentation defines no maximum size for what it sends. The Hub signs timestamp.delivery_id.body with HMAC SHA-256, and the signature arrives in X-Hub-Signature-256 as sha256=HEX.
curl -X POST https://crprohub.com/api/v1/webhooks \
-H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \
-H "Content-Type: application/json" \
-d '{"name":"Recebimento","url":"https://your-domain.com/webhooks/crprohub","event_types":["message.received"]}'package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
)
type evento struct {
ID string `json:"id"`
Event string `json:"event"`
ChannelID string `json:"channel_id"`
Data struct {
MessageID string `json:"message_id"`
From string `json:"from"`
Text string `json:"text"`
} `json:"data"`
}
func assinaturaValida(r *http.Request, corpo []byte) bool {
mac := hmac.New(sha256.New, []byte(os.Getenv("CRPRO_WEBHOOK_SECRET")))
mac.Write([]byte(r.Header.Get("X-Hub-Timestamp") + "." + r.Header.Get("X-Hub-Delivery-Id") + "."))
mac.Write(corpo)
recebido, err := hex.DecodeString(strings.TrimPrefix(r.Header.Get("X-Hub-Signature-256"), "sha256="))
if err != nil {
return false
}
return hmac.Equal(mac.Sum(nil), recebido) // tempo constante
}
var vistos sync.Map // troque por um armazenamento compartilhado em producao
func webhook(w http.ResponseWriter, r *http.Request) {
corpo, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "corpo invalido", http.StatusRequestEntityTooLarge)
return
}
if !assinaturaValida(r, corpo) {
http.Error(w, "assinatura invalida", http.StatusUnauthorized)
return
}
var ev evento
if err := json.Unmarshal(corpo, &ev); err != nil {
http.Error(w, "json invalido", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK) // o Hub espera um 2xx em ate 10 s
if _, repetido := vistos.LoadOrStore(ev.ID, struct{}{}); repetido {
return
}
if ev.Event != "message.received" || ev.Data.Text == "" {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := enviarTexto(ctx, ev.ChannelID, ev.Data.From, "Recebemos sua mensagem.", "resp-"+ev.Data.MessageID); err != nil {
log.Println(err)
}
}()
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /webhooks/crprohub", webhook) // metodo no padrao: Go 1.22 ou superior
log.Fatal(http.ListenAndServe(":8080", mux))
}{
"id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b",
"event": "message.received",
"channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d",
"occurred_at": "2026-08-21T12:00:00.000Z",
"data": {
"message_id": "wamid.EXEMPLO123",
"from": "5521999999999",
"type": "text",
"text": "Oi, ainda tem em estoque?"
}
}Duplicates, goroutines and context
Short answer: answer before processing, deduplicate on the body id and do not use the request context inside the goroutine. After the response, the request context is canceled, and the Hub call would abort.
That is why the example creates a context.Background with context.WithTimeout inside the goroutine. The Hub repeats a delivery when it gets no 2xx: up to nine retries over about four days, and after 20 consecutive failures the endpoint is paused. The id field in the body stays the same on retry and replay, and is the right key to deduplicate. The example's sync.Map lives in memory and vanishes on restart; in production, use shared storage, such as a table with a unique constraint.
| Situation | Response | Effect on the Hub |
|---|---|---|
| Invalid signature | 401 | Counts as a failure |
| Body over the limit | 413 | Counts as a failure |
| Invalid JSON | 400 | Counts as a failure |
| New or repeated event | 200 | Delivery complete |
If the endpoint is paused, reactivate with PATCH /api/v1/webhooks/{id} and {"status":"active"}. Events during the pause generate no delivery; recover them with GET /api/v1/channels/{id}/messages and direction=inbound. Full diagnosis is on the webhooks page.
Common mistakes in Go and how to avoid them
Short answer: the five most frequent slips are a client with no timeout, a body read twice, string comparison on the signature, a reused request context and a slow answer to the Hub.
- Body read twice: r.Body is a stream and can be read only once. Read it with io.ReadAll, keep the bytes and use them for both the signature and json.Unmarshal.
- Closing the response body: after cliente.Do, always defer resp.Body.Close(), or connections do not return to the pool.
- Comparing with ==: replace it with hmac.Equal over bytes, as in the example.
- Answering late: if the handler calls the Hub before answering, any slowness blows past the 10 seconds and triggers a retry.
- Same key with different text: the Hub answers 409; generate the text once and keep it.
For errors from the API itself, like 401 for an invalid key, 403 for a missing scope or 429 for a limit, see the docs home.
How to test the signature
Short answer: compute the HMAC in the test itself with the same formula, build the request with httptest.NewRequest and call assinaturaValida. Test a correct signature and a swapped one.
func TestAssinatura(t *testing.T) {
t.Setenv("CRPRO_WEBHOOK_SECRET", "whsec_teste")
corpo := []byte(`{"id":"e1","event":"webhook.test"}`)
mac := hmac.New(sha256.New, []byte("whsec_teste"))
mac.Write([]byte("123.d-1."))
mac.Write(corpo)
req := httptest.NewRequest(http.MethodPost, "/webhooks/crprohub", bytes.NewReader(corpo))
req.Header.Set("X-Hub-Timestamp", "123")
req.Header.Set("X-Hub-Delivery-Id", "d-1")
req.Header.Set("X-Hub-Signature-256", "sha256="+hex.EncodeToString(mac.Sum(nil)))
if !assinaturaValida(req, corpo) {
t.Fatal("assinatura correta recusada")
}
req.Header.Set("X-Hub-Signature-256", "sha256="+strings.Repeat("0", 64))
if assinaturaValida(req, corpo) {
t.Fatal("assinatura trocada aceita")
}
}This test needs the imports bytes, crypto/hmac, crypto/sha256, encoding/hex, net/http, net/http/httptest, strings and testing. It uses no network and no Hub. For a real delivery, the POST /api/v1/webhooks/{id}/test endpoint sends an event to your server, up to 10 times per hour per endpoint. See the headers and rules in the webhooks page linked above.
Frequently asked questions
Do I need any third-party library in Go?
No. net/http, crypto/hmac, crypto/sha256, encoding/json and encoding/hex are enough. The example uses no external package.
Why not use http.DefaultClient?
Because the default client has no timeout. With a zero Timeout, a stuck connection waits forever. Create a client with a Timeout and reuse it.
What is the minimum Go version?
Go 1.22, because of the method pattern in ServeMux ("POST /webhooks/crprohub"). On earlier versions, check the method inside the handler.
Can I use the request context in the goroutine?
No. It is canceled when the handler returns. Create your own context with context.WithTimeout inside the goroutine.
Fontes
Documentação oficial da Meta, conferida em 31 de outubro de 2026.