Webhooks ואירועים
טרינג מודיעה למערכת שלכם כשמשהו קורה, בבקשת POST חתומה בפרוטוקול HTTPS לכתובת שרשמתם. ההודעה דלה: מה קרה, מתי, לאיזה עסק, והמזהים. את הפרטים קוראים עם המפתח שלכם; הקריאה הזו היא גם הדרך לדעת שההודעה אמיתית.
האירועים
type | מתי | data |
|---|---|---|
document.issued | הופק מסמך, דרך ה-API או בפורטל | documentId |
document.cancelled | מסמך בוטל | documentId |
draft.confirmed | הטיוטה שלכם הפכה למסמך | draftId, documentId |
draft.expired | הטיוטה שלכם פגה בלי אישור | draftId |
delivery.opened | עמוד של קישור אישי נפתח בפעם הראשונה | documentId, linkId |
delivery.downloaded | קובץ הורד דרך קישור: בפעם הראשונה זה המקור | documentId, linkId, deliveryId |
consent.changed | לקוח נתן הסכמה או חזר בו | customerKey |
allocation.received, allocation.held, allocation.failed | מספר הקצאה התקבל, עוכב או נדחה | documentId |
transmission.status_changed, transmission.failed | שידור של הקובץ האחיד השתנה או נכשל | exportId |
issuer.activated, issuer.granted, issuer.revoked | עסק הופעל, נתן הרשאה למערכת שלכם או חזר בו | |
endpoint.test | נשלח מ-POST /v1/webhook-endpoints/{id}/test | endpointId |
{
"id": "0b3c0b6e-35d4-4ab5-9e43-6a3e1f0d6f21",
"object": "event",
"type": "document.issued",
"created": "2026-11-20T09:15:02.418Z",
"environment": "sandbox",
"issuerId": "8d0f4b5e-0c6b-4c1e-9d56-1f3f8f7a2b10",
"data": { "documentId": "d6980f12-1c28-49dd-9449-efde29b023df" }
}כותרות: Tring-Signature, Tring-Event-Id, Tring-Event-Type, Tring-Delivery-Id, Tring-Delivery-Attempt. הספריות מגדירות טיפוס לכל גוף (TringWebhookEvent, לפי type).
רישום כתובת
const { endpoint, secret } = await tring.createWebhookEndpoint({
url: 'https://example.com/tring/webhook',
eventTypes: ['document.issued', 'delivery.downloaded'], // or ['*']
});
// store `secret` now, like the API key: no later answer holds it
await tring.sendWebhookTest(endpoint.id); // posts an endpoint.test notice at oncecreated = tring.create_webhook_endpoint({
"url": "https://example.com/tring/webhook",
"eventTypes": ["document.issued", "delivery.downloaded"],
})
secret = created["secret"] # store it now: no later answer holds it
tring.send_webhook_test(created["endpoint"]["id"])curl -sS -X POST "$TRING_BASE_URL/v1/webhook-endpoints" \
-H "Authorization: Bearer $TRING_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/tring/webhook", "eventTypes": ["document.issued"]}'הכתובת חייבת להיות https עם שרת ציבורי (בסביבת הניסוי מותר גם http והמחשב שלכם). רישום, שינוי, החלפת סוד ובדיקה צריכים מפתח עם ההרשאה webhooks; הקריאות צריכות read. עד 16 כתובות.
בודקים כל הודעה
Tring-Signature הוא t=<unix seconds>,v1=<hex>. v1 הוא HMAC-SHA256 בהקסדצימלי באותיות קטנות של <t>. ואחריו הגוף הגולמי, עם הסוד שלכם (כל המחרוזת whsec_...). דוחים הודעה שה-t שלה רחוק יותר מ-300 שניות מהשעון שלכם. פונקציית העזר של הספרייה עושה את כל זה, בזמן קבוע, ומקבלת כמה סודות בזמן החלפה:
// A webhook receiver: check the signature on the raw body, answer 2xx at once, then do the work once per
// event id. Works the same in Express (express.raw({ type: 'application/json' })), Next.js route handlers
// (await request.arrayBuffer()) and edge runtimes.
// Run: TRING_WEBHOOK_SECRET=whsec_... node webhook-handler.mjs
import http from 'node:http';
import { constructWebhookEvent, TringSignatureError } from 'tring-sdk';
// During a rotation put the old and the new secret here: TRING_WEBHOOK_SECRET=old,new
const secrets = (process.env.TRING_WEBHOOK_SECRET ?? '').split(',').filter(Boolean);
const seen = new Set(); // keep this in your database: a notice can arrive more than once
http
.createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
let event;
try {
// the raw bytes: a body parsed and written again would not match the signature
event = await constructWebhookEvent({ payload: Buffer.concat(chunks), headers: req.headers, secret: secrets });
} catch (err) {
res.writeHead(err instanceof TringSignatureError ? 400 : 500).end();
return;
}
res.writeHead(204).end(); // answer within 10 seconds, before the work
if (seen.has(event.id)) return;
seen.add(event.id);
// A notice holds identifiers only: read the details with your key, e.g. tring.getDocument(event.data.documentId)
console.log(event.type, event.data);
})
.listen(Number(process.env.PORT ?? 3000));from tring_sdk import construct_webhook_event, TringSignatureError
# Flask: request.get_data(); Django: request.body; FastAPI: await request.body()
try:
event = construct_webhook_event(request.get_data(), headers=request.headers, secret=[WEBHOOK_SECRET])
except TringSignatureError:
abort(400)
# answer 2xx now; do the work once per event["id"]- משתמשים בגוף הגולמי, בבתים כמו שהגיעו. גוף שפוענח ונכתב מחדש הוא לא אותם בתים.
- עונים
2xxבתוך 10 שניות, לפני העבודה. - שומרים את ה-
idשל האירוע ולא עושים פעמיים את אותו דבר לאותו מזהה: הודעה יכולה להגיע יותר מפעם אחת, ובכל סדר. - הודעה אף פעם לא מבקשת להפיק משהו. אם אתם מפיקים בעקבותיה, עדיין מכינים ומאשרים עם Idempotency-Key משלכם.
ניסיונות חוזרים, החלפת סוד, יומן
הודעה שלא נענתה 2xx בתוך 10 שניות נשלחת שוב אחרי כדקה, 5 דקות, 25 דקות, שעתיים, 10 שעות, ואז כל 12 שעות, במשך שלושה ימים. כתובת שלא קיבלה כלום שלושה ימים מושבתת; מפעילים אותה שוב עם updateWebhookEndpoint(id, { enabled: true }).
rotateWebhookSecret(id, { overlapSeconds: 86400 }) מחזירה סוד חדש; הישן ממשיך לחתום לצדו בזמן החפיפה, ולכן כל הודעה נושאת שני v1. שמים את שני הסודות אצלכם, ואחר כך מוציאים את הישן. { overlapSeconds: 0 } מסיים מיד סוד שדלף.
listWebhookDeliveries(endpointId) ו-getWebhookDelivery(deliveryId) מציגות כל ניסיון (מה ענית, כמה זמן, למה נכשל); redeliverWebhook(deliveryId) שולחת שוב עם אותו מזהה אירוע.
קריאת אירועים אחרי הפסקה
כל אירוע שמיועד למערכת שלכם נמצא גם ב-GET /v1/events, מהישן לחדש. שומרים את המזהה של האירוע האחרון שטופל ומבקשים את מה שבא אחריו:
let after = lastHandledEventId;
for (;;) {
const page = await tring.listEvents({ after, limit: 100 });
for (const event of page.items) await handle(event);
if (!page.nextCursor) break;
after = page.items.at(-1).id;
}after = last_handled_event_id
while True:
page = tring.list_events(after=after, limit=100)
for event in page["items"]:
handle(event)
if not page["nextCursor"]:
break
after = page["items"][-1]["id"]לנסות במחשב שלכם
שרת הדמה שולח הודעות חתומות אמיתיות: מריצים npx tring-mock-server, רושמים את http://127.0.0.1:3000/ כשהמטפל שלמעלה רץ, ומפיקים קבלה מההתחלה המהירה.