Integrate a CRM or SaaS

Connect your product to your customers' Tally, end to end, with working Node code.


This guide is for a developer connecting a CRM, billing tool or vertical SaaS to their customers' Tally. By the end your product can create customers in Tally, post GST invoices, record receipts, pull outstandings back, and show the true state of every write.

All the code is Node 18 or later and runs on your server.

How it fits together

Your customer's browser ──▶ your product's server ──HTTP/JSON──▶ AutoTally API ◀── extension ◀▶ Tally
                             holds one encrypted                                   on their machine
                             key per customer

Three facts shape the whole design:

  1. Your server calls the API, with your customer's key. Browsers cannot call it, and a key must never reach one.
  2. Writes are not synchronous. A commit queues a write. It lands when a person has approved it (if the key needs that) and the customer's machine is on. That can be seconds or days, so your UI needs to show a state, not a spinner.
  3. There are no webhooks. You poll for write status and for changes.

Onboard a customer

There is no OAuth for the REST API and no partner key. Each customer issues a key in their own workspace and pastes it into your product. Here is what to ask them to do. Link them to these steps from your settings screen:

  1. Sign up at www.autotally.ai and follow Connect Tally. Wait for their company to appear under Bridges.
  2. Open API keys and choose Issue key. An owner or admin has to do this, and it needs a paid seat. See API keys.
  3. Name it after your product. Turn on Allow writes, and leave Require approval on.
  4. Copy the tapi_ key into your product's settings. It is shown once.

Store the key encrypted, per customer, like a password. Then list their companies and let them pick:

// autotally.js
const BASE = "https://relay.autotally.ai";

export class AutoTallyError extends Error {
  constructor(status, body, retryAfter) {
    super(body?.message ?? body?.messages?.join("; ") ?? body?.error ?? `HTTP ${status}`);
    this.status = status;
    this.code = body?.error;
    this.body = body;
    this.retryAfter = retryAfter;
  }
}

export async function autotally(token, method, path, { body, idempotencyKey } = {}) {
  const headers = { authorization: `Bearer ${token}` };
  if (body !== undefined) headers["content-type"] = "application/json";
  if (idempotencyKey) headers["idempotency-key"] = idempotencyKey;

  const res = await fetch(`${BASE}${path}`, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
    signal: AbortSignal.timeout(30_000),
  });

  const text = await res.text();
  let data = null;
  try { data = text ? JSON.parse(text) : null; } catch { data = { error: "bad_response", message: text }; }
  if (!res.ok) throw new AutoTallyError(res.status, data, res.headers.get("retry-after"));
  return { data, status: res.status, headers: res.headers };
}

export async function withRetry(call, attempts = 5) {
  for (let i = 0; ; i++) {
    try {
      return await call();
    } catch (err) {
      const status = err.status;
      const transient = status === undefined || status === 429 || status >= 500;
      if (!transient || i >= attempts - 1) throw err;
      const wait = Math.max(Number(err.retryAfter) * 1000 || 0, 2 ** i * 1000 + Math.random() * 250);
      await new Promise((resolve) => setTimeout(resolve, wait));
    }
  }
}
// onboarding.js
export async function listCompanies(apiKey) {
  const { data } = await autotally(apiKey, "GET", "/v1/companies");
  return data.map((c) => ({ name: c.name, guid: c.guid, gstEnabled: c.features?.gst ?? null }));
}

GET /v1/companies covers every company in the customer's workspace. Save both the name and the guid: reads use the name, writes use the guid. An empty list means nothing has synced yet.

A key's writes go to its bridge. If the customer has several bridges, the key must be issued on the bridge that holds the company.

Map their ledgers

Every Tally book names things differently. Sales, Sales Accounts, Local Sales 18% are all plausible. Do not guess. Read the ledgers and let the customer choose in your settings screen:

