# WhatsApp Cloud API in Go: inviare un messaggio e ricevere webhook

> Invia messaggi WhatsApp di testo e modelli e ricevi webhook in un solo file Go 1.27 con la sola net/http: controllo HMAC, ripiego sul BSUID e un worker.

Published 2026-11-04. Z-API Omni team.

Per inviare messaggi WhatsApp da Go usa `http.NewRequestWithContext` e una POST JSON a `/v26.0/<PHONE_NUMBER_ID>/messages`. Per ricevere i webhook bastano due pattern con metodo: `GET /webhook` per la verifica e `POST /webhook` per gli eventi. La POST legge il corpo, controlla `X-Hub-Signature-256` con `hmac.Equal`, passa i byte a una goroutine worker e restituisce 200. Il `main.go` qui sotto fa entrambe le cose con la sola libreria standard.

## Prepara il modulo

La release attuale è go1.27.3, del 2026-10-19 ([cronologia delle release di Go, consultato il 2026-11-04](https://go.dev/doc/devel/release)). Il file gira anche su go1.26, l'altra linea supportata. Il pattern matching di `ServeMux` «è cambiato in modo significativo in Go 1.22», la versione in cui sono arrivati i pattern con metodo ([net/http](https://pkg.go.dev/net/http)). Su macOS, Go 1.27 richiede macOS 13 o successivo ([note di rilascio di Go 1.27](https://go.dev/doc/go1.27)).

```bash
mkdir whatsapp-go && cd whatsapp-go
go mod init example.com/whatsapp-go
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
export APP_SECRET="APP_SECRET"
export VERIFY_TOKEN="VERIFY_TOKEN"
```

`GRAPH_VERSION` vale `v26.0` per impostazione predefinita, la versione dell'esempio di invio di Meta ([Meta, inviare messaggi, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages)). `GRAPH_BASE` vale `https://graph.facebook.com` per impostazione predefinita, e il test finale la punta verso un mock. Token e ID dei numeri di telefono vengono dalla [guida al numero di test](/academy/it/articles/whatsapp-cloud-api-test-number-get-started/).

## main.go

```go
// main.go
package main

import (
	"bytes"
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
)

var (
	graphBase    = envOr("GRAPH_BASE", "https://graph.facebook.com")
	graphVersion = envOr("GRAPH_VERSION", "v26.0")
	client       = &http.Client{Timeout: 15 * time.Second} // our choice; Meta documents none
)

func envOr(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

func mustEnv(key string) string {
	v := os.Getenv(key)
	if v == "" {
		log.Fatalf("set the %s environment variable", key)
	}
	return v
}

// ---- Sending ----

type OutMessage struct {
	MessagingProduct string    `json:"messaging_product"`
	RecipientType    string    `json:"recipient_type"`
	To               string    `json:"to"`
	Type             string    `json:"type"`
	Text             *Text     `json:"text,omitempty"`
	Template         *Template `json:"template,omitempty"`
}

type Text struct {
	PreviewURL bool   `json:"preview_url"`
	Body       string `json:"body"`
}

type Template struct {
	Name       string      `json:"name"`
	Language   Language    `json:"language"`
	Components []Component `json:"components,omitempty"`
}

type Language struct {
	Code string `json:"code"`
}

type Component struct {
	Type       string      `json:"type"`
	Parameters []Parameter `json:"parameters"`
}

type Parameter struct {
	Type          string `json:"type"`
	ParameterName string `json:"parameter_name,omitempty"`
	Text          string `json:"text"`
}

type SendResponse struct {
	Contacts []struct {
		WaID string `json:"wa_id"`
	} `json:"contacts"`
	Messages []struct {
		ID            string `json:"id"`
		MessageStatus string `json:"message_status"`
	} `json:"messages"`
	Error *APIError `json:"error"`
}

type APIError struct {
	Status    int    `json:"-"`
	Message   string `json:"message"`
	Code      int    `json:"code"`
	FBTraceID string `json:"fbtrace_id"`
	ErrorData struct {
		Details string `json:"details"`
	} `json:"error_data"`
}

func (e *APIError) Error() string {
	return fmt.Sprintf("HTTP %d, code %d: %s %s (fbtrace_id %s)",
		e.Status, e.Code, e.Message, e.ErrorData.Details, e.FBTraceID)
}

func textMessage(to, body string) OutMessage {
	return OutMessage{MessagingProduct: "whatsapp", RecipientType: "individual",
		To: to, Type: "text", Text: &Text{Body: body}}
}

func templateMessage(to, name, lang string, params []string) OutMessage {
	t := &Template{Name: name, Language: Language{Code: lang}}
	if len(params) > 0 { // name=value becomes a named parameter, a bare value a positional one
		c := Component{Type: "body"}
		for _, p := range params {
			if k, v, ok := strings.Cut(p, "="); ok {
				c.Parameters = append(c.Parameters, Parameter{Type: "text", ParameterName: k, Text: v})
			} else {
				c.Parameters = append(c.Parameters, Parameter{Type: "text", Text: p})
			}
		}
		t.Components = []Component{c}
	}
	return OutMessage{MessagingProduct: "whatsapp", RecipientType: "individual",
		To: to, Type: "template", Template: t}
}

func postMessage(ctx context.Context, token, phoneNumberID string, msg OutMessage) (*SendResponse, error) {
	body, err := json.Marshal(msg)
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("%s/%s/%s/messages", strings.TrimRight(graphBase, "/"), graphVersion, phoneNumberID)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var out SendResponse
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return nil, fmt.Errorf("HTTP %d, body is not JSON: %w", resp.StatusCode, err)
	}
	if out.Error != nil || resp.StatusCode >= 400 {
		if out.Error == nil {
			out.Error = &APIError{Message: "no error object in the response"}
		}
		out.Error.Status = resp.StatusCode
		return nil, out.Error
	}
	return &out, nil
}

func send(ctx context.Context, token, phoneNumberID string, msg OutMessage) (*SendResponse, error) {
	const attempts = 4
	for attempt := 0; ; attempt++ {
		out, err := postMessage(ctx, token, phoneNumberID, msg)
		var apiErr *APIError
		if err == nil || !errors.As(err, &apiErr) || attempt == attempts-1 {
			return out, err
		}
		var wait time.Duration
		switch apiErr.Code {
		case 131056: // pair rate: Meta's 4^X schedule, 1, 4, 16 s
			wait = time.Duration(1<<(2*attempt)) * time.Second
		case 130429: // throughput: our choice, 1, 2, 4 s
			wait = time.Duration(1<<attempt) * time.Second
		default:
			return nil, err
		}
		log.Printf("code %d, retrying in %s", apiErr.Code, wait)
		select {
		case <-time.After(wait):
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	}
}

// ---- Receiving ----

type Webhook struct {
	Object string `json:"object"`
	Entry  []struct {
		Changes []struct {
			Field string `json:"field"`
			Value struct {
				Messages []struct {
					ID         string `json:"id"`
					From       string `json:"from"`
					FromUserID string `json:"from_user_id"`
					Timestamp  string `json:"timestamp"`
					Type       string `json:"type"`
					Text       struct {
						Body string `json:"body"`
					} `json:"text"`
				} `json:"messages"`
				Statuses []struct {
					ID              string          `json:"id"`
					Status          string          `json:"status"`
					RecipientID     string          `json:"recipient_id"`
					RecipientUserID string          `json:"recipient_user_id"`
					Errors          json.RawMessage `json:"errors"`
				} `json:"statuses"`
			} `json:"value"`
		} `json:"changes"`
	} `json:"entry"`
}

var (
	seenMu sync.Mutex
	seen   = map[string]struct{}{} // in-memory dedupe for the demo; use a unique index in production
)

func firstTime(key string) bool {
	seenMu.Lock()
	defer seenMu.Unlock()
	if _, ok := seen[key]; ok {
		return false
	}
	seen[key] = struct{}{}
	return true
}

func validSignature(secret, raw []byte, header string) bool {
	hexSig, ok := strings.CutPrefix(header, "sha256=")
	if !ok {
		return false
	}
	got, err := hex.DecodeString(hexSig)
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, secret)
	mac.Write(raw)
	return hmac.Equal(got, mac.Sum(nil))
}

func worker(jobs <-chan []byte) {
	for raw := range jobs {
		var wh Webhook
		if err := json.Unmarshal(raw, &wh); err != nil {
			log.Printf("bad payload: %v", err)
			continue
		}
		process(wh)
	}
}

func process(wh Webhook) {
	if wh.Object != "whatsapp_business_account" {
		return
	}
	for _, e := range wh.Entry {
		for _, c := range e.Changes {
			if c.Field != "messages" {
				continue
			}
			for _, m := range c.Value.Messages {
				if !firstTime("msg:" + m.ID) {
					continue
				}
				sender := m.From
				if sender == "" {
					sender = m.FromUserID
				}
				text := "[" + m.Type + "]"
				if m.Type == "text" {
					text = m.Text.Body
				}
				log.Printf("message %s from %s at %s: %s", m.ID, sender, m.Timestamp, text)
			}
			for _, s := range c.Value.Statuses {
				if !firstTime("status:" + s.ID + ":" + s.Status) {
					continue
				}
				recipient := s.RecipientID
				if recipient == "" {
					recipient = s.RecipientUserID
				}
				log.Printf("status %s for %s to %s", s.Status, s.ID, recipient)
				if s.Status == "failed" {
					log.Printf("errors: %s", s.Errors)
				}
			}
		}
	}
}

func serve() {
	appSecret := []byte(mustEnv("APP_SECRET"))
	verifyToken := mustEnv("VERIFY_TOKEN")
	jobs := make(chan []byte, 100)
	go worker(jobs)

	mux := http.NewServeMux()
	mux.HandleFunc("GET /webhook", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query() // Go keeps the dots: hub.mode stays hub.mode
		challenge := q.Get("hub.challenge")
		if q.Get("hub.mode") == "subscribe" && q.Get("hub.verify_token") == verifyToken && challenge != "" {
			w.Header().Set("Content-Type", "text/plain")
			io.WriteString(w, challenge)
			return
		}
		w.WriteHeader(http.StatusForbidden)
	})
	mux.HandleFunc("POST /webhook", func(w http.ResponseWriter, r *http.Request) {
		raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<20)) // 4 MiB: our limit, Meta states none
		if err != nil {
			var tooBig *http.MaxBytesError
			if errors.As(err, &tooBig) {
				w.WriteHeader(http.StatusRequestEntityTooLarge)
				return
			}
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if !validSignature(appSecret, raw, r.Header.Get("X-Hub-Signature-256")) {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		if !json.Valid(raw) {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		select {
		case jobs <- raw:
			w.WriteHeader(http.StatusOK)
		default: // queue full: a non-200 makes Meta retry later
			w.WriteHeader(http.StatusServiceUnavailable)
		}
	})

	srv := &http.Server{
		Addr:              envOr("ADDR", ":8080"),
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      10 * time.Second,
	}
	log.Printf("listening on %s", srv.Addr)
	log.Fatal(srv.ListenAndServe())
}

// ---- CLI ----

func usage() {
	fmt.Fprintln(os.Stderr, "usage: go run . serve | text TO BODY | template TO NAME LANGUAGE [PARAMS...]")
	os.Exit(2)
}

func runSend(args []string) {
	if (args[0] == "text" && len(args) != 3) || (args[0] == "template" && len(args) < 4) {
		usage()
	}
	token := mustEnv("WHATSAPP_TOKEN")
	phoneNumberID := mustEnv("PHONE_NUMBER_ID")
	var msg OutMessage
	if args[0] == "text" {
		msg = textMessage(args[1], args[2])
	} else {
		msg = templateMessage(args[1], args[2], args[3], args[4:])
	}
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()
	out, err := send(ctx, token, phoneNumberID, msg)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		var apiErr *APIError
		if errors.As(err, &apiErr) {
			switch apiErr.Code {
			case 131047:
				fmt.Fprintln(os.Stderr, "Window closed: send an approved template instead.")
			case 190:
				fmt.Fprintln(os.Stderr, "Token expired: create a new access token.")
			}
		}
		cancel()
		os.Exit(1)
	}
	if len(out.Messages) > 0 {
		fmt.Println("accepted:", out.Messages[0].ID, out.Messages[0].MessageStatus)
	}
	if len(out.Contacts) > 0 {
		fmt.Println("wa_id:", out.Contacts[0].WaID)
	}
}

func main() {
	if len(os.Args) < 2 {
		usage()
	}
	switch os.Args[1] {
	case "serve":
		serve()
	case "text", "template":
		runSend(os.Args[1:])
	default:
		usage()
	}
}
```

La CLI corrisponde allo [script di invio in Python](/academy/it/articles/send-whatsapp-message-python-cloud-api/) e al suo gemello Node.js, e il server corrisponde al [ricevitore FastAPI](/academy/it/articles/whatsapp-webhook-python-fastapi-receive-messages/) e al suo gemello Express:

```bash
go run . text +16505551234 "Your order shipped"
go run . template +16505551234 order_confirmation en_US first_name=Jessica order_number=SKBUP2-4CPIG9
go run . serve
```

## Invio: struct, errori e retry

`omitempty` su `text`, `template` e `components` tiene le parti inutilizzate fuori dal JSON. Un modello senza parametri, quindi, non invia affatto la chiave `components`. `Unmarshal` ignora «le chiavi dell'oggetto che non hanno un campo corrispondente nella struct», per cui `SendResponse` dichiara solo i campi che la CLI legge ([encoding/json, consultato il 2026-11-04](https://pkg.go.dev/encoding/json)). In Go 1.27, `encoding/json` gira sull'implementazione v2 con lo stesso comportamento, anche se il testo dei messaggi di errore può cambiare.

L'`http.Client` è condiviso perché i client «sono sicuri per l'uso concorrente da parte di più goroutine». Il suo `Timeout` di 15 secondi è una scelta di questo file, dato che «un Timeout pari a zero significa nessun timeout» ([net/http, consultato il 2026-11-04](https://pkg.go.dev/net/http)). `defer resp.Body.Close()` segue l'indicazione della documentazione: «il chiamante deve chiudere resp.Body quando ha finito di leggerlo».

`send` decide in base a `Error.Code`. L'indicazione di Meta è di «costruire la logica di gestione degli errori della tua app attorno ai valori di `code` e alle proprietà del payload `details`» ([Meta, codici di errore, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes)). `send` ritenta solo due codici. Per 131056, Meta dice di «riprovare dopo 4^X secondi (partendo da X=0 e aumentando X di 1 dopo ogni fallimento)» ([Meta, informazioni sulla piattaforma, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/about-the-platform)). Meta non indica alcuno schema per 130429, quindi 1, 2 e 4 secondi sono una scelta di questo file. Entrambi i limiti sono spiegati in [Limiti di frequenza della Cloud API](/academy/it/articles/whatsapp-cloud-api-rate-limits-throughput-pair-rate/), e tutti gli altri codici nel [riferimento dei codici di errore](/academy/it/articles/whatsapp-cloud-api-error-codes-reference/).

## Ricezione: leggi il corpo, poi rispondi

Un pattern «con il metodo GET corrisponde sia alle richieste GET sia a quelle HEAD» ([net/http, consultato il 2026-11-04](https://pkg.go.dev/net/http)). Un metodo sbagliato riceve un 405 con un header `Allow` ([miglioramenti del routing in Go, 2024-02-13, consultato il 2026-11-04](https://go.dev/blog/routing-enhancements)). `r.URL.Query()` mantiene i nomi `hub.*` con i punti, così come li invia Meta. PHP li riscrive con il trattino basso, come mostra la [guida a Laravel](/academy/it/articles/whatsapp-webhook-laravel-receive-messages/).

L'handler della POST legge tutto il corpo prima di scrivere il 200. Secondo la documentazione di net/http, dopo che un handler ha restituito non è più valido leggere `Request.Body`. Una goroutine che riceve `r` potrebbe trovare il corpo sparito. Per questo l'handler invia invece lo slice di byte al canale. `MaxBytesReader` limita la lettura a 4 MiB, e un corpo troppo grande restituisce un `MaxBytesError`. Meta non documenta una dimensione del payload, quindi scegli un limite adatto al tuo traffico. Meta raggruppa fino a 1000 aggiornamenti in una sola POST ([Meta, creare un endpoint webhook, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)).

`validSignature` toglie `sha256=`, decodifica in esadecimale il resto e confronta i byte grezzi. La documentazione di `crypto/hmac` dice a chi riceve di «usare Equal per confrontare i MAC, così da evitare side-channel temporali» ([crypto/hmac, consultato il 2026-11-04](https://pkg.go.dev/crypto/hmac)). Un header con caratteri non esadecimali fallisce in `DecodeString` e riceve un 401. La [guida alla verifica della firma](/academy/it/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) spiega perché l'hash va calcolato sui byte grezzi.

Il canale contiene 100 payload. Quando è pieno, l'handler risponde 503. Il buffer da 100 posti e il 503 sono scelte di questo file. A Meta basta una risposta diversa da 200 per ritentare, e ritenta una consegna fallita per un massimo di 7 giorni. Un payload già nel canale va perso se il processo muore, la stessa avvertenza dei background task di FastAPI. [Architettura a coda per i webhook](/academy/it/articles/whatsapp-webhook-queue-architecture-workers/) spiega come scrivere su una coda durevole prima del 200.

L'`http.Server` esplicito pone dei limiti a ogni connessione. `ReadHeaderTimeout` è «il tempo concesso per leggere gli header della richiesta», `ReadTimeout` copre «l'intera richiesta, corpo incluso», e `WriteTimeout` limita la scrittura della risposta. I valori sono una scelta di questo file. Meta richiede HTTPS con un certificato valido, quindi metti un proxy TLS o [un tunnel come ngrok](/academy/it/articles/whatsapp-webhook-local-testing-ngrok/) davanti alla porta 8080.

## Mittenti e deduplicazione

Il mittente è `from`, con `from_user_id` come ripiego. Meta dice che `from` «verrà omesso se il numero di telefono non può essere incluso», e `from_user_id` contiene il BSUID dell'utente ([Meta, business-scoped user ID, consultato il 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)). Gli stati usano `recipient_id`, poi `recipient_user_id`. Nel payload di Meta `timestamp` è una stringa, quindi la struct lo dichiara come tale. [Business-scoped user ID](/academy/it/articles/whatsapp-usernames-business-scoped-user-ids/) copre il lato della tabella contatti.

Le chiavi di deduplicazione sono `msg:<id>` e `status:<id>:<status>`. La mappa si perde al riavvio e non è condivisa tra istanze, quindi in produzione serve un indice univoco nel tuo database.

## Testalo

Avvia il server in un terminale. La GET dovrebbe stampare `123`:

```bash
curl "http://localhost:8080/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
```

Firma l'esempio di webhook di testo di Meta, compattato su una riga, e invialo:

```bash
cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:8080/webhook \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json
```

La prima esecuzione restituisce 200 e il server registra la riga del messaggio. Una ripetizione restituisce 200 e non registra nulla. Un file modificato e non firmato restituisce 401.

Per il lato invio, `httptest` fa le veci di Meta. Questo test risponde a ogni chiamata con una copia ridotta dell'esempio 130429 di Meta. Lo stato 400 è una scelta del mock, perché Meta non documenta uno stato HTTP per ogni codice.

```go
// main_test.go
package main

import (
	"context"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"testing"
)

func TestRetriesThroughputLimit(t *testing.T) {
	var calls atomic.Int32
	mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		calls.Add(1)
		w.WriteHeader(http.StatusBadRequest)
		io.WriteString(w, `{"error":{"message":"(#130429) Rate limit hit","code":130429,"error_data":{"details":"Cloud API message throughput has been reached."},"fbtrace_id":"Az8or2yhqkZfEZ-_4Qn_Bam"}}`)
	}))
	defer mock.Close()
	graphBase = mock.URL

	_, err := send(context.Background(), "TOKEN", "PHONE_NUMBER_ID", textMessage("+16505551234", "test"))
	var apiErr *APIError
	if !errors.As(err, &apiErr) || apiErr.Code != 130429 || calls.Load() != 4 {
		t.Fatalf("got err %v after %d calls, want code 130429 after 4", err, calls.Load())
	}
}
```

`go test` impiega circa sette secondi, cioè le attese di 1, 2 e 4 secondi, e passa. Per provare il ripiego sul lato ricezione, rinomina `"from"` in `"from_user_id"` in `sample.json`, cambia l'ID del messaggio, firma di nuovo e invia ancora.

*Il team di Z-API Omni*
