WhatsApp· 5 min de lectura

WhatsApp Cloud API en Go: enviar un mensaje y recibir webhooks


Para enviar mensajes de WhatsApp desde Go usa http.NewRequestWithContext y un POST JSON a /v26.0/<PHONE_NUMBER_ID>/messages. Para recibir webhooks, registra dos patrones con método: GET /webhook para la verificación y POST /webhook para los eventos. El POST lee el cuerpo, comprueba X-Hub-Signature-256 con hmac.Equal, pasa los bytes a una goroutine worker y devuelve 200. El main.go de abajo hace las dos cosas solo con la biblioteca estándar.

Prepara el módulo

La versión actual es go1.27.3, del 2026-10-19 (historial de versiones de Go, consultado el 2026-11-04). El archivo también corre en go1.26, la otra línea con soporte. La coincidencia de patrones de ServeMux “cambió de forma significativa en Go 1.22”, que es cuando llegaron los patrones con método (net/http). En macOS, Go 1.27 necesita macOS 13 o posterior (notas de versión de Go 1.27).

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 por defecto, la versión del ejemplo de envío de Meta (Meta, enviar mensajes, consultado el 2026-11-04). GRAPH_BASE vale https://graph.facebook.com por defecto, y la prueba del final lo apunta a un mock. Los tokens y los IDs de número de teléfono salen de la guía del número de prueba.

main.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 se corresponde con el script de envío en Python y su gemelo en Node.js, y el servidor con el receptor en FastAPI y su gemelo en Express:

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

Envío: structs, errores y reintentos

omitempty en text, template y components deja fuera del JSON las partes que no se usan. Así, una plantilla sin parámetros no envía ninguna clave components. Unmarshal ignora “las claves de objeto que no tienen un campo de struct correspondiente”, así que SendResponse declara solo los campos que lee la CLI (encoding/json, consultado el 2026-11-04). En Go 1.27, encoding/json corre sobre la implementación v2 con el mismo comportamiento, aunque el texto de los mensajes de error puede variar.

El http.Client se comparte porque los clientes “son seguros para uso concurrente por varias goroutines”. Su Timeout de 15 segundos es una elección de este archivo, ya que “un Timeout de cero significa sin timeout” (net/http, consultado el 2026-11-04). defer resp.Body.Close() sigue la indicación de la documentación: “quien llama debe cerrar resp.Body al terminar de leerlo”.

send decide según Error.Code. La guía de Meta es “construir la lógica de manejo de errores de tu app en torno a los valores de code y las propiedades del payload details” (Meta, códigos de error, consultado el 2026-11-04). send solo reintenta con dos códigos. Para 131056, Meta dice que hay que “reintentar después de 4^X segundos (empezando con X=0 e incrementando X en 1 después de cada fallo)” (Meta, acerca de la plataforma, consultado el 2026-11-04). Meta no da un calendario para 130429, así que 1, 2 y 4 segundos es una elección de este archivo. Los dos límites se explican en límites de frecuencia de la Cloud API, y todos los demás códigos en la referencia de códigos de error.

Recepción: lee el cuerpo y luego responde

Un patrón “con el método GET coincide tanto con peticiones GET como HEAD” (net/http, consultado el 2026-11-04). Un método incorrecto recibe un 405 con un header Allow (mejoras de enrutamiento en Go, 2024-02-13, consultado el 2026-11-04). r.URL.Query() conserva los nombres hub.* con puntos, tal como los envía Meta. PHP los reescribe con guiones bajos, como muestra la guía de Laravel.

El handler del POST lee todo el cuerpo antes de escribir el 200. La documentación de net/http dice que, después de que un handler retorna, no es válido leer Request.Body. Una goroutine que reciba r podría encontrarse sin cuerpo. Por eso el handler envía el slice de bytes al canal. MaxBytesReader limita la lectura a 4 MiB, y un cuerpo demasiado grande devuelve un MaxBytesError. Meta no documenta un tamaño de payload, así que elige un límite que se ajuste a tu tráfico. Meta agrupa hasta 1000 actualizaciones en un solo POST (Meta, crear un endpoint de webhook, consultado el 2026-11-04).

validSignature quita sha256=, decodifica el resto desde hexadecimal y compara bytes crudos. La documentación de crypto/hmac indica a los receptores “usar Equal para comparar MAC y así evitar canales laterales de tiempo” (crypto/hmac, consultado el 2026-11-04). Un header con caracteres no hexadecimales falla en DecodeString y recibe un 401. La guía de verificación de firma explica por qué el hash debe calcularse sobre los bytes crudos.

El canal guarda 100 payloads. Cuando está lleno, el handler responde 503. El buffer de 100 posiciones y el 503 son elecciones de este archivo. A Meta le basta una respuesta distinta de 200 para reintentar, y reintenta una entrega fallida durante hasta 7 días. Un payload que ya está en el canal se pierde si el proceso muere, la misma salvedad que con las background tasks de FastAPI. Arquitectura de colas para webhooks explica cómo escribir en una cola duradera antes del 200.

El http.Server explícito pone límites a cada conexión. ReadHeaderTimeout es “el tiempo permitido para leer los headers de la petición”, ReadTimeout cubre “la petición completa, incluido el cuerpo”, y WriteTimeout limita la escritura de la respuesta. Los valores son una elección de este archivo. Meta exige HTTPS con un certificado válido, así que pon un proxy TLS o un túnel como ngrok delante del puerto 8080.

Remitentes y deduplicación

El remitente es from, con from_user_id como alternativa. Meta dice que from “se omitirá si no se puede incluir el número de teléfono”, y from_user_id guarda el BSUID del usuario (Meta, business-scoped user IDs, consultado el 2026-11-04). Los estados usan recipient_id y luego recipient_user_id. timestamp es un string en el payload de Meta, así que el struct lo declara como tal. Business-scoped user IDs cubre el lado de la tabla de contactos.

Las claves de deduplicación son msg:<id> y status:<id>:<status>. El map se pierde al reiniciar y no se comparte entre instancias, así que en producción necesitas un índice único en tu base de datos.

Pruébalo

Corre el servidor en una terminal. El GET debería imprimir 123:

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

Firma el ejemplo de webhook de texto de Meta, compactado en una línea, y envíalo:

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 primera ejecución devuelve 200 y el servidor registra la línea del mensaje. Una repetición devuelve 200 y no registra nada. Un archivo editado y sin firmar devuelve 401.

Para el lado del envío, httptest hace de Meta. Esta prueba responde a cada llamada con una copia recortada del ejemplo 130429 de Meta. El estado 400 es una elección del mock, porque Meta no documenta un estado HTTP por código.

// 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 tarda unos siete segundos, las esperas de 1, 2 y 4 segundos, y pasa. Para probar la alternativa en el lado de la recepción, cambia "from" por "from_user_id" en sample.json, cambia el ID del mensaje, vuelve a firmar y envíalo otra vez.

Equipo de Z-API Omni