export async function listAllLedgers(tenant) {
  const all = [];
  const company = encodeURIComponent(tenant.companyName);
  for (let page = 1; ; page++) {
    const { data } = await withRetry(() =>
      autotally(tenant.token, "GET", `/v1/ledgers?company=${company}&page=${page}&pageSize=1000`));
    all.push(...data.items);
    if (data.items.length === 0 || all.length >= data.total) return all;
  }
}

Each ledger has name, guid, parent, gstin and a few more fields. Filter by parent to narrow the dropdowns. Sales Accounts, Duties & Taxes and Bank Accounts are Tally's usual groups.

Save the choices on your customer record. The rest of this guide uses this shape:

const tenant = {
  token: decrypt(customer.autotallyKey),
  companyName: "Sharma Traders",
  companyGuid: "a1b2c3d4-0000-0000-0000-000000000001",
  ledgers: {
    sales: "Sales",
    cgst: "Output CGST 9%",
    sgst: "Output SGST 9%",
    igst: "Output IGST 18%",
    bank: "HDFC Bank",
  },
};

Map customers to ledgers

In Tally a customer is a ledger, normally under Sundry Debtors. Before you post an invoice you need the exact ledger name. Find it first, and only create it if it is truly new.

Match by GSTIN first, because names drift between systems. Then match by name.

export async function findCustomerLedger(tenant, customer) {
  const ledgers = await listAllLedgers(tenant);
  const folded = (s) => (s ?? "").trim().toLowerCase();

  const byGstin = customer.gstin
    ? ledgers.filter((l) => folded(l.gstin) === folded(customer.gstin))
    : [];
  if (byGstin.length === 1) return byGstin[0].name;
  if (byGstin.length > 1) return { needsReview: byGstin.map((l) => l.name) };

  const byName = ledgers.filter((l) => folded(l.name) === folded(customer.name));
  if (byName.length === 1) return byName[0].name;
  if (byName.length > 1) return { needsReview: byName.map((l) => l.name) };

  return null;
}

If it returns null, create the ledger. gstRegistrationDetails carries the GSTIN, and isBillWise lets Tally track invoices against it.

export function customerLedgerPayload(customer) {
  return {
    name: customer.name,
    group: "Sundry Debtors",
    isBillWise: true,
    email: customer.email,
    addresses: [{
      addressLines: customer.addressLines,
      state: customer.state,
      country: "India",
      pinCode: customer.pinCode,
    }],
    ...(customer.gstin
      ? {
          panNumber: customer.gstin.slice(2, 12),
          gstRegistrationDetails: [{
            applicableFrom: "2026-04-01",
            gstRegistrationType: "Regular",
            state: customer.state,
            placeOfSupply: customer.state,
            gstin: customer.gstin,
          }],
        }
      : {}),
  };
}

export async function createCustomerLedger(tenant, customer, { confirmedNew = false } = {}) {
  const body = {
    companyGuid: tenant.companyGuid,
    ledger: customerLedgerPayload(customer),
    ...(confirmedNew ? { acknowledge: ["similar-name"] } : {}),
  };
  const idempotencyKey = `crm:customer:${customer.id}:ledger:v1`;

  // A master dry run checks the shape only. Names are checked at commit.
  await autotally(tenant.token, "POST", "/v1/ledgers", { body, idempotencyKey });

  try {
    const { data } = await withRetry(() =>
      autotally(tenant.token, "POST", "/v1/ledgers?commit=true", { body, idempotencyKey }));
    return { intentId: data.intentId, state: data.state };
  } catch (err) {
    if (err.code === "similar_master_exists") return { needsReview: err.body.candidates };
    throw err;
  }
}

Two refusals deserve a screen of their own, because a duplicate customer ledger is painful to undo:

  • 409 similar_master_exists: the book has a ledger that looks like this one. candidates lists each with a name, a relation of identical, nearby or similar, and sometimes why. Show them to a person. If one is right, save its name against your customer. If the customer really is new, call again with confirmedNew: true, which sends "acknowledge": ["similar-name"].
  • 409 ambiguous_name: a name you used matches several records. candidates lists them with name and parent. Pick one and use its exact name.

