xero-node
Xero NodeJS OAuth 2.0 client for xero-node
Last updated 10 days ago by serknight .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install xero-node 
SYNC missed versions from official npm registry.

xero-node

npm

Release of SDK with oAuth 2 support

Version 4.x of Xero NodeJS SDK only supports oAuth2 authentication and the following API sets.

Looking for OAuth 1.0a support?

npm package

We've moved this code into the oauth1 branch.

Getting Started

Create a Xero App

Follow these steps to create your Xero app

  • Create a free Xero user account (if you don't have one)
  • Login to Xero developer center
  • Click "New App" link
  • Enter your App name, company url, privacy policy url.
  • Enter the redirect URI (this is your callback url - localhost, etc)
  • Agree to terms and condition and click "Create App".
  • Click "Generate a secret" button.
  • Copy your client id and client secret and save for use later.
  • Click the "Save" button. You secret is now hidden.

Repo Context & Contributing

This SDK's functionality is majority generated from our OpenAPISpec. The exception is the src/xeroClient.ts which contains the typescript that is unique to this repository. Contributions are welcome but please keep in mind that majority of SDK is auto-generated from the OpenAPISpec. We try to get changes in that projects to be released on a reasonable cadence.

Read more about our process in maintaining our suite of SDK's

Testing

We are working to build out a more robust test suite, and currently just have tests setup for our xeroClient.ts - PR's will now run against a CI build - and as we add more tests to this project community collaboration will be easier to incorporate.

npm test

Authentication

We use OAuth2.0 to generate access tokens that authenticate requests against our API. Each API call will need to have a valid token populated on the API client to succeed. In a tokenSet will be an access_token which lasts for 30 minutes, and a refresh_token which lasts for 60 days. If you don't want to require your users to re-authenticate each time you want to call the API on their behalf, you will need a datastore for these tokens and will be required to refresh the tokens at least once per 60 days to avoid expiration. The offline_access scope is required for refresh tokens to work.

In Xero a user can belong to multiple organisations. Tokens are ultimately associated with a Xero user, who can belong to multiple tenants/organisations. If your user 'Allows Access' to multiple organisations, be hyper aware of which tenantId you are passing to each function.


Step 1: Initialize the XeroClient, and redirect user to xero auth flow

Step 2: Call apiCallback to get your tokenSet

Step 3: Call updateTenats to populate additional tenant data You will need to have the accounting.settings scope in order to use this helper

NOTE: If you have already authorized the user and have stored a valid tokenSet, you can create a new XeroClient() and refresh your token without triggering the openid-client dependency:

  const tokenSet = getTokenSetFromUserId(user.id) // example function
  const newXeroClient = new XeroClient()
  const newTokenSet = await newXeroClient.refreshWithRefreshToken(xero_client_id, xero_client_secret, tokenSet.refresh_token)
  // refreshWithRefreshToken calls setAccessToken() so the refreshed token will be stored on newXeroClient
  await newXeroClient.accountingApi.getInvoices('my-tenant-uuid))

Step 1

  • Configure client and generate Authorization URL
  • Choose XeroAPI Scopes based on the access you need
  • initialize() the client to set up the 'openid-client'
  • Build the consentUrl
  • Redirect to auth flow
const port = process.env.PORT || 3000

const xero = new XeroClient({
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  redirectUris: [`http://localhost:${port}/callback`],
  scopes: 'openid profile email accounting.transactions offline_access'.split(" ")
});

// `buildConsentUrl()` calls `await xero.initialize()`
let consentUrl = await xero.buildConsentUrl();

res.redirect(consentUrl);

Step 2

Call apiCallback function with the response url which returns a tokenSet you can save in your datastore for future calls.

The tokenSet can also be accessed from the client as xero.readTokenSet().


const { TokenSet } = require('openid-client');

const tokenSet: TokenSet = await xero.apiCallback(req.url);

The tokenSet is what you should store in your database. That object is what you will need to pass to the client. It contains your access_token and refresh_token as well as other information regarding your connection.

{
  id_token: 'eyJhxxxx.yyy',
  access_token: 'eyJxxx.yyy.zzz',
  expires_at: 1231231234,
  token_type: 'Bearer',
  refresh_token: 'xxxyyyyzzz',
  scope: 'openid profile email accounting.settings accounting.reports.read accounting.journals.read accounting.contacts accounting.attachments accounting.transactions offline_access',
  session_state: 'xxx.yyy'
}

Step 3 (convenience step)

Populate the XeroClient's active tenant data

For most integrations you will always want to display the org name and additional metadata about the connected org. The /connections endpoint does not currently serialize that data so requires developers to make additional api calls for each org that your user connects to surface that information.

The updatedTenants function will query & nest the additional orgData results in your xeroClient under each connection/tenant object and return the array of tenants. This requires accounting.settings scope because updateTenants calls the organisation endpoint.

const tenants = await xero.updateTenants()

console.log(tenants || xero.tenants)
[
  {
    id: 'xxx-yyy-zzz-xxx-yyy',
    tenantId: 'xxx-yyy-zzz-xxx-yyy',
    tenantType: 'ORGANISATION',
    createdDateUtc: 'UTC-DateString',
    updatedDateUtc: 'UTC-DateString',
    orgData: {
      organisationID: 'xxx-yyy-zzz-xxx-yyy',
      name: 'My first org',
      version: 'US',
      shortCode: '!2h37s',
      ...
    }
  },
  {
    id: 'xxx-yyy-zzz-xxx-yyy',
    tenantId: 'xxx-yyy-zzz-xxx-yyy',
    tenantType: 'ORGANISATION',
    createdDateUtc: 'UTC-DateString',
    updatedDateUtc: 'UTC-DateString',
    orgData: {
      organisationID: 'xxx-yyy-zzz-xxx-yyy',
      name: 'My second org',
      version: 'AUS',
      shortCode: '!yrcgp',
      ...
    }
  }
]

Making offline_access calls

Once you have a valid token/tokenSet saved you can set the tokenSet on the client without going through the callback by calling setTokenSet.

For example - once a user authenticates you can refresh the token (which will also set the new token on the client) to make authorized api calls.

There are two ways to refresh a token.

// refreshToken()
const validTokenSet = await xero.refreshToken()

If you already generated a valid access token, you can initialize an empty client and refresh any saved access_tokens by passing the client, secret, and refresh_token to refreshWithRefreshToken()

const newXeroClient = new XeroClient()
const refreshedTokenSet = await newXeroClient.refreshWithRefreshToken(client_id, client_secret, tokenSet.refresh_token)

Making AUthorized API calls:

const tokenSet = getTokenSetFromDatabase(userId) // example function name

await xero.setTokenSet(tokenSet)

// you can call this to fetch/set your connected tenant data on your client, or you could also store this information in a database so you don't need to updateTenants every time you connect to API
await xero.updateTenants()

await xero.accountingApi.getInvoices(xero.tenants[0].tenantId)

SDK Documentation

Basics

// example flow of initializing and using the client after someone has already authenticated and you have saved their tokenSet
const xero = new XeroClient({
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  redirectUris: [`http://localhost:${port}/callback`],
  scopes: 'openid profile email accounting.transactions offline_access'.split(" ")
});
await xero.initialize();

const tokenSet = getYourTokenSetFromSavedLocation(currentUser)

await xero.setTokenSet(tokenSet)
...

const activeTenantId = xero.tenants[0].tenantId

const getOrgs = await xero.accountingApi.getOrganisations(activeTenantId)
const orgCountry= getOrgs.body.organisations[0].countryCode

const contactsResponse = await xero.accountingApi.getContacts(activeTenantId)
const contactId = getContactsResponse.body.contacts[0].contactID

---
import { XeroClient, Invoice } from "xero-node";

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 createdInvoice = await xero.accountingApi.createInvoices(activeTenantId, invoices)

Sample App

For more robust examples in how to utilize our accounting api we have (roughly) every single endpoint mapped out with an example in our sample app - complete with showing the Xero data dependencies required for interaction with many objects ( ie. types, assoc. accounts, tax types, date formats).

Just visit the repo https://github.com/XeroAPI/xero-node-oauth2-app configure your credentials & get started.

Other Helper functions

xero.tenants

// This needs to be called to setup relevant openid-client on the XeroClient
await xero.initialize()

// buildConsentUrl calls `await xero.initialize()` so if you wint't need to call initialize()
await xero.buildConsentUrl()

const tokenSet = await xero.readTokenSet();

if (tokenSet.expired()) {
  // refresh etc.
}

// some endpoints date fields require
// the MS date format for POST'ing data
const dateString = "1990-02-05"
const birthday = await xero.formatMsDate(dateString)

const validTokenSet = await xero.refreshToken()

await xero.refreshWithRefreshToken(client_id, client_secret, tokenSet.refresh_token)

await xero.disconnect(xero.tenants[0].id)

await xero.readIdTokenClaims()

await xero.readTokenSet()

const tokenSet = await xero.readTokenSet()
await xero.setTokenSet(tokenSet)

Current Tags

  • 4.6.0                                ...           latest (10 days ago)
  • 3.0.0-alpha.6                                ...           next (2 years ago)

108 Versions

  • 4.6.0                                ...           10 days ago
  • 4.5.2                                ...           17 days ago
  • 4.5.1                                ...           a month ago
  • 4.5.0                                ...           a month ago
  • 4.4.9                                ...           2 months ago
  • 4.4.8                                ...           2 months ago
  • 4.4.7                                ...           2 months ago
  • 4.4.6                                ...           2 months ago
  • 4.4.5                                ...           2 months ago
  • 4.4.4                                ...           2 months ago
  • 4.4.3                                ...           3 months ago
  • 4.4.2                                ...           3 months ago
  • 4.4.1                                ...           3 months ago
  • 4.4.0                                ...           3 months ago
  • 4.2.0                                ...           3 months ago
  • 4.1.7                                ...           3 months ago
  • 4.1.6                                ...           4 months ago
  • 4.1.5                                ...           4 months ago
  • 4.1.4                                ...           4 months ago
  • 4.1.3                                ...           4 months ago
  • 4.1.2                                ...           4 months ago
  • 4.1.1                                ...           4 months ago
  • 4.1.0                                ...           4 months ago
  • 4.0.7                                ...           4 months ago
  • 4.0.6                                ...           5 months ago
  • 4.0.5                                ...           5 months ago
  • 4.0.4                                ...           6 months ago
  • 4.0.3                                ...           6 months ago
  • 3.1.2                                ...           6 months ago
  • 4.0.2                                ...           6 months ago
  • 4.0.1                                ...           6 months ago
  • 4.0.0                                ...           6 months ago
  • 3.1.1                                ...           8 months ago
  • 4.0.0-alpha.3                                ...           8 months ago
  • 4.0.0-alpha.2                                ...           8 months ago
  • 4.0.0-alpha.1                                ...           8 months ago
  • 3.1.0                                ...           9 months ago
  • 3.0.21                                ...           a year ago
  • 3.0.20                                ...           a year ago
  • 3.0.19                                ...           a year ago
  • 3.0.17                                ...           a year ago
  • 3.0.16                                ...           a year ago
  • 3.0.15                                ...           a year ago
  • 3.0.14                                ...           2 years ago
  • 3.0.13                                ...           2 years ago
  • 3.0.12                                ...           2 years ago
  • 3.0.11                                ...           2 years ago
  • 3.0.10                                ...           2 years ago
  • 3.0.9                                ...           2 years ago
  • 3.0.8                                ...           2 years ago
  • 3.0.7                                ...           2 years ago
  • 3.0.6                                ...           2 years ago
  • 3.0.4                                ...           2 years ago
  • 3.0.3                                ...           2 years ago
  • 3.0.2                                ...           2 years ago
  • 3.0.1                                ...           2 years ago
  • 3.0.0                                ...           2 years ago
  • 3.0.0-alpha.10                                ...           2 years ago
  • 3.0.0-alpha.9                                ...           2 years ago
  • 3.0.0-alpha.8                                ...           2 years ago
  • 3.0.0-alpha.7                                ...           2 years ago
  • 2.20.0                                ...           2 years ago
  • 3.0.0-alpha.6                                ...           2 years ago
  • 3.0.0-alpha.5                                ...           2 years ago
  • 3.0.0-alpha.4                                ...           2 years ago
  • 3.0.0-alpha.3                                ...           2 years ago
  • 2.19.1                                ...           2 years ago
  • 3.0.0-alpha.2                                ...           2 years ago
  • 3.0.0-alpha.1                                ...           2 years ago
  • 2.19.0                                ...           2 years ago
  • 2.18.0                                ...           2 years ago
  • 2.17.0                                ...           2 years ago
  • 2.16.0                                ...           2 years ago
  • 2.15.0                                ...           2 years ago
  • 2.14.0                                ...           2 years ago
  • 2.13.0                                ...           2 years ago
  • 2.11.0                                ...           2 years ago
  • 2.12.0                                ...           2 years ago
  • 2.10.1                                ...           3 years ago
  • 2.10.0                                ...           3 years ago
  • 2.9.0                                ...           3 years ago
  • 2.8.0                                ...           3 years ago
  • 2.7.0                                ...           3 years ago
  • 2.6.0                                ...           3 years ago
  • 2.5.3                                ...           3 years ago
  • 2.5.2                                ...           3 years ago
  • 2.5.1                                ...           3 years ago
  • 2.5.0                                ...           3 years ago
  • 2.4.0                                ...           3 years ago
  • 2.3.0                                ...           3 years ago
  • 2.2.2                                ...           3 years ago
  • 2.2.1                                ...           3 years ago
  • 2.2.0                                ...           3 years ago
  • 2.1.8                                ...           3 years ago
  • 2.1.7                                ...           3 years ago
  • 2.1.6                                ...           3 years ago
  • 2.1.5                                ...           3 years ago
  • 2.1.4                                ...           3 years ago
  • 2.1.3                                ...           3 years ago
  • 2.1.2                                ...           3 years ago
  • 2.1.1                                ...           3 years ago
  • 2.1.0                                ...           3 years ago
  • 2.0.2                                ...           3 years ago
  • 2.0.1                                ...           3 years ago
  • 2.0.0                                ...           3 years ago
  • 1.1.2                                ...           3 years ago
  • 1.1.0                                ...           3 years ago
  • 1.0.0                                ...           3 years ago
Downloads
Today 0
This Week 0
This Month 150
Last Day 0
Last Week 0
Last Month 65
Dependencies (2)
Dev Dependencies (10)

Copyright 2014 - 2016 © taobao.org |