WeSaveTax
Back to portal

WeSaveTax Partner Integration

Embed GST invoicing, payment tracking, and compliance into your product in a weekend.

WeSaveTax provides a complete GST billing platform that can be embedded inside any CRM, ERP, or business software via iframe. Partners get full invoicing, GST filing, buyer/item sync, and webhook events — without building any billing infrastructure.


#Getting Started

1
Get credentials
WeSaveTax issues your API Key, Embed Secret, and Webhook Secret — a live set and a sandbox set.
2
Sync data
Push your buyers and items via the REST API before embedding.
3
Embed & listen
Render the iframe in your frontend and listen for postMessage events.

#Onboarding Flow

When a company completes your onboarding form, call POST /provision from your backend with all their details — business info, bank details, and logo URL. This creates their full WeSaveTax account in one call, no setup wizard needed.

  1. 1Company completes your onboarding form with business details.
  2. 2Your backend calls POST /provision with all their info — business name, GSTIN, address, bank details, logo URL.
  3. 3WeSaveTax creates a fully configured billing account with billing profile populated.
  4. 4Embed the iframe for that company — the setup wizard opens pre-filled with what you sent, and one confirmation finishes onboarding.

Example — provision a company with full details

json
{
  "partnerTenantId":  "company_123",
  "partnerUserEmail": "owner@abctraders.com",
  "businessName":     "ABC Traders",
  "legalName":        "ABC Traders Pvt Ltd",
  "gstin":            "27AAACR5055K1Z5",
  "state":            "Maharashtra",
  "address": {
    "street":  "123 MG Road",
    "city":    "Mumbai",
    "pincode": "400001"
  },
  "bankDetails": {
    "bank":      "HDFC Bank",
    "accountNo": "12345678901234",
    "ifsc":      "HDFC0001234",
    "branch":    "Andheri West"
  }
}
Tip:Logos are not accepted from partners; the business adds its own in Settings. The legalName field is stored on the billing profile — used on invoice headers for companies where the trading name differs from their registered legal name.

#Credentials

CredentialFormatUsed For
API Keytxe_partner_{id}_{hex}Server-to-server API calls. Send as Authorization: Bearer header.
Embed Secret64 hex charsSign iframe JWT tokens with HS256.
Webhook Secret32 hex charsVerify HMAC-SHA256 webhook signatures.

You receive two sets: live (partner id {id}, API key txe_partner_{id}_{hex}) and sandbox (partner id {id}_sandbox, API key txe_partner_{id}_sandbox_{hex}). The partnerId you put in the embed JWT decides which set is used — sign it with that set's Embed Secret.

Warning:Credentials are shown once on creation. Store them securely in environment variables. Never commit them to git.

#API keys and scopes

Your existing API key has full access and is unchanged. On request, WeSaveTax can issue extra keys for the same partner account, for example a read-only key for a reporting tool. Each key has a label and is shown once when it is issued. There is no self-serve key management yet; ask WeSaveTax support. Revoking a key takes effect immediately.

ScopeAllowed
fullEvery request.
readGET and HEAD requests, plus these read-only POST routes: /invoices/preview.

A read key used on a request that would change data gets 403 with code KEY_SCOPE_INSUFFICIENT (error.details.scope is read). An unknown or revoked key is 401 UNAUTHORIZED.

All keys share your rate limit, usage counters and webhook settings. The embed token exchange is not affected by API keys.


#Merchants that are unregistered or on the composition scheme

WeSaveTax decides the document from the merchant, not from your request. You do not send a document type.

MerchantDocument issued (documentType)
Registered, billing profile has a GSTINtax_invoice
Unregistered, or the billing profile has no GSTINunregistered_invoice
Composition schemebill_of_supply

An invoice dated before a merchant switched from unregistered to regular is also an unregistered_invoice.

No GST is charged on an unregistered invoice or a bill of supply. If a line carries a gstRate other than 0, the rate is ignored, the line is issued at 0%, and the response carries a TAX_NOT_APPLICABLE warning in warningDetails with details.documentType and details.ignoredRates (the distinct rates you sent). The invoice total is the taxable amount; a CRM that sends 18% will not see 18% charged. The rates counted include those on additionalCharges (a shipping charge at 18% is ignored the same way). The warning appears whenever the issued document is not a tax invoice and a rate you sent was ignored, whatever the merchant's scheme (a merchant with no GSTIN on its billing profile, or an invoice dated before the switch to regular, is issued an unregistered_invoice); nothing is raised for a tax invoice or for rates at 0%.

POST /invoices/preview returns the same documentType, totals and warning as the create would, so you can show the merchant what will be issued.

documentType appears on: the POST /invoices 201 body, the preview body, GET /invoices/{id}, every row of GET /invoices (including the updatedSince / cursor reconcile rows), and the payload of every invoice.* webhook. It is tax_invoice when none is stored.

Composition scheme support needs a plan that includes it. Without it the request is refused with 403 PLAN_UPGRADE_REQUIRED and error.details.scheme is composition. A credit note against an invoice keeps that invoice's document type.


#Embed Integration

#How It Works

  1. 1Your backend generates a signed JWT (30 min max expiry, unique jti per token) using Embed Secret.
  2. 2Your frontend renders an iframe: https://staging.wesavetax.com/embed?token={jwt} (production: https://www.wesavetax.com/embed?token={jwt}).
  3. 3WeSaveTax verifies the JWT, authenticates the user, loads the portal.
  4. 4User interacts with full WeSaveTax portal inside your app.
  5. 5Events fire back via window.postMessage.

#JWT Token Format

js
import jwt from "jsonwebtoken";
import { randomUUID } from "crypto";

const token = jwt.sign(
  {
    // Required
    partnerId:        "your_partner_id",
    partnerTenantId:  "company_123",      // YOUR id for the end customer's business — one per company
    partnerUserEmail: "user@company.com",

    // Required — MUST be unique per token. WeSaveTax rejects any jti
    // it has already seen within the token's lifetime (single-use).
    jti:              randomUUID(),

    // Optional: pre-fill company info for setup wizard
    companyName:    "ABC Traders",
    companyGstin:   "27AAACR5055K1Z5",
    companyState:   "Maharashtra",
    companyAddress: {
      street:  "123 MG Road",
      city:    "Mumbai",
      pincode: "400001"
    },

    // Optional: for deal deep link context
    context:  "deal",
    entityId: "prefill_token_from_invoices_prefill_api",
  },
  process.env.WESAVETAX_EMBED_SECRET, // Example only — replace with your actual secret from the partner admin dashboard
  { expiresIn: "30m", algorithm: "HS256" } // Max 30 min from iat — WeSaveTax rejects older tokens
);

const embedUrl = `https://staging.wesavetax.com/embed?token=${token}`;

#Embed Contexts

context valueentityId required?What opens in the embed
billing (default)NoFull WeSaveTax dashboard
dealYes — prefillToken from POST /invoices/prefillInvoice builder pre-filled with deal buyer + line items
contactYes — taxEasyyBuyerIdBuyer detail and transaction history

#Setup Wizard

The first time a company connects, WeSaveTax shows a 4-step setup wizard automatically:

  • → Step 1: Confirm business details (pre-filled from JWT payload)
  • → Step 2: Add bank details
  • → Step 3: Upload logo (optional)
  • → Step 4: Set the invoice number prefix

After completion the full portal loads. Never shown again for that company.

Tip:Pre-fill companyName, companyGstin, companyState, and companyAddress in the JWT payload to skip manual entry in Step 1.

#Session Expiry & Refresh

When the embed is opened with an expired token (older than 30 minutes), WESAVETAX_SESSION_EXPIRED fires. Your app should:

js
window.addEventListener("message", async (event) => {
  if (event.data.type !== "WESAVETAX_SESSION_EXPIRED") return;

  // Fetch a fresh token from your backend
  const { token } = await fetch("/api/wesavetax/embed-token").then(r => r.json());

  // Reload the iframe with the new token
  const iframe = document.getElementById("wesavetax-embed");
  iframe.src = `https://staging.wesavetax.com/embed?token=${token}`;
});

#REST API Reference

Base URLStaging: https://staging.wesavetax.com/api/connect/v1Production: https://www.wesavetax.com/api/connect/v1
Auth headerAuthorization: Bearer {your_api_key}

All requests: Content-Type: application/json

#Field names: reading vs writing

Item reads (GET /items, GET /items/:id) use different field names from the write endpoints (items/upsert, items/sync, invoices). Send the write name. The read name is also accepted as an alias on writes, so an item you just read can be sent straight back; if you send both, the write name is used.

MeaningWrite name (preferred)Read name (also accepted)Where
Item or line nametitlenameitems/upsert, items/sync
Line descriptiondescriptionnameinvoices (lineItems)
HSN / SAC codehsnhsnCodeitems/upsert, items/sync, invoices (lineItems)
WeSaveTax item idsavedItemIdtaxEasyyItemIdinvoices (lineItems)
Note:Unrecognised fields are ignored, not rejected. A field we don't know (for example medicineId, or a misspelt hsn) is dropped and the response lists it in warnings, e.g. "Line 1: unrecognised field "medicineId" ignored.". Check warnings after your first call to each endpoint. This applies to buyers/upsert, buyers/sync, items/upsert, items/sync and invoices. Buyer fields use the same names for reading and writing.

#GET/verify

Confirm your API key is valid. Use this to test credentials and check connectivity.

bash
curl https://staging.wesavetax.com/api/connect/v1/verify \
  -H "Authorization: Bearer txe_partner_yourname_sandbox_abc123"

Response

json
{
  "valid": true,
  "partnerId": "your_partner_id",
  "mode": "sandbox"
}

#POST/provision

Create a WeSaveTax account for a company in your platform. Call this when a company first connects, OR let the embed setup wizard handle it automatically.

Request body