A ledger create is a write like any other, and it may wait for approval. Wait until you can read the ledger back before you post an invoice against it: GET /v1/ledgers/<name>?company=<company> returns 200. applied is not enough. Voucher names are checked against the synced copy, so until the next sync reads the ledger the voucher is refused with no_such_master.

Push an invoice

You state each tax as a ledger entry with its amount, and the entries must net to zero with the party and sales entries. Positive is debit, negative is credit, so on a sale the party is positive and sales and tax are negative.

Same state means CGST and SGST. Different state means IGST.

Work in paise to avoid rounding drift, and put the bill on the party's entry with billAllocations. That is what makes the invoice appear in the customer's outstandings. New Ref creates a bill.

const rupees = (paise) => paise / 100;

export function salesVoucher(tenant, invoice, partyLedger) {
  const { sales, cgst, sgst, igst } = tenant.ledgers;
  const taxable = invoice.taxablePaise;
  const tax = invoice.intraState
    ? [
        { ledger: cgst, amount: -rupees(invoice.cgstPaise) },
        { ledger: sgst, amount: -rupees(invoice.sgstPaise) },
      ]
    : [{ ledger: igst, amount: -rupees(invoice.igstPaise) }];
  const total = taxable + (invoice.intraState ? invoice.cgstPaise + invoice.sgstPaise : invoice.igstPaise);

  return {
    voucherType: "Sales",
    date: invoice.date,
    voucherNumber: invoice.number,
    narration: `Invoice ${invoice.number}`,
    placeOfSupply: invoice.placeOfSupply,
    ledgerEntries: [
      {
        ledger: partyLedger,
        amount: rupees(total),
        billAllocations: [{
          name: invoice.number,
          billType: "New Ref",
          amount: rupees(total),
          dueDate: invoice.dueDate,
        }],
      },
      { ledger: sales, amount: -rupees(taxable) },
      ...tax,
    ],
  };
}

Then dry run and commit. The idempotency key comes from your invoice id, so a retry can never post a second invoice.

export function invoiceKey(invoice) {
  return `crm:invoice:${invoice.id}:v${invoice.postVersion ?? 1}`;
}

export async function pushInvoice(tenant, invoice, partyLedger, { acknowledge } = {}) {
  const body = {
    companyGuid: tenant.companyGuid,
    voucher: salesVoucher(tenant, invoice, partyLedger),
    ...(acknowledge ? { acknowledge } : {}),
  };
  const idempotencyKey = invoiceKey(invoice);

  // The dry run checks names, arithmetic, and money guards, and stores nothing.
  const { data: check } = await withRetry(() =>
    autotally(tenant.token, "POST", "/v1/vouchers", { body, idempotencyKey }));
  if (check.gates?.length && !acknowledge) return { needsReview: check.gates };

  const { data } = await withRetry(() =>
    autotally(tenant.token, "POST", "/v1/vouchers?commit=true", { body, idempotencyKey }));

  // Save this straight away. There is no endpoint to list writes.
  return { intentId: data.intentId, state: data.state, warnings: check.warnings ?? [] };
}

Things to know:

  • Send voucherNumber. It keeps your numbering in your hands and makes retries safe. If you leave it out and AutoTally allocates a number, a retry can get a different one and come back 409 idempotency_key_reused.
  • resolved on the dry run shows the voucher exactly as it would post, with each name in the book's spelling, and partyName filled in.
  • warnings do not block anything, but show them to someone. For example, ₹ and Indian scripts in a narration cannot be read back from Tally, so keep narrations to Latin characters.
  • GST rates and HSN codes are not fields on a voucher. Tally takes them from the ledger and stock item masters. partyGstin, gstRegistrationType and placeOfSupply are optional overrides.
  • A non-GST customer is the same voucher without tax entries.

Item invoices

