vsmsconnect — API — xero

← all endpoints

GET/api/v1/accounting/xero/start auth: jwt (administrator)

Begin a Xero OAuth2 authorisation flow for the caller's business. Generates a PKCE verifier + state, persists them in OAuthStates, and returns the Xero authorisation URL the app/browser must redirect to. Rate-limited (10/min open bucket).

handlers: XeroAuthController.start

Inputs

No parameters.

Outputs

200
APIResponseDataObject<XeroStartResponse>
`{ authorizationUrl }` — the Xero hosted-consent URL.
409
APIError
BUSINESS_CONTEXT_REQUIRED — caller has not completed business registration.
429
APIError
Rate limit exceeded.
GET/api/v1/accounting/xero/callback auth: none

OAuth callback target hit by the user's browser after Xero consent. Validates the state (constant-time), exchanges the authorisation code, upserts XeroConnections rows for every tenant returned, and either 302-redirects (desktop) or serves a 200 text/html bridge page (mobile UA) that opens the native `vsms://auth/xero/...` deep link.

handlers: XeroAuthController.callback

Inputs

namerequireddefaultdescription
code query
string
no—OAuth authorisation code returned by Xero on success.
state query
string
no—Opaque PKCE state value previously issued by `/start`. Constant-time compared against OAuthStates row.
error query
string
no—Set by Xero when the user denies consent or the flow fails. Triggers the failure bridge / failure deep link.
error_description query
string
no—Human-readable error message from Xero (logged, sanitised before being exposed).

Outputs

302
redirect
Desktop User-Agent — Location header points at `${XERO_FRONTEND_WEB_BASE_URL}/auth/xero/{success|failure}` carrying tenant name or sanitised error code.
200
text/html
Mobile User-Agent — HTML bridge page that tries `XERO_FRONTEND_SUCCESS_URL` / `XERO_FRONTEND_FAILURE_URL` deep link then falls through to the web URL after 900 ms.
GET/api/v1/accounting/xero/status auth: jwt

Connection summary for the caller's business — whether a Xero connection exists, the active tenant, the list of authorised tenants (no tokens), and the current `autoFiscaliseInvoices` flag.

handlers: XeroAuthController.status

Inputs

No parameters.

Outputs

200
APIResponseDataObject<XeroStatusResponse>
Connection summary including `connected`, `activeTenant`, `tenants[]`, and `autoFiscaliseInvoices`.
409
APIError
BUSINESS_CONTEXT_REQUIRED — caller has no businessId on the JWT.
GET/api/v1/accounting/xero/tenants auth: jwt

List every Xero tenant authorised for the caller's business. Each entry carries `isActive` to indicate which tenant is the current target of sync / webhooks.

handlers: XeroAuthController.tenants

Inputs

No parameters.

Outputs

200
APIResponseDataList<XeroTenantSummary>
Tenant list with `tenantName`, `tenantId`, `isActive`.
DELETE/api/v1/accounting/xero/connection auth: jwt (administrator)

Hard-disconnect Xero for the caller's business — deletes every XeroConnections row, drops encrypted tokens, fires `XERO_DISCONNECTED` audit.

handlers: XeroAuthController.disconnect

Inputs

No parameters.

Outputs

200
APIResponseDataObject<{ deletedCount: number }>
Number of connection rows deleted.
GET/api/v1/accounting/xero/tax-mappings auth: jwt (administrator)

List all Xero tax-type to V-SDC tax-label mappings for the business (active and inactive). Active rows ordered first, then alphabetically. `isActive: boolean` per row so the admin UI can surface a Restore action on soft-deleted entries.

handlers: XeroTaxMappingsController.list

Inputs

No parameters.

Outputs

200
APIResponseDataList<TaxRateMappingDTO>
Mappings for `Provider='xero'`.
POST/api/v1/accounting/xero/tax-mappings/auto-map auth: jwt (administrator)

Fetch Xero `/TaxRates` from the active tenant + V-SDC `/status`, then return match suggestions with `needsReview` flags + alternatives. Does NOT persist — the admin confirms each suggestion via PUT. Rate-limited (10/min open bucket).

handlers: XeroTaxMappingsController.autoMap

Inputs

No parameters.

Outputs

200
APIResponseDataObject<XeroTaxMappingAutoMapResponse>
Suggestions array with `providerTaxType`, `suggestedVsdcLabel`, `alternatives[]`, `needsReview`.
401
APIError
REAUTH_REQUIRED — Xero refresh token rejected.
429
APIError
Rate limit exceeded (caller or Xero).
PUT/api/v1/accounting/xero/tax-mappings auth: jwt (administrator)

