Getting Started with Xero .NET SDK

Jenks Guo
Xero Developer
Published in
6 min readJun 24, 2020

--

image by Clint Adair on unsplash

Xero-Net and Xero-NetStandard are two popular libraries with the Xero developer community. Through our new approach of generating SDKs from OpenAPI specification, we now offer a single .NET SDK for Xero OAuth 2.0 APIs under the Xero-NetStandard repository.

This SDK is built with the target framework of netstandard 2.0 which works for both .NET Core version v2.0+ and .NET Framework version v4.6.1+.

.NET implementation support

The SDK is stable and supports many of the API sets Xero platform has to offer. This article shows how to bootstrap your .NET project and save time in your development while focusing on building #beautiful solutions for our shared customers.

Where to get the goodies

The SDK is available from nuget.org as Xero.NetStandard.OAuth2 & Xero.NetStandardOAuth2Client. The codebase is available on Github under the MIT licence, so you have the ability to contribute or modify for your specific situation.

OAuth 2.0 client and Xero’s API client are decoupled for more flexibility:

  • The OAuth 2.0 Client package handles Xero OAuth 2.0 authentication. We include identity models for Xero tokens and tenants along with methods to perform actions such as retrieving a list of connected tenants and disconnecting individual tenants.
  • The Xero API client classes house the main HTTP client with hundreds of operations/methods and models for interacting with our endpoints.

So include SDK in your code is as easy as adding the following to your package reference :

Include the SDK in your project with the following package reference:

<PackageReference Include=”Xero.NetStandard.OAuth2Client” />
<PackageReference Include=”Xero.NetStandard.OAuth2"/>

… or Download them through the Visual Studio Package Manager console:

Install-Package Xero.NetStandard.OAuth2ClientInstall-Package Xero.NetStandard.OAuth2

… or via dotnet CLI:

dotnet add package Xero.NetStandard.OAuth2Clientdotnet add package Xero.NetStandard.OAuth2

Looks easy? Great, let’s see how it works on a high level.

How does it deal with Xero OAuth 2.0?

Start by declaring the following dependencies to connect to Xero OAuth 2.0:

using Xero.NetStandard.OAuth2.Client;using Xero.NetStandard.OAuth2.Config;using Xero.NetStandard.OAuth2.Token;

Once you have your Xero OAuth 2.0 app credentials & settings, keep them in appsettings.json so they are accessible via the IOptions<> pattern.

/appsettings.json

With the help of IHttpClientFactory interface. Instantiating the client just takes:

var client = new XeroClient(xconfig, httpClientFactory);

And building the redirect url to Xero login is as easy as:

Var redirect_url = client.BuildLoginUri();

When the code and state are returned by Xero identity server via CallbackUri, get your access token by simply passing the code :

var xeroToken = (XeroOAuth2Token)await client.RequestXeroTokenAsync(code);

The Xero tenant IDs can be accessed by:

List<Tenant> tenants = await client.GetConnections();

Now having both the xeroToken object and the list of Tenants you are ready to make calls to Xero’s API.

How does it interact with Xero APIs?

We’ve grouped methods for various API sets into classes in the Xero.NetStandard.OAuth2’s /Api directory.

A list of current Api client classes

To make an API call, all you need is the right method, accessToken object, xeroTenantId and any additional required or optional parameters.

For example, getting invoices over the last 7 days:

Another example, creating a fixed asset:

Now we are in business, go ahead and build your API workflow with all of the methods and models we offer in the SDK.

Sample Apps Walk-through

The best way to learn how to use an SDK, in my opinion, is to look at someone else’s work. So we have written sample applications for .NET Core MVC and .NET Framework MVC. Read on for a quick walkthrough of them.

The demo app has a few functions such as viewing organisation information, managing contracts and managing invoices. We are adding more functions to demo the capabilities of the SDK constantly. To not make this article short, I will focus on the authorization & invoice controllers only.

Authorization Controller

/NetSstandardApp/Controllers/AuthorizationController.cs Index method

The first step of the OAuth 2.0 flow is to redirect users to Xero login and get their consent so you can make API calls on behalf of. So in the authorization controller we have included IXeroConfig and IHttpClientFactory via dependency injection, created an Index method to return an redirect action to the login uri built by the SDK method. Any controller

/XeroNetStandardApp/Views/Home/Index.cshtml The view of HomeController

In the Index view of the HomeController, this is achieved by having a user click the “connect to Xero” button which triggers the GET /Authorization controller action.

XeroNetStandardApp/Controllers/AuthorizationController.cs Callback method

Once the authorization flow is complete, the user is redirected back to the redirectUri/callbackUri. The url includes the query parameters (code and the same state you sent over). These query params are captured by the Callback() method and used to obtain the xeroToken object.

Then a GetConnectionAsyc() method is called using the xeroToken object.

Resulting in a List<Tenant> object. As you can see, I am simply getting the first tenant in the list.

You can imagine, for a real life scenario, you’ll carefully map user account identity with this Xero tenant identity.

XeroNetStandardApp/Controllers/AuthorizationController.cs Disconnect method

To disconnect, you’ll use the Disconnect() method which performed a GET /Authorization/Disconnect request. Using the TokenUtilities’ method to destroy credentials.

Invoice Controller

XeroNetStandardApp/Controllers/InvoiceSyncController.cs Index method

The objective is to show a summary of invoices raised over the last 7 days. The best practice is to use Xero’s API top element filter which is supported by the SDK. So in the Index() method we first instantiate the DateTime object of 7 days ago, and build the invoiceFilter string as per Xero API’s documentation, then pass them into GetInvoicesAsync() method with the parameters in the correct locations.

XeroNetStandardApp/Views/InvoiceSync/Index.cshtml Invoice view

Loop over the List<Invoice> object returned from the API and render in a table /Views/InvoiceSync/Index.cshtml

The InvoiceSync screen

The intention is to also redirect users back to this screen so they can see the invoice they just created.

XeroNetStandardApp/Controllers/InvoiceSyncController.cs Create method
XeroNetStandardApp/Views/InvoiceSync/Create.cshtml
The create invoice screen

Gather user data through a simple webform to create a new invoice. The /Views/InvoiceSync/Create.cshtml displays a simple html form which POSTs to the InvoiceSyncController’s

XeroNetStandardApp/Controllers/InvoiceSyncController.cs Create method

The Invoice object is then constructed carefully and put into an Invoices object ready to be sent to Xero API via the CreateInvoicesAsync() method.

The user is then redirected back to the list of invoices and see the latest one they have just created.

What is different in .NET Framework

The code is only slightly different for .NET Framework. Instead of , the config is included in the Web.config

/Web.config

The XeroConfiguration object is constructed by reading the Web.config parameters:

Because dependency injection is not supported out of the box, you will need to include an extra package:

using Microsoft.Extensions.DependencyInjection;

The IHttpClientFactory is included by using ServiceCollection Class from the Microsoft.Extensions.DependencyInjection package like so.

var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

The rest of the code is identical to .NET Core.

I hope this article improves your understanding of the .NET SDK and accelerates your development.

Help us to make it better! We welcome developer feedback and contributions to our SDKs. They are fully open source. Raise an issue on the Github repository to share feedback and read our code of conduct and contribution guide as well.

Over two million small businesses, and their advisors are looking for the best cloud apps that integrate with Xero. Partner with us, and we’ll make sure they find yours.

--

--