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

ספריות SDK

שתי הספריות נבנות מתוך מפרט ה-OpenAPI: כל פעולה של ה-API היא מתודה בשם ה-operationId שלה (camelCase ב-TypeScript, snake_case בפייתון), עם טיפוסי הבקשה והתשובה מהמפרט. שכבה דקה שנכתבה ביד מוסיפה שליחה חוזרת, שגיאות ופונקציות עזר.

TypeScript / JavaScriptPython
התקנהnpm install tring-sdkpip install tring-sdk
סביבהNode 18 ומעלה, Bun, Deno; ESM3.9 ומעלה, סינכרוני ואסינכרוני (httpx)
לקוחnew Tring()Tring() / AsyncTring()

הגדרות

js
import { Tring } from 'tring-sdk';

const tring = new Tring({
  apiKey: process.env.TRING_API_KEY, // default: TRING_API_KEY
  baseUrl: process.env.TRING_BASE_URL, // default: by the key's prefix
  timeoutMs: 60_000, // one attempt
  maxRetries: 2, // reads and idempotent requests
  confirmMaxRetries: 8, // a confirm whose outcome is unknown
  appInfo: 'my-shop/1.4', // added to the User-Agent
});

מפתח kbl_live_ מול כתובת סביבת הניסוי, או מפתח kbl_test_ מול הייצור, נדחים לפני שנשלח משהו. הדפסת הלקוח מציגה רק את החלק הציבורי של המפתח.

קריאה לפעולות

js
const page = await tring.listDocuments(issuerId, { docType: 400, from: '2026-11-01', limit: 50 });
const doc = await tring.getDocument(page.items[0].id);
const pdf = await tring.downloadDocument(doc.id); // Uint8Array, a signed copy
const link = await tring.createDocumentLink(doc.id, { recipientName: 'ישראלה ישראלי' });

// any operation by name, typed, including ones added after this SDK version
const same = await tring.request('listDocuments', { path: { issuerId }, query: { limit: 50 } });

גוף הבקשה משתמש בשמות השדות של ה-API (docType, documentDate) בשתי השפות, כך שאפשר להדביק כמו שהוא את ה-JSON שבתיעוד ובמפרט.

הכנה ואישור בקריאה אחת

issue() מכינה, נותנת לכם לבדוק את הטיוטה, ומאשרת. אם המפתח כבר שימש לאותה בקשה והפך למסמך, היא מחזירה את המסמך ולא מפיקה שוב.

js
const document = await tring.issue(issuerId, body, {
  idempotencyKey: `order-${order.id}-receipt`,
  approve: async (draft) => draft.document.amounts.total === order.total, // false: nothing is issued
});

שליחת קובץ

פעולה שמקבלת קובץ (הקבלה של הספק על הוצאה, putExpenseReceipt) מקבלת את הקובץ עצמו כגוף הבקשה, לא JSON: הבתים שלו, עם סוג המדיה שלו (image/jpeg, image/png או application/pdf, עד 5 MiB). ב-JavaScript מעבירים Buffer, Uint8Array, ArrayBuffer, Blob או File; ב-Python בתים, נתיב או קובץ שנפתח ב-"rb". כשלא מציינים את סוג המדיה הוא נקרא מהבתים הראשונים (contentType / content_type קובעים אותו), והשם של File או של נתיב נותן שם לקובץ השמור, אלא אם fileName / file_name נותנים אחר. קובץ שהבתים הראשונים שלו אינם סוג המדיה שנשלח איתו נדחה (422 EXPENSE_REFUSED, details.file: "file-kind"); אותו קובץ שוב לא שומר כלום ("replayed": true). ההורדה (getExpenseReceipt) מחזירה את אותם בתים.

