# Go میں WhatsApp Cloud API: میسج بھیجیں اور ویب ہُکس وصول کریں

> صرف net/http کے ساتھ ایک Go 1.27 فائل میں WhatsApp ٹیکسٹ اور ٹیمپلیٹ میسج بھیجیں اور ویب ہُکس وصول کریں: HMAC چیک، BSUID متبادل اور ایک worker۔

Published 2026-11-04. Z-API Omni team.

Go سے WhatsApp میسج بھیجنے کے لیے `http.NewRequestWithContext` اور `/v26.0/<PHONE_NUMBER_ID>/messages` پر ایک JSON POST استعمال کریں۔ ویب ہُکس (webhooks) دو method patterns سے وصول کریں: تصدیق کے لیے `GET /webhook` اور events کے لیے `POST /webhook`۔ POST باڈی پڑھتا ہے، `hmac.Equal` سے `X-Hub-Signature-256` چیک کرتا ہے، bytes کو ایک worker goroutine کے حوالے کرتا ہے اور 200 واپس کرتا ہے۔ نیچے دی گئی `main.go` صرف standard library سے دونوں کام کرتی ہے۔

## Module سیٹ اپ کریں

موجودہ ریلیز go1.27.3 ہے، جو 2026-10-19 کو آئی ([Go release history، رسائی 2026-11-04](https://go.dev/doc/devel/release))۔ فائل go1.26 پر بھی چلتی ہے، جو دوسری supported لائن ہے۔ `ServeMux` کی pattern matching «Go 1.22 میں نمایاں طور پر بدلی»، اور method patterns اسی وقت آئے ([net/http](https://pkg.go.dev/net/http))۔ macOS پر Go 1.27 کو macOS 13 یا اس سے نیا ورژن چاہیے ([Go 1.27 release notes](https://go.dev/doc/go1.27))۔

```bash
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` کی ڈیفالٹ قدر `v26.0` ہے، یعنی Meta کی بھیجنے والی مثال کا ورژن ([Meta send messages، رسائی 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages))۔ `GRAPH_BASE` کی ڈیفالٹ قدر `https://graph.facebook.com` ہے، اور آخر والا ٹیسٹ اسے ایک mock کی طرف موڑ دیتا ہے۔ ٹوکنز اور فون نمبر IDs [ٹیسٹ نمبر کی گائیڈ](/academy/ur/articles/whatsapp-cloud-api-test-number-get-started/) سے ملتے ہیں۔

## main.go

```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 send اسکرپٹ](/academy/ur/articles/send-whatsapp-message-python-cloud-api/) اور اس کے Node.js جڑواں ورژن جیسا ہے، اور سرور [FastAPI receiver](/academy/ur/articles/whatsapp-webhook-python-fastapi-receive-messages/) اور اس کے Express جڑواں ورژن جیسا:

```bash
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
```

## بھیجنا: structs، errors اور retries

`text`، `template` اور `components` پر `omitempty` غیر استعمال شدہ حصوں کو JSON سے باہر رکھتا ہے۔ یوں بغیر parameters والا ٹیمپلیٹ کوئی `components` key نہیں بھیجتا۔ `Unmarshal` ان «object keys کو نظر انداز کرتا ہے جن کا کوئی متعلقہ struct field نہ ہو»، اس لیے `SendResponse` صرف وہ fields declare کرتا ہے جو CLI پڑھتا ہے ([encoding/json، رسائی 2026-11-04](https://pkg.go.dev/encoding/json))۔ Go 1.27 میں `encoding/json` اسی رویے کے ساتھ v2 implementation پر چلتا ہے، اگرچہ error میسج کا متن مختلف ہو سکتا ہے۔

`http.Client` مشترک رکھا گیا ہے کیونکہ clients «متعدد goroutines کے بیک وقت استعمال کے لیے محفوظ ہیں»۔ اس کا 15 سیکنڈ کا `Timeout` اس فائل کا انتخاب ہے، کیونکہ «صفر Timeout کا مطلب ہے کوئی timeout نہیں» ([net/http، رسائی 2026-11-04](https://pkg.go.dev/net/http))۔ `defer resp.Body.Close()` docs کی اس ہدایت پر عمل ہے: «پڑھنا مکمل ہونے پر caller کو resp.Body بند کرنی چاہیے۔»

`send`، `Error.Code` پر فیصلہ کرتا ہے۔ Meta کی ہدایت ہے کہ «اپنی ایپ کی error handling logic کو `code` قدروں اور `details` payload properties کے گرد بنائیں» ([Meta error codes، رسائی 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes))۔ `send` صرف دو کوڈز پر retry کرتا ہے۔ 131056 کے لیے Meta کہتا ہے کہ «4^X سیکنڈ بعد دوبارہ کوشش کریں (X=0 سے شروع کریں اور ہر ناکامی کے بعد X کو 1 بڑھائیں)» ([Meta about the platform، رسائی 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/about-the-platform))۔ Meta، 130429 کے لیے کوئی شیڈول نہیں دیتا، اس لیے 1، 2 اور 4 سیکنڈ اس فائل کا انتخاب ہیں۔ دونوں حدیں [Cloud API ریٹ لمٹس](/academy/ur/articles/whatsapp-cloud-api-rate-limits-throughput-pair-rate/) میں بیان ہیں، اور باقی ہر کوڈ [error codes ریفرنس](/academy/ur/articles/whatsapp-cloud-api-error-codes-reference/) میں۔

## وصول کرنا: پہلے باڈی پڑھیں، پھر جواب دیں

ایسا pattern جو «GET method کے ساتھ ہو، GET اور HEAD دونوں requests سے میل کھاتا ہے» ([net/http، رسائی 2026-11-04](https://pkg.go.dev/net/http))۔ غلط method پر `Allow` ہیڈر کے ساتھ 405 ملتا ہے ([Go routing enhancements، 2024-02-13، رسائی 2026-11-04](https://go.dev/blog/routing-enhancements))۔ `r.URL.Query()` نقطوں والے `hub.*` نام ویسے ہی رکھتا ہے جیسے Meta بھیجتا ہے۔ PHP انہیں underscores میں بدل دیتا ہے، جیسا کہ [Laravel گائیڈ](/academy/ur/articles/whatsapp-webhook-laravel-receive-messages/) میں دکھایا گیا ہے۔

POST handler، 200 لکھنے سے پہلے پوری باڈی پڑھ لیتا ہے۔ net/http docs کے مطابق handler کے return ہونے کے بعد `Request.Body` پڑھنا درست نہیں۔ جو goroutine `r` وصول کرے، اسے باڈی غائب مل سکتی ہے۔ اس لیے handler اس کے بجائے byte slice کو channel میں بھیجتا ہے۔ `MaxBytesReader` پڑھنے کی حد 4 MiB رکھتا ہے، اور اس سے بڑی باڈی `MaxBytesError` واپس کرتی ہے۔ Meta کوئی payload سائز دستاویز نہیں کرتا، اس لیے اپنی ٹریفک کے مطابق حد چنیں۔ Meta ایک POST میں 1000 تک updates اکٹھے بھیجتا ہے ([Meta create a webhook endpoint، رسائی 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint))۔

`validSignature`، `sha256=` ہٹاتا ہے، باقی کو hex-decode کرتا ہے اور raw bytes کا موازنہ کرتا ہے۔ `crypto/hmac` docs وصول کرنے والوں سے کہتی ہیں کہ «timing side-channels سے بچنے کے لیے MACs کا موازنہ Equal سے کریں» ([crypto/hmac، رسائی 2026-11-04](https://pkg.go.dev/crypto/hmac))۔ غیر hex حروف والا ہیڈر `DecodeString` پر ناکام ہوتا ہے اور اسے 401 ملتا ہے۔ [Signature verification گائیڈ](/academy/ur/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) بتاتی ہے کہ hash کو raw bytes ہی پر کیوں چلنا چاہیے۔

Channel میں 100 payloads کی گنجائش ہے۔ جب یہ بھر جائے تو handler، 503 سے جواب دیتا ہے۔ 100 slots والا buffer اور 503 اس فائل کے انتخاب ہیں۔ Meta کو retry کے لیے صرف 200 کے علاوہ کوئی جواب چاہیے، اور وہ ناکام ڈیلیوری کو 7 دن تک دوبارہ بھیجتا ہے۔ اگر process ختم ہو جائے تو channel میں موجود payload ضائع ہو جاتا ہے، بالکل FastAPI کے background tasks والی احتیاط کی طرح۔ [ویب ہُک queue architecture](/academy/ur/articles/whatsapp-webhook-queue-architecture-workers/) میں 200 سے پہلے ایک پائیدار queue میں لکھنے کا طریقہ ہے۔

واضح `http.Server` ہر connection کی حد مقرر کرتا ہے۔ `ReadHeaderTimeout` «request headers پڑھنے کے لیے دیا گیا وقت» ہے، `ReadTimeout` «باڈی سمیت پوری request» پر لاگو ہوتا ہے، اور `WriteTimeout` response لکھنے کی حد رکھتا ہے۔ یہ قدریں اس فائل کا انتخاب ہیں۔ Meta کو درست سرٹیفکیٹ کے ساتھ HTTPS چاہیے، اس لیے port 8080 کے آگے ایک TLS proxy یا [ngrok جیسا tunnel](/academy/ur/articles/whatsapp-webhook-local-testing-ngrok/) رکھیں۔

## بھیجنے والے اور dedupe

بھیجنے والا `from` ہے اور `from_user_id` متبادل ہے۔ Meta کہتا ہے کہ `from` «اگر فون نمبر شامل نہ کیا جا سکے تو چھوڑ دیا جائے گا»، اور `from_user_id` میں صارف کا BSUID ہوتا ہے ([Meta business-scoped user IDs، رسائی 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids))۔ Statuses میں پہلے `recipient_id` اور پھر `recipient_user_id` استعمال ہوتا ہے۔ Meta کے payload میں `timestamp` ایک string ہے، اس لیے struct اسے string ہی declare کرتا ہے۔ [Business-scoped user IDs](/academy/ur/articles/whatsapp-usernames-business-scoped-user-ids/) میں contact ٹیبل والا پہلو بیان ہے۔

Dedupe کلیدیں `msg:<id>` اور `status:<id>:<status>` ہیں۔ Map، restart پر ختم ہو جاتا ہے اور instances کے درمیان مشترک نہیں ہوتا، اس لیے پروڈکشن میں آپ کے ڈیٹا بیس میں unique index ضروری ہے۔

## اسے ٹیسٹ کریں

سرور کو ایک ٹرمینل میں چلائیں۔ GET کو `123` پرنٹ کرنا چاہیے:

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

Meta کے text ویب ہُک نمونے کو ایک لائن میں سمیٹ کر sign کریں اور post کریں:

```bash
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
```

پہلی بار 200 واپس آتا ہے اور سرور میسج والی لائن لاگ کرتا ہے۔ دوہرانے پر 200 آتا ہے اور کچھ لاگ نہیں ہوتا۔ ترمیم شدہ، بغیر sign کی فائل پر 401 آتا ہے۔

بھیجنے والی طرف کے لیے `httptest`، Meta کی جگہ لیتا ہے۔ یہ ٹیسٹ ہر کال کا جواب Meta کی 130429 مثال کی مختصر کاپی سے دیتا ہے۔ 400 اسٹیٹس mock کا انتخاب ہے، کیونکہ Meta ہر کوڈ کے لیے کوئی HTTP اسٹیٹس دستاویز نہیں کرتا۔

```go
// 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` تقریباً سات سیکنڈ لیتا ہے، یعنی 1، 2 اور 4 سیکنڈ کے وقفے، اور پاس ہو جاتا ہے۔ وصول کرنے والی طرف متبادل کو آزمانے کے لیے `sample.json` میں `"from"` کو `"from_user_id"` میں بدلیں، message ID تبدیل کریں، دوبارہ sign کریں اور پھر post کریں۔

*Z-API Omni ٹیم*