If the customer tracks stock, add inventoryEntries. The stock line then carries the sales ledger in accountingLedger, and the sales ledger is not a top-level entry. Party and tax entries plus inventory amounts net to zero.

{
  "voucherType": "Sales",
  "date": "2026-10-15",
  "voucherNumber": "INV-1043",
  "ledgerEntries": [
    { "ledger": "Mehta Retail", "amount": 11800 },
    { "ledger": "Output CGST 9%", "amount": -900 },
    { "ledger": "Output SGST 9%", "amount": -900 }
  ],
  "inventoryEntries": [
    {
      "stockItemName": "Steel Almirah",
      "quantity": 2,
      "rate": 5000,
      "amount": -10000,
      "accountingLedger": "Sales"
    }
  ]
}

Record a receipt

When your CRM records a payment, post a Receipt. The bank is debited, the party is credited, and Agst Ref settles the invoice by its bill name. Bill allocation amounts carry the same sign as the entry they sit on.

export function receiptVoucher(tenant, payment, partyLedger) {
  const amount = rupees(payment.amountPaise);
  return {
    voucherType: "Receipt",
    date: payment.date,
    voucherNumber: payment.number,
    narration: `Payment ${payment.reference} against ${payment.invoiceNumber}`,
    ledgerEntries: [
      {
        ledger: tenant.ledgers.bank,
        amount,
        bankAllocations: [{ transferMode: "NEFT", utr: payment.reference, instrumentDate: payment.date }],
      },
      {
        ledger: partyLedger,
        amount: -amount,
        billAllocations: [{ name: payment.invoiceNumber, billType: "Agst Ref", amount: -amount }],
      },
    ],
  };
}

export async function pushReceipt(tenant, payment, partyLedger) {
  const body = { companyGuid: tenant.companyGuid, voucher: receiptVoucher(tenant, payment, partyLedger) };
  const idempotencyKey = `crm:payment:${payment.id}:v1`;
  await withRetry(() => autotally(tenant.token, "POST", "/v1/vouchers", { body, idempotencyKey }));
  const { data } = await withRetry(() =>
    autotally(tenant.token, "POST", "/v1/vouchers?commit=true", { body, idempotencyKey }));
  return { intentId: data.intentId, state: data.state };
}

Splitting a payment across invoices? Add one Agst Ref allocation per invoice, summing to the party entry's amount. A payment with no invoice yet takes "billType": "Advance" with a name of your choice, or "billType": "On Account" with no name. If the bill name is not found on the dry run, you get an unknown_bill_reference warning, not an error. The usual cause is that the invoice has not synced yet.

Follow a write

Poll GET /v1/intents/<intentId> from a background job. It returns:

{
  "state": "applied",
  "resultGuid": "9f8e7d6c-0000-0000-0000-000000000042",
  "resultMasterId": 18274,
  "resultVoucherNumber": "INV-1042",
  "error": null
}

There is no list of writes, so keep every intentId you are given. Polling every 30 seconds while a write is moving is plenty. Slow right down once it has been pending for a while, since a person may take days.

The write state machine

             approve (a person), or no approval needed
  pending ──────────────────────────────────▶ claimed ──▶ applied ──▶ read back: confirmed
     │                                           │   │
     │ reject (a person) or retract              │   └──▶ submitted (reply unreadable)
     ▼                                           ▼
  rejected                                    failed
state Terminal? Show in your UI What your job does
pending No "Waiting in Tally queue: may need approval in AutoTally" Keep polling. Ask the customer to check Agent activity if it sits for long
claimed No "Sending to Tally" Keep polling. If the extension loses it, it can go back to pending
submitted No "Sent. Checking Tally" Keep polling. If it stays here, ask someone to look in Tally. Do not post again
applied, resultGuid null No, for your purposes "Accepted by Tally. Confirming" Keep polling for up to 30 minutes while the extension is online. If it stays null, do not resend. Search GET /v1/vouchers for the voucher number or date and party, and mark it for a person to check
applied, resultGuid set Yes, once read back "In Tally" GET the voucher to confirm, then stop
failed Yes "Failed: error" Stop. Show error. Never resend automatically: some failures changed the book or left the result unknown. See Errors. A person checks Tally and fixes the cause, then you send with a new key
rejected Yes "Rejected in AutoTally" Stop. Ask your user what to do. The reason is not in the API

