← Blog

·

WhatsApp Bot in Go with the Official Cloud API: Sending and Webhooks from Scratch

Updated on November 4, 2026

To build a WhatsApp bot in Go on the official Cloud API, the standard library is all you need: a net/http server with two routes on the same path, a GET /webhook that echoes Meta’s verification challenge and a POST /webhook that validates the body’s HMAC-SHA256 signature, returns 200 immediately and handles the message in a goroutine. Sending is a JSON POST to the Cloud API /messages endpoint, for both text and templates. No SDK and no third-party dependencies: the whole bot fits in a single main.go.

This tutorial gives you the complete code, for Go 1.22 or later, and walks through each part: verification, signature, a deduplicating queue, sending with retries, local testing and a Docker deploy.

How the bot works

  1. A customer messages your number.
  2. Meta sends a POST to your webhook with the JSON event and an X-Hub-Signature-256 header.
  3. Your server validates the signature, returns 200 and pushes the event onto a queue (a chan).
  4. Workers read the queue, drop duplicates by message ID (wamid) and call the API to reply.
  5. Statuses (sent, delivered, read, failed) arrive on the same webhook and get logged.

If you’ve seen our Python with FastAPI or Node.js with Express versions, the logic is the same. Go adds a small static binary, cheap goroutines and method-based routing in http.ServeMux since 1.22.

What you need first

VariableWhat it isWhere to find it
ACCESS_TOKENSystem user access tokenBusiness Settings > System users
PHONE_NUMBER_IDID of the sending numberApp Dashboard > WhatsApp > API Setup
VERIFY_TOKENA string you make up for verificationYou set it and repeat it in the App Dashboard
APP_SECRETApp secret, used for the signatureApp Dashboard > Settings > Basic
PORTHTTP port (default 8080)You set it

Use a permanent system user token, not the temporary one from the dashboard. Your webhook also needs HTTPS with a valid certificate: the webhook endpoint docs state that self-signed certificates aren’t supported.

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

1. Set up the project

mkdir whatsapp-bot-go && cd whatsapp-bot-go
go mod init whatsapp-bot-go

go.mod only needs to declare the minimum version, 1.22, because of the method patterns in the router ("GET /webhook"):

module whatsapp-bot-go

go 1.22

2. The complete code

Save this as main.go. The sections below explain each part.

package main

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

type Config struct {
	VerifyToken   string
	AppSecret     string
	AccessToken   string
	PhoneNumberID string
	APIURL        string
	WebhookKey    string
	Port          string
}

func loadConfig() Config {
	c := Config{
		VerifyToken:   os.Getenv("VERIFY_TOKEN"),
		AppSecret:     os.Getenv("APP_SECRET"),
		AccessToken:   os.Getenv("ACCESS_TOKEN"),
		PhoneNumberID: os.Getenv("PHONE_NUMBER_ID"),
		APIURL:        os.Getenv("API_URL"),
		WebhookKey:    os.Getenv("WEBHOOK_KEY"),
		Port:          os.Getenv("PORT"),
	}
	if c.APIURL == "" {
		c.APIURL = "https://graph.facebook.com/v26.0/" + c.PhoneNumberID + "/messages"
	}
	if c.Port == "" {
		c.Port = "8080"
	}
	return c
}

// ---------- webhook types ----------

type WebhookPayload struct {
	Object string  `json:"object"`
	Entry  []Entry `json:"entry"`
}

type Entry struct {
	ID      string   `json:"id"`
	Changes []Change `json:"changes"`
}

type Change struct {
	Field string `json:"field"`
	Value Value  `json:"value"`
}

type Value struct {
	Metadata struct {
		PhoneNumberID string `json:"phone_number_id"`
	} `json:"metadata"`
	Messages []Message `json:"messages"`
	Statuses []Status  `json:"statuses"`
}

type Message struct {
	From string `json:"from"`
	ID   string `json:"id"`
	Type string `json:"type"`
	Text *struct {
		Body string `json:"body"`
	} `json:"text,omitempty"`
}

