[SalesForce] Salesforce to Xero integration using Named Credentials by OAuth 2.0

I am trying to do the integration between Salesforce and Xero by using Named Credentials (Authentication Protocol is OAuth 2.0).
I created an Auth provider –

enter image description here

Then created Named credentials of OAuth 2.0 type and authenticated with required scopes mentioned in the Xero developer document.

enter image description here

When I am trying to run the below code to get the Account details from Xero, I am getting "AuthenticationUnsuccessful".

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:XeroDev/api.xro/2.0/Accounts');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

This is the response –

{"title":"Forbidden","status":403,"detail":"AuthenticationUnsuccessful","instance":"707450d8-b455-47ec-a1b4-85bcb2cf80c9"}

Any suggestion on how to make it work by using Named Credential?

Xero URL – https://developer.xero.com/documentation/oauth2/auth-flow

Best Answer

Try adding xero-tenant-id header in you apex code. For this you may need to check "Allow merge fields in HTTP Header" or else it wont allow.

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:XeroDev/api.xro/2.0/Accounts');
req.setMethod('GET');
/* tenant id is different for different organization */
req.setHeader('xero-tenant-id', 'd5ae8ed7-be06-43c0-a3ee-39e40e4b1eff');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

If you want you can dynamically fetch xero-tenant-id

GET https://api.xero.com/connections
Authorization Bearer {{access_token}}

response

[
    {
        "id": "f192b8df-f13c-4c12-8b01-d3f7590e98fe",
        "tenantId": "d5ae8ed4-be07-43c0-a3ee-31e40e4b1dff",
        "tenantType": "ORGANISATION",
        "createdDateUtc": "2019-12-11T17:08:13.7204600",
        "updatedDateUtc": "2019-12-12T11:19:59.1985240"
    }
]
Related Topic