json
{
  "partnerTenantId":  "company_123",
  "partnerUserEmail": "owner@company.com",
  "businessName":     "ABC Traders",
  "gstin":            "27AAACR5055K1Z5",
  "legalName":        "ABC Traders Pvt Ltd",
  "state":            "Maharashtra",
  "address": {
    "street":  "123 MG Road",
    "city":    "Mumbai",
    "pincode": "400001"
  },
  "bankDetails": {
    "bank":      "HDFC Bank",
    "accountNo": "12345678901234",
    "ifsc":      "HDFC0001234",
    "branch":    "Andheri West"
  },
  "invoicePrefix":  "ABC",
  "startingNumber": 101
}
Note:All fields except partnerTenantId, partnerUserEmail, and businessName are optional. invoicePrefix (up to 10 letters, digits, / or -) and startingNumber (a positive whole number) set the merchant's invoice numbering and apply only when this call creates the merchant. If the merchant numbers invoices by year, startingNumber applies again at the start of each new year's series. Each merchant needs its own partnerUserEmail: reusing one for a second partnerTenantId is refused with EMAIL_EXISTS_TENANT_MISMATCH; nothing is merged.

Responses

json
// New account created (201)
{ "success": true, "isNew": true, "alreadyExists": false, "clientId": "...", "billingProfileId": "..." }

// partnerTenantId already provisioned (200) — nothing is updated
{ "success": true, "isNew": false, "alreadyExists": true, "clientId": "...", "billingProfileId": "..." }
Note:Provisioning is create-only: calling it again for the same partnerTenantId returns the existing account and does not change any details.

Refusals

StatuscodeMeaning
409EMAIL_EXISTS_NEEDS_CONSENTThe email already has its own WeSaveTax account
409EMAIL_BELONGS_TO_OTHER_PARTNERThe email belongs to another partner's company
409EMAIL_EXISTS_TENANT_MISMATCHThe email is already used by a different partnerTenantId of yours
409GSTIN_ALREADY_PROVISIONEDThe GSTIN already has a WeSaveTax account
403PARTNER_CLIENT_LIMIT_REACHEDYour live company limit is reached — contact WeSaveTax

#GET/billing-profile

Read a company's billing profile — business details, bank info, and logo.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company

Response

json
{
  "businessName": "ABC Traders",
  "legalName":    "ABC Traders Pvt Ltd",
  "gstin":        "27AAACR5055K1Z5",
  "state":        "Maharashtra",
  "address":      "123 MG Road",
  "city":         "Mumbai",
  "pincode":      "400001",
  "country":      "IN",
  "bankDetails": {
    "bank":      "HDFC Bank",
    "accountNo": "...",
    "ifsc":      "HDFC0001234",
    "branch":    "Andheri West"
  },
  "logo": { "url": "https://..." }
}

#PATCH/billing-profile

Change a company's invoice prefix and starting number. Allowed only until the company has used its first invoice number; after that it is refused with 409 NUMBERING_LOCKED, because GST rules require invoice numbers to run in one unbroken series.

json
{ "partnerTenantId": "company_123", "invoicePrefix": "ABC", "startingNumber": 101 }

// 200
{ "invoicePrefix": "ABC", "startingNumber": 101 }

#GET/buyers

List all buyers/customers for a company. Use this to show existing WeSaveTax buyers in your UI.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company
pageNoPage number (default: 1)
limitNoResults per page (default: 50, max: 100)
searchNoSearch by buyer name or GSTIN

Response

json
{
  "data": [
    {
      "taxEasyyBuyerId":     "64f1a2b3c4d5e6f7a8b9c0d1",
      "partnerContactId":    "contact_456",
      "legalName":           "Reliance Industries Ltd",
      "gstin":               "27AAACR5055K1Z5",
      "gstRegistrationType": "regular",
      "billingAddress": {
        "street":  "3rd Floor, Maker Chambers IV",
        "city":    "Mumbai",
        "state":   "Maharashtra",
        "pincode": "400021"
      },
      "createdAt": "2026-06-22T10:30:00.000Z"
    }
  ],
  "pagination": { "page": 1, "limit": 50, "total": 45, "totalPages": 1 }
}
Note:gstRegistrationType values: regular · composition · unregistered · consumer · sez · government (default: unregistered)

#GET/buyers/:id

Fetch a single buyer by their taxEasyyBuyerId.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company

Response

Single buyer object — same shape as a list item.

#POST/buyers/upsert

Sync a contact from your CRM as a buyer in WeSaveTax. Call this before /invoices/prefill so the buyer exists.

Request body

json
{
  "partnerTenantId":     "company_123",
  "partnerContactId":    "contact_456",
  "legalName":           "Reliance Industries Ltd",
  "gstin":               "27AAACR5055K1Z5",
  "gstRegistrationType": "regular",
  "billingAddress": {
    "street":  "3rd Floor, Maker Chambers IV",
    "city":    "Mumbai",
    "state":   "Maharashtra",
    "pincode": "400021"
  }
}

Response

json
{ "taxEasyyBuyerId": "64f1a2b3c4d5e6f7a8b9c0d1", "isNew": true }
FieldRequiredNotes
partnerContactIdYesYour id for the contact. It is how we match this buyer on later calls
legalNameYesShown as the buyer's name in WeSaveTax (both the B2B and B2C lists)
gstinNoWith a GSTIN the buyer is B2B; without one it is B2C unless you send buyerType
gstRegistrationTypeNoregular, composition, unregistered, consumer, sez or government
buyerTypeNoB2B or B2C. An update never changes the type unless you send this
pan, email, phoneNoOptional contact and tax details
billingAddressNostreet, city, state, stateCode, pincode, country
gstStateCodeNoTwo-digit state code. Defaults to the first two digits of the GSTIN, then billingAddress.stateCode
Note:How a buyer is matched. First by partnerContactId; if there is none and you sent a GSTIN, by GSTIN. A GSTIN match on a buyer the company added by hand in WeSaveTax updates that buyer with the fields you sent and links it to your partnerContactId. Otherwise a new buyer is created. Partner buyers appear in the company's normal Buyers list.
Note:Store taxEasyyBuyerId in your CRM — use it to avoid re-syncing the same contact repeatedly. Fields not listed above (for example tradeName or companyName) are ignored and returned as "warnings": ["Unrecognised field "companyName" ignored."].

#POST/buyers/sync

Bulk upsert up to 200 buyers in one call. Use on first connect to sync all your contacts.

Request body

json
{
  "partnerTenantId": "company_123",
  "buyers": [
    {
      "partnerContactId":    "contact_001",
      "legalName":           "Tata Consultancy Services",
      "gstin":               "27AAACR5055K1Z5",
      "gstRegistrationType": "regular"
    },
    {
      "partnerContactId": "contact_002",
      "legalName":        "Walk-in Customer",
      "gstRegistrationType": "consumer"
    }
  ]
}

Response

json
{ "synced": 2, "created": 1, "updated": 1, "failed": 0, "errors": [] }

Same fields and matching rules as /buyers/upsert. When a buyer carries a field we don't recognise, the response adds "warnings": ["Buyer 1: unrecognised field "companyName" ignored."] (the number is the buyer's position in your list).

The whole body is validated before anything is saved. If any buyer is malformed the call answers 400 VALIDATION_FAILED, error.field names the record (for example buyers.1.email) and nothing is written; fix it and resend the batch. In a 200 response, failed and errors cover only buyers that passed validation but could not be saved; each is listed as { partnerContactId, error } and the rest are still saved.

#GET/items

List all items/products for a company, scoped to tenant. Use this to show existing WeSaveTax items in your UI — for example, when building a prescription or selecting products.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company
pageNoPage number (default: 1)
limitNoResults per page (default: 50, max: 100)
searchNoSearch by item name

Response

json
{
  "data": [
    {
      "taxEasyyItemId": "64f1a2b3c4d5e6f7a8b9c0d2",
      "partnerItemId":  "item_789",
      "name":           "Website Design",
      "rate":           50000,
      "unit":           "NOS",
      "hsnCode":        "998314",
      "gstRate":        18,
      "imageUrl":       "https://res.cloudinary.com/wesavetax/image/upload/v1/wesavetax/item-images/abc123.jpg",
      "barcode":        null,
      "trackInventory": false,
      "currentStock":   null,
      "createdAt":      "2026-06-22T10:30:00.000Z"
    }
  ],
  "pagination": { "page": 1, "limit": 50, "total": 45, "totalPages": 1 }
}
Note:API field names are name (mapped from internal title) and hsnCode (mapped from internal hsn). Use these exact field names when reading item data. Writes (items/upsert, items/sync, invoices) take title/description, hsn and savedItemId, but also accept the read names name, hsnCode and taxEasyyItemId as aliases, so an item you read can be sent straight back. When both are sent, the write name wins. A field we don't recognise is ignored and listed in the response warnings. The imageUrl field is a Cloudinary CDN URL when the merchant has added a photo to the item; otherwise null. This field is read-only via the partner API — images are uploaded through the WeSaveTax portal, not via API in this version.
Note:currentStock is the sellable stock in the item's unit, or null when trackInventory is false (services). The list includes items the company created in WeSaveTax itself — those have partnerItemId: null; link them on invoices by savedItemId.

#GET/items/:id

Fetch a single item by its taxEasyyItemId.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company

Response

Single item object — same shape as a list item (includes imageUrl).

#POST/items/upsert

Create or update a product or service from your catalogue, matched on partnerItemId.

Request body

json
{
  "partnerTenantId": "company_123",
  "partnerItemId":   "item_789",
  "title":           "Paracetamol 500mg (strip of 10)",
  "rate":            25,
  "unit":            "PAC",
  "hsn":             "3004",
  "gstRate":         5
}
FieldRequiredNotes
partnerItemIdYesYour id for the item — also how invoice lines refer to it
titleYesItem name (max 200). Must be unique within the company
rateYesSelling price per unit
hsnNoHSN (goods) or SAC (services) code — find it with GET /hsn. A SAC code (starting 99) makes the item a service
gstRateNo0, 0.25, 3, 5, 18 or 40
unitNoAn official GST unit code (default NOS) — see below
descriptionNoMax 1000

Response

json
{ "taxEasyyItemId": "64f1a2b3c4d5e6f7a8b9c0d2", "isNew": true }
Note:Send title and hsn. name and hsnCode (the names GET /items returns) are accepted as aliases. Any other unknown field is ignored and listed in a warnings array in the response.
Note:Set on creation only: unit and the goods/service type (from hsn) define how stock is counted, so later upserts don't change them — the company edits them in WeSaveTax. Goods are stock-tracked and start at 0 stock; the company adds opening stock in WeSaveTax. Services are never stock-tracked.

Allowed units

