Salesforce + OAuth 1.0


Salesforce integration

The below code is OAuth 1.0 from salesforce.
Here i just give Yelp api intregration example, you can change the code as per your requirement.

public class YelpApiCallout {
    public String consumerKey = 'xxxxxxxxxxxxxxxxx';
    public String token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    public String timestamp = '';
    public String nonce = '';
    public String consumerSecret = 'xxxxxxxxxxxxxx';
    public String tokenSecret = 'xxxxxxxxxxxxxxxxxxx';
    public String signature = '';
    public Map<String, String> parameters = new Map<String, String>();
 
    public String location  {get; set;}
    public String jasonData ;
    public YelpDataWrapper apiRecords   {get; set;}
    public String term   {get; set;}
 
    public void accessToken(){
        term = ApexPages.CurrentPage().getParameters().get('term');
        String locationWOspace = location.replace(' ', '%20');
        String termWOspace;
        if(term != null){
            termWOspace = term.replace(' ', '%20');
        }
        HttpRequest req = new HttpRequest();
        String endpointurl ='http://api.yelp.com/v2/search?                            location='+locationWOspace+'&limit=20&term='+termWOspace;   
        req.setEndpoint(endpointurl);
        req.setMethod('GET');
        sign(req);
        Http httpOath = new Http();
        HTTPResponse res = httpOath.send(req);
     
        jasonData = res.getBody();
     
        //Step 3:parse the received JSON
        JSONParser parser = JSON.createParser(jasonData);
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                 apiRecords = ( YelpDataWrapper)parser.readValueAs(YelpDataWrapper.class);
            }
        }
    }
 
    private void refreshParameters() {
        parameters.clear();
        parameters.put('oauth_consumer_key',consumerKey);
        if(token!=null) {
            parameters.put('oauth_token',token);
        }
        parameters.put('oauth_signature_method','HMAC-SHA1');
        parameters.put('oauth_timestamp',timestamp);
        parameters.put('oauth_nonce',nonce);
    }
 
    private Map<String,String> getUrlParams(String value) {
        Map<String,String> res = new Map<String,String>();
        if(value==null || value=='') {
            return res;
        }
        for(String s : value.split('&')) {
            System.debug('getUrlParams: '+s);
            List<String> kv = s.split('=');
            if(kv.size()>1) {
              String encName = EncodingUtil.urlEncode(EncodingUtil.urlDecode(kv[0], 'UTF-8'), 'UTF-8').replace('+','%20');
              String encValue = EncodingUtil.urlEncode(EncodingUtil.urlDecode(kv[1], 'UTF-8'), 'UTF-8').replace('+','%20');
              System.debug('getUrlParams:  -> '+encName+','+encValue);
              res.put(encName,encValue);
            }
        }
        return res;
    }
 
    private String createBaseString(Map<String,String> oauthParams, HttpRequest req) {
        Map<String,String> p = oauthParams.clone();
        if(req.getMethod().equalsIgnoreCase('post') && req.getBody()!=null &&
           req.getHeader('Content-Type')=='application/x-www-form-urlencoded') {
            p.putAll(getUrlParams(req.getBody()));
        }
        String host = req.getEndpoint();
        Integer n = host.indexOf('?');
        if(n>-1) {
            p.putAll(getUrlParams(host.substring(n+1)));
            host = host.substring(0,n);
        }
        List<String> keys = new List<String>();
        keys.addAll(p.keySet());
        keys.sort();
        String s = keys.get(0)+'='+p.get(keys.get(0));
        for(Integer i=1;i<keys.size();i++) {
            s = s + '&' + keys.get(i)+'='+p.get(keys.get(i));
        }
 
        return req.getMethod().toUpperCase()+ '&' +
            EncodingUtil.urlEncode(host, 'UTF-8') + '&' +
            EncodingUtil.urlEncode(s, 'UTF-8');
    }
 
    public void sign(HttpRequest req) {
        nonce = String.valueOf(Crypto.getRandomLong());
        timestamp = String.valueOf(DateTime.now().getTime()/1000);
 
        refreshParameters();
 
        String s = createBaseString(parameters, req);
 
        System.debug('Signature base string: '+s);
 
        Blob sig = Crypto.generateMac('HmacSHA1', Blob.valueOf(s),
                       Blob.valueOf(consumerSecret+'&'+
                                    (tokenSecret!=null ? tokenSecret : '')));
        signature = EncodingUtil.urlEncode(EncodingUtil.base64encode(sig), 'UTF-8');
        System.debug('Signature: '+signature);
 
        String header = 'OAuth ';
        for (String key : parameters.keySet()) {
            header = header + key + '="'+parameters.get(key)+'", ';
        }
        header = header + 'oauth_signature="'+signature+'"';
        System.debug('Authorization: '+header);
        req.setHeader('Authorization',header);
    }
 
    public class YelpDataWrapper
    {
       public List<businesses> businesses  {get; set;}
    }
 
    public class businesses
    {
        public String rating               {get; set;}
        public String image_url            {get; set;}
        public String review_count         {get; set;}
        public String name                 {get; set;}
        public String snippet_image_url    {get; set;}
        public String url                  {get; set;}
        public String rating_img_url_large {get; set;}
        public String id                   {get; set;}
        public String snippet_text         {get; set;}
    }
 
}

No comments:

Post a Comment