GithubHelp home page GithubHelp logo

apex-for-xero's Introduction

Apex-for-Xero

Deploy to Salesforce

(deploy from Github from https://githubsfdeploy.herokuapp.com/app/githubdeploy/benedwards44/Apex-for-Xero)

This application contains Apex utilities for accessing the Xero REST APIs.

These classes are set up to use the Private Application type.

The aim of this project is to act as a starting point for accessing Xero APIs via Apex. I wanted to share this project as I spent a lot of time getting the authentication working for Xero, as Apex doesn't have a standard OAuth 1.0 library and there wasn't much detail online about it.

For more information about the Xero APIs, check out: http://developer.xero.com/documentation/api/api-overview/

Quick Setup

  1. Create an Auth. Provider within your Salesforce Org:

    1. Setup -> Security Controls -> Auth. Providers -> New
    2. Provider Type = Open ID Connect
    3. Name = Xero
    4. Consumer Key = ABC (this is temporary, we will update this with the Xero Consumer Key once we have it)
    5. Consumer Secret = ABC (as above)
    6. Authorize Endpoint URL = https://login.xero.com/identity/connect/authorize
    7. Token Endpoint URL = https://identity.xero.com/connect/token
    8. User Info Endpoint URL = https://identity.xero.com/connect/userinfo
    9. Token Issuer = https://identity.xero.com
    10. Default Scopes: "openid profile email offline_access accounting.transactions accounting.contacts" (you can see all scopes here https://developer.xero.com/documentation/oauth2/scopes)

    Leave everything as is. Click save and then copy the generated "Callback URL". Eg. https://login.salesforce.com/services/authcallback/00D2v000003QVUrCAO/Xero

  2. Create the Xero App:

    1. https://developer.xero.com -> My Apps -> New app
    2. App name = Your unique name
    3. Company or application URL = Can be anything, suggest either your Salesforce Org URL or your company website
    4. OAuth 2.0 redirect URI = Paste in the "Callback URL" copied from step 1 above
    5. Take the generated Client Id and Client Secret and paste into the Auth. Provider created above
  3. Create the Salesforce Named Credential:

    1. Setup -> Named Credential -> New Named Credential
    2. Label = Xero
    3. Name = Xero
    4. URL = https://api.xero.com
    5. Identity Type = Named Principal
    6. Authentication Protocol = OAuth 2.0
    7. Authentication Provider = Xero (the provider created in step 1)
    8. Start Authentication Flow on Save = Checked (this will trigger the OAuth process to Xero)
  4. Deploy this package to a Salesforce environment (Deploy to Org)

  5. You now need to retrieve the Xero Tenant ID and store in the Custom Label:

    1. Run the Apex method XeroAPI.getXeroTenantId();
    2. Copy the returned value
    3. Update to the label: Setup -> Create -> Custom Labels -> Xero_Tenant_Id -> Edit -> Paste in value from above
  6. You can now access Xero API resources via Apex. Eg... XeroAPI.getContacts();

Webhooks

In order to use Xero Webhooks, some additional setup is required:

  1. First, you need to create a public URL for Xero to send webhooks to. To do this:
    1. Setup -> Develop -> Sites -> New (Note: you could use an existing Site if you prefer)
    2. Give the Site a name. Could be "API" or "Webhooks" or what is preferred.
    3. Give the site a URL suffix (eg. "api")
    4. For Active Site Homepage, select InMaintance or you could create a landing page. This isn't actually needed for this scenario
    5. Click Save, then Public Access Settings
    6. Under Enabled Apex Classes, select XeroWebhook and save.
  2. Now, you need to enable Xero Webhooks in Xero. Following the instructions here: https://developer.xero.com/documentation/guides/webhooks/creating-webhooks/
    1. For the Notifications URL, enter the domain and URL created above and also include /services/apexrest/xero/webhook which is the endpoint for the Apex Class XeroWebhook. For example https://mydomain.my.salesforce-sites.com/api/services/apexrest/xero/webhook. You can test the URL by navigating to it, you should receive a "HTTP Method 'GET' not allowed. Allowed are POST" error, which at least means the URL is correct
    2. Click Save and copy the "Webhook Key"
    3. Paste this key into the Xero Settings custom setting.
  3. Lastly, you need to activate the "Intent to Receive". This is a security measure which tells Xero the webhooks are signed and going to the right place.
    1. Setup -> Develop -> Custom Settings -> Xero Settings -> Manage
    2. Check "Intent to Receive" and click save
    3. Click "Send Intent to Recieve" on the Xero side. This will send a few messages to Salesforce and Salesforce will validate these are received and Xero will validate they're processed correctly. Once Xero returns "OK", go back to Salesforce and uncheck "Intent to Receive".
  4. Webhooks should now be sending! You will need to update the XeroWebhook.processRecordChange() with your logic to process webhooks how you like.

Usage

Once the above steps are complete, you can now access the example methods to access the Xero API resources. There are currently only a few pre-built methods set up to start using. Please use these as a base and extend as necessary.

Get Contacts

This method queries all contacts in your Xero org. To execute, simply run:

XeroAPI.getContacts();

And a list of type XeroContact is returned.

Create Contact

// Send Contact to Xero
Account myAccount = [SELECT Name, ... FROM Account];
XeroAPI.sendAccount(myAccount);

You can view example JSON requests here

Get Invoices

This method queries all invoices in your Xero org. To execute, run:

XeroAPI.getInvoices();

Create Invoice

This method creates an invoice for the given XML:

XeroInvoice newInvoice = new XeroInvoice();
newInvoice.Date_x = system.today();
... // Add additional Invoice details based on the XeroInvoice wrapper

// Send Invoice to Xero
XeroAPI.sendInvoice(XeroXmlUtility.serialize(newInvoice, 'Invoice'));

You can view example JSON requests here

Contributing

Feel free to fork this repo and use as you wish. I'd welcome anyone to add additional methods and add to this project, I will do the same as I go.

apex-for-xero's People

Contributors

benedwards44 avatar gordienoye avatar jairoi28 avatar jgaurav-dev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apex-for-xero's Issues

Tests

Hey Ben,

Thanks for making this code available.

I was wondering if you had test classes for more of the code? :)

Token not refreshed

Hi @benedwards44 ,
I tried to connect Salesforce with Xero using Named Credentials. But after some time when I am Token expired error(401). Do you face any issues like this?

Thanks,
Lavanya

Issue with not being authorised

Hi Ben,

have you had any issues with 401 errors being returned after the Refresh token expires. I know this is all supposed to be handled by the Salesforce side of things, but Xero are saying that a successful refresh is happening but the next call out is using the old token (I raised a case with them). Before I raise a Salesforce case, I just wanted to know if you'd had any similar issues?

Kind Regards

Jon

Xero OAuth 1 Endpoint Depreciated

Hi Ben,

Thanks for the effort that you have put into this project, it has been very useful.

With Xero depreciating Oauth 1 as of earlier this month no new private apps can be created. I am wondering if you have plans to update this repo to support Oauth2?

Regards

Daniel

Deployment Failures

Hi Ben,

When deploying to a dev org I receive the following Failures:
classes/XeroCalloutResponseParser.cls(32,74):Invalid type: XeroInvoice
classes/XeroAccountingApiTest.cls(131,8):Invalid type: XeroInvoice
classes/XeroAccountingApi.cls(96,51):Invalid type: XeroInvoice
classes/XeroInvoice.cls(22,16):Identifier name is reserved: Date

Any ideas?

Many thanks

Deployment Errors

Class Name Method Name Error Message
XeroAccountingApiTest getContactsFail System.AssertException: Assertion Failed: The 500 error code should be contained in the string. Stack Trace: Class.XeroAccountingApiTest.getContactsFail: line 54, column 1
XeroAccountingApiTest getContactsSuccess System.NullPointerException: Attempt to de-reference a null object Stack Trace: Class.XeroCalloutUtility.executeCallout: line 33, column 1 Class.XeroAccountingApi.getContacts: line 20, column 1 Class.XeroAccountingApiTest.getContactsSuccess: line 21, column 1
XeroAccountingApiTest getInvoicesFail System.AssertException: Assertion Failed: The 500 error code should be contained in the string. Stack Trace: Class.XeroAccountingApiTest.getInvoicesFail: line 164, column 1
XeroAccountingApiTest getInvoicesForContactSuccess System.NullPointerException: Attempt to de-reference a null object Stack Trace: Class.XeroCalloutUtility.executeCallout: line 33, column 1 Class.XeroAccountingApi.getInvoicesForContact: line 182, column 1 Class.XeroAccountingApiTest.getInvoicesForContactSuccess: line 186, column 1
XeroAccountingApiTest getInvoicesSuccess System.NullPointerException: Attempt to de-reference a null object Stack Trace: Class.XeroCalloutUtility.executeCallout: line 33, column 1 Class.XeroAccountingApi.getInvoices: line 127, column 1 Class.XeroAccountingApi.getInvoices: line 99, column 1 Class.XeroAccountingApiTest.getInvoicesSuccess: line 131, column 1

Paging Get Results

Hi Ben,

I love you work. Such an easy starting base!

I am adding in support for filtering invoices, will do a pull request once it's tidy.

I had a glance through your code and it doesn't look like it does any paging of any sort. Is that right? because the getInvoices() to my understanding would only return the first 100 records (page 1).

It would be good to build paging right into the XeroCalloutUtility. Let me know if you had any thoughts on the matter before I start meddling.

Thanks
Dan

Invalid :Type XeroContact

Hi benedwards44,

I want to integrate salesforce contact with xero I copied your code but it showing an error invalid Type XeroContact.

Could you please help me with this?
Here is my code

public class casToXero {

    public static XeroContact createContact (String contactBody) {

    // The created contact to return
    XeroContact createdContact;

    // Execute the callout to the Contacts resource
    HttpResponse response = XeroCalloutUtility.executeCallout('POST', 'Contacts', contactBody);

    // If successful response
    if (response.getStatusCode() == 200) {

        // Use the parser to convert the response into Xero objects
        createdContact = XeroCalloutResponseParser.parseContacts(response.getBody())[0];
    }
    else {

        // Raise error
        throw new XeroAccountingApiException(response.getStatusCode() + ': ' + response.getBody());
    }

    return createdContact;
}

public class XeroAccountingApiException extends Exception {}

}

Please help me with this.

Many Thanks,
Saniya

Line: 55, Column: 1 System.NoDataFoundException: Data Not Available:

Hi Ben,

Thanks for your awesome code.

Have follow your steps and deployed the package in my production org and this is working fine and as expected.But when i deployed the package in sandbox and try to fetch contact etc it is giving error

Line: 55, Column: 1
System.NoDataFoundException: Data Not Available: The data you were trying to access could not be found. It may be due to another user deleting the data or a system error. If you know the data is not deleted but cannot access it, please look at our support page.

Can you please guide for same.

Regards
Narveer

Errors when trying to insert invoices

I get validation errors when inserting invoices:

"Message": "The TaxType field is mandatory"
"Message": "Account code must be specified"

but I can't find anywhere within the invoice class to specify these values.

Other endpoints

Hi Ben,

I'm trying to connect to the Items endpoint and keep getting the following Error:

{"Type":null,"Title":"Unauthorized","Status":401,"Detail":"AuthorizationUnsuccessful","Instance":"3e2b3bc7-21dc-4c20-8943-bb84bb16db39","Extensions":{}}

I've written a new wrapper class and added a method into XeroAPI (basically copied the invoice one), but I get the same even if I just run:

XeroCalloutService.executeCallout('GET','Items');

The following works:

XeroCalloutService.executeCallout('GET','Invoices');

Which is suggesting its not the actual authorisation, so I've tried:

XeroCalloutService.executeCallout('GET','Accounts');
XeroCalloutService.executeCallout('GET','Organisation');
XeroCalloutService.executeCallout('GET','Users');

Also all being lowercase as well, but I still get the AuthorizationUnsuccessful error. I'm able to access all of these endpoints using the API Previewer so I'm assuming its not a Xero setting / issue, but I can't see anywhere in the Salesforce side that should be limiting the endpoints available.

Any ideas or is this one for Xero support?

Kind Regards

Jon

Not find "Manage on Xero Settings"

Hi benedwards44,
Thanks for your information, I think is very useful, but I got issue on SalesForce. I can´t find the Xero Settings on the Setup ->Develop -> Custom Settings or anywhere else.
I would like to know what is the reason than I can find this setting. Could I be for the version?
Or Does Salesforce no longer work with Xero?
Or Could be this option in another site of the Salesforce's Software?

I would really appreciate your answer.
Thanks so much.

Test Failure deploying to production

Deployment Complete
Code coverage issue -- Average test coverage across all Apex Classes and Triggers is 59%, at least 75% test coverage is required.

Prior to deploying there is only 1 custom Apex class with 100% code coverage.

oAuth1.0a is Deprecated

As this is built on oAuth1.0 for Private application, I am afraid this will going to work in near future. Xero is now forcing to use oAuth 2.0 protocol for authentication.

Contact not inserting in SF

Can you please help me that how we can insert the xero contacts in Salesforce? because as per the recent code we are not able to find out any DML operations over here.

and also what if we need to reauthenticate the process do we need to again update the data in auth providers?

How do you even get this to work

Deployment completes but Deployment CompleteTest fails with the following resut:

method: XeroAPITest.getGetInvoice -- System.AssertException: Assertion Failed: Xero Invoice ID should be loaded against the response.: Expected: 10b46b4c-35c1-49c4-a7eb-983ab08ebe1a, Actual: 30aa67f9-d5e5-4351-9e28-c085a6b2d37f stack Class.XeroAPITest.getGetInvoice: line 86, column 1

Test failure, method: XeroAPITest.testGetInvoices -- System.AssertException: Assertion Failed: Xero Invoice ID should be loaded against the response.: Expected: 10b46b4c-35c1-49c4-a7eb-983ab08ebe1a, Actual: 30aa67f9-d5e5-4351-9e28-c085a6b2d37f stack Class.XeroAPITest.testGetInvoices: line 105, column 1

Test failure, method: XeroAPITest.testGetInvoicesWithDaysFilter -- System.AssertException: Assertion Failed: Xero Invoice ID should be loaded against the response.: Expected: 10b46b4c-35c1-49c4-a7eb-983ab08ebe1a, Actual: 30aa67f9-d5e5-4351-9e28-c085a6b2d37f stack Class.XeroAPITest.testGetInvoicesWithDaysFilter: line 124, column 1

Test failure, method: XeroAPITest.testSendInvoice -- System.AssertException: Assertion Failed: Xero Invoice ID should be loaded against the response.: Expected: 10b46b4c-35c1-49c4-a7eb-983ab08ebe1a, Actual: 30aa67f9-d5e5-4351-9e28-c085a6b2d37f stack Class.XeroAPITest.testSendInvoice: line 164, column 1

image

Cannot deploy to SalesForce

Ben,

first of all, thanks for this code that would have taken me days to write. I'm sure it works perfectly but I am having some trouble deploying to Salesforce.

When trying to use the "Deploy to Salesforce" button you included, the following failures occur and no class is deployed:

Failures: classes/XeroJournal.cls(16,28):Unexpected token 'JournalLines'. classes/XeroJournal.cls(16,28):Unexpected token 'JournalLines'. classes/XeroAccountingApi.cls(14,33):Method does not exist or incorrect signature: void generateJsonStringForParsing(String, String) from the type XeroAccountingApi classes/XeroAccountingApiTest.cls(14,33):Dependent class is invalid and needs recompilation: Class XeroAccountingApi : Method does not exist or incorrect signature: void generateJsonStringForParsing(String, String) from the type XeroAccountingApi classes/XeroJournal.cls(16,40):Unexpected token '['. classes/XeroJournal.cls(16,44):Variable does not exist: get classes/XeroJournal.cls(16,49):Variable does not exist: set classes/XeroJournalLine.cls(18,33):Unexpected token 'TrackingCategories'. classes/XeroJournalLine.cls(18,33):Unexpected token 'TrackingCategories'. classes/XeroJournalLine.cls(18,51):Unexpected token '['. classes/XeroJournalLine.cls(18,55):Variable does not exist: get classes/XeroJournalLine.cls(18,60):Variable does not exist: set classes/XeroTrackingCategory.cls(10,31):Unexpected token 'Options'. classes/XeroTrackingCategory.cls(10,31):Unexpected token 'Options'. classes/XeroTrackingCategory.cls(10,38):Unexpected token '['. classes/XeroTrackingCategory.cls(15,19):Unexpected token 'Where'. classes/XeroTrackingCategory.cls(15,19):Unexpected token 'Where'. classes/XeroTrackingCategory.cls(14,19):Duplicate field: TrackingCategoryID classes/XeroTrackingCategory.cls(10,42):Variable does not exist: get classes/XeroTrackingCategory.cls(10,47):Variable does not exist: set classes/XeroTrackingCategory.cls(15,26):Variable does not exist: get classes/XeroTrackingCategory.cls(15,31):Variable does not exist: set

Then, when trying to deploy it manually, only 10 classes can be deployed with no errors, the other ones all throw different errors.

Is there something I might be missing that is causing the errors?

Thanks!

Cannot deploy to Production

Hi Ben,

Thank for your great code. It can deploy to Sandbox but if deploy to Production it shows error as below.

Deployment CompleteTest failure, method: ChatterAnswersAuthProviderRegTest.validateCreateUpdateUser -- System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ProfileId]: [ProfileId] stack Class.ChatterAnswersAuthProviderRegTest.validateCreateUpdateUser: line 31, column 1

Code coverage issue -- Average test coverage across all Apex Classes and Triggers is 63%, at least 75% test coverage is required.

Could you please fix or guide to make deploy happen?

Regards,
In

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.