WhatsApp API in Go: net/http, Retries and Signed Webhooks

Send WhatsApp messages from Go with Meta’s official Cloud API: net/http for text and templates, retries, and a Go 1.22 webhook that checks the signature.

Illustration: a Go file in an editor next to a phone receiving a WhatsApp order update (sample data)

To send a WhatsApp message from Go, POST JSON to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with net/http and an Authorization: Bearer token. Meta’s Cloud API is plain HTTPS and JSON, and Go’s standard library already has everything you need: no third-party module, no SDK.

This guide builds one file, main.go: a send helper, text and template messages, typed errors with retries, a small worker pool, and a Go 1.22 webhook that answers Meta’s handshake and checks the X-Hub-Signature-256 signature. It uses Graph API v27.0, the latest in Meta’s changelog (4 November 2026). For other languages, see the Java, Python, Node.js and C# guides.

Key takeaways

  • Meta doesn’t publish a Go SDK. The standard library (net/http, encoding/json, crypto/hmac) covers sending and webhooks.
  • You need Go 1.22 or later for method patterns such as "POST /webhook" in http.ServeMux.
  • Return a typed error carrying Meta’s code, and check it with errors.As to retry only on throughput errors.
  • Hash the raw request body with your app secret and compare with hmac.Equal, before you parse anything.
  • Go libraries that drive WhatsApp Web, such as whatsmeow, aren’t the official API and can put a business number at risk.

Is there an official WhatsApp Go SDK?

No. Meta’s Cloud API pages describe HTTP requests only and name no Go package. That leaves three options:

OptionWhat it isUse it for a business number?
Standard library (this guide)net/http and encoding/json calling graph.facebook.comYes. It always matches Meta’s current format
Community Cloud API wrappersGo modules by independent developers that call the same Graph APIPossibly. Check that it calls graph.facebook.com and keeps up with new versions
WhatsApp Web libraries, such as whatsmeowA Go library for WhatsApp Web’s multi-device protocol: it connects as a linked deviceNo. It isn’t Meta’s Business API

whatsmeow connects to WhatsApp the way WhatsApp Web does, not through Meta’s Business API. WhatsApp says unofficial apps break its Terms of Service and can get an account banned, so it’s the wrong tool for a business number you depend on. The full comparison is in official vs unofficial WhatsApp APIs.

Before you write any Go

  • Go 1.22 or later, and a module: go mod init example.com/wa. Make sure go.mod says go 1.22 or later, or the method patterns won’t work. No go get is needed.
  • A phone number ID and a permanent system-user token. The token in API Setup expires; the Cloud API setup guide shows how to make a lasting one, and this guide shows where the phone number ID is.
  • Your app secret and a verify token you choose, for the webhook.
  • A test recipient who has agreed to hear from you, such as your own phone on Meta’s test number.

The code reads WHATSAPP_TOKEN, PHONE_NUMBER_ID, APP_SECRET and VERIFY_TOKEN from the environment.

A send helper with net/http

Start main.go with package main and these imports: bytes, context, crypto/hmac, crypto/sha256, encoding/hex, encoding/json, errors, fmt, io, log, net/http, os, strings, sync and time. Every one of them is used by the end of the file.

Linemain.go
1const apiVersion = "v27.0"
2type obj = map[string]any
3var (token = os.Getenv("WHATSAPP_TOKEN"); appSecret = os.Getenv("APP_SECRET"); verifyToken = os.Getenv("VERIFY_TOKEN")
4messagesURL = "https://graph.facebook.com/" + apiVersion + "/" + os.Getenv("PHONE_NUMBER_ID") + "/messages"
5client = &http.Client{Timeout: 15 * time.Second})
6type APIError struct { Code int; Message string; Body string }
7func (e *APIError) Error() string { return fmt.Sprintf("whatsapp error %d: %s", e.Code, e.Message) }
8func send(ctx context.Context, payload obj) (string, error) {
9body, err := json.Marshal(payload); if err != nil { return "", err }
10req, err := http.NewRequestWithContext(ctx, http.MethodPost, messagesURL, bytes.NewReader(body)); if err != nil { return "", err }
11req.Header.Set("Authorization", "Bearer "+token); req.Header.Set("Content-Type", "application/json")
12res, err := client.Do(req); if err != nil { return "", err }; defer res.Body.Close()
13raw, err := io.ReadAll(res.Body); if err != nil { return "", err }
14var out struct { Messages []struct{ ID string }; Error *struct { Code int; Message string } }
15if err := json.Unmarshal(raw, &out); err != nil { return "", fmt.Errorf("whatsapp: status %d: %w", res.StatusCode, err) }
16if out.Error != nil { return "", &APIError{Code: out.Error.Code, Message: out.Error.Message, Body: string(raw)} }
17if res.StatusCode/100 != 2 || len(out.Messages) == 0 { return "", fmt.Errorf("whatsapp: unexpected status %d: %s", res.StatusCode, raw) }
18return out.Messages[0].ID, nil }

