WhatsApp· 4 min read

WhatsApp Cloud API in Go: send a message and receive webhooks


Send WhatsApp messages from Go with http.NewRequestWithContext and a JSON POST to /v26.0/<PHONE_NUMBER_ID>/messages. Receive webhooks with two method patterns, GET /webhook for verification and POST /webhook for events. The POST reads the body, checks X-Hub-Signature-256 with hmac.Equal, hands the bytes to a worker goroutine and returns 200. The main.go below does both with the standard library only.

Set up the module

The current release is go1.27.3, from 2026-10-19 (Go release history, accessed 2026-11-04). The file also runs on go1.26, the other supported line. ServeMux pattern matching “changed significantly in Go 1.22”, which is when method patterns arrived (net/http). On macOS, Go 1.27 needs macOS 13 or later (Go 1.27 release notes).

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 defaults to v26.0, the version in Meta’s send sample (Meta send messages, accessed 2026-11-04). GRAPH_BASE defaults to https://graph.facebook.com, and the test at the end points it at a mock. Tokens and phone number IDs come from the test number guide.

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()
	}
}

The CLI matches the Python send script and its Node.js twin, and the server matches the FastAPI receiver and its Express twin:

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

Sending: structs, errors and retries

omitempty on text, template and components keeps unused parts out of the JSON. A template without parameters then sends no components key at all. Unmarshal ignores “object keys which don’t have a corresponding struct field”, so SendResponse declares only the fields the CLI reads (encoding/json, accessed 2026-11-04). In Go 1.27, encoding/json runs on the v2 implementation with the same behaviour, though error message text may differ.

The http.Client is shared because clients “are safe for concurrent use by multiple goroutines”. Its 15-second Timeout is this file’s choice, since “A Timeout of zero means no timeout” (net/http, accessed 2026-11-04). defer resp.Body.Close() follows the docs’ “Caller should close resp.Body when done reading from it.”

send branches on Error.Code. Meta’s guidance is to “build your app’s error handling logic around code values and details payload properties” (Meta error codes, accessed 2026-11-04). send retries only two codes. For 131056, Meta says to “retry after 4^X seconds (starting with X=0 and increasing X by 1 after each failure)” (Meta about the platform, accessed 2026-11-04). Meta gives no schedule for 130429, so 1, 2 and 4 seconds is this file’s choice. Both limits are explained in Cloud API rate limits, and every other code in the error codes reference.

Receiving: read the body, then reply

A pattern “with the method GET matches both GET and HEAD requests” (net/http, accessed 2026-11-04). A wrong method gets a 405 with an Allow header (Go routing enhancements, 2024-02-13, accessed 2026-11-04). r.URL.Query() keeps the dotted hub.* names as Meta sends them. PHP rewrites them to underscores, as the Laravel guide shows.

The POST handler reads the whole body before it writes the 200. After a handler returns, the net/http docs say it is not valid to read Request.Body. A goroutine that receives r could find the body gone. The handler sends the byte slice to the channel instead. MaxBytesReader caps the read at 4 MiB, and an oversized body returns a MaxBytesError. Meta documents no payload size, so pick a limit that fits your traffic. Meta batches up to 1000 updates in one POST (Meta create a webhook endpoint, accessed 2026-11-04).

validSignature strips sha256=, hex-decodes the rest and compares raw bytes. The crypto/hmac docs tell receivers to “use Equal to compare MACs in order to avoid timing side-channels” (crypto/hmac, accessed 2026-11-04). A header with non-hex characters fails at DecodeString and gets a 401. The signature verification guide covers why the hash must run on the raw bytes.

The channel holds 100 payloads. When it is full, the handler answers 503. The 100-slot buffer and the 503 are this file’s choices. Meta only needs a non-200 to retry, and it retries a failed delivery over up to 7 days. A payload already in the channel is lost if the process dies, the same caveat as FastAPI’s background tasks. Webhook queue architecture covers writing to a durable queue before the 200.

The explicit http.Server bounds each connection. ReadHeaderTimeout is “the amount of time allowed to read request headers”, ReadTimeout covers “the entire request, including the body”, and WriteTimeout limits writing the response. The values are this file’s choice. Meta requires HTTPS with a valid certificate, so put a TLS proxy or a tunnel such as ngrok in front of port 8080.

Senders and dedupe

The sender is from, with from_user_id as the fallback. Meta says from “Will be omitted if the phone number cannot be included”, and from_user_id holds the user’s BSUID (Meta business-scoped user IDs, accessed 2026-11-04). Statuses use recipient_id, then recipient_user_id. timestamp is a string in Meta’s payload, so the struct declares it as one. Business-scoped user IDs covers the contact table side.

Dedupe keys are msg:<id> and status:<id>:<status>. The map is lost on restart and isn’t shared between instances, so production needs a unique index in your database.

Test it

Run the server in one terminal. The GET should print 123:

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

Sign Meta’s text webhook sample, compacted to one line, and post it:

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

The first run returns 200 and the server logs the message line. A repeat returns 200 and logs nothing. An edited, unsigned file returns 401.

For the send side, httptest stands in for Meta. This test answers every call with a trimmed copy of Meta’s 130429 example. The 400 status is the mock’s choice, because Meta documents no HTTP status per code.

// 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 takes about seven seconds, the 1, 2 and 4 second waits, and passes. To exercise the fallback on the receive side, rename "from" to "from_user_id" in sample.json, change the message ID, re-sign and post again.

Z-API Omni team