Create or update one Xero tax-type to V-SDC label mapping (MERGE on (businessId, 'xero', providerTaxType)). Re-activates an existing inactive row instead of inserting a duplicate. Fires `XERO_TAX_MAPPING_UPDATED` audit.

handlers: XeroTaxMappingsController.upsert

Inputs

namerequireddefaultdescription
providerTaxType body
string
yes—Xero tax-type code (e.g. `OUTPUT2`, `ZERORATED`). Trimmed, 1–100 chars.
providerTaxName body
string | null
no—Human-readable Xero tax name for display.
providerRate body
number | null
no—Xero rate percent.
vsdcTaxLabel body
string
yes—Target V-SDC tax label (must be one of `F/N/P/E/T/A/B/C/D`).
vsdcRate body
number | null
no—V-SDC rate percent for display.

Outputs

200
APIResponseDataObject<TaxRateMappingDTO>
Upserted mapping row.
422
APIError
XERO_TAX_MAPPING_INVALID_LABEL — `vsdcTaxLabel` is not a valid V-SDC label.
DELETE/api/v1/accounting/xero/tax-mappings/:providerTaxType auth: jwt (administrator)

Soft-delete a Xero tax mapping — sets `IsActive=0`. Row is retained for history and can be re-activated via the restore endpoint. Idempotent.

handlers: XeroTaxMappingsController.remove

Inputs

namerequireddefaultdescription
providerTaxType path
string
yes—Xero tax-type code to deactivate.

Outputs

204
empty
No content.
PATCH/api/v1/accounting/xero/tax-mappings/:providerTaxType/restore auth: jwt (administrator)

Re-activate a previously soft-deleted Xero tax mapping (`IsActive=0` → `1`). Idempotent.

handlers: XeroTaxMappingsController.restore

Inputs

namerequireddefaultdescription
providerTaxType path
string
yes—Xero tax-type code to re-activate.

Outputs

204
empty
No content.
POST/webhooks/xero auth: hmac (x-xero-signature)

Xero-initiated webhook delivery. Verifies HMAC-SHA256 over the raw request body using `XERO_WEBHOOK_SIGNING_KEY` (constant-time compared to the base64 `x-xero-signature` header). Valid signature → fan each event to the `xero:webhook:events` Redis Stream and respond `200` within Xero's 5-second ack budget. Xero's intent-to-receive handshake (`events: []`) flows through the same code path. NOT mounted under `/api/v1`.

handlers: XeroWebhookController.handle

Inputs

namerequireddefaultdescription
x-xero-signature header
string
yes—Base64-encoded HMAC-SHA256 of the raw request body.
events body
XeroWebhookEvent[]
no—Array of event objects (`tenantId`, `tenantType`, `eventCategory`, `eventType`, `resourceId`, `resourceUrl`, `eventDateUtc`, `eventSequence`). Empty array is the intent-to-receive ping.
firstEventSequence body
integer
no—Sequence number of the first event in the batch.
lastEventSequence body
integer
no—Sequence number of the last event in the batch.
entropy body
string
no—Random salt included by Xero.

Outputs

200
empty
Valid signature — events XADDed to Redis Stream, empty body.
401
APIError
XERO_WEBHOOK_SIGNATURE_INVALID — HMAC mismatch.
503
APIError
XERO_WEBHOOK_NOT_CONFIGURED — `XERO_WEBHOOK_SIGNING_KEY` is unset (dev safe default).
GET/api/v1/accounting/xero/sync auth: jwt (administrator | view_invoices | submit_invoices)

Pull-sync PAID invoices from the active Xero tenant: fetch via `XeroProvider.getInvoices`, normalise to `AccountingInvoice[]`, persist to `Invoices` table (`Source='xero'`) with one `ImportBatches` row per call. Idempotency key = `SHA-256(businessId:xeroTenantId:xeroInvoiceId)`. When `AutoFiscaliseInvoices=1`, newly-inserted eligible invoices are chunked (10) and dispatched as fiscalisation jobs. Returns the `AccountingInvoice[]` plus a summary message including `jobIds=`. HTTP caching disabled. Runs in the background: replies `202 { runId }` at once and stores the outcome on the run. The finished run's `result` is the old synchronous body: `data` is now an empty list, `totalRows` the fetched count and `message` the counters string.