The semicolons only fit lines into the table; gofmt splits them. Points to note:

  • One shared http.Client is safe across goroutines and reuses connections; the Timeout and context stop a slow call hanging.
  • No struct tags needed. encoding/json matches JSON keys to field names without regard to case, so ID reads "id" and Messages reads "messages".
  • Body keeps Meta’s whole error reply, including error_data and fbtrace_id, for your logs and for Meta support.
  • obj is a type alias, so payloads read like Meta’s JSON. Never build the JSON with fmt.Sprintf.

Send a text and a template message

A free-form text reaches the customer only inside the 24-hour customer service window, which opens when they message you. Outside it, send an approved template.

MessageGo
Textid, err := send(ctx, obj{"messaging_product": "whatsapp", "recipient_type": "individual", "to": "919800000000", "type": "text", "text": obj{"preview_url": false, "body": "Hi Priya, your table for 4 is booked for 8 pm tonight."}})
Template valuesparams := []obj{{"type": "text", "text": "Priya"}, {"type": "text", "text": "ORD-1042"}}
Templatetpl := obj{"name": "order_update", "language": obj{"code": "en"}, "components": []obj{{"type": "body", "parameters": params}}}
Send itid, err := send(ctx, obj{"messaging_product": "whatsapp", "recipient_type": "individual", "to": "919800000000", "type": "template", "template": tpl})
Named valueobj{"type": "text", "parameter_name": "first_name", "text": "Priya"}, for templates made with named variables

These lines run inside a function that has a ctx context.Context. If you send both in one function, use id, err = ... for the second send, and log or store id so Go doesn’t report it as unused.

  • Store the returned ID (wamid…): webhook statuses refer to it.
  • A nil error means Meta accepted the request, not that the phone received it. Statuses arrive later at the webhook.
  • Templates send only when APPROVED, and the name and language code must match WhatsApp Manager exactly. Positional values follow {{1}}, {{2}}; named ones can come in any order.

Headers with images, and buttons, are extra components, shown in how to send a WhatsApp template message with the API. Why free text fails after a day is explained in the WhatsApp 24-hour rule.

Errors, retries and sending to many numbers

Because send returns an *APIError, callers can branch on Meta’s code with errors.As. These four come up most:

CodeMeaningWhat your Go code should do
190Access token expired or invalidStop and alert: retrying won’t help. Use a permanent system-user token
131047More than 24 hours since the customer last wroteSend an approved template instead
132001Template doesn’t exist in that language or isn’t approvedFix the name or language code; don’t retry
130429Throughput limit reachedWait and retry with a growing delay

Add a retry that waits only on 130429, and a worker pool that sends to a list with at most a few requests in flight:

Linemain.go
19func sendWithRetry(ctx context.Context, payload obj) (string, error) {
20delay := time.Second
21for attempt := 1; ; attempt++ { id, err := send(ctx, payload); var apiErr *APIError
22if err == nil || attempt == 4 || !errors.As(err, &apiErr) || apiErr.Code != 130429 { return id, err }
23select { case <-time.After(delay): delay *= 2; case <-ctx.Done(): return "", ctx.Err() } } }
24func sendAll(ctx context.Context, numbers []string, build func(to string) obj) {
25var wg sync.WaitGroup; slots := make(chan struct{}, 5)
26for _, to := range numbers { wg.Add(1); slots <- struct{}{}
27go func(to string) { defer wg.Done(); defer func() { <-slots }()
28if _, err := sendWithRetry(ctx, build(to)); err != nil { log.Println(to, err) } }(to) }
29wg.Wait() }

The slots channel caps sends in flight (five here), and build makes each person’s template payload. Only message people who opted in. Limits are in WhatsApp API rate limits, and every code in WhatsApp API error codes.

A webhook with Go 1.22’s ServeMux

Meta sends incoming messages and delivery statuses to a URL you own: a GET handshake when you save the URL, then signed POSTs. Go 1.22 lets the standard ServeMux route by method, so each gets its own handler:

