Xero - beautiful accounting software

Xero Developer Help Center

Xero Developer Community

Community > API Authentication >

Sample code to authenticate with the Xero-Net api on webforms (asp.net) - VB.NET Sample Code WORKING

Started by Simon Richardson -   in API Authentication

Please find attached simple code to authenticate with asp.net webforms.
The code is in vb.net but can easily be converted to c#.

Hope this helps everyone who is looking for this:

Imports Xero.Api.Core
Imports Xero.Api.Infrastructure.Interfaces
Imports Xero.Api.Example.Applications.Public
Imports Xero.Api.Infrastructure.OAuth
Imports System.Collections.Concurrent
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myxeroapi As XeroCoreApi
If IsPostBack = False Then
If Request.QueryString("oauth_verifier") Is Nothing Then
myxeroapi = XeroAuthenticate(Me, False, "")
Else
myxeroapi = XeroAuthenticate(Me, True, "")
If Not myxeroapi Is Nothing Then
response.write (myxeroapi.organisation.name)
End If
End If
End If
End Sub

Protected Function XeroAuthenticate(inpage As Page, authpagereturnedauthentication As Boolean, incode As String) As XeroCoreApi
' This procedure will return w working XeroCoreApi if successful and nothing otherwise
' Set client secrets for general use and then load any override ones from the web.config file
Dim myxeroconsumer As New Consumer("xxxxxxxxxx", "yyyyyyyyyy")
Dim myxerouser = New ApiUser() With {.Name = "MYUSER"}

' If user defined ID and Secrets exist then use those instead
If Not System.Configuration.ConfigurationManager.AppSettings("XeroAPIClientId") Is Nothing Then
If Not System.Configuration.ConfigurationManager.AppSettings("XeroAPIClientSecret") Is Nothing Then
If System.Configuration.ConfigurationManager.AppSettings("XeroAPIClientId").ToString <> "" Then
myxeroconsumer = New Consumer(System.Configuration.ConfigurationManager.AppSettings("XeroAPIClientId").ToString, System.Configuration.ConfigurationManager.AppSettings("XeroAPIClientSecret").ToString)
End If
End If
End If

' Define Page Call Information
Dim myxerocallbackurl = "http://localhost:51598/AccountingXero.aspx"
Dim myxeromemorystore = New MemoryAccessTokenStore()
Dim myxerorequestTokenStore = New MemoryRequestTokenStore()
Dim myxerobaseapiurl = "https://api.xero.com"

' Authenticate with Xero
Dim myxeroauthenticator As New PublicMvcAuthenticator(myxerobaseapiurl, myxerobaseapiurl, myxerocallbackurl, myxeromemorystore, myxeroconsumer, myxerorequestTokenStore)

If authpagereturnedauthentication = False Then
' Redirect to the authentication page
Dim requri As String = myxeroauthenticator.GetRequestTokenAuthorizeUrl(myxerouser.Name)
If requri <> "" Then Response.Redirect(requri, True)
Return Nothing
Else
' Validate token using querystrings that have been returned from the authentication process
Dim myxerotoken As IToken = myxeroauthenticator.RetrieveAndStoreAccessToken(myxerouser.Name, Request.QueryString("oauth_token").ToString, Request.QueryString("oauth_verifier").ToString, Request.QueryString("org").ToString)
If Not myxerotoken Is Nothing Then
Dim myxeroapi As New XeroCoreApi("https://api.xero.com", myxeroauthenticator, myxeroconsumer, myxerouser)
Return myxeroapi
Else
Return Nothing
End If
End If
End Function
End Class
Public Class MemoryAccessTokenStore
Implements ITokenStore
Private Shared ReadOnly _tokens As IDictionary(Of String, IToken) = New ConcurrentDictionary(Of String, IToken)()
Protected Function Find(userId As String) As IToken Implements ITokenStore.Find
Dim token As IToken = Nothing
If String.IsNullOrWhiteSpace(userId) Then
Else
_tokens.TryGetValue(userId, token)
End If
Return token
End Function
Protected Sub Add(token As IToken) Implements ITokenStore.Add
_tokens(token.UserId) = token
End Sub
Protected Sub Delete(token As IToken) Implements ITokenStore.Delete
If _tokens.ContainsKey(token.UserId) Then
_tokens.Remove(token.UserId)
End If
End Sub
End Class
Public Class MemoryRequestTokenStore
Implements ITokenStore
Private Shared ReadOnly _tokens As IDictionary(Of String, IToken) = New ConcurrentDictionary(Of String, IToken)()
Protected Function Find(userId As String) As IToken Implements ITokenStore.Find
If String.IsNullOrWhiteSpace(userId) Then
Return Nothing
End If

Dim token As IToken = Nothing

_tokens.TryGetValue(userId, token)
Return token
End Function
Protected Sub Add(token As IToken) Implements ITokenStore.Add
_tokens(token.UserId) = token
End Sub
Protected Sub Delete(token As IToken) Implements ITokenStore.Delete
If _tokens.ContainsKey(token.UserId) Then
_tokens.Remove(token.UserId)
End If
End Sub
End Class
Hi Simon,

Just wanted to thank you for sharing this with the community. We love seeing developers take the time to help others.

Thanks
Sid
 

Sidney Maestre (Community Manager)  

Thanks Simon.

Are you able to copy this into an example project and post it into a GitHub repo?
 

Phil Alsford (Xero Staff)  

C# Example.

Hope this helps!!!

Cheers

GIT
This code is provided by the developer community - Xero does not warrant it in any way
 

Philip P  

Thanks a lot for sharing.

My question is on the callback URL, how can I use the provided oauth_token and verifier to be able to use Xero.Api?

I need to connect to Xero to be able to work with
Xero.Api.Core.Model.PurchaseOrder

Would you please help?

Thanks.
 

Iman Alimi  

Hi Iman,

You don't use the query string params returned by the callback URL to access API end points. You swap the verifier and temporary oauth_token on line 99 and store the 30 min oauth_token and oauth_token_secret for use in your app. "myxeroapi" is returned from the method and used to call the Organisation endpoint in line ... 49

myxeroapi = XeroAuthenticate(this, true, "");
if ((myxeroapi != null))
{
//Do something with myxeroapi
Response.Write(myxeroapi.Organisation.Name);
}
 

Sidney Maestre (Community Manager)  

Hi. Thanks very much for the code. I am very new to this. I put it in a WebForm. If want to do something like list contacts what code would I use and most importantly how would it look at the company that I am logged into?
 

Murray Brown  

Thanks a lot Sidney,

Would you please teach me how to disconnect the connected company.

I need to be able to disconnect the connected app in order to connect a new one.

Thanks again.
 

Iman Alimi  

Maybe I need to explain more.

When I connect to a company in Xero, it connects well using your code.

When I want to connect to another Company, it works and I receive the new oauth_token, oauth_verifier, and org, but I still connected to the old one!

What am I doing wrong you reckon?

Thanks :)
 

Iman Alimi