This example demonstrates the workflow for accessing the Accounting API: initializing the client, setting the token, updating tenants to find the active tenant ID, and performing CRUD operations on Invoices and History Records.
Note: When creating invoices, use the Invoice.TypeEnum and Invoice.StatusEnum for type safety.
import { XeroClient, HistoryRecords, Invoice } from 'xero-node';
const xero = new XeroClient({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
redirectUris: [`http://localhost:${port}/callback`],
scopes: 'openid profile email accounting.settings accounting.transactions offline_access'.split(" ")
});
await xero.initialize();
const tokenSet = getTokenSetFromDatabase(userId);
await xero.setTokenSet(tokenSet);
if(tokenSet.expired()){
const validTokenSet = await xero.refreshToken();
}
await xero.updateTenants();
const activeTenantId = xero.tenants[0].tenantId;
// GET all Accounts
const getAccountsResponse = await xero.accountingApi.getAccounts(activeTenantId);
const accountId = getAccountsResponse.body.accounts[0].accountID;
// CREATE an Invoice
const invoices = {
invoices: [
{
type: Invoice.TypeEnum.ACCREC,
contact: { contactID: contactId },
lineItems: [
{
description: "Acme Tires",
quantity: 2.0,
unitAmount: 20.0,
accountCode: "500",
taxType: "NONE",
lineAmount: 40.0
}
],
date: "2019-03-11",
dueDate: "2018-12-10",
reference: "Website Design",
status: Invoice.StatusEnum.AUTHORISED
}
]
};
const createdInvoicesResponse = await xero.accountingApi.createInvoices(activeTenantId, invoices);
const invoiceId = createdInvoicesResponse.body.invoices[0].invoiceID;
// CREATE a History Record
const historyRecords = {
historyRecords: [
{
details: "This is a history record"
}
]
};
await xero.accountingApi.createInvoiceHistory(activeTenantId, invoiceId, historyRecords);