type Status struct {
	ID          string `json:"id"`
	Status      string `json:"status"`
	RecipientID string `json:"recipient_id"`
	Errors      []struct {
		Code  int    `json:"code"`
		Title string `json:"title"`
	} `json:"errors,omitempty"`
}

// ---------- send client ----------

type Client struct {
	cfg  Config
	http *http.Client
}

type APIError struct {
	Status  int
	Code    int
	Message string
}

func (e *APIError) Error() string {
	return fmt.Sprintf("api http %d, code %d: %s", e.Status, e.Code, e.Message)
}

// 130429 = throughput limit; 5xx = temporary instability
func (e *APIError) retryable() bool { return e.Status >= 500 || e.Code == 130429 }

func (c *Client) post(ctx context.Context, payload any) (string, error) {
	body, err := json.Marshal(payload)
	if err != nil {
		return "", err
	}
	var lastErr error
	for attempt := 0; attempt < 3; attempt++ {
		if attempt > 0 {
			time.Sleep(time.Duration(attempt*attempt) * time.Second)
		}
		req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cfg.APIURL, bytes.NewReader(body))
		if err != nil {
			return "", err
		}
		req.Header.Set("Authorization", "Bearer "+c.cfg.AccessToken)
		req.Header.Set("Content-Type", "application/json")

		resp, err := c.http.Do(req)
		if err != nil {
			lastErr = err
			continue
		}
		raw, _ := io.ReadAll(resp.Body)
		resp.Body.Close()

		if resp.StatusCode == http.StatusOK {
			var out struct {
				Messages []struct {
					ID string `json:"id"`
				} `json:"messages"`
			}
			if err := json.Unmarshal(raw, &out); err != nil || len(out.Messages) == 0 {
				return "", fmt.Errorf("unexpected response: %s", raw)
			}
			return out.Messages[0].ID, nil
		}
		var ge struct {
			Error struct {
				Code    int    `json:"code"`
				Message string `json:"message"`
			} `json:"error"`
		}
		_ = json.Unmarshal(raw, &ge)
		apiErr := &APIError{Status: resp.StatusCode, Code: ge.Error.Code, Message: ge.Error.Message}
		if !apiErr.retryable() {
			return "", apiErr // request error: retrying won't help
		}
		lastErr = apiErr
	}
	return "", lastErr
}

func (c *Client) SendText(ctx context.Context, to, body string) (string, error) {
	return c.post(ctx, map[string]any{
		"messaging_product": "whatsapp",
		"to":                to,
		"type":              "text",
		"text":              map[string]any{"body": body},
	})
}

func (c *Client) SendTemplate(ctx context.Context, to, name, lang string, params ...string) (string, error) {
	tpl := map[string]any{
		"name":     name,
		"language": map[string]string{"code": lang},
	}
	if len(params) > 0 {
		ps := make([]map[string]string, len(params))
		for i, p := range params {
			ps[i] = map[string]string{"type": "text", "text": p}
		}
		tpl["components"] = []map[string]any{{"type": "body", "parameters": ps}}
	}
	return c.post(ctx, map[string]any{
		"messaging_product": "whatsapp",
		"to":                to,
		"type":              "template",
		"template":          tpl,
	})
}

// ---------- webhook ----------

type Server struct {
	cfg    Config
	client *Client
	jobs   chan Value
	seen   sync.Map // wamid -> time.Time
}

func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	if q.Get("hub.mode") == "subscribe" && q.Get("hub.verify_token") == s.cfg.VerifyToken {
		w.WriteHeader(http.StatusOK)
		io.WriteString(w, q.Get("hub.challenge"))
		return
	}
	http.Error(w, "forbidden", http.StatusForbidden)
}

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

