טרינג למפתחים English

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}/testendpointId
הודעה
{
  "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).

רישום כתובת

js
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 once

הכתובת חייבת להיות https עם שרת ציבורי (בסביבת הניסוי מותר גם http והמחשב שלכם). רישום, שינוי, החלפת סוד ובדיקה צריכים מפתח עם ההרשאה webhooks; הקריאות צריכות read. עד 16 כתובות.

בודקים כל הודעה

Tring-Signature הוא t=<unix seconds>,v1=<hex>. ‏v1 הוא HMAC-SHA256 בהקסדצימלי באותיות קטנות של <t>. ואחריו הגוף הגולמי, עם הסוד שלכם (כל המחרוזת whsec_...). דוחים הודעה שה-t שלה רחוק יותר מ-300 שניות מהשעון שלכם. פונקציית העזר של הספרייה עושה את כל זה, בזמן קבוע, ומקבלת כמה סודות בזמן החלפה:

examples/js/webhook-handler.mjs
// 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));
  1. משתמשים בגוף הגולמי, בבתים כמו שהגיעו. גוף שפוענח ונכתב מחדש הוא לא אותם בתים.
  2. עונים 2xx בתוך 10 שניות, לפני העבודה.
  3. שומרים את ה-id של האירוע ולא עושים פעמיים את אותו דבר לאותו מזהה: הודעה יכולה להגיע יותר מפעם אחת, ובכל סדר.
  4. הודעה אף פעם לא מבקשת להפיק משהו. אם אתם מפיקים בעקבותיה, עדיין מכינים ומאשרים עם 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, מהישן לחדש. שומרים את המזהה של האירוע האחרון שטופל ומבקשים את מה שבא אחריו:

js
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;
}

לנסות במחשב שלכם

שרת הדמה שולח הודעות חתומות אמיתיות: מריצים npx tring-mock-server, רושמים את http://127.0.0.1:3000/ כשהמטפל שלמעלה רץ, ומפיקים קבלה מההתחלה המהירה.