Hadisələrin imzalanması
Hər POST /v1/events iki sübut daşıyır: Authorization-dakı API açarı sorğunun kimə aid olduğunu, imza isə gövdənin yolda dəyişdirilmədiyini göstərir. İmza açıq Standard Webhooks sxemi ilə qurulur, vebhukları imzaladığımız eyni sxemlə.
Nə imzalanır
“Nə imzalanır” bölməsi| Başlıq | İçində nə var |
|---|---|
webhook-id |
göndərmənin identifikatoru; event_id ötürmək rahatdır |
webhook-timestamp |
göndərmə vaxtı, Unix saniyələri |
webhook-signature |
v1, və base64-də imza |
İmza {webhook-id}.{webhook-timestamp}.{gövdə} sətrindən HMAC-SHA256-dır:
- Açar hadisə imzasının məxfi açarıdır (
whsec_…):whsec_-dən sonrakı hissə, base64-dən deşifrə olunmuş. - Gövdə sorğuda gedən baytların özüdür. JSON-u bir dəfə serializasiya edin, bu sətri imzalayın və onu da göndərin. HTTP müştərisi obyekti özü serializasiya edərsə, imza uyğun gəlməyəcək.
- Vaxt
occurred_atyox, göndərmə vaxtıdır. Bir saat sonrakı təkrarı yeni vaxt nişanı ilə yenidən imzalayın.
// app/lib/aapp.ts: only on the server, never in a client componentimport { createHmac } from 'node:crypto';
const API = 'https://test-api.zirva.xyz';
export async function sendEvent(event: Record<string, unknown> & { event_id: string }) { const body = JSON.stringify(event); const timestamp = Math.floor(Date.now() / 1000).toString(); const key = Buffer.from(process.env.AAPP_SIGNING_SECRET!.slice('whsec_'.length), 'base64'); const signature = createHmac('sha256', key) .update(`${event.event_id}.${timestamp}.${body}`) .digest('base64');
const res = await fetch(`${API}/v1/events`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.AAPP_API_KEY}`, 'Content-Type': 'application/json', 'webhook-id': event.event_id, 'webhook-timestamp': timestamp, 'webhook-signature': `v1,${signature}`, }, body, signal: AbortSignal.timeout(10_000), }); return { status: res.status, body: await res.json() };}
await sendEvent({ event_id: 'evt_90114', type: 'order.paid', user_ref: '4f9a', order_id: 'ord_78123', occurred_at: new Date().toISOString(), amount: 25.0, currency: 'AZN', items: [{ sku: 'game-123', category: 'rpg', price: 25.0, qty: 1 }],});import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.time.Instant;import java.util.Base64;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
public class AappEvents { static final String API = "https://test-api.zirva.xyz";
public static void main(String[] args) throws Exception { String id = "evt_90114"; String body = """ {"event_id":"evt_90114","type":"order.paid","user_ref":"4f9a","order_id":"ord_78123",\ "occurred_at":"%s","amount":25.00,"currency":"AZN"}""".formatted(Instant.now()); String timestamp = Long.toString(Instant.now().getEpochSecond());
String secret = System.getenv("AAPP_SIGNING_SECRET"); // whsec_… byte[] key = Base64.getDecoder().decode(secret.substring("whsec_".length())); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); String signature = Base64.getEncoder().encodeToString( mac.doFinal((id + "." + timestamp + "." + body).getBytes(StandardCharsets.UTF_8)));
HttpRequest request = HttpRequest.newBuilder(URI.create(API + "/v1/events")) .timeout(Duration.ofSeconds(10)) .header("Authorization", "Bearer " + System.getenv("AAPP_API_KEY")) .header("Content-Type", "application/json") .header("webhook-id", id) .header("webhook-timestamp", timestamp) .header("webhook-signature", "v1," + signature) .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)) .build(); HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.body()); }}package main
import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "os" "strconv" "strings" "time")
const api = "https://test-api.zirva.xyz"
func main() { event := map[string]any{ "event_id": "evt_90114", "type": "order.paid", "user_ref": "4f9a", "order_id": "ord_78123", "occurred_at": time.Now().UTC().Format(time.RFC3339), "amount": 25.00, "currency": "AZN", } body, _ := json.Marshal(event) id := "evt_90114" timestamp := strconv.FormatInt(time.Now().Unix(), 10)
key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(os.Getenv("AAPP_SIGNING_SECRET"), "whsec_")) if err != nil { panic(err) } mac := hmac.New(sha256.New, key) mac.Write([]byte(id + "." + timestamp + "." + string(body))) signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
req, _ := http.NewRequest(http.MethodPost, api+"/v1/events", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("AAPP_API_KEY")) req.Header.Set("Content-Type", "application/json") req.Header.Set("webhook-id", id) req.Header.Set("webhook-timestamp", timestamp) req.Header.Set("webhook-signature", "v1,"+signature)
client := &http.Client{Timeout: 10 * time.Second} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() out, _ := io.ReadAll(res.Body) fmt.Println(res.StatusCode, string(out))}API=https://test-api.zirva.xyzBODY='{"event_id":"evt_90114","type":"order.paid","user_ref":"4f9a","order_id":"ord_78123","occurred_at":"2026-11-29T10:00:00Z","amount":25.00,"currency":"AZN"}'ID=evt_90114TS=$(date +%s)KEY_HEX=$(printf %s "${AAPP_SIGNING_SECRET#whsec_}" | base64 -d | od -An -tx1 | tr -d ' \n')SIG=$(printf %s "$ID.$TS.$BODY" | openssl dgst -sha256 -mac HMAC -macopt hexkey:$KEY_HEX -binary | base64)
curl -sS "$API/v1/events" \ -H "Authorization: Bearer $AAPP_API_KEY" \ -H 'Content-Type: application/json' \ -H "webhook-id: $ID" \ -H "webhook-timestamp: $TS" \ -H "webhook-signature: v1,$SIG" \ -d "$BODY"Dörd nümunənin hamısı rəsmi Standard Webhooks kitabxanası ilə yoxlanılıb. Ondan da istifadə edə bilərsiniz: Webhook.sign(id, timestamp, body) eyni imzanı verir.
İmza xətaları
“İmza xətaları” bölməsi| Cavab | Nə deməkdir | Nə etməli |
|---|---|---|
401 invalid_api_key |
API açarı yoxdur, yanlışdır və ya geri alınıb | Authorization: Bearer aapp_… başlığını və açarın rejimini yoxlayın |
401 invalid_signature |
imza uyğun gəlmədi | göndərilən baytların imzalandığını və məxfi açarın açarla eyni rejimdən olduğunu yoxlayın |
401 timestamp_out_of_tolerance |
vaxt nişanı bizim vaxtımızdan 5 dəqiqədən çox fərqlənir | server saatını sinxronlaşdırın (NTP) və göndərmədən dərhal əvvəl imzalayın |
İmza xətalı hadisə jurnala düşmür. Düzəltdikdən sonra onu eyni event_id ilə yenidən göndərin.
Məxfi açarın dəyişdirilməsi
“Məxfi açarın dəyişdirilməsi” bölməsiMəxfi açarı fasiləsiz dəyişmək olar. Yeni məxfi açar veririk və bir müddət hər ikisi qüvvədə olur. Bu vaxt iki imzanı boşluqla ötürün: v1,<köhnə ilə imza> v1,<yeni ilə imza>. İstənilən düzgün imza keçir. Yeni məxfi açar bütün serverlərə yayılanda köhnəni geri almağımızı xahiş edin.