Xero Integration Create Access Token With Working Example.

This blog was written on 21 Nov 2021 and the example uses ASP.NET MVC, you can download the working example at GitHub.

The example site uses Xero.API.SDK version 2.2.9, Xero.NetStandards.OAuth2 version 3.20.0 and Xero.NetStandards.OAuth2Client version 1.5.1.

Xero is an online accounting software that allows you to create customers and send invoices as well as connect to your bank.

This blog is the first of three parts that will show you how to do the following:

So just like most blogs that I write, let's just jump straight into it.

Create an Access Token.

For Xero Integration to work, you must first create your app in the developer portal on the Xero website, you need to fill in a few fields, but for this example, the most important is the Redirect URLs and client credentials which are the client id and client secret as the image below shows. You will need to keep these somewhere safe as you will need them later. This blog shows you how to use the standard authorization code flow.

Xero Integration Create Access Token With Working ExampleNow that you have created your app, let's add the code to retrieve the access token, in this example, I have created a helper class and the code for this is below.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Xero.NetStandard.OAuth2.Config;
using Xero.NetStandard.OAuth2.Models;

namespace XeroIntergration.Models.XeroBearerToken
{
    public static class XeroConfigurationHelper
    {
        public static XeroConfiguration XeroConfiguration()
        {
            string clientId         = ConfigurationManager.AppSettings["XeroClientId"];
            string clientSecret     = ConfigurationManager.AppSettings["XeroClientSecret"];
            string baseUrl          = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

            XeroConfiguration xconfig = new XeroConfiguration
            {
                ClientId        = clientId,
                ClientSecret    = clientSecret,
                CallbackUri     = new Uri($"{baseUrl}/home/authorize"),
                Scope           = "openid"
            };

            return xconfig;
        }

        public static void StoreToken(XeroToken xeroToken)
        {
            var dir         = HttpContext.Current.Server.MapPath("~/XeroToken");
            var file        = Path.Combine(dir, "xeroToken.json");
            string serilizeToken   = JsonConvert.SerializeObject(xeroToken);
            File.WriteAllText(file,serilizeToken);
        }

        public static XeroToken RetrieveToken()
        {
            var dir = HttpContext.Current.Server.MapPath("~/XeroToken");
            var file = Path.Combine(dir, "xeroToken.json");

            using (StreamReader streamReader = new StreamReader(file))
            {
                string json = streamReader.ReadToEnd();
                XeroToken token = JsonConvert.DeserializeObject(json);
                return token;
            }
        }

        public class XeroToken
        {
            public string AccessToken    { get; set; }
            public DateTime ExpiresAtUtc { get; set; }
            public string IdToken        { get; set; }
            public string RefreshToken   { get; set; }
            public List Tenant   { get; set; }
        }

        public static bool DoesXeroTokenFileExist()
        {
            var dir = HttpContext.Current.Server.MapPath("~/XeroToken");
            var file = Path.Combine(dir, "xeroToken.json");

            bool fileExists = File.Exists(file);

            return fileExists;
        }
    }
}

The code above does a number of things, the XeroConfiguration method retrieves the clientId and client secret from the app setting in the web.config file, it also gets the callback URL that Xero requires.

  • StoreToken method simple stores the token in a JSON file.
  • RetrieveToken method retrieves the token.
  • The DoesXeroTokenFileExist ckecks if the file exists
  • XeroToken class is the model for storing the token data returned from Xero

The next class is the XeroBearerToken class and the code for that is below, this is the class that creates the login link for Xero and also retrieves the token on successful login.

using System;
using System.Threading.Tasks;
using Xero.NetStandard.OAuth2.Client;
using Xero.NetStandard.OAuth2.Token;

namespace XeroIntergration.Models.XeroBearerToken
{
    public class XeroBearerToken : IXeroBearerToken
    {
        public string LoginUrl()
        {
            bool doesXeroTokenFileExist = XeroConfigurationHelper.DoesXeroTokenFileExist();

            XeroClient client;
            string authorizeUrl;

            if (doesXeroTokenFileExist)
            {
                var token = XeroConfigurationHelper.RetrieveToken();

                if (token != null )
                {
                    //var xeroToken = token.Token;
                    var xeroTokenExpires = token.ExpiresAtUtc;

                    if (DateTime.Now.ToUniversalTime() > xeroTokenExpires)
                    {
                        client          = new XeroClient(XeroConfigurationHelper.XeroConfiguration());
                        authorizeUrl    = client.BuildLoginUri();

                        return authorizeUrl;
                    }
                }
            }

            client = new XeroClient(XeroConfigurationHelper.XeroConfiguration());
            authorizeUrl = client.BuildLoginUri();
            return authorizeUrl;

        }

        public string BearerToken(string code)
        {
            var client          = new XeroClient(XeroConfigurationHelper.XeroConfiguration());
            var bearerToken     = Task.Run(()=>client.RequestAccessTokenAsync(code));
            
            IXeroToken token            = bearerToken.Result;
            DateTime expiryDateTime   = bearerToken.Result.ExpiresAtUtc;

            XeroConfigurationHelper.XeroToken xeroToken = new XeroConfigurationHelper.XeroToken
            {
                AccessToken     = token.AccessToken,
                ExpiresAtUtc    = expiryDateTime,
                IdToken         = token.IdToken,
                RefreshToken    = token.RefreshToken,
                Tenant          = token.Tenants
            };

            XeroConfigurationHelper.StoreToken(xeroToken);
           
            return token.AccessToken;
        }
    }
}

The LoginUrl returns the login URL from Xero and creates the link which is on the home page, once you click the link on the home page, you are sent to the login page on Xero and then returned to the callback URL with the code, the BearerToken class then creates the access token.

The access token is then stored in a JSON file and is checked to see if the expiry date is greater than the current date-time.  

The home controller is very simple and the code is below:

using System.Web.Mvc;
using XeroIntergration.Models.XeroBearerToken;

namespace XeroIntergration.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            IXeroBearerToken token  = new XeroBearerToken();
            var loginUrl     = token.LoginUrl();

            ViewBag.AuthUrl        = loginUrl;
            return View();
        }

        public ActionResult Authorize(string code)
        {
            IXeroBearerToken token  = new XeroBearerToken();
            var xeroToken    = token.BearerToken(code);
            ViewBag.Token          = xeroToken;
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

If you download the code from Github and run the example, you should see the access token as the image below shows.

Xero Access Token

That's all for this blog, in the next blogs I will show you how to create a customer and send invoices. 

Thanks for reading.