WhatsApp· 4 dk okuma

Go ile WhatsApp Cloud API: mesaj gönderin ve webhook alın


Go’dan WhatsApp mesajı göndermek için http.NewRequestWithContext ile /v26.0/<PHONE_NUMBER_ID>/messages adresine bir JSON POST isteği yapın. Webhook’ları iki metot kalıbıyla alın: doğrulama için GET /webhook, olaylar için POST /webhook. POST isteği gövdeyi okur, X-Hub-Signature-256 başlığını hmac.Equal ile kontrol eder, byte’ları bir worker goroutine’e verir ve 200 döndürür. Aşağıdaki main.go ikisini de yalnızca standart kütüphaneyle yapar.

Modülü hazırlayın

Güncel sürüm 2026-10-19 tarihli go1.27.3’tür (Go sürüm geçmişi, erişim tarihi 2026-11-04). Dosya, desteklenen diğer sürüm hattı olan go1.26 üzerinde de çalışır. ServeMux kalıp eşleştirmesi “Go 1.22’de önemli ölçüde değişti”; metot kalıpları da o sürümle geldi (net/http). macOS üzerinde Go 1.27, macOS 13 veya üstünü gerektirir (Go 1.27 sürüm notları).

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 varsayılan olarak Meta’nın gönderim örneğindeki sürüm olan v26.0 değerini alır (Meta mesaj gönderme, erişim tarihi 2026-11-04). GRAPH_BASE varsayılan olarak https://graph.facebook.com olur; sondaki test onu bir mock’a yönlendirir. Token’lar ve telefon numarası ID’leri test numarası kılavuzundan gelir.

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

CLI, Python gönderim betiği ve onun Node.js ikiziyle aynı şekilde çalışır; sunucu ise FastAPI alıcısı ve onun Express ikiziyle eşleşir:

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

Gönderim: struct’lar, hatalar ve yeniden denemeler

text, template ve components üzerindeki omitempty, kullanılmayan kısımları JSON’un dışında tutar. Parametresiz bir şablon böylece hiç components anahtarı göndermez. Unmarshal “karşılık gelen bir struct alanı olmayan nesne anahtarlarını” yok sayar; bu yüzden SendResponse yalnızca CLI’ın okuduğu alanları tanımlar (encoding/json, erişim tarihi 2026-11-04). Go 1.27’de encoding/json aynı davranışla v2 uygulaması üzerinde çalışır, ancak hata mesajı metinleri farklı olabilir.

http.Client paylaşılır, çünkü istemciler “birden çok goroutine tarafından eşzamanlı kullanım için güvenlidir”. 15 saniyelik Timeout bu dosyanın tercihidir, çünkü “sıfır değerindeki bir Timeout, zaman aşımı olmadığı anlamına gelir” (net/http, erişim tarihi 2026-11-04). defer resp.Body.Close(), dokümantasyondaki “Çağıran taraf, okumayı bitirdiğinde resp.Body’yi kapatmalıdır” kuralını izler.

send, Error.Code değerine göre dallanır. Meta’nın yönergesi, “uygulamanızın hata işleme mantığını code değerleri ve details payload özellikleri etrafında kurmanızdır” (Meta hata kodları, erişim tarihi 2026-11-04). send yalnızca iki kodda yeniden dener. 131056 için Meta, “4^X saniye sonra yeniden denemenizi (X=0 ile başlayıp her başarısızlıktan sonra X’i 1 artırarak)” söyler (Meta platform hakkında, erişim tarihi 2026-11-04). Meta 130429 için bir takvim vermez, bu yüzden 1, 2 ve 4 saniye bu dosyanın tercihidir. İki sınır da Cloud API hız sınırları yazısında, diğer tüm kodlar ise hata kodları referansında açıklanıyor.

Alma: önce gövdeyi okuyun, sonra yanıt verin

“GET metoduna sahip bir kalıp hem GET hem de HEAD isteklerini eşleştirir” (net/http, erişim tarihi 2026-11-04). Yanlış bir metot, Allow başlığıyla birlikte 405 alır (Go routing iyileştirmeleri, 2024-02-13, erişim tarihi 2026-11-04). r.URL.Query(), noktalı hub.* adlarını Meta’nın gönderdiği gibi korur. PHP ise Laravel kılavuzunda gösterildiği gibi onları alt çizgiye dönüştürür.

