Skip to content

Xero Example

The code below is an example of a process connecting to Xero, making a request using the tokens from a Standard Integration. A single Xero connection can grant access to multiple organisations (tenants), so this example lists the available connections and then fetches the organisation details for each one, using the required Xero-tenant-id header.

INFO

This process requires a Standard Integration to have been set up with Xero - see Creating an Integration. CONNECTOR_NAME below must match the name of the connection you created there.

Process Code

js
function pre() {
    // This function is called once before the process is executed.
    // Use this to setup prompts.
    script.log('process pre-execution parameters parsed.');
}

function begin() {
    // This function is called once at the start of the process
    script.log('process execution started.');

    let orgsProcessed = [];

    const authData = JSON.parse(script.getOAuth("CONNECTOR_NAME"));
    const accessToken = "Bearer " + authData.access_token;

    const connectionsResponse = web.get("https://api.xero.com/connections", {
        "Accept": "application/json",
        "Authorization": accessToken
    });

    if (connectionsResponse.status < 200 || connectionsResponse.status >= 300) {
        console.log(`Failed to fetch connections, status code: ${connectionsResponse.status}.`);
        return;
    }

    const connections = JSON.parse(connectionsResponse.body);

    for (const connection of connections) {
        if (orgsProcessed.includes(connection.id)) {
            continue;
        }
        orgsProcessed.push(connection.id);

        const orgResponse = web.get("https://api.xero.com/api.xro/2.0/Organisation", {
            "Accept": "application/json",
            "Authorization": accessToken,
            "Xero-tenant-id": connection.tenantId
        });

        if (orgResponse.status >= 200 && orgResponse.status < 300) {
            const body = JSON.parse(orgResponse.body);
            console.log(body.Organisations[0]);
        } else {
            console.log(`Failed to fetch organisation for tenant ${connection.tenantId}, status code: ${orgResponse.status}.`);
        }
    }
}

function data(record) {
    // This function is called once for each line of data on the second cycle
    // Use this to build dimensions and push data into cubes
}

function end() {
    // This function is called once at the end of the process
    script.log('process execution finished.');
}