• Aleksandar Cvetanovski
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
I'm really new to Apex and coding in general, so I seem to get stuck while trying to retrieve an access token.
I still can't quite figure out the logic between how to send the request and how to retrieve the access token and how to make it all work.
 
public with sharing class CleverreachTest {
    String username = 'myemail';
    String password = 'mypass'; 
    String accesstoken;
    String instanceURL;
    String clientID = 'clientid' ;
    string clientSecret = 'clientsecret';
    
    public CleverreachTest(string username, string pwd, string clientId, string clientsecret)
    {
        this.username = username;
        this.password = pwd;
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }
    public void startAuth(){
        //Get the token
        Http httpCls = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://rest.cleverreach.com/oauth/authorize.php');
        request.setMethod('GET');
        request.setTimeout(2 * 60 * 1000);
     
        
        request.setHeader('Token', 'https://rest.cleverreach.com/oauth/token.php');
        request.setBody('grand_type=password' + 
                       '&client_id=' + clientId +
                       '&client_secret=' + clientSecret + 
                       '&username=' + username +
                       '&password=' + password);
        
        httpResponse response = httpCls.send(request);
        
        if(response.getStatusCode() == 200){
            system.debug('## Succesfully retrieving access token');
            map<string,Object> resultMap = (map<string,Object>)JSON.deserializeUntyped(response.getBody());
            accesstoken = (String)resultMap.get('access_token');
            instanceURL = (String)resultMap.get('instance_url');
                                                
        }
        
        else{
            system.debug('## Could not retrieve the access token');
            system.debug('## response status:' + response.getStatus());
            system.debug('## response message:' + response.getBody());
        }
        
            
    }

}