Official GST unit codes (GSTR-1 reports them as-is): BAG BAL BDL BKL BOU BOX BTL BUN CAN CBM CCM CMS CTN DOZ DRM GGK GMS GRS GYD KGS KLR KME LTR MLT MTR MTS NOS OTH PAC PCS PRS QTL ROL SET SQF SQM SQY TBS TGM THD TON TUB UGS UNT YDS. Case doesn't matter. The unit names used inside the WeSaveTax app are accepted too and converted (for example LTRS becomes LTR, BOXES becomes BOX, TABLETS becomes TBS); item reads always return the GST code. Units the app has but GST doesn't (HRS DAYS MONTHS YEARS STRIPS SHEETS) are accepted and stored as sent; GSTR-1 reports them as-is, so prefer a GST code where one fits. Anything else returns 400 INVALID_UNIT with the list in allowedUnits.

#POST/items/sync

Bulk upsert up to 500 items in one call.

Request body

json
{
  "partnerTenantId": "company_123",
  "items": [
    { "partnerItemId": "item_001", "title": "Paracetamol 500mg", "rate": 25, "unit": "PAC", "hsn": "3004", "gstRate": 5 },
    { "partnerItemId": "item_002", "title": "IT Consulting",     "rate": 500, "hsn": "998313", "gstRate": 18 }
  ]
}

Response

json
{ "synced": 2, "created": 2, "updated": 0, "failed": 0, "errors": [] }

Same fields and rules as /items/upsert, including the name and hsnCode aliases; unknown fields come back in a warnings array ("Item 2: unrecognised field ..."). An item that passes validation but cannot be saved is reported in errors: [{ partnerItemId, error }] without stopping the rest.

The whole body is validated before anything is saved. If any item is malformed (for example a negative rate) the call answers 400 VALIDATION_FAILED, error.field names the record (items.1.rate) and nothing is written; fix it and resend the batch. failed and errors in a 200 response cover only items that passed validation but could not be saved.

#GET/hsn

Search HSN (goods) and SAC (services) codes with their default GST rate — use it to pick hsn and gstRate before creating an item. No partnerTenantId needed.

ParamRequiredDescription
qNoCode or description text, e.g. 3004 or paracetamol
limitNoResults (default: 10, max: 20)
json
{
  "data": [
    { "hsn": "3004", "type": "HSN", "description": "Medicaments in measured doses", "gstRate": 5 }
  ]
}
Note:gstRate is the usual rate for the code; some codes carry more than one rate, so confirm with the company when it matters. type: "SAC" means a service.

#GET/gst-rates

The GST rates an invoice line may use, the abolished rates and the tax categories. Static data: no partnerTenantId needed. Offer exactly rates in a setup screen.

Response

json
{
  "rates":         [0, 0.25, 3, 5, 18, 40],
  "abolished":     [12, 28],
  "taxCategories": ["taxable", "nil", "exempt", "non_gst"]
}

#GET/invoices

