Tring for developers עברית

SDKs

Both SDKs are generated from the OpenAPI spec: every operation of the API is a method named by its operationId (camelCase in TypeScript, snake_case in Python), with the request and answer types of the spec. A thin hand-written layer adds retries, errors and helpers.

TypeScript / JavaScriptPython
Installnpm install tring-sdkpip install tring-sdk
RuntimeNode 18+, Bun, Deno; ESM3.9+, sync and async (httpx)
Clientnew Tring()Tring() / AsyncTring()

Configuration

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

A kbl_live_ key against the sandbox address, or a kbl_test_ key against production, is refused before anything is sent. Printing the client shows the public part of the key only.

Calling operations

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

Request bodies use the API's field names (docType, documentDate) in both languages, so the JSON in the docs and in the spec can be pasted as it is.

Prepare and confirm in one call

issue() prepares, lets you look at the draft, and confirms. If the key was already used for this request and became a document, it returns that document and issues nothing.

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

Sending a file

An operation that takes a file (the supplier's receipt of an expense, putExpenseReceipt) takes the file itself as the body, not JSON: its bytes, sent with its media type (image/jpeg, image/png or application/pdf, at most 5 MiB). Pass a Buffer, Uint8Array, ArrayBuffer, Blob or File in JavaScript; bytes, a path or a file opened with "rb" in Python. The media type is read from the first bytes when you leave it out (contentType / content_type says it), and the name of a File or a path names the stored file unless fileName / file_name does. A file whose first bytes are not the media type it was sent as is refused (422 EXPENSE_REFUSED, details.file: "file-kind"); the same file again stores nothing ("replayed": true). The download (getExpenseReceipt) hands back the same bytes.

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'}`);

Retries

Each operation has a retry policy, generated from the spec (spec/retry-policy.json and the x-tring-retry field):

PolicyOperationsSent again after
safeevery GETa lost answer, 502, 503, 504, 429
idempotentprepare, add a business, uniform export, backups, allocation numbera lost answer, 504 OUTCOME_UNKNOWN, 429; with the same Idempotency-Key
confirmconfirmthe same, until the outcome is known (confirmMaxRetries)
unsafelinks, emails, cancellation, consent429 and 503 UNAVAILABLE only: requests the service did not process

The wait follows Retry-After when the answer has one, otherwise 0.5 s doubled each time with jitter.

Errors

Class (JS / Python)When
TringApiErrorThe API answered with its error body. code, status, details, issues, requestId, retryAfter.
TringOutcomeUnknownErrorA confirm still has no known outcome. Confirm draftId again later; never prepare again.
TringConnectionErrorNo answer, and the request was not safe to send again. mayHaveTakenEffect tells whether it changes something.
TringConfigErrorWrong use, such as a missing key or Idempotency-Key. Nothing was sent.
TringApprovalDeclinedErrorissue() was declined by approve. Nothing was issued.
TringSignatureErrorA webhook signature did not verify.
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;
}

Pagination

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

Helpers

JSPythonDoes
amount(118)amount(118)"118.00"; refuses more than two decimals instead of rounding
quantity(2)quantity(2)"2.0000"
todayInIsrael()today_in_israel()today's date in Asia/Jerusalem, "YYYY-MM-DD"
idempotencyKey('order', 1001, 400)idempotency_key("order", 1001, 400)"order-1001-400", checked
DocType.ReceiptDocType.RECEIPT400, and the other types
PaymentMethod.BankTransferPaymentMethod.BANK_TRANSFER4, and the other methods
redactKeys(text)redact_keys(text)keeps only the public part of any key in a log line
fileMediaType(bytes)file_media_type(data)the media type the first bytes of a file say (application/pdf, image/jpeg, image/png), as the API reads it; null / None otherwise

Webhook signatures

Check the signature on the raw body before you act on a notice. The helpers follow the service's format: Tring-Signature: t=<unix seconds>,v1=<hex>, HMAC-SHA256 of <t>. and the raw bytes, two v1 during a rotation, 300 seconds of tolerance. The events, registering an address and retries are on Webhooks and events.

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

The header name, its parsing and the signed text are a scheme option, so a different format is a configuration change:

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

Regenerating from the spec

The typed parts of both SDKs and of the MCP server come from 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