Two limits of this API:

  • pending covers both "waiting for a person" and "approved, waiting for the machine". You cannot tell them apart, so word your UI to cover both.
  • If the customer's machine is off, writes wait in pending with no expiry.
export async function followWrite(tenant, intentId) {
  const { data: w } = await withRetry(() =>
    autotally(tenant.token, "GET", `/v1/intents/${encodeURIComponent(intentId)}`));

  if (w.state === "failed") return { status: "failed", reason: w.error };
  if (w.state === "rejected") return { status: "rejected" };
  if (w.state !== "applied" || !w.resultGuid) return { status: "in_progress", state: w.state };

  // `applied` is Tally's word. The read back is the proof.
  const company = encodeURIComponent(tenant.companyName);
  try {
    const { data: voucher } = await autotally(tenant.token, "GET",
      `/v1/vouchers/${encodeURIComponent(w.resultGuid)}?company=${company}`);
    return { status: "confirmed", guid: voucher.guid, voucherNumber: voucher.voucherNumber };
  } catch (err) {
    if (err.status === 404) return { status: "in_progress", state: w.state };
    throw err;
  }
}

For a master, there is no voucher to fetch. When the write is applied, re-read it by name: GET /v1/ledgers/<name>?company=<company>. A 404 means it has not synced yet.

For a voucher delete, do not wait on resultGuid. When the write is applied, read the voucher by its own guid until you get 404. A deletion takes longer to show than an edit. See Synced data and freshness.

Approval

If the key has Require approval on, nothing reaches Tally until a person in the customer's workspace approves it. Your key cannot approve or reject. The customer goes to Agent activity in their workspace at www.autotally.ai/app and chooses Approve write or Reject. See Approving writes.

Tell them about this in onboarding. A good screen says: "12 invoices are waiting for approval in AutoTally", with a link. Once they trust your integration, an owner or admin can issue a key with approval off. Writes then go straight to Tally, so keep your dry runs and checks in place.

Cancel a queued write

If the invoice is voided in your CRM while the write still waits for approval, take it back:

export async function retractWrite(tenant, intentId, reason) {
  const { data } = await autotally(tenant.token, "POST",
    `/v1/intents/${encodeURIComponent(intentId)}/supersede`, { body: { reason } });
  return data.superseded ? { retracted: true } : { retracted: false, why: data.reason };
}

This works only while the write is pending and nobody has approved it. Otherwise you get 200 with superseded: false and a reason of already-applied, failed, already-withdrawn or approved-and-in-flight. An applied voucher has to be deleted.

Pull outstandings back

GET /v1/outstandings returns open bills for a company, and party narrows it to one exact ledger name. It is not paged.

export async function outstandingFor(tenant, partyLedger) {
  const company = encodeURIComponent(tenant.companyName);
  const party = encodeURIComponent(partyLedger);
  const { data, headers } = await withRetry(() =>
    autotally(tenant.token, "GET", `/v1/outstandings?company=${company}&party=${party}`));

  const summary = data.parties?.find((p) => p.party === partyLedger);
  return {
    asOf: headers.get("x-tally-synced-at"),
    total: summary ? Number(summary.outstanding) : null,
    bills: data.bills.map((b) => ({
      invoiceNumber: b.billName,
      dueDate: b.dueDate,
      overdueDays: b.overdueDays,
      open: Number(b.openAmount ?? b.amount ?? 0),
    })),
  };
}

Use openAmount when it is there. It is what is really still open once on-account receipts are applied, while amount is Tally's raw bill-wise figure. Amounts are signed: a positive amount is money owed to your customer.

