Tyf0x / Xero-NetStandard

A wrapper of the Xero API in the .NetStandard 2.0 framework. Supports Accounting, Payroll AU/US, and Files

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Xero OAuth2 .Net SDK

This code is generated from the openapi-generator based on Xero OpenAPI 3.0 Specification

NuGet.org

Current release of SDK with OAuth2 support

Xero-NetStandard SDK supports OAuth2 authentication and the following API sets.

  • accounting
  • fixed asset
  • identity
  • payroll AU
  • payroll UK
  • payroll NZ
  • projects
  • bank feeds
  • files

Documentation

Xero API Documentaion

For full Xero API documentation please visit developer portal documentation.

API Client Docs

How to handle OAuth 2.0 authentication & authorization?

We have built Xero OAuth 2.0 Client. Check out Xero.NetStandard.OAuth2Client

NuGet.org

To learn more about how our OAuth 2.0 flow works and how to use the OAuth 2.0 client, check out our Xero developer blog post: Up and running with .NET and Xero OAuth 2.0

Looking for previous SDK with oAuth 1.0a support?

Codebase, samples and setup instructions located in oauth1 branch.

Getting Started

Sample apps

Looking for sample apps for this SDK? A dotnet core 3.1 MVC one is available here. A .NET Framework 4.6.1 one is available here.

Create a Xero App