func (s *Server) receive(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<20))
	if err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	switch {
	case s.cfg.AppSecret != "":
		if !validSignature(body, r.Header.Get("X-Hub-Signature-256"), s.cfg.AppSecret) {
			http.Error(w, "invalid signature", http.StatusUnauthorized)
			return
		}
	case s.cfg.WebhookKey != "":
		if !hmac.Equal([]byte(r.URL.Query().Get("key")), []byte(s.cfg.WebhookKey)) {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
	default:
		http.Error(w, "webhook protection not configured", http.StatusInternalServerError)
		return
	}

	var p WebhookPayload
	if err := json.Unmarshal(body, &p); err != nil {
		http.Error(w, "bad json", http.StatusBadRequest)
		return
	}
	w.WriteHeader(http.StatusOK) // acknowledge before processing

	for _, e := range p.Entry {
		for _, ch := range e.Changes {
			if ch.Field != "messages" {
				continue
			}
			select {
			case s.jobs <- ch.Value:
			default:
				log.Println("queue full, event dropped")
			}
		}
	}
}

func (s *Server) firstTime(wamid string) bool {
	_, loaded := s.seen.LoadOrStore(wamid, time.Now())
	return !loaded
}

func (s *Server) cleanSeen(ctx context.Context) {
	t := time.NewTicker(10 * time.Minute)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			s.seen.Range(func(k, v any) bool {
				if time.Since(v.(time.Time)) > 24*time.Hour {
					s.seen.Delete(k)
				}
				return true
			})
		}
	}
}

func (s *Server) worker(ctx context.Context) {
	for v := range s.jobs {
		for _, m := range v.Messages {
			if !s.firstTime(m.ID) {
				continue
			}
			s.handleMessage(ctx, m)
		}
		for _, st := range v.Statuses {
			if st.Status == "failed" && len(st.Errors) > 0 {
				log.Printf("failed %s to %s: %d %s", st.ID, st.RecipientID, st.Errors[0].Code, st.Errors[0].Title)
			}
		}
	}
}

func (s *Server) handleMessage(ctx context.Context, m Message) {
	ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()

	var reply string
	switch {
	case m.Type == "text" && m.Text != nil:
		txt := strings.ToLower(strings.TrimSpace(m.Text.Body))
		switch txt {
		case "hi", "hello", "menu":
			reply = "Hi! Type 1 for opening hours, 2 to talk to our team."
		case "1":
			reply = "We're open Monday to Friday, 9 am to 6 pm."
		case "2":
			reply = "Got it! Someone from our team will reply shortly."
		default:
			reply = "You said: " + m.Text.Body + "\nType menu to see the options."
		}
	default:
		reply = "For now I only understand text messages. Type menu."
	}

	if _, err := s.client.SendText(ctx, m.From, reply); err != nil {
		var apiErr *APIError
		if errors.As(err, &apiErr) {
			log.Printf("API error replying to %s: %v", m.From, apiErr)
			return
		}
		log.Printf("network error replying to %s: %v", m.From, err)
	}
}

// ---------- main ----------

func main() {
	cfg := loadConfig()
	client := &Client{cfg: cfg, http: &http.Client{Timeout: 15 * time.Second}}

	// CLI mode: go run . template 15551234567 order_shipped en_US Ana "#4821"
	if len(os.Args) >= 5 && os.Args[1] == "template" {
		id, err := client.SendTemplate(context.Background(), os.Args[2], os.Args[3], os.Args[4], os.Args[5:]...)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("sent:", id)
		return
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	s := &Server{cfg: cfg, client: client, jobs: make(chan Value, 1000)}
	for i := 0; i < 4; i++ {
		go s.worker(ctx)
	}
	go s.cleanSeen(ctx)

	mux := http.NewServeMux()
	mux.HandleFunc("GET /webhook", s.verify)
	mux.HandleFunc("POST /webhook", s.receive)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })

	srv := &http.Server{
		Addr:              ":" + cfg.Port,
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      15 * time.Second,
	}

	go func() {
		log.Printf("listening on :%s", cfg.Port)
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	srv.Shutdown(shutdownCtx)
	close(s.jobs)
	log.Println("stopped")
}