parties[].outstanding is what the party owes overall, taken from the ledger's closing balance where the two can be reconciled. parties can be absent, so treat a missing one as "not computed", not zero.

Your invoice number comes back as billName, because you sent it as the New Ref name. That is how you match bills to invoices.

Do not mark an invoice paid only because its bill is missing from a response. First check GET /v1/status: the OutstandingBill entry for the company should have a recent lastSyncedAt. An unsynced company returns no bills at all, and that must not read as "everything is paid". Show the date from X-Tally-Synced-At beside the figure.

To sync on a schedule, see Keeping data in sync.

Retries and dedupe

One idempotency key per logical write, derived from your own record:

Write Key
Create a customer ledger crm:customer:<id>:ledger:v1
Post an invoice crm:invoice:<id>:v1
Record a payment crm:payment:<id>:v1
Edit a posted invoice crm:invoice:<id>:edit:<revision>
Delete a posted invoice crm:invoice:<id>:delete:v1

Keys are shared across the customer's workspace and do not expire, so include enough to be unique. Build the payload the same way every time: a retry with the same key and a different payload gets 409 idempotency_key_reused.

What happened What to do
Network error, timeout, 429, 500, 503 Retry with the same key and body, with backoff
202 with "deduped": true Your first attempt landed. Use this intentId
409 idempotency_key_reused Stop. Read the first attempt's result before you write again
422 gate_blocked, duplicate-bill The party already has this bill from another voucher. See below
Write failed or rejected It stays that way under its key. A person checks Tally and fixes the cause, then you bump postVersion and send again

Retrying an invoice. Resend the same body with the same key. A first attempt that got through comes back with "deduped": true, and a New Ref bill on it does not trip the duplicate-bill guard. A 422 gate_blocked with duplicate-bill on a first attempt means the bill came from somewhere else.

Save your state in this order, so a crash between steps cannot lose a write:

  1. Mark the invoice "posting" with its idempotency key.
  2. Commit.
  3. Save the intentId.

Failure handling

Symptom Likely cause Your response
401 The customer revoked or rotated the key Stop all jobs for them. Ask for a new key
402 plan_required Their plan lapsed or a seat is missing Show a banner. Hold commits. Dry runs still work
409 no_such_master A ledger was renamed in Tally, or the mapping is stale Reopen the ledger mapping screen
409 masters_not_synced First sync is not finished Wait, and check /v1/status
400 invalid_voucher, numbering message This voucher type needs a number Send voucherNumber
Writes stuck in pending Waiting on a person, or the machine is off Check tallyReachable on /v1/status, and show both possibilities
failed with Tally's error Tally refused the voucher Show error to a person. Retry with a new key after the fix

See Errors for every code.

Edits work the same way as posts. PATCH /v1/vouchers/<guid> replaces the whole voucher, so send every entry. See the alter recipe.

Go-live checklist

  • Keys are encrypted at rest, per customer, and never reach a browser or a log.
  • Every API call is made from your server.
  • Your ledger mapping is chosen by the customer, not hard-coded.
  • Idempotency keys come from your record ids and are stable across retries.
  • You send voucherNumber on every voucher.
  • You save every intentId as soon as you get it.
  • A dry run with companyGuid runs before every voucher commit, and gates go to a person.
  • You handle gate_blocked, similar_master_exists, ambiguous_name and no_such_master on commit, not only on the dry run.
  • Your UI shows all write states, including submitted, failed and rejected.
  • "In Tally" only shows after the read back, not at applied.
  • A retried invoice uses the same key and body, and treats "deduped": true as the first attempt.
  • Amounts are calculated in paise and parsed defensively on reads.
  • Every figure you show from Tally carries its synced-at date.
  • You check tallyReachable and show when the customer's machine is off.
  • Statements are checked for status before you read figures.
  • You have tested on a copy of a company, with approval on, through to a confirmed read back.