Monday, August 25, 2014

Accessing FaceBook from Salesforce

Here is an example to get connected to Facebook and get the Facebook information

Need to create 2 visual force pages and 2 controllers.

Before creating the vf pages and controller you need to create an app in facebook.
To create an app navigate to
https://developers.facebook.com/
and create an app you will get Client Id and secret. Paste those values in FBRedirectURI class .

Vf Page:
<apex:page controller="FaceBookApp" showHeader="false" sidebar="false" action="{!getAccessToken}">
</apex:page>

Controller:
public class FaceBookApp {
    String ClientId='Your Facebook App Id';
    public PageReference getAccessToken() {
        PageReference pgReference=new PageReference('https://graph.facebook.com/oauth/authorize?client_id='+ClientId+'&redirect_uri=https://ap1.salesforce.com/apex/facebook/FaceBookRedirecturi&scope=user_about_me&state=/FaceBookApp');
pgReference.setRedirect(true);
return pgReference;
        pgReference.setRedirect(true);
        return pgReference;
    }
}

Vf Page :
<apex:page controller="FBRedirectURI" action="{!init}"  sidebar="false" showHeader="false">
<html>
<body>
<h2 style="align:middle">Congratulations, You have added the app to your account </h2>
</body>
</html>
</apex:page>

Controller:
public class FBRedirectURI {
    public PageReference init() {
         String ClientId='Your Facebook App Id';
         String Secret='Your Facebook App Secret';
        try{
            if (! ApexPages.currentPage().getParameters().containsKey('code')) {
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.FATAL, 'Missing code parameter');
                ApexPages.addMessage(msg);
            }
        String code = ApexPages.currentPage().getParameters().get('code');
        System.debug('Facebook OAuth Step 2 - code:'+code);
        String state =  ApexPages.currentPage().getParameters().get('state');
        System.debug('state:'+state);
        String tokenURI = 'https://graph.facebook.com/oauth/access_token?client_id='+ClientId+'&redirect_uri='+
            +'https://ap1.salesforce.com/apex/FaceBookRedirecturi'+
                        + '&client_secret='+decrypt(Secret)+'&code='+code;                  
        System.debug('tokenURI is:'+tokenURI);
             
        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenURI);
        req.setMethod('GET');
        req.setTimeout(60*1000);
     
        Http h = new Http();
        String response;
        if (code != '' || code != null) {
            HttpResponse res = h.send(req);
            response = res.getBody();
        }
        if(response.contains('access_token'))
        {
        System.debug('Facebook response is:'+response);
        String accessToken = '';
        Integer acc = response.indexOf('access_token');
        Integer amp = response.indexOf('&');
        if ( amp == -1 ) {
            accessToken = response.substring(acc + 13, response.length());
        } else {
            accessToken = response.substring(acc + 13, amp);
        }
        System.debug(accessToken);
                String me=doGet('https://graph.facebook.com/me?access_token='+accessToken);
                System.debug(me);
            }
        }catch(Exception e){
            System.debug(e.getMessage()+e.getStackTraceString());
        }
        return null;
    }

    public FBRedirectURI(){
    }

    private static String doGet(String url) {
        String response;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        req.setTimeout(60*1000);
        HttpResponse res;
            res = h.send(req);
            response = res.getBody();        
     
        //fb returns a 302 temp redirect with the url for the profile image
        if(res.getStatusCode() == 302)
        {
            System.debug('Received a 302, Header Location value is:'+res.getHeader('Location'));
            response = '{"data": [{"url": "'+res.getHeader('Location')+'"},]}';
        }
     
        System.debug('API RESP: '+response);

        return response;
    }
    public static String decrypt(String data) {
        EncryptionSettings__c settings = EncryptionSettings__c.getOrgDefaults();
        /*if (settings.key__c == null) {
            throw new FacebookException('Cannot decrypt without a key!');
        }*/
        Blob key = EncodingUtil.base64Decode('Ad40G2d8aNE3z9YD1cHRLtiO4vCxMrZg5ZHcs6jm/cc=');
        return Crypto.decryptWithManagedIV('AES256', key, EncodingUtil.base64Decode(data)).toString();
    }
}

You Can find the example in the below link:
http://skm.force.com/facebook

1 comment: