Monday, October 22, 2018

Salesforce Integration with Facebook

Create a connected app in facebook, it will generate clientid, clientsecret, redirecturi:

We are using client_credentials in facebook, so we are not requesting code first and then acces_token, directly we are requesting for access_token.



 Storing these values in custom object:
Requesting for acces token from facebook:

Visaulforce Homepage:
<apex:page controller="Rest_OAuth_Facebook">
    <apex:form >
       <apex:commandButton value="gettoken" action="{!requestToken}"/>
    </apex:form>
</apex:page>

Apex Class:
public class Rest_OAuth_Facebook {
    public string accesstoken {set; get;}
    public Serverdata__c data {set; get;}
    public Rest_OAuth_Facebook(){
        data = [select Client_ID__c, Client_Secret__c, Redirect_URL__c from Serverdata__c where Name = 'Facebook'];
    }
    public void readcode(){
            accesstoken=Apexpages.currentPage().getparameters().get('access_token');   
        }
    public PageReference requestToken(){
        string endpoint='https://graph.facebook.com/oauth/access_token?';
        endpoint=endpoint+'client_id='+ data.Client_ID__c;
        endpoint=endpoint+'&client_secret='+data.Client_Secret__c;
        endpoint=endpoint+'&redirect_uri='+data.Redirect_URL__c;
        endpoint=endpoint+'&grant_type=client_credentials';
        PageReference p = new PageReference(endpoint);
        return p;
    } 
}

Visualforce Response Page:

<apex:page controller="Rest_OAuth_Facebook">
    {!accesstoken}
</apex:page>

By using this access_token we can request other resources from facebook.

No comments:

Post a Comment