handlers: AccountingInvoicesController.xeroSync

Inputs

namerequireddefaultdescription
contactId query
string
no—Provider-native contact GUID — narrows the result to invoices for that contact.
modifiedSince query
ISO-8601 datetime
no—Only invoices updated after this date are returned (passed as `If-Modified-Since` to Xero).
dateTo query
ISO-8601 datetime
no—Post-fetch filter on `updatedAt` (Xero has no `dateTo` param).
page query
integer
no—1-based page. Omit to auto-paginate.
pageSize query
integer
no—1–100. Capped by the provider.

Outputs

202
APIResponseDataObject<BackgroundRunAcceptedDTO>
Started in the background: `{ runId }`. Poll `GET /api/v1/businesses/:businessId/background-runs/:runId`; once `status` is `done`, `result` holds the response body this endpoint used to return.
409
APIError
BACKGROUND_RUN_IN_PROGRESS — a Sync Now for this provider and business is already running. `data` is `BackgroundRunInProgressDTO` (`runId`, `kind`, `params`, `startedAt`) of the running run.
401
APIError
REAUTH_REQUIRED — Xero refresh token rejected.
409
APIError
ACCOUNTING_PROVIDER_NOT_CONFIGURED — no active Xero connection.
429
APIError
XERO_RATE_LIMITED — propagated from Xero with `Retry-After`.
PATCH/api/v1/accounting/xero/connections/:connectionId/location auth: jwt (administrator)

Map one Xero organisation (connection) to the VSMS Location whose certificate signs its invoices. locationId is required but nullable: null clears the mapping and returns the organisation to the business-default fallback. A non-null assignment triggers a best-effort re-sync of the backlog that became signable. Returns the refreshed tenant list for the business. Assigning a location starts the business-wide blocked-invoice re-sync as a background run and replies without waiting for it; if a re-sync is already running, none is started.

handlers: XeroAuthController.setConnectionLocation

Inputs

namerequireddefaultdescription
connectionId path
uuid
yes—XeroConnections row id (one row per organisation).
locationId body
uuid | null
yes—Location to map; null clears. Required — omission is rejected.

Outputs

200
APIResponseDataList<XeroTenantSummary>
All of the business's Xero tenants with their current location mapping.
404
APIError
ACCOUNTING_PROVIDER_NOT_CONFIGURED (connection not found for this business) or LOCATION_NOT_FOUND.
409
APIError
BUSINESS_CONTEXT_REQUIRED.
422
APIError
VALIDATION_ERROR — invalid uuid or missing locationId.
POST/api/v1/accounting/xero/organisations/refresh auth: jwt (administrator)

Re-read the organisations on the stored Xero authorisation. Adds any the grant now covers as PENDING (not syncing until accepted) and refreshes the name and short code of those already held. It can only see organisations the existing authorisation already includes: granting access to a further organisation in Xero still needs the admin to reconnect.

handlers: XeroAuthController.refreshOrganisations

Inputs

No parameters.

Outputs

200
APIResponseDataList<XeroTenantSummary>
The refreshed organisation list. What changed rides in `message`, e.g. `added=1 missing=0`.
409
APIError
BUSINESS_CONTEXT_REQUIRED.
POST/api/v1/accounting/xero/connections/:connectionId/reject auth: jwt (administrator)

Decline one connected Xero organisation: it is forced disabled and stays that way until accepted again. Refused while a signing location is assigned - clear the mapping first.

handlers: XeroAuthController.rejectConnection

Inputs

namerequireddefaultdescription
connectionId path
string (uuid)
yes—Xero connection id (one per organisation).

Outputs

200
APIResponseDataObject<XeroTenantSummary>
The organisation after the change.
409
APIError
XERO_ORGANISATION_MAPPED_CANNOT_REJECT - the organisation still has a signing location; or BUSINESS_CONTEXT_REQUIRED.
POST/api/v1/accounting/xero/connections/:connectionId/accept auth: jwt (administrator)

Accept one Xero organisation: a PENDING one (newly authorised, not yet reviewed) or a rejected one coming back. Either way it becomes live - enabled and syncing - and unmapped, so its invoices are held until an admin assigns a signing location.

handlers: XeroAuthController.acceptConnection

Inputs

namerequireddefaultdescription
connectionId path
string (uuid)
yes—Xero connection id (one per organisation).

Outputs

200
APIResponseDataObject<XeroTenantSummary>
The organisation after the change.
409
APIError
BUSINESS_CONTEXT_REQUIRED.