ספריות SDK
שתי הספריות נבנות מתוך מפרט ה-OpenAPI: כל פעולה של ה-API היא מתודה בשם ה-operationId שלה (camelCase ב-TypeScript, snake_case בפייתון), עם טיפוסי הבקשה והתשובה מהמפרט. שכבה דקה שנכתבה ביד מוסיפה שליחה חוזרת, שגיאות ופונקציות עזר.
| TypeScript / JavaScript | Python | |
|---|---|---|
| התקנה | npm install tring-sdk | pip install tring-sdk |
| סביבה | Node 18 ומעלה, Bun, Deno; ESM | 3.9 ומעלה, סינכרוני ואסינכרוני (httpx) |
| לקוח | new Tring() | Tring() / AsyncTring() |
הגדרות
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
});from tring_sdk import Tring
tring = Tring(
api_key=None, # default: TRING_API_KEY
base_url=None, # default: by the key's prefix
timeout=60.0, # one attempt, seconds
max_retries=2, # reads and idempotent requests
confirm_max_retries=8, # a confirm whose outcome is unknown
app_info="my-shop/1.4", # added to the User-Agent
)מפתח kbl_live_ מול כתובת סביבת הניסוי, או מפתח kbl_test_ מול הייצור, נדחים לפני שנשלח משהו. הדפסת הלקוח מציגה רק את החלק הציבורי של המפתח.
קריאה לפעולות
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 } });page = tring.list_documents(issuer_id, doc_type=400, from_="2026-11-01", limit=50)
doc = tring.get_document(page["items"][0]["id"])
pdf = tring.download_document(doc["id"]) # bytes, a signed copy
link = tring.create_document_link(doc["id"], {"recipientName": "ישראלה ישראלי"})
# any operation by name
same = tring.request("listDocuments", path={"issuerId": issuer_id}, query={"limit": 50})גוף הבקשה משתמש בשמות השדות של ה-API (docType, documentDate) בשתי השפות, כך שאפשר להדביק כמו שהוא את ה-JSON שבתיעוד ובמפרט.
הכנה ואישור בקריאה אחת
issue() מכינה, נותנת לכם לבדוק את הטיוטה, ומאשרת. אם המפתח כבר שימש לאותה בקשה והפך למסמך, היא מחזירה את המסמך ולא מפיקה שוב.
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
});document = tring.issue(
issuer_id,
body,
idempotency_key=f"order-{order.id}-receipt",
approve=lambda draft: draft["document"]["amounts"]["total"] == order.total,
)שליחת קובץ
פעולה שמקבלת קובץ (הקבלה של הספק על הוצאה, 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) מחזירה את אותם בתים.
// 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'}`);# Record an expense and attach the supplier's receipt (a JPEG, PNG or PDF), then read the file back.
# Run: python expense-receipt.py receipt.pdf (reads TRING_API_KEY, TRING_ISSUER_ID and, if set, TRING_BASE_URL)
import os
import sys
from pathlib import Path
from tring_sdk import Tring, amount, today_in_israel
tring = Tring()
issuer_id = os.environ["TRING_ISSUER_ID"]
path = Path(sys.argv[1] if len(sys.argv) > 1 else "receipt.pdf")
expense = tring.create_expense(
issuer_id,
{"date": today_in_israel(), "supplier": "ספק לדוגמה", "amount": amount(118), "vat": amount(18), "category": "office"},
idempotency_key="expense-2026-0042", # one key per expense
)["expense"]
# The body is the file itself: a path (its name names the file), bytes, or a file opened with "rb".
# Its media type is read from its first bytes; pass content_type= to say it.
attached = tring.put_expense_receipt(issuer_id, expense["id"], path)
receipt = attached["expense"]["receipt"]
assert receipt is not None
print(f"{'Already attached' if attached['replayed'] else 'Attached'}: {receipt['fileName']} ({receipt['mediaType']}, {receipt['sizeBytes']} bytes)")
back = tring.get_expense_receipt(issuer_id, expense["id"]) # bytes, byte for byte as sent
print(f"Read back {len(back)} bytes, {'the same file' if back == path.read_bytes() else '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 חסר. לא נשלח כלום. |
TringApprovalDeclinedError | approve דחתה ב-issue(). לא הופק כלום. |
TringSignatureError | חתימת webhook לא אומתה. |
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;
}from tring_sdk import TringApiError
try:
tring.prepare_draft(issuer_id, body, idempotency_key=key)
except TringApiError as err:
if err.code != "DOCUMENT_REFUSED":
raise
for issue in err.issues:
print(issue["code"], issue["path"])דפדוף
for await (const doc of tring.paginate((cursor) => tring.listDocuments(issuerId, { cursor }))) {
console.log(doc.number, doc.total);
}for doc in tring.paginate(lambda cursor: tring.list_documents(issuer_id, cursor=cursor)):
print(doc["number"], doc["total"])פונקציות עזר
| JS | Python | מה עושה |
|---|---|---|
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.Receipt | DocType.RECEIPT | 400, ושאר הסוגים |
PaymentMethod.BankTransfer | PaymentMethod.BANK_TRANSFER | 4, ושאר אמצעי התשלום |
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 ואירועים.
// 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() is the raw body
try:
event = construct_webhook_event(request.get_data(), headers=request.headers, secret=[WEBHOOK_SECRET])
except TringSignatureError:
abort(400)שם הכותרת, הפירוק שלה והטקסט שנחתם הם האפשרות scheme, כך שפורמט אחר הוא שינוי הגדרה:
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:
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