function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Gaurav DhandreGaurav Dhandre 

How can I get the access token using oauth?

I need to access the SHOPPER API which needs the access_token, but I didn't find the document which suggests how I can do that or any other alternate way to do it.
Thanks 
Sai PraveenSai Praveen (Salesforce Developers) 
hi Gaurav,

Do you need access token of salesforce?

Thanks,
 
Shri RajShri Raj
To obtain an access token using OAuth in Salesforce, you need to follow these steps:
Create a connected app: Go to Setup -> Create -> Apps -> Connected Apps -> New. Fill in the required fields and select the OAuth scopes that your app will need to access. Make sure to also select the appropriate OAuth Callback URL.
Obtain an authorization code: In order to obtain an access token, you need to first obtain an authorization code by sending a user to the Salesforce OAuth authorization endpoint. This can be done in a few ways, but one common way is to redirect the user to a Salesforce login page with the authorization endpoint URL and the necessary query parameters.
Exchange the authorization code for an access token: Once you have obtained an authorization code, you can exchange it for an access token by making a POST request to the Salesforce OAuth token endpoint. Include the authorization code, client ID, client secret, and redirect URI in the request body.
Here is some sample code that demonstrates how to obtain an access token using OAuth in Salesforce:
String authEndpoint = 'https://login.salesforce.com/services/oauth2/authorize';
String clientId = '<your_client_id>';
String redirectUri = '<your_redirect_uri>';
String scope = '<your_oauth_scopes>';

// Redirect the user to the Salesforce login page to obtain an authorization code
String authUrl = authEndpoint + '?response_type=code&client_id=' + clientId + '&redirect_uri=' + redirectUri + '&scope=' + scope;
System.debug('Authorization URL: ' + authUrl);

// Once the user has granted authorization, exchange the authorization code for an access token
String tokenEndpoint = 'https://login.salesforce.com/services/oauth2/token';
String clientSecret = '<your_client_secret>';
String authorizationCode = '<authorization_code>';

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint(tokenEndpoint);
request.setMethod('POST');
request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
request.setBody('grant_type=authorization_code&client_id=' + clientId + '&client_secret=' + clientSecret + '&redirect_uri=' + redirectUri + '&code=' + authorizationCode);
HttpResponse response = http.send(request);

// Parse the access token from the response
String accessToken = (String) JSON.deserialize(response.getBody(), Map<String, Object>.class).get('access_token');
System.debug('Access token: ' + accessToken);