3. Webhook verification (GET)

When you register the URL in the App Dashboard, Meta sends a GET with three parameters: hub.mode (always subscribe), hub.verify_token (the string you typed in the dashboard) and hub.challenge (a number). Your server checks the token and returns the raw hub.challenge with status 200. Any other response fails verification. That’s what the verify function does.

Common mistakes: returning the challenge as JSON ({"challenge": "123"}) instead of plain text, or comparing against the access token instead of VERIFY_TOKEN.

4. HMAC signature (X-Hub-Signature-256)

Every POST from Meta carries an X-Hub-Signature-256: sha256=<hex> header: an HMAC-SHA256 of the raw body computed with your app secret. The validSignature function:

  1. strips the sha256= prefix with strings.CutPrefix;
  2. decodes the hex;
  3. computes the body’s HMAC with crypto/hmac and crypto/sha256;
  4. compares with hmac.Equal, which runs in constant time and prevents timing attacks.

The key point: the hash must be computed over the exact bytes received. That’s why the handler reads the whole body with io.ReadAll before any json.Unmarshal. If you decode first and re-serialize, key order and whitespace change and the signature never matches. http.MaxBytesReader caps the body at 4 MB; the webhooks overview says payloads can be up to 3 MB.

The other classic mistake is the wrong key: the signature uses the app secret, not the access token or VERIFY_TOKEN. The full topic, with tests and other languages, is in WhatsApp webhook signature validation.

5. Acknowledge fast, process later

Meta expects a 200, and if it doesn’t get one it retries: immediately, then a few more times over 7 days. Batches can carry up to 1,000 updates, and the docs themselves recommend handling each POST independently and deduplicating. So the handler:

  • validates, decodes and returns 200 before any outbound call;
  • pushes each change with field == "messages" onto a channel buffered for 1,000 items;
  • logs and drops the event if the channel is full, instead of blocking the response.

Four worker goroutines consume the channel. Deduplication uses a sync.Map keyed by wamid, with a cleanup every 10 minutes for IDs older than 24 hours. For a single process, that’s enough. With several replicas behind a load balancer, swap the sync.Map for a Redis key or a database unique constraint, and the channel for a real queue. The full design, with idempotency and retries, is in integration architecture.

On shutdown, signal.NotifyContext catches SIGTERM, srv.Shutdown waits for in-flight requests and only then is the channel closed, which stops the workers. The process doesn’t wait for the queue to empty: events that already got a 200 and were still in the channel are lost, and Meta won’t resend them. If that matters, write each event to a persistent queue before responding.

6. Sending text and templates

Client has a single low-level method, post, that serializes the payload, calls API_URL with the token in the Authorization header and reads the wamid from the response. On top of it:

  • SendText builds {"type": "text", "text": {"body": ...}}. Free-form text can only be sent inside the 24-hour window opened by the customer’s last message.
  • SendTemplate builds {"type": "template", "template": {"name", "language": {"code"}, "components"}}, with body parameters in the order of the {{1}}, {{2}}… variables. Outside the window, approved templates only.

main also works as a command-line tool to send a template, handy for testing:

export ACCESS_TOKEN=... PHONE_NUMBER_ID=...
go run . template 15551234567 order_shipped en_US Ana "#4821"
# sent: wamid.HBgLMTU1NTEyMzQ1NjcVAgARGBI...

Template formats with header media, buttons and dynamic URLs are covered in how to send a WhatsApp template message via API.

Retries: when to repeat and when not to

Meta’s API returns errors in the body as {"error": {"code": ..., "message": ...}}. The code reads that code and only retries (up to 3 attempts, waiting 1 s and then 4 s) in two cases:

  • HTTP 5xx, temporary instability;
  • code 130429, the number’s throughput limit.

