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 :

Labels

visualforce page ( 13 ) apex integration ( 5 ) apex trigger ( 4 ) csv file from vf page ( 4 ) javascript ( 4 ) csv visualforce page ( 3 ) Too many ( 2 ) call out ( 2 ) integration ( 2 ) rest api ( 2 ) salesforce rest api ( 2 ) salesforce to salesforce integration ( 2 ) sfdc rest api ( 2 ) trigger ( 2 ) 15 digit to 18 digit ( 1 ) DML rows in Apex ( 1 ) Date Conversion ( 1 ) Date/Time conversion ( 1 ) Deploy ( 1 ) Objects to Future Annotated Methods ( 1 ) SFDC limits ( 1 ) Sobject to Future Annotated Methods ( 1 ) Test Class ( 1 ) TimeZone Conversion ( 1 ) Too many dml rows ( 1 ) Too many future calls ( 1 ) annotations ( 1 ) apex code ( 1 ) closed opportunities ( 1 ) commit ( 1 ) convert ( 1 ) create records ( 1 ) csv create records ( 1 ) custom setting ( 1 ) deployment ( 1 ) deployment changeset ( 1 ) disable apex class ( 1 ) disable apex trigger ( 1 ) disable in production ( 1 ) document ( 1 ) download ( 1 ) field name ( 1 ) formula fields ( 1 ) iframe ( 1 ) inactive ( 1 ) intellisense ( 1 ) jsforce ( 1 ) limits ( 1 ) matrix report in vf page ( 1 ) multi select ( 1 ) multi select salesforce ( 1 ) multiselect ( 1 ) paypal ( 1 ) picklist ( 1 ) record type ( 1 ) rollback ( 1 ) salesforce limits ( 1 ) salesforce list ( 1 ) salesforce map ( 1 ) salesforce rest ( 1 ) salesforce set ( 1 ) salesforce1 ( 1 ) sandbox deployment ( 1 ) sfdc collection ( 1 ) sfdc list ( 1 ) sfdc map ( 1 ) sfdc rest ( 1 ) sfdc set ( 1 ) uncommitted ( 1 ) updated field ( 1 ) user ( 1 ) validation rule opportunity ( 1 ) validation rules opportunities ( 1 ) vf page ( 1 )

Ad