List invoices for a company.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company
pageNoPage number (default: 1)
limitNoResults per page (default: 50, max: 100)
statusNoFilter by status: draft, sent, partially_paid, paid
partnerDealIdNoFilter by your deal ID
includeTestNoInclude sandbox invoices (default: false)
updatedSinceNoISO 8601 date-time. Only invoices changed at or after it, oldest change first (catch-up mode, see below)
cursorNoThe nextCursor of the previous catch-up page
fromNoYYYY-MM-DD, invoice date from (the merchant's timezone, inclusive)
toNoYYYY-MM-DD, invoice date to (the merchant's timezone, inclusive)
buyerGstinNoOnly invoices to this buyer GSTIN

Response

json
{
  "data": [
    {
      "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
      "invoiceNumber":     "INV-2026-00001",
      "invoiceDate":       "2026-06-22T00:00:00.000Z",
      "buyerName":         "Reliance Industries Ltd",
      "documentType":      "tax_invoice",
      "grandTotal":        118000,
      "amountPaid":        0,
      "amountDue":         118000,
      "paymentStatus":     "unpaid",
      "status":            "sent",
      "partnerDealId":     "deal_789",
      "partnerContactId":  "contact_456",
      "updatedAt":         "2026-06-22T09:30:00.000Z",
      "totalCredited":     0
    }
  ],
  "pagination": { "page": 1, "limit": 50, "total": 12, "totalPages": 1 }
}
Note:Test/sandbox invoices are excluded by default. Pass includeTest=true to include them.

Catching up after a missed webhook

Send updatedSince (or cursor) and the list switches to catch-up mode: invoices come oldest change first, and the response is { data, pagination: { limit, hasMore, nextCursor } } (no page or total). Every payment, credit note, e-invoice cancel and edit moves an invoice's updatedAt, so a change shows up again here.

  1. Call GET /invoices?partnerTenantId=...&updatedSince=<last updatedAt you saved>.
  2. Apply each row (it is the whole current state; applying it twice is harmless).
  3. While hasMore is true, call again with cursor=<nextCursor> (keep the same filters).
  4. Save the updatedAt of the last row you applied for the next run. When polling, re-request from 5 minutes before the last updatedAt you processed and treat repeated rows as idempotent: a change that commits late can carry an updatedAt older than one you already read. Paging with cursor inside one run is exact.
Note:A deleted draft does not appear in this list (invoices are deleted softly and hidden from every list). Deletions are visible only through the invoice.deleted / invoice.cancelled events in GET /webhook-events, so read that log as well when you catch up.

#GET/invoices/:id

Fetch full invoice detail including line items, tax breakdown, buyer, and a PDF download URL. Returns 404 if the invoice does not belong to the authenticated partner's tenant — a partner cannot access invoices belonging to another tenant or another partner.

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company

Response

json
{
  "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
  "invoiceNumber":     "INV-2026-00001",
  "documentType":      "tax_invoice",     // tax_invoice | bill_of_supply | unregistered_invoice
  "invoiceDate":       "2026-06-01T00:00:00.000Z",
  "dueDate":           "2026-06-30T00:00:00.000Z",
  "status":            "sent",            // invoice workflow status
  "paymentStatus":     "unpaid",          // unpaid | partial | paid
  "amountPaid":        0,
  "amountDue":         59000,
  "grandTotal":        59000,             // top-level alias (= taxBreakdown.grandTotal)
  "buyerName":         "Acme Corp",       // top-level alias (= buyer.legalName)
  "pdfUrl":            "https://www.wesavetax.com/api/connect/v1/invoices/64f.../pdf?partnerTenantId=company_123",
  "currency":          "INR",
  "supplyType":        "domestic",
  "isInterState":      false,
  "buyer": {
    "legalName":  "Acme Corp",
    "gstin":      null,
    "address":    "123 MG Road",
    "city":       "Mumbai",
    "state":      "Maharashtra",
    "stateCode":  "27",
    "pincode":    "400001",
    "country":    null,
    "email":      null,
    "phone":      null
  },
  "lineItems": [
    {
      "name":        "Web Design Services",   // API alias (= description in DB)
      "description": "Web Design Services",
      "hsn":         null,
      "quantity":    1,
      "unit":        "NOS",
      "rate":        50000,
      "gstRate":     18,
      "taxCategory": "taxable",               // taxable | nil | exempt | non_gst (untagged 0% = nil)
      "cgst":        4500,
      "sgst":        4500,
      "igst":        0,
      "amount":      50000
    }
  ],
  "taxBreakdown": {
    "subtotal":       50000,
    "taxableAmount":  50000,
    "totalCgst":      4500,
    "totalSgst":      4500,
    "totalIgst":      0,
    "totalGst":       9000,
    "discountAmount": 0,
    "grandTotal":     59000,
    "tcs":            null
  },
  "partnerDealId":    "deal_789",
  "partnerContactId": "contact_456",
  "totalCredited":    0,                  // issued credit notes, added up
  "netAmount":        59000,              // grandTotal - totalCredited
  "isCredited":       false,
  "creditNotes":      [],                 // [{ id, creditNoteNumber, status, total }], issued only, up to 100
  "isVoid":           false,              // true when the e-invoice IRN was cancelled: no sale
  "eInvoice":         { "status": "generated", "irn": "a1b2..." }  // only once an e-invoice exists
}
Note:paymentStatus values: unpaid · partial · paid. A void invoice (isVoid: true) is no sale: nothing can be paid or credited against it.pdfUrl points to the partner-authenticated PDF endpoint — call it with the same Bearer key (no extra auth needed). lineItems[].name is an alias for description for forward compatibility.

Error responses

StatusMeaning
401Missing or invalid API key
400partnerTenantId query param missing
404Invoice not found, or belongs to a different partner/tenant
429Rate limit exceeded

#GET/invoices/:id/pdf

Download an invoice as a PDF file. Authenticates with the same Bearer key as all other endpoints. Returns 404 if the invoice does not belong to the authenticated partner's tenant (same isolation guarantee as GET /invoices/:id).

Query params

ParamRequiredDescription
partnerTenantIdYesYour own id for the end customer's business — one per company

Response

Binary PDF stream. Content-Type: application/pdf. Content-Disposition: attachment; filename="INV-2026-00001.pdf".

bash
# Download the PDF for an invoice
curl https://www.wesavetax.com/api/connect/v1/invoices/64f1a2b3.../pdf?partnerTenantId=company_123 \
  -H "Authorization: Bearer txe_partner_dxyra_abc123" \
  -o invoice.pdf

Using pdfUrl from GET /invoices/:id

The GET /invoices/:id response includes a ready-to-use pdfUrl field. Call it directly with the same Bearer key — no URL construction needed.

js
// Fetch invoice details
const inv = await fetch(`/api/connect/v1/invoices/${invoiceId}?partnerTenantId=${tenantId}`, {
  headers: { Authorization: `Bearer ${apiKey}` }
}).then(r => r.json());

// Download PDF using the pdfUrl from the response
const pdf = await fetch(inv.pdfUrl, {
  headers: { Authorization: `Bearer ${apiKey}` }
});
const blob = await pdf.blob();

Error responses

StatusMeaning
401Missing or invalid API key
400partnerTenantId query param missing
404Invoice not found, or belongs to a different partner/tenant
429Rate limit exceeded
500PDF generation failed

#POST/invoices (Headless Invoice Creation)

Create an invoice programmatically without opening the embed. Use this to auto-generate invoices from your own workflows — for example, from a completed prescription or deal.

Specifying the buyer

MethodFieldWhen to use
By WeSaveTax buyer IDbuyerIdUse taxEasyyBuyerId from a previous /buyers/upsert
By your contact IDpartnerContactIdIf the contact was already synced
Inline buyer objectbuyer: { ... }One-off buyer, no prior sync needed

Request body

json
{
  "partnerTenantId":  "company_123",
  "buyerId":          "64f1a2b3...",     // OR partnerContactId OR buyer{}
  "partnerDealId":    "deal_789",         // optional — links invoice to your deal
  "partnerContactId": "contact_456",      // optional
  "invoiceType":      "B2B",              // optional — auto-derived if omitted
  "status":           "sent",             // optional — "sent" (default, issued) or "draft"
  "lineItems": [
    {
      "partnerItemId": "item_789",        // links the item — stock moves; unit/hsn come from it if omitted
      "description":   "Paracetamol 500mg (strip of 10)",
      "quantity":      2,
      "rate":          25,
      "gstRate":       5                  // required on every line, linked or not
    },
    {
      "description": "Home delivery",     // free-text line — no item, no stock
      "quantity":    1,
      "rate":        50,
      "gstRate":     18,
      "hsn":         "996812"             // required on a line not linked to an item
    },
    {
      "description": "Fresh vegetables",
      "quantity":    2.5,                 // fractional quantities are fine (kg, litres)
      "unit":        "KGS",
      "rate":        40,
      "gstRate":     0,
      "taxCategory": "nil",               // optional, 0% lines only: nil | exempt | non_gst
      "hsn":         "0709"
    }
  ],
  "pricesIncludeTax": false,              // optional, reserved: only false (or omitted) is accepted
  "dueDate": "2026-07-31"                  // optional
}

Linking lines to items (stock)

Stock moves only for lines linked to an item. Link with partnerItemId (your id from /items/upsert) or savedItemId (taxEasyyItemId from GET /items — needed for items the company created in WeSaveTax). A linked line takes the item's unit and hsn when you leave them out — if you send unit, it must be the item's exact unit. An id that matches no item returns 400 ITEM_NOT_FOUND.

Line rules

FieldRule
gstRateRequired on every line, linked or not; never taken from the item. One of 0, 0.25, 3, 5, 18, 40 (see GET /gst-rates). 12 and 28 return 422 ABOLISHED_GST_RATE with error.field set to the line (e.g. lineItems.0.gstRate); any other value is 400 VALIDATION_FAILED. If it differs from a linked item's stored rate, your rate is used and the response carries a RATE_DIFFERS_FROM_ITEM warning.
hsn4, 6 or 8 digits. Required on a line not linked to an item (400 VALIDATION_FAILED, error.field lineItems.N.hsn); a linked line may omit it.
quantityGreater than 0; fractions allowed (rounded to 3 decimals).
taxCategoryOptional, only on a 0% line: nil, exempt or non_gst. An untagged 0% line is nil-rated. On any other rate it is 400 VALIDATION_FAILED.
pricesIncludeTaxReserved. Prices are always exclusive of GST; true returns 400 PRICES_INCLUDE_TAX_NOT_SUPPORTED.

A draft gets no invoice number and moves no stock until it is issued.

Response (201)

The same invoice object GET /invoices/:id returns, plus warnings and warningDetails:

json
{
  "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
  "invoiceNumber":     "INV-2026-00001",
  "documentType":      "tax_invoice",
  "grandTotal":        59000,
  "status":            "sent",
  "paymentStatus":     "unpaid",
  "partnerDealId":     "deal_789",
  // ...every other GET /invoices/:id field
  "warnings":          ["Line 1 uses GST 5% but the linked item is stored at 12%. The declared rate was used."],
  "warningDetails":    [{ "code": "RATE_DIFFERS_FROM_ITEM", "field": "lineItems.0.gstRate", "message": "..." }]
}
Note:Check warnings — e.g. a goods line that isn't linked to an item (stock not tracked), stock going negative, a line rate that differs from its item, or a line field we didn't recognise. A warning never blocks the invoice.
Note:HSN/SAC on the invoice and PDF comes from the line. Send it as hsn on the line (hsnCode is accepted as an alias), or link the line to an item with partnerItemId or savedItemId (taxEasyyItemId is accepted as an alias) and it is copied from the item when you leave it out. A line with neither is refused. Your own item id (for example medicineId) is not recognised and links nothing: send partnerItemId instead. The line's unit may be a GST code or the matching app unit name; for a linked line it should match the item's unit.

Error responses

StatusErrorMeaning
400VALIDATION_FAILEDBody doesn't match the schema (missing gstRate, a rate not in the list, hsn missing on an unlinked line…) — see field and details
400PRICES_INCLUDE_TAX_NOT_SUPPORTEDpricesIncludeTax was true
400BUYER_REQUIREDNo buyer specified in request body
400BUYER_NOT_FOUNDbuyerId or partnerContactId matches no buyer
400ITEM_NOT_FOUNDpartnerItemId or savedItemId matches no item — see partnerItemIds / savedItemIds
404Tenant not foundInvalid or unknown partnerTenantId
403FEATURE_LOCKEDThe company's plan or business type doesn't include this (e.g. export supply types)
409TRANSACTION_CONFLICTTemporary conflict — safe to retry (retryable: true)
422INSUFFICIENT_STOCKNot enough stock for a linked item, and the company doesn't allow negative stock
422UNIT_NOT_CONFIGUREDThe line's unit isn't the item's unit
422ABOLISHED_GST_RATE12% or 28% — abolished in September 2025; error.field is the line
402plan_limit_reachedCompany hit their monthly invoice limit — account admin must upgrade
429RATE_LIMITEDSee Rate Limits
Note:For a registered merchant GST is calculated automatically based on buyer location and seller GSTIN — CGST+SGST for intra-state, IGST for inter-state. An unregistered or composition merchant issues a document with no GST (see documentType). Invoice numbering follows the company's configured prefix and sequence. An invoice.created webhook fires after creation (for drafts too).
Warning:Headless invoices count against the company's monthly plan limit, exactly like invoices created in the embed. If the limit is reached, this endpoint returns 402.

#POST/invoices/preview

Show the buyer the totals at checkout before you commit. Send the same body as POST /invoices; the answer is the invoice WeSaveTax would create, worked out by the same code. Nothing is saved: no invoice, no invoice number taken, no plan quota used, no webhook, no deal claim. No Idempotency-Key is needed; a preview is safe to repeat.

Response (200)

json
{
  "preview":        true,
  "invoiceNumber":  null,              // never invented; the real number is given by POST /invoices
  "pdfUrl":         null,
  "status":         "sent",
  "isInterState":   true,
  "lineItems":      [ { "name": "Widget", "amount": 999.99, "igst": 180, "cgst": 0, "sgst": 0, "taxCategory": "taxable" } ],
  "taxBreakdown":   { "totalIgst": 183.07, "grandTotal": 1244.56 },
  "roundOff":       { ... },
  "additionalCharges": [ ... ],
  "grandTotal":     1244.56,
  "warnings":       [],
  "warningDetails": []
}

The fields are those of the POST /invoices 201 response, except that there is no taxEasyyInvoiceId. Send invoiceDate if you want to compare a preview with the create: it defaults to today.

Errors

The same refusals as POST /invoices, with the same status and code: validation, GST rates, HSN, buyer, items, stock, and the plan gates including the monthly invoice limit (402 plan_limit_reached when the company is already at it).

An invoiceDate (or today, when you send none) in a period the company has locked in its books is refused with 409 PERIOD_LOCKED (error.details.lockedThrough), and one in a month whose GSTR-1 is already filed with 409 GSTR1_PERIOD_FILED. Both carry field: "invoiceDate", apply to drafts too, and are checked before any invoice number is taken. Date the invoice in the current open period. A retry of a create that already succeeded still returns the stored invoice. The WeSaveTax app itself only warns for a filed GSTR-1 month; the refusal is for API calls.

Differences from create

CasePreview
A partnerDealId that already has an invoiceA DEAL_ALREADY_INVOICED warning in warningDetails (details: taxEasyyInvoiceId, invoiceNumber), not an error. POST /invoices would answer 409. If the body is also refused for another reason, preview returns that refusal (create checks the deal first).
Warnings that exist only after the insert (stock deduction, delivery challan)Never appear
additionalCharges itemsCarry no _id in a preview (nothing is saved, so no id exists)
Values only the invoice store refuses (for example an unparseable dueDate, a negative additional charge or a very large exchangeRate)400 VALIDATION_FAILED with error.field, the same as create (which takes no invoice number for it).
Note:A preview is not a reservation: stock, the plan limit or the deal can change before you create. A preview counts as an API call for usage and the rate limit.

#POST/invoices/:id/credit-notes

Create and issue a credit note against an issued invoice in one step. Requires an Idempotency-Key; a retry with the same key never makes a second note. Needs the credit notes plan feature (403 PLAN_UPGRADE_REQUIRED).

Request body

json
{
  "partnerTenantId": "company_123",
  "mode":            "partial_items",    // full | partial_items | custom_amount
  "reason":          "Goods returned",
  "issueDate":       "2026-06-25",       // optional, defaults to today; not before the invoice date, not in the future
  "lineItems": [                         // partial_items only
    { "invoiceLineIndex": 0, "quantity": 1 }
  ],
  "customAmount":    500                 // custom_amount only, GST-inclusive, at most the invoice total
}
ModeWhat is credited
fullThe whole invoice.
partial_itemsThe named invoice lines at the given quantity. invoiceLineIndex is the line's position (from 0) in the invoice detail's lineItems; rate, GST, HSN and discount come from that line, so a credit never exceeds what was charged.
custom_amountA GST-inclusive amount (customAmount), split by the invoice's rates.

Response (201)

json
{
  "creditNoteId":     "64f1a2b3c4d5e6f7a8b9c0e1",
  "creditNoteNumber": "CN-2026-00001",
  "status":           "issued",
  "total":            590,
  "invoice":          { /* the invoice as GET /invoices/:id returns it, after the credit */ }
}

Error responses

StatusErrorMeaning
400VALIDATION_FAILEDA field is missing or invalid, or an unknown / repeated invoiceLineIndex
400CN_QTY_EXCEEDS_AVAILABLEMore than the line's quantity, or than is left to credit on it
400CN_CUMULATIVE_CEILING_EXCEEDEDThe credit notes on the invoice would add up to more than its total
400CN_AMOUNT_EXCEEDS_INVOICEcustomAmount is more than the invoice total
400CN_ISSUE_DATE_BEFORE_INVOICE / CN_ISSUE_DATE_IN_FUTUREissueDate out of range
400CN_ZERO_TOTALThe credit would be zero
400FOREIGN_BUYER_UNSUPPORTEDCredit notes for international buyers are not supported yet
409INVOICE_VOIDThe invoice's e-invoice IRN was cancelled: it is no sale
409INVOICE_DRAFTA draft cannot be credited; issue it first (or cancel it)
409PERIOD_LOCKEDThe credit note date is in a locked books period; error.details.lockedThrough
409CN_DUPLICATEA credit note number collided; retry with the same key
404NOT_FOUNDNo such invoice for this tenant
422IDEMPOTENCY_KEY_REUSEDThe key was used with another body or another invoice
Note:The invoice is checked again at the moment the note is issued (void, books lock, credit ceiling), also when a retry finishes a note an earlier attempt left as a draft. A refusal cancels that draft and frees the key. Sends credit_note.created once.

#POST/invoices/:id/cancel

Cancel an invoice. Requires an Idempotency-Key; a retry with the same key answers the original outcome.

json
{ "partnerTenantId": "company_123", "reason": "Order cancelled in CRM" }
InvoiceWhat happensResponse (200)
Draft created by you through the APIDeleted. Its partnerDealId is freed, so the deal can be invoiced again. Webhooks invoice.deleted and invoice.cancelled. No plan feature needed.{ taxEasyyInvoiceId, outcome: "deleted" }
IssuedReversed by one full credit note; the invoice keeps its number and its partnerDealId (a new invoice for that deal is still DEAL_ALREADY_INVOICED). Webhooks credit_note.created and invoice.cancelled. Needs the credit notes plan feature.{ taxEasyyInvoiceId, outcome: "credited", creditNoteId, creditNoteNumber, invoice }

Error responses

StatusErrorMeaning
409INVOICE_VOIDThe e-invoice IRN was cancelled (checked first)
409PAYMENT_RECORDEDMoney is recorded against it (payment, advance, credit or loyalty points): reverse it first. Final.
409ALREADY_CANCELLEDAlready fully credited. Final.
409INVOICE_LOCKEDA draft under an e-invoice, e-way bill, Tally or manual lock; error.details.reason
409INVOICE_STATE_CHANGEDA draft cancel retried after the invoice was issued: send a new key. Final for that key.
409PERIOD_LOCKEDToday is in a locked books period (issued invoice)
400CN_CUMULATIVE_CEILING_EXCEEDEDPart of the invoice is already credited
400CN_ZERO_TOTALZero-value invoice
400VALIDATION_FAILEDreason missing or blank
404NOT_FOUNDNo such invoice, or a draft not created by you through the API (a portal draft or POS hold bill is never deleted)

#POST/invoices/:id/payments

Record a payment against an issued invoice. Requires an Idempotency-Key; a retry with the same key returns the original payment and never records a second.

json
{
  "partnerTenantId": "company_123",
  "amount":          500.50,           // rupees, whole paise (at most 2 decimals)
  "paymentDate":     "2026-06-25",     // YYYY-MM-DD, not after today (India time)
  "paymentMode":     "upi",            // cash | bank_transfer | upi | cheque | card | credit_card | debit_card | other
  "referenceNumber": "UTR123456",      // optional
  "notes":           "Advance",        // optional
  "moneyAccountId":  "cash"            // optional: "cash", a bank account id, or null; omitted = the company's default
}

Response (201)

json
{
  "paymentId":         "64f1a2b3c4d5e6f7a8b9c0d4",
  "isOverpayment":     false,
  "overpaymentAmount": 0,
  "invoice":           { /* the invoice as GET /invoices/:id returns it, after the payment */ }
}
Note:More than the amount due is recorded and reported as an overpayment, not refused; a payment on a fully credited invoice (amountDue 0) is recorded wholly as an overpayment. Sends payment.recorded once.

Error responses

StatusErrorMeaning
400VALIDATION_FAILEDamount 0, negative or with more than 2 decimals; unknown paymentMode; bad date
400PAYMENT_DATE_IN_FUTUREpaymentDate is after today
400CURRENCY_NOT_SUPPORTEDForeign-currency invoice
400INVALID_MONEY_ACCOUNTmoneyAccountId is not an active account of the company, or not valid for the mode
409INVOICE_VOIDThe e-invoice IRN was cancelled
409INVOICE_DRAFTIssue the invoice first
409PERIOD_LOCKEDpaymentDate is in a locked books period; error.details.lockedThrough
409PAYMENT_RECONCILIATION_REQUIREDA half-written earlier payment for this key needs the company to reconcile it
403PLAN_UPGRADE_REQUIREDPayment tracking is switched off for the company
404NOT_FOUNDNo such invoice for this tenant
422IDEMPOTENCY_KEY_REUSEDThe key was used with another body or another invoice

#POST/invoices/prefill

Create a 30-minute prefill token for deal-to-invoice deep linking. Call this from your backend when a user opens the invoice tab on a deal, then pass the token as entityId in the embed JWT with context=deal.

Request body

json
{
  "partnerTenantId":  "company_123",
  "partnerContactId": "contact_456",
  "partnerDealId":    "deal_789",
  "lineItems": [
    {
      "partnerItemId": "item_001",
      "description":   "Paracetamol 500mg (strip of 10)",
      "quantity":      2,
      "rate":          25
    }
  ],
  "dealValue": 50000,
  "dueDate":   "2026-07-31"
}

Response

json
{ "prefillToken": "a3f8c2d1...", "expiresIn": 1800 }

Deal-to-invoice flow

  1. 1User opens "GST Invoice" tab on a deal in your CRM.
  2. 2Your backend calls POST /invoices/prefill → gets prefillToken.
  3. 3Your backend generates embed JWT with: context: "deal", entityId: prefillToken.
  4. 4iframe opens → WeSaveTax reads the token → invoice builder opens pre-filled with buyer + line items.
  5. 5User clicks Create → WESAVETAX_INVOICE_CREATED fires.
Note:prefillToken expires in 30 minutes and works once. Generate it fresh each time the user opens the invoice tab. Lines link to items exactly as in POST /invoices (partnerItemId or savedItemId; unknown ids return 400 ITEM_NOT_FOUND).

#GET/invoice-fields

Returns the invoice field schema — the complete list of fields a partner-built invoice form must render to produce a valid POST /invoices payload. Use this to dynamically drive your form rather than hardcoding field definitions.

Auth

Requires a valid partner API key (Bearer token). No partnerTenantId needed — the schema is not tenant-specific.

Response

json
{
  "lineItemFields": [
    { "key": "partnerItemId", "label": "Item", "type": "text", "required": false, "maxLength": 200, "hint": "Your item id from items/upsert — links the line to the item so stock moves; omitted unit, HSN and GST rate come from the item" },
    { "key": "description", "label": "Description", "type": "text",   "required": true, "maxLength": 2000 },
    { "key": "quantity",    "label": "Quantity",    "type": "number", "required": true, "min": 1, "max": 999999 },
    { "key": "rate",        "label": "Rate (₹)",   "type": "number", "required": true, "min": 0 },
    {
      "key":     "gstRate",
      "label":   "GST Rate (%)",
      "type":    "select",
      "required": false,
      "options": [
        { "label": "0%",    "value": 0    },
        { "label": "0.25%", "value": 0.25 },
        { "label": "3%",    "value": 3    },
        { "label": "5%",    "value": 5    },
        { "label": "18%",   "value": 18   },
        { "label": "40%",   "value": 40   }
      ]
    },
    { "key": "unit",     "label": "Unit",            "type": "text", "required": false, "maxLength": 50,   "hint": "For a linked item, omit it or send the item's exact unit" },
    { "key": "hsn",      "label": "HSN / SAC Code",  "type": "text", "required": false, "maxLength": 20,   "hint": "Harmonized System Nomenclature (goods) or Service Accounting Code" }
  ],
  "headerFields": [
    { "key": "dueDate", "label": "Due Date", "type": "date",     "required": false, "hint": "ISO 8601 date string, e.g. 2026-07-31" },
    { "key": "notes",   "label": "Notes",    "type": "textarea", "required": false, "maxLength": 5000 },
    { "key": "poNumber","label": "PO Number","type": "text",     "required": false, "maxLength": 50, "hint": "Buyer's purchase order reference" },
    { "key": "discount", "label": "Discount", "type": "object", "required": false,
      "fields": [
        { "key": "type",  "label": "Discount Type",  "type": "select", "options": [{ "label": "Percent (%)", "value": "percent" }, { "label": "Flat (₹)", "value": "flat" }] },
        { "key": "value", "label": "Discount Value", "type": "number", "min": 0 }
      ]
    }
  ]
}
Note:GST rates 12% and 28% were abolished in September 2025 (GST 2.0) and are intentionally absent from the gstRate options. Using an abolished rate in POST /invoices returns 422 ABOLISHED_GST_RATE.

Error responses

StatusMeaning
401Missing or invalid API key
429Rate limit exceeded

#POST/auth/exchange

Called automatically by the WeSaveTax embed — you do not need to call this from your backend. Documented here for reference.

Request body

json
{ "token": "eyJhbGci..." }

Response

json
// Success
{ "status": "ok", "clientId": "..." }

// Company not provisioned yet — setup wizard will show
{ "status": "setup_required", "setupData": { ... } }
Note:The embed calls this endpoint automatically when it loads. Your frontend only needs to provide the token in the iframe URL.

#Webhooks

WeSaveTax sends a POST request to your configured webhook URL when key events happen. All requests are signed with HMAC-SHA256.

Your webhook URL is set by WeSaveTax when your integration is provisioned (there is no partner self-service page for this yet) — separate URLs for live and sandbox. Contact WeSaveTax to change it. If the URL is a bare origin (no path, or just /), WeSaveTax POSTs to /api/webhooks/wesavetax/{event} on it; if it already has a path, the event name is appended to that path (https://example.com/hook becomes https://example.com/hook/invoice.created; trailing slashes are dropped first, so /hook/ gives the same). A query string stays at the end (https://example.com/hook?t=1 becomes https://example.com/hook/invoice.created?t=1). The URL must be https and a public host: localhost, .local, .internal, .lan,.home.arpa, single-word names and private IP addresses are refused.

The deliveries picked up in one sending round are sent in parallel, so they can arrive out of order: sort by sequence.

Example: if your webhook URL is https://crm.example.com, WeSaveTax will POST to:

https://crm.example.com/api/webhooks/wesavetax/invoice.created
https://crm.example.com/api/webhooks/wesavetax/payment.recorded

Events

EventWhen
invoice.createdAn invoice is created — including drafts, which have invoiceNumber: null. A POS held bill sends it when the bill is finalized, not when it is held
invoice.updatedAn invoice is edited or issued (a draft's number arrives here)
invoice.deletedAn invoice is deleted
invoice.cancelledAn invoice is cancelled through POST /invoices/{id}/cancel (a draft deleted, or an issued invoice fully credited). It is also sent when a credit note issued in the WeSaveTax app fully credits an invoice, and when an e-invoice IRN is cancelled in the app.
payment.recordedA payment is recorded: through POST /invoices/{id}/payments (any invoice of the company), or in the WeSaveTax app on an invoice of a company linked to you
payment.updatedA payment is edited
payment.deletedA payment is deleted
payment.reversedA payment is reversed — reversedFromId names the original
payment.refundedA refund is paid out against a credit note
webhook.testOnly when you call POST /webhook-events/test. Data: { "message": "test event" }. It belongs to no merchant and never means a business change: ignore it in your business logic
credit_note.createdA credit note is issued through the API (POST /invoices/{id}/credit-notes or POST /invoices/{id}/cancel); also sent when a credit note is issued in the WeSaveTax app (payload: taxEasyyCreditNoteId, creditNoteNumber, taxEasyyInvoiceId, invoiceNumber, total, status, issueDate, reason, partnerDealId)

invoice.* events share the invoice.created data; payment.* events share the payment.recorded data.

When an event is sent

An action made through the API (create an invoice, issue a credit note, record a payment, delete a draft through POST /invoices/{id}/cancel) saves its event in the same database transaction as the change itself: the change never commits without its event. (On a database without transactions the event is written right after the change; a retry of the same request writes it if it was missed for credit notes, payments, cancels and invoice creates that sent a partnerDealId.) Actions made in the WeSaveTax app send events too: an invoice created, edited, issued or deleted; a credit note issued (credit_note.created, plus invoice.cancelled when it fully credits the invoice); and a payment recorded, edited, reversed, refunded or deleted. Most of these are saved with the change. Three are queued right after it (one retry, then logged): an invoice edit (PATCH), an e-invoice IRN cancel and a POS bill finalized. If that queueing keeps failing, the event is lost, so reconcile with GET /invoices from time to time. The older Payments page flow also queues right after the change (a payment recorded on an invoice there, and an edit of a payment record); deleting a payment from that record page sends no event, so reconcile those too. Companies without a partner send nothing.

Warning:Not sent today: there is no credit_note.cancelled event. A credit note cancelled in the app, a credit note adjusted against an invoice (and the reversal of that adjustment), an advance or loyalty adjustment, and any invoice edit send invoice.updated instead; read the invoice (resource or GET /invoices/{id}) for the new balance. A draft issued in the app sends invoice.updated (with its number), because its invoice.created was already sent when the draft was made; a POS held bill sends invoice.created when it is finalized. Restoring a deleted invoice sends nothing, and a second invoice.deleted after a restore is dropped as a duplicate of the first.

#Delivery guarantees

  • At least once. The same event can arrive more than once. Ignore a delivery whose eventId you already processed; it is the same on every retry and on a replay.
  • Order by sequence. Each merchant (partnerTenantId) has its own counter that only goes up, taken when the event is queued. It is not gapless (a missing number does not mean a lost event), and events can arrive out of order, because a retried event arrives after later ones. Keep the highest sequence you applied per merchant and ignore an older event for the same object.
  • Retries. A response other than 2xx, a timeout (10 seconds per attempt) or a connection error is retried: 6 attempts in total, waiting 30 s, 2 min, 10 min, 1 h and 6 h after each failure, each wait varied by up to 20% either way. After the sixth failure the event is dead; replay it below. The sender runs once a minute, so a delivery can start up to a minute after its time.
  • Redirects are not followed. A 301, 302, 307 or 308 answer counts as a failed attempt. Give us the final URL.
  • After a crash on our side an attempt that never finished is picked up again after 5 minutes and counts as an attempt. If your server did receive the first one, you get the same eventId twice.

#Body and headers

Body fieldMeaning
eventThe event name
eventIdUnique id of the event. Stable across retries and replays
partnerIdYour partner id (live and sandbox are different partners)
sequencePer-merchant counter, see Delivery guarantees. null for webhook.test
partnerTenantIdThe merchant the event belongs to. null for webhook.test
occurredAtWhen the event happened (when it was queued). Stable across retries
resourceAsOfWhen this attempt's body was built. Changes on every attempt, like timestamp
timestampWhen this attempt was sent (ISO). The signed timestamp header is the same moment in Unix seconds
dataThe summary captured when the event happened. Never changes, even on a retry
resourceThe thing the event is about, read when this attempt is sent: its state at or after the event, so a delayed event can already show a later change. invoice.*: the invoice as GET /invoices/{id} returns it. payment.*: id, invoiceId, amount, mode, date, reference and the invoice. credit_note.created: id, creditNoteNumber, status, total, invoiceId, issueDate, reason. It is null when it could not be read within 3 seconds or no longer exists: use data then. For a deleted invoice it is the last state; a payment.* event for an invoice deleted later has resource.invoice: null

Headers: X-WeSaveTax-Signature (sha256=hex), X-WeSaveTax-Event, X-WeSaveTax-Event-Id, X-WeSaveTax-Timestamp, X-WeSaveTax-Partner, X-WeSaveTax-Mode (live or sandbox) and X-WeSaveTax-Sequence (not sent for webhook.test). The signature recipe is unchanged (see Signature Verification). Fields may be added to the body later: ignore ones you do not know. The examples below show the fields that differ per event; every body also carries the common fields above. In the invoice resource examples the invoice is shortened to a few fields.

#invoice.created

json
{
  "event":           "invoice.created",
  "eventId":         "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
  "partnerId":       "your_partner_id",
  "sequence":        41,
  "partnerTenantId": "tenant_123",
  "occurredAt":      "2026-06-22T14:30:00.000Z",
  "resourceAsOf":    "2026-06-22T14:30:02.000Z",
  "timestamp":       "2026-06-22T14:30:02.000Z",
  "data": {
    "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
    "invoiceNumber":     "INV-2026-00001",
    "documentType":      "tax_invoice",
    "grandTotal":        118000,
    "status":            "sent",
    "partnerDealId":     "deal_789",
    "partnerContactId":  "contact_456",
    "buyerName":         "Reliance Industries Ltd",
    "invoiceDate":       "2026-06-22T00:00:00.000Z"
  },
  "resource": {
    "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
    "invoiceNumber":     "INV-2026-00001",
    "status":            "sent",
    "paymentStatus":     "unpaid",
    "amountDue":         118000,
    "grandTotal":        118000,
    "isVoid":            false,
    "creditNotes":       [],
    "pdfUrl":            "https://.../api/connect/v1/invoices/64f1a2b3c4d5e6f7a8b9c0d3/pdf?partnerTenantId=tenant_123"
  }
}

#invoice.cancelled

Sent by POST /invoices/{id}/cancel only. For an issued invoice it follows credit_note.created (the full credit); for a draft it comes with invoice.deleted. A fully credited invoice reads paymentStatus: "paid" (nothing is left to pay), so detect a cancel by the event, or by isCredited: true with netAmount: 0, never by paymentStatus.

json
{
  "event":           "invoice.cancelled",
  "eventId":         "c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6",
  "partnerId":       "your_partner_id",
  "sequence":        43,
  "partnerTenantId": "tenant_123",
  "occurredAt":      "2026-06-23T09:00:00.000Z",
  "resourceAsOf":    "2026-06-23T09:00:01.000Z",
  "timestamp":       "2026-06-23T09:00:01.000Z",
  "data": { "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3", "invoiceNumber": "INV-2026-00001", "documentType": "tax_invoice", "grandTotal": 118000, "status": "sent", "partnerDealId": "deal_789", "partnerContactId": "contact_456", "buyerName": "Reliance Industries Ltd", "invoiceDate": "2026-06-22T00:00:00.000Z" },
  "resource": {
    "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
    "status":            "paid",
    "paymentStatus":     "paid",
    "amountDue":         0,
    "totalCredited":     118000,
    "netAmount":         0,
    "isCredited":        true,
    "creditNotes":       [{ "id": "64f1a2b3c4d5e6f7a8b9c0e1", "creditNoteNumber": "CN-2026-00001", "status": "issued", "total": 118000 }]
  }
}

#invoice.deleted

A draft deleted through POST /invoices/{id}/cancel, or an invoice deleted in the WeSaveTax app. resource is the invoice's last state before the delete, with invoiceNumber: null for a draft.

json
{
  "event":           "invoice.deleted",
  "eventId":         "d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1",
  "partnerId":       "your_partner_id",
  "sequence":        44,
  "partnerTenantId": "tenant_123",
  "occurredAt":      "2026-06-23T09:05:00.000Z",
  "resourceAsOf":    "2026-06-23T09:05:01.000Z",
  "timestamp":       "2026-06-23T09:05:01.000Z",
  "data": { "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0f2", "invoiceNumber": null, "documentType": "tax_invoice", "grandTotal": 5900, "status": "draft", "partnerDealId": "deal_790", "partnerContactId": null, "buyerName": "Acme Traders", "invoiceDate": "2026-06-23T00:00:00.000Z" },
  "resource": { "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0f2", "invoiceNumber": null, "status": "draft", "paymentStatus": "unpaid", "amountDue": 5900, "grandTotal": 5900 }
}

#credit_note.created

json
{
  "event":           "credit_note.created",
  "eventId":         "e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
  "partnerId":       "your_partner_id",
  "sequence":        42,
  "partnerTenantId": "tenant_123",
  "occurredAt":      "2026-06-23T09:00:00.000Z",
  "resourceAsOf":    "2026-06-23T09:00:01.000Z",
  "timestamp":       "2026-06-23T09:00:01.000Z",
  "data": {
    "taxEasyyCreditNoteId": "64f1a2b3c4d5e6f7a8b9c0e1",
    "creditNoteNumber":     "CN-2026-00001",
    "taxEasyyInvoiceId":    "64f1a2b3c4d5e6f7a8b9c0d3",
    "invoiceNumber":        "INV-2026-00001",
    "total":                118000,
    "status":               "issued",
    "issueDate":            "2026-06-23T00:00:00.000Z",
    "reason":               "Order cancelled",
    "partnerDealId":        "deal_789"
  },
  "resource": {
    "id":               "64f1a2b3c4d5e6f7a8b9c0e1",
    "creditNoteNumber": "CN-2026-00001",
    "status":           "issued",
    "total":            118000,
    "invoiceId":        "64f1a2b3c4d5e6f7a8b9c0d3",
    "issueDate":        "2026-06-23T00:00:00.000Z",
    "reason":           "Order cancelled"
  }
}

#payment.recorded

json
{
  "event":           "payment.recorded",
  "eventId":         "b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5",
  "partnerId":       "your_partner_id",
  "sequence":        45,
  "partnerTenantId": "tenant_123",
  "occurredAt":      "2026-06-22T14:30:00.000Z",
  "resourceAsOf":    "2026-06-22T14:30:02.000Z",
  "timestamp":       "2026-06-22T14:30:02.000Z",
  "data": {
    "taxEasyyPaymentId": "64f1a2b3c4d5e6f7a8b9c0d4",
    "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
    "invoiceNumber":     "INV-2026-00001",
    "amountPaid":        118000,
    "paymentMethod":     "bank_transfer",
    "paymentDate":       "2026-06-22T14:30:00.000Z",
    "invoiceStatus":     "paid",
    "amountDue":         0,
    "reference":         "UTR123456",
    "reversedFromId":    null,
    "partnerDealId":     "deal_789",
    "partnerContactId":  "contact_456"
  },
  "resource": {
    "id":        "64f1a2b3c4d5e6f7a8b9c0d4",
    "invoiceId": "64f1a2b3c4d5e6f7a8b9c0d3",
    "amount":    118000,
    "mode":      "bank_transfer",
    "date":      "2026-06-22T14:30:00.000Z",
    "reference": "UTR123456",
    "invoice":   { "taxEasyyInvoiceId": "64f1a2b3c4d5e6f7a8b9c0d3", "paymentStatus": "paid", "amountPaid": 118000, "amountDue": 0 }
  }
}
Note:paymentMethod: cash · bank_transfer · upi · cheque · card · credit_card · debit_card · online_gateway · other. invoiceStatus is the invoice's payment status (unpaid · partial · paid). partnerDealId / partnerContactId are the invoice's, or null when it has none. data.amountDue and data.invoiceStatus are as of the event; resource.invoice is current, so prefer it.

Responses of POST /invoices/{id}/cancel, /payments and /credit-notes can carry invoice: null if the invoice was deleted between the write and the response; the write itself still happened.

#Held events

An event that happens while no webhook URL is set is kept with status held, not dropped. When a URL is set, held events are queued in sequence order. Held events older than 30 days are deleted. Delivered events are kept 30 days from when the event was queued and dead events 180 days (the replay window); for a gap older than that, read GET /invoices and compare. A list that returns only what changed since a date is planned.

#Event log and replay

See what was sent and send it again. You only ever see your own events: a sandbox key sees sandbox events, a live key live ones, and another partner's eventId answers 404 NOT_FOUND. These calls need no Idempotency-Key, count as API calls (usage label webhook-events, webhook-events.replay) and share your hourly rate limit.

CallWhat it does
GET /webhook-eventsNewest first. Filters: status (pending, delivering, delivered, failed, dead, held), event, since (ISO date-time, by occurredAt), partnerTenantId, sinceSequence (needs partnerTenantId). page and limit (default 50, capped at 100). Items: eventId, event, status, sequence, partnerTenantId, occurredAt, attempts, lastStatus, lastError, nextAttemptAt and deliveredAt once delivered. No body and no URL.
GET /webhook-events/{eventId}The same item plus data, the summary stored when the event happened
POST /webhook-events/{eventId}/replayRe-queues a failed, dead or delivered event: 200 { eventId, status: "pending", nextAttemptAt }. A pending, delivering or held event answers 409 ALREADY_QUEUED and nothing changes. Replaying a failed event that is waiting for its automatic retry resets its attempts to 0.
POST /webhook-events/replayBody (optional): status (failed or dead; default both), since, partnerTenantId, limit (1 to 500, default 100). Re-queues the oldest first; only failed and dead events. 200 { replayed: n }.

A replay sends the same event again: same eventId and sequence, but a fresh timestamp, resourceAsOf and resource, so de-duplicate on eventId. It is delivered usually within a minute; large replays take longer (the sender takes 50 events per minute), and a replayed event arrives out of order relative to newer ones.

#Signature Verification

Warning:The signed message is ${timestamp}.${eventId}.${rawBody} — NOT the raw body alone.timestamp and eventId come from the X-WeSaveTax-Timestamp and X-WeSaveTax-Event-Id headers (timestamp is Unix seconds, not the ISO string inside the JSON body). Signing the raw body alone will never match — verification will always fail.
js
const crypto = require("crypto");

// Verify the signature against the RAW request body bytes plus the
// timestamp + eventId headers — all three are covered by the signature.
// Re-stringifying req.body (after express.json() parses it) will NOT
// byte-match what WeSaveTax signed, so you must capture the raw body first.
function verifyWebhookSignature(rawBody, signatureHeader, timestampHeader, eventIdHeader, secret) {
  if (typeof signatureHeader !== "string") return false;

  // Header format: "sha256=<hex>". Strip the "sha256=" prefix before decoding.
  const prefix = "sha256=";
  if (!signatureHeader.startsWith(prefix)) return false;
  const providedHex = signatureHeader.slice(prefix.length);

  const signedMessage = `${timestampHeader}.${eventIdHeader}.${rawBody}`;
  const expectedHex = crypto
    .createHmac("sha256", secret)
    .update(signedMessage)                // rawBody here is a Buffer of the exact bytes we signed
    .digest("hex");

  // timingSafeEqual throws when lengths differ — guard first.
  const a = Buffer.from(providedHex, "hex");
  const b = Buffer.from(expectedHex, "hex");
  if (a.length !== b.length) return false;
  return crypto.timingSafeEqual(a, b);
}

// Express handler — use express.raw() so req.body is a Buffer of the exact
// bytes WeSaveTax signed. Do NOT use express.json() on this route; parse
// JSON only AFTER verification passes.
app.post(
  "/api/webhooks/wesavetax/:event",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    const signature   = req.headers["x-wesavetax-signature"];
    const timestampHdr = req.headers["x-wesavetax-timestamp"];   // Unix seconds
    const eventIdHdr    = req.headers["x-wesavetax-event-id"];

    if (!verifyWebhookSignature(req.body, signature, timestampHdr, eventIdHdr, process.env.WESAVETAX_WEBHOOK_SECRET)) {
      return res.status(401).json({ error: "Invalid signature" });
    }

    // Recommended: reject payloads older than 5 minutes to limit replay
    // exposure if a signed request is captured in transit. timestampHdr is
    // covered by the signature (tamper-proof), unlike a value read from the
    // JSON body before verification.
    if (Date.now() - Number(timestampHdr) * 1000 > 5 * 60 * 1000) {
      return res.status(400).json({ error: "Payload too old" });
    }

    // Signature is valid — safe to parse the JSON body.
    const payload = JSON.parse(req.body.toString("utf8"));
    const { event, data } = payload;

    switch (event) {
      case "invoice.created":
        await Deal.findOneAndUpdate(
          { _id: data.partnerDealId },
          { invoiceNumber: data.invoiceNumber, invoiceId: data.taxEasyyInvoiceId }
        );
        break;

      case "payment.recorded":
        await Deal.findOneAndUpdate(
          { _id: data.partnerDealId },
          { paymentStatus: data.invoiceStatus, amountPaid: data.amountPaid }
        );
        break;
    }

    res.json({ received: true });
  }
);
Warning:Always return a 2xx response quickly. WeSaveTax times out after 10 seconds. Process events asynchronously if needed.
Warning:Webhook secrets can be rotated with a 7-day grace period from the WeSaveTax admin. During the grace window, WeSaveTax signs with the NEW secret only, but your verifier should accept EITHER the current or previous secret so in-flight deliveries are not dropped mid-rotation. Store both WESAVETAX_WEBHOOK_SECRET andWESAVETAX_WEBHOOK_SECRET_PREVIOUS and treat verification as passing when either HMAC matches the signature.

#postMessage Events

The WeSaveTax embed communicates with your parent window via window.postMessage. Set up a listener in your iframe wrapper component.

js
window.addEventListener("message", (event) => {
  // Always verify the origin
  if (event.origin !== "https://staging.wesavetax.com") return;

  const { type, ...data } = event.data;

  switch (type) {
    case "WESAVETAX_READY":
      // User authenticated and the portal is loading
      hideLoadingSpinner();
      break;

    case "WESAVETAX_INVOICE_CREATED":
      // data: { invoiceId, invoiceNumber, grandTotal, partnerDealId }
      updateDealWithInvoice(data);
      break;

    case "WESAVETAX_PAYMENT_RECORDED":
      // data: { invoiceId, invoiceNumber, amountPaid, invoiceStatus, partnerDealId }
      updateDealPaymentStatus(data);
      break;

    case "WESAVETAX_SESSION_EXPIRED":
      // Fetch a new token and reload the iframe
      refreshEmbedToken();
      break;

    case "WESAVETAX_SESSION_INVALID":
      // Token missing, malformed, or rejected — reopen the panel from your CRM
      closeEmbedPanel();
      break;

  }
});

#WESAVETAX_READY

User authenticated and the portal is loading. For a company's first visit it fires after the setup wizard is submitted — so keep the iframe visible before READY, or new users won't see the wizard.

Payload: none

#WESAVETAX_INVOICE_CREATED

Invoice saved or issued.

Payload fieldDescription
invoiceIdWeSaveTax invoice ID
invoiceNumberInvoice number string
grandTotalTotal amount including GST
partnerDealIdYour deal ID (if linked)

#WESAVETAX_PAYMENT_RECORDED

Payment recorded against an invoice.

Payload fieldDescription
invoiceIdWeSaveTax invoice ID
invoiceNumberInvoice number string
amountPaidAmount paid in this payment
invoiceStatusUpdated invoice status (e.g. paid)
partnerDealIdYour deal ID (if linked)

#WESAVETAX_SESSION_EXPIRED

User session expired inside the embed.

Payload: none. Fetch a new token and reload the iframe src.

#WESAVETAX_SESSION_INVALID

The token was missing, malformed, or rejected.

Payload: none. Also sent when a token is reused (tokens are single-use — mint a new one per load) or when WeSaveTax is briefly unavailable. If a fresh token keeps failing, check the signing secret and that the JWT partnerId matches it (live vs sandbox).

Note:A page that frames the embed from a domain that isn't on your allow-list is blocked by the browser — the iframe stays blank and no event is sent.

Note: WESAVETAX_INVOICE_CREATED and WESAVETAX_PAYMENT_RECORDED only fire when the invoice has a partnerDealId — i.e. when opened via a deal deep link. They do not fire for invoices created directly from the billing dashboard.


#Allowed Domains

For security, WeSaveTax restricts which domains can embed the portal via iframe. Send your domains to WeSaveTax to add them to your allow-list.

PatternWhat it matches
*.dxyra.comapp.dxyra.com, crm.dxyra.com, any subdomain — and dxyra.com itself
dxyra.comApex domain only
*.localhostdentist11.localhost:3000, any subdomain of localhost (automatically allowed in sandbox mode)
https://app.dxyra.comExact match with protocol
Note:Sandbox mode automatically allows all localhost origins (http://localhost:*, http://*.localhost:*) for local development. You only need to add localhost to Allowed Domains in live mode.

#Errors, Request IDs & Idempotency

Every error from /api/connect/v1 has the same JSON body. Branch on code, not on message. The machine-readable contract is at /api/docs/connect-openapi.json.

json
{
  "error": {
    "code":      "DEAL_ALREADY_INVOICED",
    "message":   "An invoice already exists for this partnerDealId",
    "field":     "partnerDealId",
    "details":   { "taxEasyyInvoiceId": "...", "invoiceNumber": "INV-0007" },
    "requestId": "req_..."
  }
}

field and details appear only when they apply. Every response, success or error, carries an X-Request-Id header equal to error.requestId; quote it when you contact support. The list of codes is not exhaustive and new ones may appear: for an unrecognised code, a 4xx means the request was refused (do not retry it unchanged); 429 and 5xx are temporary (retry with the same Idempotency-Key). An unrecognised 409 may be either: retry it up to 3 times with backoff, then treat it as refused. Known 409s: temporary = IDEMPOTENCY_IN_PROGRESS, TRANSACTION_CONFLICT, CONFLICT; final = DEAL_ALREADY_INVOICED, PAYMENT_RECORDED, ALREADY_CANCELLED, INVOICE_STATE_CHANGED, ALREADY_QUEUED, PERIOD_LOCKED, GSTR1_PERIOD_FILED, NUMBERING_LOCKED, MERCHANT_OFFBOARDED, WEBHOOK_URL_NOT_SET.

POST /invoices, POST /invoices/:id/credit-notes, POST /invoices/:id/cancel, POST /invoices/:id/payments, POST /merchants/offboard and POST /webhook-events/test require an Idempotency-Key header (8-64 characters of A-Z a-z 0-9 _ -). Send a new key per invoice and the same key when retrying it. A retry with the same key and body returns the original 201 with the header Idempotent-Replayed: true and creates nothing. Keys are kept for 24 hours. A call still running holds its key (409 IDEMPOTENCY_IN_PROGRESS with Retry-After) for up to 5 minutes; after that it is presumed dead and the next retry takes over.

OutcomeWhat you seeWhat to do
Success2xxStore the invoice id. A replay of the same call returns the same body.
Refused4xx (e.g. VALIDATION_FAILED, DEAL_ALREADY_INVOICED, IDEMPOTENCY_KEY_REUSED)Do not retry unchanged. Fix the request; the key is free to reuse.
Temporary failure409 IDEMPOTENCY_IN_PROGRESS, 429, 5xxRetry with the same key, after Retry-After when present.
UnknownTimeout or dropped connectionRetry with the same key: you get the stored result or it runs once.
Note:A partnerDealId can be invoiced once per company. A second invoice for the same deal is refused with DEAL_ALREADY_INVOICED. A blank partnerDealId counts as none. Always send a stable partnerDealId (your order id) with every invoice: together with the Idempotency-Key it guarantees one invoice per order even if a request dies after committing.

#Rate Limits

Requests are counted per partner id per hour — live and sandbox separately — across every /api/connect/v1 endpoint, including the embed's own /auth/exchange call on each load. Limits per hour by tier: standard 1,000, growth 5,000, enterprise 20,000; contact WeSaveTax for a higher tier.

Per-merchant limit (optional). There is none unless WeSaveTax sets one for your account. When set, it is an hourly cap per merchant, so one busy merchant cannot use up your whole quota. It applies to calls that read or change a merchant's data: buyers, items, invoices (create, preview, prefill, list, detail, PDF, cancel, payments, credit notes) and billing-profile. It does not apply to /webhook-events (and its replay), /provision, /auth/exchange, /verify, /gst-rates, /hsn or /invoice-fields. A preview and every executed call consume the merchant bucket; a stored idempotent replay (same Idempotency-Key and body, answered from the saved response) does not, though it still counts against the partner-wide limit. An unknown partnerTenantId is 404 and consumes nothing. When the merchant limit is hit, error.details.scope is "merchant" (only that merchant is limited; wait Retry-After seconds); the partner-wide 429 has no scope.

Usage counting. Each authenticated request counts once toward your usage, including calls that return an error and calls that are rate-limited. Unauthenticated calls (401) and /auth/exchange are not counted. A stored idempotent replay counts for you (the partner) but not for the merchant.

json
// 429 Too Many Requests
// Headers: Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
{
  "error": {
    "code":      "RATE_LIMITED",
    "message":   "Rate limit exceeded",
    "details":   { "limit": 1000, "remaining": 0, "resetAt": "2026-06-22T15:00:00.000Z", "retryAfter": 1234 },  // + "scope": "merchant" when the per-merchant limit was hit
    "requestId": "req_..."
  }
}

#Offboarding a merchant

When a merchant leaves your product, call POST /merchants/offboard with { "partnerTenantId": "..." } and an Idempotency-Key. The response is { partnerTenantId, offboarded: true, offboardedAt }; a repeat returns the same body.

  • Every other call for that merchant answers 403 MERCHANT_INACTIVE (error.details.reason is offboarded, or deactivated when WeSaveTax deactivated the company).
  • No new webhook events are sent for it, and events still waiting are not delivered. Its past events stay readable in GET /webhook-events.
  • The merchant keeps its own login, invoices and data; offboarding only ends your access to it.
  • POST /provision for an offboarded partnerTenantId answers 409 MERCHANT_OFFBOARDED. Offboarding cannot be undone through the API: contact WeSaveTax support.

#Testing your integration

A short checklist to run in your sandbox before going live.

  1. Send a test event. POST /webhook-events/test with an Idempotency-Key queues one webhook.test event (data { "message": "test event" }) to your webhook URL. It is signed, checked and retried like a real event, and you can find it (and replay it) in GET /webhook-events. The response is { eventId, status: "pending" }; the same key returns the same event. With no webhook URL set it answers 409 WEBHOOK_URL_NOT_SET and nothing is queued. The test has no sequence, no partnerTenantId and no sequence header, and goes to <your base>/webhook.test like any event goes to its own name: make sure that route exists.
  2. Read your usage. GET /usage?from=YYYY-MM-DD&to=YYYY-MM-DD returns { data: [{ date, endpoint, method, calls, errors }], totals: { calls, errors } } from your own counters, per UTC day. Without dates it covers the last 30 days; a range may span at most 92 days (otherwise 400 VALIDATION_FAILED with field). Add partnerTenantId for one merchant: you get one row per day with endpoint and method null (no endpoint breakdown), and an offboarded merchant answers 403 MERCHANT_INACTIVE. The call is counted like any other.
  3. Reconcile. Webhooks are not the only source of truth. Loop GET /invoices?partnerTenantId=...&updatedSince=<last updatedAt> with cursor while hasMore, treat repeated rows as idempotent, and compare with what your system holds.
  4. Offboard. Try offboarding a sandbox merchant and check that your code handles 403 MERCHANT_INACTIVE.

Sandbox and live are separate partners: counters, events and merchants are not shared. Sandbox invoices are test documents and stay out of GST reports.


#Testing & Sandbox

Use sandbox credentials (format: txe_partner_yourname_sandbox_*) for all testing. Sandbox mode:

  • → Invoices are marked as test documents
  • → Never appear in GST reports (GSTR-1, GSTR-3B)
  • → A "🧪 Sandbox Mode" banner shows in the setup wizard
  • → Webhooks fire to your configured webhook URL normally

Local webhook testing with ngrok

bash
# Start ngrok on your webhook port
ngrok http 5001

# Ask WeSaveTax to point your sandbox webhook URL at your ngrok URL:
# https://a1b2c3d4.ngrok-free.app

# Watch incoming webhooks
ngrok http 5001 --inspect

Full test checklist

GET /verify → { valid: true }
POST /provision → creates test company
POST /buyers/upsert → syncs a contact
POST /items/upsert → syncs a product
GET /buyers → returns synced buyers
GET /items → returns synced items
Generate JWT → open embed URL in browser
Complete setup wizard (first time only)
POST /invoices → creates a headless invoice
GET /invoices → lists the created invoice
Create an invoice via embed → webhook fires invoice.created
Record a payment → webhook fires payment.recorded
GET /billing-profile → returns company details
Check postMessage events fire in browser console
Test session expiry handling

#Going Live

Switch to your live credentials — and the live partnerId in the embed JWT
Update environment variables:
WESAVETAX_BASE_URL=https://www.wesavetax.com
WESAVETAX_PARTNER_ID=yourname
WESAVETAX_API_KEY=txe_partner_yourname_xxx
WESAVETAX_EMBED_SECRET=<64 hex chars>
WESAVETAX_WEBHOOK_SECRET=<32 hex chars>
Ask WeSaveTax to add your production domain to Allowed Domainse.g. *.yourdomain.com
Update iframe origin check in postMessage listener:
event.origin !== "https://www.wesavetax.com"
Test once with a real company before full rollout
WeSaveTax — ITR, GST, Audit & Tax Advisory