Integrating Salesforce with external Web Applications
Published: 2020-02-20 03:25:52

Need to configure a connected app on the Salesforce is required for external API calls to work. Please refer to this link - https://trailhead.salesforce.com/content/learn/modules/connected-app-basics


Example API calls:

To make the initial authorization request for a user to grant your app access to their data (this is where your user is initially directed to a Saleforce.com authorization endpoint and logs in) you’d make the following request. The client_id in the below call will be your consumer ID from the connected app. The redirect_uri will be the Callback URL.


curl https://login.salesforce.com/services/oauth2/authorize?response_type=code
&client_id=YOURCONSUMERID&redirect_uri=https://www.yourappname.com/api/callback
A successful response from this will redirect the page to a Salesforce login page where the user is able to login and authenticate. After Salesforce confirms that the client has authorized your app to access their data, the end-users browser is redirected to the callback URL you’ve specified by the redirect_uri parameter. Salesforce then appends an authorization code to the redirect URL, their request will look similar to the below.


https://www.yourappname.com/api/callback?code=aWekysIEeqM9PiThEfm0Cnr6MoLIfwWyRJcqOqHdF8f9INokharAS09ia7UNP6RiVScerfhc4w%3D%3D
You’ll use this as the value for your code parameter when you make a request to Salesforce’s token endpoint to receive your Access and Refresh Token.

Example request:

curl login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=https://www.yourappname.com/api/callback&client_id=YOUR_CONSUMER_ID&client_secret=YOUR_CONSUMER_SECRET&code=aWekysIEeqM9PiThEfm0Cnr6MoLIfwWyRJcqOqHdF8f9INokharAS09ia7UNP6RiVScerfhc4w%3D%3D
Example Response:

{
  "access_token": "YOUR_ACCESS_TOKEN",
  "refresh_token": "YOUR_REFRESH_TOKEN",
  "signature": "signature",
  "scope": "refresh_token api id",
  "instance_url": "https://instance.salesforce.com",
  "id": "https://login.salesforce.com/id/id,
  "token_type": "Bearer",
  "issued_at": "timestamp"
}
Outside of the access and response token, the instance_url is import also. It’s what you’ll need to build the base of your future API calls.

Now we have the access token, we’re able to start making requests to send and receive data on our user's behalf. Something to keep in mind though, as mentioned earlier, is that these access tokens will always expire at some point.

Due to that, you’ll want to keep your access token up to date by making a call to the token endpoint and changing the grant_type to ‘refresh_token’ along with including the refresh token you had received in the previous call.

Example call:

curl https://login.salesforce.com/services/oauth2/token?grant_type=refresh_token&client_id=YOUR_CONSUMER__ID&client_secret=YOUR_CONSUMER__SECRET&refresh_token=YOUR_REFRESH_TOKEN
Example response:

{
  "access_token": "REFRESHED_ACCESS_TOKEN",
  "signature": "signature",
  "scope": "refresh_token id api",
  "instance_url": "https://INSTANCE.salesforce.com",
  "id": "https://login.salesforce.com/id/idE",
  "token_type": "Bearer",
  "issued_at": "timestamp"
}
Now we have a way to keep our access tokens valid and up to date, we’re set up and ready to start working with Salesforce objects.

Understanding Salesforce objects
Salesforce objects (sObjects) are effectively database tables that contain an organization’s data. Examples of standard Salesforce objects will be “Accounts”, “Contacts”, “Leads”, and “Tasks.” You also have scope to create your own custom objects.

A Salesforce record describes a specific occurrence of an object (such as a specific contact like “Jonny Appleseed” that is represented by a Contact object). A basic comparison would be like a row in a database table.

For the following examples, we’re just going to focus on Contacts.

Send data from your app to Salesforce
Creating a contact in salesforce is really straightforward. You just need to build the API url using the instance from your access token response and use the access token value as your bearer token in the header.

One thing to keep an eye out for through is for characters that need to be escaped in your access token.

For example, this access token should have the exclamation mark escaped

So this:


00D1r000000dumU!AQEAQFd.O1Q5DVQrUYvr.........
Becomes this:


00D1r000000dumU\!AQEAQFd.O1Q5DVQrUYvr........
you can then make the below call to create a contact.

Example request

curl https://INSTANCE.salesforce.com/services/data/v42.0/sobjects/Contact -H "Authorization: Bearer YOUR_ACCESS_TOKEN" -H "Content-Type: application/json" -d '{"FirstName" : "Johnny", "LastName" : "Appleseed"}'
(Your contact will need a last name as the minimum for an entry to be created.)

The response you get back will be the id of your contact


{"id":"0031r000029NDckAAG","success":true,"errors":[]}
Which will also let you build a link directly to the contact.


https://INSTANCE.salesforce.com/0031r000029NDckAAG
Retrieving data from Salesforce to your app
If you want to retrieve a list of contacts there are a few ways you can do it. You can make a request to the contact endpoint and it will return a bunch of information about your contacts that I found a bit cumbersome to navigate.

I actually prefer to use a combination a contacts ‘describe’ endpoint, which will return all of the fields we can populate about our user.

Example request:


curl https://INSTANCE.salesforce.com/services/data/v20.0/sobjects/Contact/describe -H  "Authorization: Bearer YOUR_ACCESS_TOKEN"
That will give a detailed response of all of the fields available. (I’ve just given an example of the ‘first name’ element for brevity)


{
      "autoNumber": false,
      "byteLength": 120,
      "calculated": false,
      "calculatedFormula": null,
      "caseSensitive": false,
      "controllerName": null,
      "createable": true,
      "custom": false,
      "defaultValue": null,
      "defaultValueFormula": null,
      "defaultedOnCreate": false,
      "dependentPicklist": false,
      "deprecatedAndHidden": false,
      "digits": 0,
      "externalId": false,
      "filterable": true,
      "groupable": true,
      "htmlFormatted": false,
      "idLookup": false,
      "inlineHelpText": null,
      "label": "First Name",
      "length": 40,
      "name": "FirstName",
      "nameField": false,
      "namePointing": false,
      "nillable": true,
      "picklistValues": [],
      "precision": 0,
      "referenceTo": [],
      "relationshipName": null,
      "relationshipOrder": null,
      "restrictedPicklist": false,
      "scale": 0,
      "soapType": "xsd:string",
      "sortable": true,
      "type": "string",
      "unique": false,
      "updateable": true,
      "writeRequiresMasterRead": false
    }
Once you’ve got the fields you can then use them (or a selection) to build a custom query:


curl https://INstance.salesforce.com/services/data/v42.0/query/?q=SELECT+id,name,email,phone+from+Contact -H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
That will return all contacts with their associated properties.


{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Contact","url":"/services/data/v42.0/sobjects/Contact/id"},"Id":"id","Name":"Jonny Appleseed","Email":"jonny.appleseed@myfriend.com","Phone":"555-555-555"} ]}


That should now give you a way to retrieve contact data from Salesforce to use within your app.


This is a good material for how to use the refresh token to get access token and some good practices.

https://www.oauth.com/oauth2-servers/making-authenticated-requests/refreshing-an-access-token/