examples/js/expense-receipt.mjs
// Record an expense and attach the supplier's receipt (a JPEG, PNG or PDF), then read the file back.
// Run: node expense-receipt.mjs receipt.pdf   (reads TRING_API_KEY, TRING_ISSUER_ID and, if set, TRING_BASE_URL)
import { readFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { Tring, amount, todayInIsrael } from 'tring-sdk';

const tring = new Tring();
const issuerId = process.env.TRING_ISSUER_ID;
const path = process.argv[2] ?? 'receipt.pdf';

const { expense } = await tring.createExpense(
  issuerId,
  { date: todayInIsrael(), supplier: 'ספק לדוגמה', amount: amount(118), vat: amount(18), category: 'office' },
  { idempotencyKey: 'expense-2026-0042' }, // one key per expense
);

// The body is the file itself. Its media type is read from its first bytes; pass { contentType } to say it.
const file = await readFile(path); // a Buffer; a Uint8Array, ArrayBuffer, Blob or File works too
const { replayed, expense: withFile } = await tring.putExpenseReceipt(issuerId, expense.id, file, { fileName: basename(path) });
console.log(`${replayed ? 'Already attached' : 'Attached'}: ${withFile.receipt.fileName} (${withFile.receipt.mediaType}, ${withFile.receipt.sizeBytes} bytes)`);

const back = await tring.getExpenseReceipt(issuerId, expense.id); // Uint8Array, byte for byte as sent
console.log(`Read back ${back.length} bytes, ${Buffer.from(back).equals(file) ? 'the same file' : 'a different file'}`);

שליחה חוזרת

לכל פעולה יש מדיניות שליחה חוזרת שנבנית מהמפרט (spec/retry-policy.json והשדה x-tring-retry):

מדיניותפעולותנשלחת שוב אחרי
safeכל GETתשובה שאבדה, 502, 503, 504, 429
idempotentהכנה, הוספת עסק, קובץ אחיד, גיבוי, מספר הקצאהתשובה שאבדה, 504 OUTCOME_UNKNOWN, 429; עם אותו Idempotency-Key
confirmאישורכמו למעלה, עד שהתוצאה ידועה (confirmMaxRetries)
unsafeקישורים, מיילים, ביטול, הסכמהרק 429 ו-503 UNAVAILABLE: בקשות שהשירות לא טיפל בהן

ההמתנה לפי Retry-After כשהוא בתשובה, ואחרת חצי שנייה שמוכפלת בכל פעם, עם פיזור אקראי.

שגיאות

מחלקה (JS / Python)מתי
TringApiErrorה-API ענה עם גוף שגיאה. code, status, details, issues, requestId, retryAfter.
TringOutcomeUnknownErrorלאישור עדיין אין תוצאה ידועה. מאשרים את draftId שוב מאוחר יותר; אף פעם לא מכינים מחדש.
TringConnectionErrorאין תשובה, ולא היה בטוח לשלוח שוב. mayHaveTakenEffect אומר אם הבקשה משנה משהו.
TringConfigErrorשימוש שגוי, כמו מפתח חסר או Idempotency-Key חסר. לא נשלח כלום.
TringApprovalDeclinedErrorapprove דחתה ב-issue(). לא הופק כלום.
TringSignatureErrorחתימת webhook לא אומתה.
js
import { isTringApiError } from 'tring-sdk';

try {
  await tring.prepareDraft(issuerId, body, { idempotencyKey });
} catch (err) {
  if (isTringApiError(err, 'DOCUMENT_REFUSED')) {
    for (const issue of err.issues) console.log(issue.code, issue.path);
  } else throw err;
}

דפדוף

js
for await (const doc of tring.paginate((cursor) => tring.listDocuments(issuerId, { cursor }))) {
  console.log(doc.number, doc.total);
}

פונקציות עזר

JSPythonמה עושה
amount(118)amount(118)"118.00"; דוחה יותר משתי ספרות אחרי הנקודה במקום לעגל
quantity(2)quantity(2)"2.0000"
todayInIsrael()today_in_israel()התאריך של היום לפי שעון ישראל, "YYYY-MM-DD"
idempotencyKey('order', 1001, 400)idempotency_key("order", 1001, 400)"order-1001-400", עם בדיקה
DocType.ReceiptDocType.RECEIPT400, ושאר הסוגים
PaymentMethod.BankTransferPaymentMethod.BANK_TRANSFER4, ושאר אמצעי התשלום
redactKeys(text)redact_keys(text)משאירה רק את החלק הציבורי של מפתח בשורת לוג
fileMediaType(bytes)file_media_type(data)סוג המדיה שהבתים הראשונים של קובץ אומרים (application/pdf, image/jpeg, image/png), כמו שה-API קורא אותם; אחרת null / None

חתימת webhook

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

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));

שם הכותרת, הפירוק שלה והטקסט שנחתם הם האפשרות scheme, כך שפורמט אחר הוא שינוי הגדרה:

js
await verifyWebhookSignature({
  payload, headers, secret,
  scheme: { header: 'X-Tring-Hmac', parse: (v) => ({ timestamp: null, signatures: [v] }), signedPayload: (_t, body) => body, encoding: 'base64' },
  toleranceSeconds: 0,
});

בנייה מחדש מהמפרט

החלקים המטופסים של שתי הספריות ושל שרת ה-MCP נבנים מ-spec/openapi.json:

sh
npm run spec:sync        # copy the current openapi.json into spec/
npm run generate         # rewrite the generated files
npm run generate:check   # CI: fails when a generated file or the spec copy is out of date