الـ Webhooks
الـ Webhooks تجعل LastMile تستدعي خادمك حين يحدث شيء للشحنة، فلا تحتاج إلى الاستعلام المتكرر. استخدمها لإبقاء حالة الطلب في نظامك محدّثة ولإشعار عملائك.
النطاق: webhooks:manage. الاشتراك يتبع تاجراً واحداً ويستقبل أحداث شحنات ذلك التاجر.
POST /merchants/{merchantId}/webhooks:
| الحقل | التفاصيل |
|---|---|
url |
مطلوب. عنوان https عام يستقبل الأحداث. العناوين المحلية والخاصة تُرفض (security.unsafe_webhook_target_url وintegrations.invalid_target_url) |
events |
مطلوب، حدث واحد على الأقل. أنواع الأحداث من الجدول أدناه، أو الرمزان shipment.* (كل أحداث الشحنة) و* (كل شيء) |
description |
نص اختياري لتمييز الاشتراك، حتى 200 محرف |
curl -X POST "https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks" \
-H "X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
-H "X-API-Secret: YOUR_API_SECRET" \
-H "Content-Type: application/json" \
-d '{
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered"
],
"description": "Order system"
}'const response = await fetch("https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks", {
method: "POST",
headers: {
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET",
"Content-Type": "application/json"
},
body: JSON.stringify({
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered"
],
"description": "Order system"
}),
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'X-API-Secret: YOUR_API_SECRET',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://shop.example.com/hooks/lastmile',
'events' => [
'shipment.created',
'shipment.out_for_delivery',
'shipment.delivered',
],
'description' => 'Order system',
], JSON_UNESCAPED_UNICODE),
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"POST",
"https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks",
headers={
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET",
},
json={
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered",
],
"description": "Order system",
},
timeout=30,
)
print(response.status_code, response.json()){
"id": "c1d6a1de-2f0e-4a7b-9c5e-6a3f6f0a9b11",
"merchantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"url": "https://shop.example.com/hooks/lastmile",
"events": [
"shipment.created",
"shipment.out_for_delivery",
"shipment.delivered"
],
"description": "Order system",
"isActive": true,
"createdAt": "2026-01-15T09:00:00Z",
"secret": "5f1c0a7e9d3b..."
}يحتوي الرد على secret التوقيع. يظهر مرة واحدة هنا: خزّنه كسر على خادمك. ولتحصل على سر جديد دوّره بـ POST /merchants/{merchantId}/webhooks/{id}/rotate-secret؛ والسر القديم يتوقف فوراً.
| العملية | ما تفعله |
|---|---|
GET /merchants/{merchantId}/webhooks |
يعرض اشتراكات التاجر (بلا أسرار) |
POST /merchants/{merchantId}/webhooks/{id}/test |
يضع في الطابور إرسال ping موقّعاً إلى العنوان كأنه حدث حقيقي. الاشتراكات الفعّالة فقط تُختبر |
POST /merchants/{merchantId}/webhooks/{id}/rotate-secret |
يرجع سراً جديداً يظهر مرة واحدة |
DELETE /merchants/{merchantId}/webhooks/{id} |
يحذف الاشتراك. سجلات الإرسال السابقة تبقى |
GET /webhooks/events |
فهرس الأحداث الحي مع الأوصاف وأمثلة الحمولة |
curl -X POST "https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks/c1d6a1de-2f0e-4a7b-9c5e-6a3f6f0a9b11/test" \
-H "X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
-H "X-API-Secret: YOUR_API_SECRET"const response = await fetch("https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks/c1d6a1de-2f0e-4a7b-9c5e-6a3f6f0a9b11/test", {
method: "POST",
headers: {
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET"
},
});
const data = await response.json();
console.log(response.status, data);<?php
$url = 'https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks/c1d6a1de-2f0e-4a7b-9c5e-6a3f6f0a9b11/test';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-Key: lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'X-API-Secret: YOUR_API_SECRET',
],
]);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status, json_decode($result, true));import requests
response = requests.request(
"POST",
"https://api.goldrock.live/api/public/v1/merchants/3fa85f64-5717-4562-b3fc-2c963f66afa6/webhooks/c1d6a1de-2f0e-4a7b-9c5e-6a3f6f0a9b11/test",
headers={
"X-API-Key": "lmc_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"X-API-Secret": "YOUR_API_SECRET",
},
timeout=30,
)
print(response.status_code, response.json())| الحدث | يُرسل عندما | اسم الحالة في الحمولة |
|---|---|---|
shipment.created | أُنشئت شحنة (من لوحة التحكم أو استيراد أو الـ API). | Created |
shipment.picked_up | استلم المندوب الشحنة من المرسل. | PickedUp |
shipment.out_for_delivery | خرجت الشحنة للتوصيل مع مندوب. | OutForDelivery |
shipment.delivered | سُلّمت الشحنة (كلياً أو جزئياً). | Delivered |
shipment.cancelled | أُلغيت الشحنة. | Cancelled |
shipment.on_hold | الشحنة محتجزة في المستودع. | OnHoldWarehouse |
shipment.lost | أُعلنت الشحنة مفقودة. | Lost |
shipment.damaged | أُعلنت الشحنة تالفة. | Damaged |
shipment.ndr_created | فشلت محاولة توصيل (تقرير عدم التسليم). | DeliveryAttempted |
shipment.rto_initiated | بدأت الشحنة رحلة العودة إلى المرسل. | RTOInitiated |
shipment.rto_received_at_warehouse | استُلمت الشحنة المرتجعة في المستودع. | RTOInitiated |
shipment.rto_out_for_return | الشحنة المرتجعة في طريقها إلى المرسل. | RTOInTransit |
shipment.rto_refused_by_merchant | رفض التاجر الشحنة المرتجعة. | RTOInTransit |
shipment.returned_to_merchant | سُلّمت الشحنة إلى التاجر. | ReturnedToSender |
الحدث ping يُرسل من نقطة الاختبار فقط ولا يمكن الاشتراك فيه. والفهرس يقدمه أيضاً GET /webhooks/events مباشرة.
كل إرسال هو POST إلى عنوانك بجسم JSON بالشكل { "event", "occurredAt", "data" }:
{
"event": "shipment.delivered",
"occurredAt": "2026-01-15T09:30:00Z",
"data": {
"trackingNumber": "AWB-RUH-000123",
"statusCode": 4040,
"statusName": "Delivered",
"trackUrl": "https://tracking.example.com/track/AWB-RUH-000123",
"awbUrl": "https://tracking.example.com/awb/AWB-RUH-000123",
"rtoTrackingNumber": null
}
}| الحقل | المعنى |
|---|---|
event |
نوع الحدث |
occurredAt |
وقت حدوثه، ISO 8601 بتوقيت UTC |
data.trackingNumber |
الشحنة. اجلب GET /shipments/{trackingNumber} إن احتجت تفاصيل أكثر |
data.statusCode وdata.statusName |
الحالة التي سببت الحدث (اسم الـ enum مثل Delivered) |
data.trackUrl وdata.awbUrl |
رابطا صفحة التتبع العامة والبوليصة |
data.rtoTrackingNumber |
رقم تتبع شحنة الإرجاع إن وُجدت؛ وإلا null |
ويحمل الطلب الترويسات التالية:
| الترويسة | القيمة |
|---|---|
X-Event-Type |
نوع الحدث مكرراً من الجسم |
X-Signature |
التوقيع بنظام سداسي عشري بأحرف صغيرة |
X-Webhook-Signature |
القيمة نفسها لـ X-Signature |
التوقيع هو hex(HMAC_SHA256(secret, rawBody)): ناتج HMAC-SHA256 بنظام سداسي عشري بأحرف صغيرة على جسم الطلب الخام (البايتات نفسها كما وصلت) بمفتاح هو سر الاشتراك. تحقق منه دائماً قبل أن تثق بالإرسال.
- اقرأ الجسم الخام قبل أي تحليل JSON. إعادة تسلسل JSON المحلَّل تغيّر البايتات وتكسر الفحص.
- احسب HMAC بالسر.
- قارنه مع
X-Signatureبزمن ثابت (constant time). - ارفض الطلب بـ
401إن لم يتطابق.
// Node.js + Express. The webhook secret comes from the environment.
import crypto from "node:crypto";
import express from "express";
const app = express();
// Keep the raw bytes: the signature is computed over them, not over parsed JSON.
app.post("/hooks/lastmile", express.raw({ type: "application/json" }), (req, res) => {
const received = String(req.get("X-Signature") ?? "");
const expected = crypto
.createHmac("sha256", process.env.LASTMILE_WEBHOOK_SECRET)
.update(req.body) // a Buffer
.digest("hex");
const a = Buffer.from(received);
const b = Buffer.from(expected);
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString("utf8"));
// Store the event, answer quickly, work later.
console.log(event.event, event.data.trackingNumber, event.data.statusName);
res.sendStatus(200);
});
app.listen(3000);<?php
// The webhook secret comes from the environment.
$secret = getenv('LASTMILE_WEBHOOK_SECRET');
$rawBody = file_get_contents('php://input'); // the exact bytes received
$received = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $rawBody, $secret); // lowercase hex
if (!hash_equals($expected, $received)) { // constant-time comparison
http_response_code(401);
exit;
}
$event = json_decode($rawBody, true);
// Store the event, answer quickly, work later.
error_log($event['event'] . ' ' . $event['data']['trackingNumber']);
http_response_code(200);# Flask. The webhook secret comes from the environment.
import hashlib
import hmac
import os
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["LASTMILE_WEBHOOK_SECRET"].encode()
@app.post("/hooks/lastmile")
def lastmile_hook():
raw = request.get_data() # the exact bytes received
received = request.headers.get("X-Signature", "")
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest() # lowercase hex
if not hmac.compare_digest(expected, received): # constant-time comparison
abort(401)
event = request.get_json(force=True)
# Store the event, answer quickly, work later.
print(event["event"], event["data"]["trackingNumber"])
return "", 200// ASP.NET Core minimal API. The webhook secret comes from configuration.
using System.Security.Cryptography;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var secret = Encoding.UTF8.GetBytes(app.Configuration["LastMile:WebhookSecret"]!);
app.MapPost("/hooks/lastmile", async (HttpRequest request) =>
{
// Read the raw bytes: the signature is computed over them, not over parsed JSON.
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer);
var raw = buffer.ToArray();
var received = request.Headers["X-Signature"].ToString();
var expected = Convert.ToHexString(HMACSHA256.HashData(secret, raw)).ToLowerInvariant();
var a = Encoding.ASCII.GetBytes(received);
var b = Encoding.ASCII.GetBytes(expected);
if (a.Length != b.Length || !CryptographicOperations.FixedTimeEquals(a, b))
return Results.Unauthorized();
var json = System.Text.Json.JsonDocument.Parse(raw);
// Store the event, answer quickly, work later.
Console.WriteLine(json.RootElement.GetProperty("event").GetString());
return Results.Ok();
});
app.Run();ردّ بأي حالة 2xx بمجرد تخزين الحدث، وأجّل العمل البطيء. أي حالة أخرى أو انتهاء مهلة أو خطأ اتصال يُعدّ فشلاً ويُعاد الإرسال بعد دقيقة و5 دقائق و15 دقيقة. وبعد ذلك لا يُرسَل ثانية، فإن كان خادمك متوقفاً طويلاً فطابق الحالات عبر GET /shipments.
ولأجل إعادة المحاولة والشبكة، استعد لما يلي:
- التكرار. قد يصل الحدث نفسه أكثر من مرة. اجعل معالجك آمناً للتكرار، مثلاً بتذكّر
event+data.trackingNumber+occurredAt. - وصول غير مرتب. استخدم
occurredAtأو اجلب الشحنة، ولا تفترض أن آخر حدث وصل هو الأحدث. - إعادة الإرسال المتعمدة. التوقيع يغطي الجسم ومنه
occurredAt. إن أردت رفض الإرسالات القديمة جداً فقارنه بساعتك.
- العنوان
httpsعام. - السر مخزّن على الخادم ولا يُكتب في السجلات.
- التوقيع يُفحص على الجسم الخام بزمن ثابت.
- المعالج يرد
2xxبسرعة وهو آمن للتكرار. - اختبرته بـ
POST .../test.