POST handler’ı, 200’ü yazmadan önce gövdenin tamamını okur. net/http dokümantasyonuna göre, bir handler döndükten sonra Request.Body okumak geçerli değildir. r değerini alan bir goroutine, gövdeyi kaybolmuş bulabilir. Bu yüzden handler kanala byte dilimini gönderir. MaxBytesReader okumayı 4 MiB ile sınırlar ve fazla büyük bir gövde MaxBytesError döndürür. Meta bir payload boyutu belgelemez, bu yüzden trafiğinize uyan bir sınır seçin. Meta tek bir POST içinde en fazla 1000 güncellemeyi birlikte gönderir (Meta webhook endpoint’i oluşturma, erişim tarihi 2026-11-04).

validSignature, sha256= ön ekini çıkarır, geri kalanı onaltılıktan çözer ve ham byte’ları karşılaştırır. crypto/hmac dokümantasyonu, alıcılara “zamanlama yan kanallarından kaçınmak için MAC’leri karşılaştırırken Equal kullanmalarını” söyler (crypto/hmac, erişim tarihi 2026-11-04). Onaltılık olmayan karakterler içeren bir başlık DecodeString aşamasında başarısız olur ve 401 alır. Hash’in neden ham byte’lar üzerinde çalışması gerektiği imza doğrulama kılavuzunda anlatılıyor.

Kanal 100 payload tutar. Dolduğunda handler 503 ile yanıt verir. 100 yuvalık tampon ve 503 bu dosyanın tercihleridir. Meta’nın yeniden denemesi için 200 dışında bir yanıt yeterlidir ve başarısız bir teslimatı 7 güne kadar yeniden dener. Süreç ölürse kanalda bekleyen bir payload kaybolur; FastAPI’nin background task’larındaki çekincenin aynısı. 200’den önce kalıcı bir kuyruğa yazmak Webhook kuyruk mimarisi yazısında ele alınıyor.

Açıkça tanımlanmış http.Server her bağlantıyı sınırlar. ReadHeaderTimeout “istek başlıklarını okumak için izin verilen süredir”, ReadTimeout “gövde dahil isteğin tamamını” kapsar, WriteTimeout ise yanıtın yazılmasını sınırlar. Değerler bu dosyanın tercihidir. Meta geçerli bir sertifikayla HTTPS ister; bu yüzden 8080 portunun önüne bir TLS proxy veya ngrok gibi bir tünel koyun.

Gönderenler ve tekilleştirme

Gönderen from alanıdır, yedek olarak from_user_id kullanılır. Meta, from alanının “telefon numarası eklenemiyorsa atlanacağını” söyler; from_user_id ise kullanıcının BSUID’sini tutar (Meta business-scoped user IDs, erişim tarihi 2026-11-04). Durumlar önce recipient_id, sonra recipient_user_id kullanır. timestamp, Meta’nın payload’unda bir string’dir, bu yüzden struct onu string olarak tanımlar. Kişi tablosu tarafı Business-scoped user ID’ler yazısında ele alınıyor.

Tekilleştirme anahtarları msg:<id> ve status:<id>:<status> biçimindedir. Map yeniden başlatmada kaybolur ve örnekler arasında paylaşılmaz; bu yüzden production ortamı veritabanınızda benzersiz bir indeks gerektirir.

Test edin

Sunucuyu bir terminalde çalıştırın. GET isteği 123 yazdırmalıdır:

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

Meta’nın tek satıra sıkıştırılmış metin webhook örneğini imzalayın ve gönderin:

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

İlk çalıştırma 200 döndürür ve sunucu mesaj satırını günlüğe yazar. Tekrarı da 200 döndürür ama hiçbir şey yazmaz. Düzenlenmiş, imzalanmamış bir dosya 401 döndürür.

Gönderim tarafında Meta’nın yerine httptest geçer. Bu test her çağrıya Meta’nın 130429 örneğinin kısaltılmış bir kopyasıyla yanıt verir. 400 durum kodu mock’un tercihidir, çünkü Meta kod başına bir HTTP durumu belgelemez.

// 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 yaklaşık yedi saniye sürer (1, 2 ve 4 saniyelik beklemeler) ve başarılı olur. Alma tarafındaki yedeği denemek için sample.json içinde "from" alanını "from_user_id" olarak yeniden adlandırın, mesaj ID’sini değiştirin, yeniden imzalayın ve tekrar gönderin.

Z-API Omni ekibi