Follow these steps to create your Xero app

  • Create a free Xero user account (if you don't have one)
  • Use this URL for beta access to oAuth2 https://developer.xero.com/myapps
  • Click "New app" link
  • Enter your App name, company url, privacy policy url, and 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.

Installation

Use Nuget to download the package

	dotnet add package Xero.NetStandard.OAuth2
	dotnet add package Xero.NetStandard.OAuth2Client

or using the Package Manager Console inside Visual Studio

	Install-Package Xero.NetStandard.OAuth2
	Install-Package Xero.NetStandard.OAuth2Client

or you can download the source code from https://github.com/XeroAPI/Xero-NetStandard and compile it by yourself.

To get started there are a few main classes.

  • The AccountingApi class
  • XeroOAuth2

The AccountingApi class is not coupled to the OAuth2 class, so feel free to use your own.

To get started you will just need two things to make calls to the Accounting Api.

  • xero-tenant-id
  • accessToken

** Note: starting from Xero.NetStandard.OAuth2Client v1.0.0, we have dropped the dependency on IHttpClientFatory. Plase refer to older IHttpClientFactory implementation example for dotnet core and dotnet framework.

Build the login link - the code flow (a .NET Core Mvc example):

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using Xero.NetStandard.OAuth2.Client;
    using Xero.NetStandard.OAuth2.Config;
    using Xero.NetStandard.OAuth2.Token;
    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Xero.NetStandard.OAuth2.Models;
    using System.Collections.Generic;


    namespace XeroNetStandardApp.Controllers
    {
      public class XeroOauth2Controller : Controller
      {
        private readonly ILogger<HomeController> _logger;
        private readonly IOptions<XeroConfiguration> XeroConfig;

        public XeroOauth2Controller(IOptions<XeroConfiguration> config, ILogger<HomeController> logger)
        {
          _logger = logger;
          this.XeroConfig = config;
        }

        public IActionResult Index()
        {
          XeroConfiguration xconfig = new XeroConfiguration();
          xconfig.ClientId = "yourClientId";
          xconfig.ClientSecret = "yourClientSecret";
          xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
          xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";

          var client = new XeroClient(xconfig);

          return Redirect(client.BuildLoginUri());
        }
      }
    }

From here the user will be redirected to login, authorise access and get redirected back

On the way back you will get a parameter with code and state

  • code
  • state
	XeroConfiguration xconfig = new XeroConfiguration(); 
    
	xconfig.ClientId = "yourClientId";
	xconfig.ClientSecret = "yourClientSecret";
	xconfig.CallbackUri = new Uri("https://localhost:5001") //default for standard webapi template
	xconfig.Scope = "openid profile email files accounting.transactions accounting.contacts offline_access";
	
	var client = new XeroClient(xconfig);
	
	//before getting the access token please check that the state matches
	await client.RequestAccessTokenAsync(code);
    
	//from here you will need to access your Xero Tenants
	List<Tenant> tenants = await client.GetConnections();
    
	// you will now have the tenant id and access token
	foreach (Tenant tenant in tenants)
	{
		// do something with your tenant and access token
		//client.AccessToken;
		//tenant.TenantId;
	}

Build the login link - the PKCE flow (a .NET Core Mvc example):

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using Xero.NetStandard.OAuth2.Client;
    using Xero.NetStandard.OAuth2.Config;
    using Xero.NetStandard.OAuth2.Token;
    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Xero.NetStandard.OAuth2.Models;
    using System.Collections.Generic;


    namespace XeroNetStandardApp.Controllers
    {
      public class XeroOauth2Controller : Controller
      {
        private readonly ILogger<HomeController> _logger;
        private readonly IOptions<XeroConfiguration> XeroConfig;

        public XeroOauth2Controller(IOptions<XeroConfiguration> config, ILogger<HomeController> logger)
        {
          _logger = logger;
          this.XeroConfig = config;
        }

        public IActionResult Index()
        {
          XeroConfiguration xconfig = new XeroConfiguration();
          xconfig.ClientId = "yourClientId";
          xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
          xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";
	  xconfig.State = "YOUR_STATE"

          var client = new XeroClient(xconfig);

          // generate a random codeVerifier
          var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";          
          Random random = new Random();
          int charsLength = random.Next(43, 128);
          char[] randomChars = new char[charsLength];
          for (int i = 0; i < charsLength; i++)  
          {  
              randomChars[i] = validChars[random.Next(0, validChars.Length)];  
          }  
          string codeVerifier = new String(randomChars);

          return Redirect(client.BuildLoginUriPkce(codeVerifier));
        }
      }
    }

From here the user will be redirected to login, authorise access and get redirected back using the Pkce method

	XeroConfiguration xconfig = new XeroConfiguration(); 
	xconfig.ClientId = "yourClientId";
	xconfig.CallbackUri = new Uri("https://localhost:5001") //default for standard webapi template
	xconfig.Scope = "openid profile email files accounting.transactions accounting.contacts offline_access";
	
	var client = new XeroClient(xconfig);
  	string codeVerifier = "Aaaaaaaaaa.Bbbbbbbbbb.0000000000.1111111111";

	await client.RequestAccessTokenPkceAsync(code, codeVerifier);

To refresh your token. Just call the refresh (shared between code & PKCE flows)

	client.RefreshTokenAsync(xeroToken);

To setup the main API object see the snippet below:

Accounting APIs:

  • Get All invoices
	var AccountingApi = new AccountingApi();
	var response = await AccountingApi.GetInvoicesAsync(accessToken, xeroTenantId);
  • Get invoices from the last 7 days:
      var AccountingApi = new AccountingApi();


      var sevenDaysAgo = DateTime.Now.AddDays(-7).ToString("yyyy, MM, dd");
      var invoicesFilter = "Date >= DateTime(" + sevenDaysAgo + ")";

      var response = await AccountingApi.GetInvoicesAsync(accessToken, xeroTenantId, null, invoicesFilter);
  • Create an invoice (Accounting APIs):
      var contact = new Contact();
      contact.Name = "John Smith";
      
      var line = new LineItem() {
        Description = "A golf ball",
        Quantity = float.Parse(LineQuantity),
        UnitAmount = float.Parse(LineUnitAmount),
        AccountCode = "200"
      };

      var lines = new List<LineItem>() {
        line
      };

      var invoice = new Invoice() {
        Type = Invoice.TypeEnum.ACCREC,
        Contact = contact,
        Date = DateTime.Today,
        DueDate = DateTime.Today.AddDays(30),
        LineItems = lines
      };

      var invoiceList = new List<Invoice>();
      invoiceList.Add(invoice);

      var invoices = new Invoices();
      invoices._Invoices = invoiceList;

      var AccountingApi = new AccountingApi();
      var response = await AccountingApi.CreateInvoicesAsync(accessToken, xeroTenantId, invoices);

Fixed Asset APIs

  • Get All Fixed Assets:
      var AssetApi = new AssetApi();
      var response = await AssetApi.GetAssetsAsync(accessToken, xeroTenantId, AssetStatusQueryParam.DRAFT);
  • Create a fixed asset:
      var asset = new Asset() {
        AssetName = "Office Computer",
        AssetNumber = "FA-001"
      };

      var AssetApi = new AssetApi();
      var response = await AssetApi.CreateAssetAsync(accessToken, xeroTenantId, asset);

Identity APIs:

  • Get Xero API Tenant/Org connections:
      var IdentityApi = new IdentityApi();
      var response = await IdentityApi.GetConnectionsAsync(accessToken);
  • Delete a Xero API Tenant/Org connection:
      Guid connectionIdGuid = Guid.Parse(connectionId);

      var IdentityApi = new IdentityApi();
      await IdentityApi.DeleteConnectionAsync(accessToken, connectionIdGuid);

Payroll AU APIs:

  • Get Employees:
      var PayrollAUApi = new PayrollAUApi();
      var response = await PayrollAUApi.GetEmployeesAsync(accessToken, xeroTenantId);

      var employees = response._Employees;
  • Create a Employee:
      DateTime dob = DateTime.Today.AddYears(-20);

      HomeAddress homeAddress = new HomeAddress() {
        AddressLine1 = "6 MeatMe Street",
        AddressLine2 = " ",
        Region = State.VIC,
        City = "Long Island",
        PostalCode = "0000", 
        Country = "New York"
      };

      Employee employee = new Employee() {
        FirstName = "Bob",
        LastName = "Belcher",
        DateOfBirth = dob,
        HomeAddress = homeAddress
      };

      var employees = new List<Employee>() { employee };

      var PayrollAUApi = new PayrollAUApi();
      var response = await PayrollAUApi.CreateEmployeeAsync(accessToken, xeroTenantId, employees);

Bankfeed APIs

Before trying the APIs, please make sure your company had been approved for Bankfeed endpoints and have the bankfeed scope enabled on your Xero OAuth 2.0 app. If you intend to become a Xero bankfeed partner please start by registering here.

  • Create a bankfeed connection
      var feedConnection = new FeedConnection{
        AccountToken = accountToken, 
        AccountNumber = accountNumber,
        AccountType =  accountTypeEnum,
        AccountName = accountName,
        Currency = currencyCode,
        Country = countryCode
      };

      List<FeedConnection> list = new List<FeedConnection>();
      list.Add(feedConnection);

      FeedConnections items = new FeedConnections{
        Pagination = new Pagination(),
        Items = list
      };

      var BankfeedsApi = new BankFeedsApi();
      await BankfeedsApi.CreateFeedConnectionsAsync(accessToken, xeroTenantId, items);
  • Get all bankfeed connections
      var BankFeedsApi = new BankFeedsApi();
      var response = await BankFeedsApi.GetFeedConnectionsAsync(accessToken, xeroTenantId);
      var feedConnections = response.Items;
  • Delete a bankfeed connection
      Guid bankfeedConnectionIdGuid = Guid.Parse(bankfeedConnectionId);

      List<FeedConnection> list = new List<FeedConnection>();
      
      list.Add(
        new FeedConnection {
          Id = bankfeedConnectionIdGuid
        }
      );

      var feedConnections = new FeedConnections{
          Items = list
      };

      var BankFeedsApi = new BankFeedsApi();
      await BankFeedsApi.DeleteFeedConnectionsAsync(accessToken, xeroTenantId, feedConnections);
  • Create statements against a bankfeed connection (plase ensure your start balance, end balance and statement amounts are mathematically correct)
      StartBalance startBalance = new StartBalance{
        Amount = decimal.Parse(startBalanceAmount),
        CreditDebitIndicator = startIndicatorEnum
      };


      StatementLine statementLine = new StatementLine{
        PostedDate = DateTime.Today,
        Description = "A bankfeed satemement description",
        Amount = 10,
        CreditDebitIndicator = startIndicatorEnum,
        TransactionId = new Guid().ToString()
      };

      EndBalance endBalance = new EndBalance{
        Amount = decimal.Parse(startBalanceAmount) + statementLine.Amount,
        CreditDebitIndicator = startIndicatorEnum
      };

      List<StatementLine> statementLines = new List<StatementLine>();
      statementLines.Add(statementLine);

      var statement = new Statement{
        FeedConnectionId = new Guid(feedConnectionId),
        StartDate = DateTime.Today.AddDays(-20),
        EndDate = DateTime.Today,
        StartBalance = startBalance,
        EndBalance = endBalance,
        StatementLines = statementLines,
      };

      List<Statement> statementList = new List<Statement>();
      statementList.Add(statement);

      Statements statements = new Statements{
        Pagination = new Pagination(),
        Items = statementList
      };

      var BankfeedsApi = new BankFeedsApi();
      await BankfeedsApi.CreateStatementsAsync(accessToken, xeroTenantId, statements);
  • Get all statements from all bankfeed connections
      var BankFeedsApi = new BankFeedsApi();
      var response = await BankFeedsApi.GetStatementsAsync(accessToken, xeroTenantId);

Files APIs:

  • Upload a file:
      var FilesApi = new FilesApi();

      // Convet IFormFile to byte array
      byte[] byteArray; 
      using (MemoryStream data = new MemoryStream())
      {
        file.CopyTo(data);
        byteArray = data.ToArray();
      }
      
      // Upload file
      var response = await FilesApi.UploadFileAsync(
          accessToken,
          xeroTenantId,
          null,
          byteArray,
          file.FileName,
          file.FileName,
          file.ContentType
      );
  • Get Files:
      var FilesApi = new FilesApi();
      var response = await FilesApi.GetFilesAsync(accessToken, xeroTenantId);
      var filesItems = response.Items;
  • Delete a File:
      Guid fileIDGuid = Guid.Parse(fileID);

      var filesApi = new FilesApi();
      await filesApi.DeleteFileAsync(accessToken, xeroTenantId, fileIDGuid);
  • Rename a File:
      Guid fileIDGuid = Guid.Parse(fileID);

      var filesApi = new FilesApi();
      FileObject file = await filesApi.GetFileAsync(accessToken, xeroTenantId, fileIDGuid);
      file.Name = newName;

      var response = await filesApi.UpdateFileAsync(accessToken, xeroTenantId, fileIDGuid, file);
  • Get Associations
      var FilesApi = new FilesApi();
      var response = await FilesApi.GetFileAssociationsAsync(accessToken, xeroTenantId, new Guid(fileId));
  • Create an Association
      var FilesApi = new FilesApi();

      var fileIdGuid = new Guid(fileId);
      var invoiceIdGuid = new Guid(invoiceId);
      Enum.TryParse<ObjectType>(objectType, out var objectTypeEnum);

      Association association = new Association{
          FileId = fileIdGuid,
          ObjectId = invoiceIdGuid,
          ObjectType = objectTypeEnum,
          ObjectGroup = ObjectGroup.Invoice
      };

      var response = await FilesApi.CreateFileAssociationAsync(accessToken, xeroTenantId, fileIdGuid, association);
  • Delete an Association
      var fileIdGuid = new Guid(fileId);
      var objectIdGuid = new Guid(objectId);

      var FilesApi = new FilesApi();
      await FilesApi.DeleteFileAssociationAsync(accessToken, xeroTenantId, fileIdGuid, objectIdGuid);

For full documentation please refer to Xero Bankfeed API documentation.

TLS 1.0 deprecation

As of June 30, 2018, Xero's API will remove support for TLS 1.0.

The easiest way to force TLS 1.2 is to set the Runtime Environment for your server (Tomcat, etc) to Java 1.8 which defaults to TLS 1.2.

Participating in Xero’s developer community

This SDK is one of a number of SDK’s that the Xero Developer team builds and maintains. We are grateful for all the contributions that the community makes.

Here are a few things you should be aware of as a contributor:

  • Xero has adopted the Contributor Covenant Code of Conduct, we expect all contributors in our community to adhere to it
  • If you raise an issue then please make sure to fill out the github issue template, doing so helps us help you
  • You’re welcome to raise PRs. As our SDKs are generated we may use your code in the core SDK build instead of merging your code directly.
  • We have a contribution guide for you to follow when contributing to this SDK
  • Curious about how we generate our SDK’s? Have a read of our process and have a look at our OpenAPISpec
  • This software is published under the MIT License

For questions that aren’t related to SDKs please refer to our developer support page.

About

A wrapper of the Xero API in the .NetStandard 2.0 framework. Supports Accounting, Payroll AU/US, and Files

License:MIT License


Languages

Language:C# 100.0%