Linemain.go
30func verify(w http.ResponseWriter, r *http.Request) { q := r.URL.Query()
31if q.Get("hub.mode") != "subscribe" || verifyToken == "" || q.Get("hub.verify_token") != verifyToken { http.Error(w, "forbidden", http.StatusForbidden); return }
32w.Header().Set("Content-Type", "text/plain"); io.WriteString(w, q.Get("hub.challenge")) }
33func validSignature(body []byte, header string) bool { hexSig, ok := strings.CutPrefix(header, "sha256=")
34sig, err := hex.DecodeString(hexSig); if !ok || err != nil || appSecret == "" { return false }
35mac := hmac.New(sha256.New, []byte(appSecret)); mac.Write(body); return hmac.Equal(sig, mac.Sum(nil)) }
36func receive(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 10<<20))
37if err != nil { http.Error(w, "bad request", http.StatusBadRequest); return }
38if !validSignature(body, r.Header.Get("X-Hub-Signature-256")) { http.Error(w, "invalid signature", http.StatusUnauthorized); return }
39w.WriteHeader(http.StatusOK); go handle(body) }
40type update struct { Entry []struct { Changes []struct { Field string; Value struct {
41Messages []struct { ID, From, Type string; Text struct{ Body string } }; Statuses []struct{ ID, Status string } } } } }
42func handle(body []byte) { var u update; if err := json.Unmarshal(body, &u); err != nil { log.Println("webhook:", err); return }
43for _, e := range u.Entry { for _, c := range e.Changes { for _, m := range c.Value.Messages { log.Printf("message %s from %s (%s): %s", m.ID, m.From, m.Type, m.Text.Body) }
44for _, s := range c.Value.Statuses { log.Printf("status %s: %s", s.ID, s.Status) } } } }
45func main() { mux := http.NewServeMux(); mux.HandleFunc("GET /webhook", verify); mux.HandleFunc("POST /webhook", receive)
46srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 10 * time.Second}; log.Fatal(srv.ListenAndServe()) }
  1. Handshake (lines 30 to 32): Meta sends hub.mode=subscribe, your verify token and a random hub.challenge. Write the challenge back with a 200; anything else leaves the URL unverified.
  2. Signature (lines 33 to 35): the header is sha256= plus the hex HMAC-SHA256 of the raw body, keyed with your app secret. hmac.Equal compares in constant time. strings.CutPrefix needs Go 1.20, the routing needs 1.22.
  3. Raw bytes first (line 36): check the signature on the exact bytes read, then parse. MaxBytesReader caps the size.
  4. Answer, then work (line 39): the 200 goes out before processing. In production, use a queue instead of a bare goroutine.

Test it locally, then go live

Run go run . with the four environment variables set, then check both routes from another terminal, with the same VERIFY_TOKEN and APP_SECRET exported there too:

  1. Handshake: curl "localhost:8080/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=12345" should print 12345. A wrong token should give 403.
  2. Signed POST: set BODY='{"entry":[]}', then SIG=$(printf %s "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}') and curl -i -X POST -H "X-Hub-Signature-256: sha256=$SIG" -d "$BODY" localhost:8080/webhook. You should get 200; change one character of the body and you should get 401.
  3. Go live: deploy behind a public HTTPS address with a valid certificate (Meta doesn’t accept self-signed ones), save https://your-domain/webhook and your verify token as the callback URL in your Meta app, and subscribe to the messages field.

Payload shapes and status types are explained in WhatsApp Cloud API webhooks. If the handshake passes but nothing arrives, work through WhatsApp webhook not receiving messages.

Go with Automate AI, or no code at all

If you’d rather not run the webhook and sending queue yourself, Automate AI connects your number to Meta and receives the webhooks, with a shared inbox, campaigns that send approved templates now or on a schedule, and no-code chatbots.

For Go developers, Automate AI also has its own REST API with API keys, endpoints for contacts, messages, templates, campaigns and automations, developer webhooks with logs, and a Postman collection. There’s no Go SDK, but the same net/http pattern works against it. The API and webhooks come with the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.

Frequently asked questions

How do I send a WhatsApp message with Go?

Marshal a map or struct to JSON with messaging_product: "whatsapp", to, type and the message object, and POST it with net/http to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with an Authorization: Bearer header. The reply holds the message ID.

Is there an official WhatsApp Go SDK or library?

Meta doesn’t publish one. Its Cloud API documentation describes HTTP requests, which Go’s standard library handles.

Can I use whatsmeow for my business?

Not for a business number you care about. whatsmeow is a library for WhatsApp Web’s multi-device protocol, not Meta’s Business API. WhatsApp says unofficial apps break its terms and can lead to a ban.

Which Go version do I need?

Go 1.22 or later, for the method patterns in http.ServeMux.

Why does my Go webhook fail the signature check?

Usually because the body was decoded, or read twice, before hashing. Read it once with io.ReadAll, hash those exact bytes with your app secret, and compare the hex after sha256= using hmac.Equal.

Which Graph API version should I use?

The latest in Meta’s changelog. On 28 November 2026 that is v27.0, released on 4 November 2026. Keep it in one constant.

Sources

  1. Meta: Send messages
  2. Meta: Templates overview
  3. Meta: Create a webhook endpoint
  4. Meta: Graph API changelog
  5. The Go Blog: Routing enhancements for Go 1.22
  6. WhatsApp Help Center: About unofficial WhatsApp apps

WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.