Request errors, such as wrong template parameters (132000) or sending outside the window (131047), return right away, since repeating won’t help. Error 131056, too many messages to the same recipient in a short time, also stays out of the immediate retry: it calls for a longer pause.

7. Test locally

Run the server:

export VERIFY_TOKEN=my-token APP_SECRET=my-secret ACCESS_TOKEN=... PHONE_NUMBER_ID=...
go run .

Test verification, which should return 123:

curl "http://localhost:8080/webhook?hub.mode=subscribe&hub.verify_token=my-token&hub.challenge=123"

Test the signature by generating the HMAC with openssl. With the right secret you get 200; with anything else, 401:

BODY='{"object":"whatsapp_business_account","entry":[]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "my-secret" | awk '{print $2}')
curl -i -X POST http://localhost:8080/webhook \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  -d "$BODY"

To receive real Meta events on your machine, expose the port through an HTTPS tunnel and register the public URL in the App Dashboard, subscribing to the messages field. Step by step in test your WhatsApp webhook locally with ngrok.

8. Deploy with Docker

A two-stage Dockerfile produces a small image containing only the static binary:

# Dockerfile
FROM golang:1.22-alpine AS build
WORKDIR /src
COPY go.mod ./
COPY *.go ./
RUN CGO_ENABLED=0 go build -o /bot .

FROM gcr.io/distroless/static-debian12
COPY --from=build /bot /bot
EXPOSE 8080
ENTRYPOINT ["/bot"]

The distroless/static image ships with CA certificates, which you need to call the API over HTTPS. Put the container behind a reverse proxy or load balancer with a valid TLS certificate and pass environment variables through your platform’s secret manager, never baked into the image. The GET /healthz route is there for health checks.

Pre-production checklist

  • Permanent system user token, stored as a secret.
  • APP_SECRET set and the signature validated on every POST.
  • HTTPS with a valid certificate.
  • Shared deduplication (Redis or database) if you run more than one replica.
  • Messages and statuses written to a database, if you need history.
  • Approved templates for anything sent outside the 24-hour window.

How to do this with Vectalk

Vectalk is a proxy for the official WhatsApp Business API: send payloads and webhook events are the same as Meta’s, so main.go works without logic changes. Three variables change:

  1. API_URL: set it to https://apis.vectalk.com.br/api/messages and use a Vectalk instance token as ACCESS_TOKEN. With it, the phone_number_id is resolved automatically (quickstart).
  2. Webhook registration: register the URL with POST https://apis.vectalk.com.br/api/webhooks, passing instance_id, url and name. You can have several URLs per instance.
  3. Endpoint protection: the Vectalk webhook docs don’t describe a signature header. Leave APP_SECRET empty, set WEBHOOK_KEY to a long random value and register the URL as https://bot.yourcompany.com/webhook?key=YOUR_VALUE. The code already handles this case and rejects requests without the key.

The Hub expects a 200 within 20 seconds and retries the event if it doesn’t get one, which deduplication already covers. Create your account and browse the other endpoints in the docs. If you work in PHP, there’s a Laravel version of this tutorial.

Frequently asked questions

Why does the signature never match?

It’s almost always one of two things: the HMAC was computed over re-serialized JSON instead of the original bytes, or the key isn’t the app secret.

Do I need Go 1.22?

For the code as written, yes, because of the "GET /webhook" and "POST /webhook" patterns in http.ServeMux. On older versions, use a single route and check r.Method inside the handler.

Can I reply with text at any time?

No. Free-form text only works inside the 24-hour window opened by the customer’s last message. Outside it, send an approved template with SendTemplate.

How do I scale to multiple replicas?

Replace in-memory deduplication with Redis or a database, and the channel with an external queue. The HTTP handler stays the same.


Official sources checked on November 4, 2026: Create a webhook endpoint (Meta), Webhooks overview (Meta), Error codes (Meta), net/http package (Go), crypto/hmac package (Go), Vectalk quickstart, Vectalk webhooks.

Try the official WhatsApp API today

Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.