Tuesday, 24 September 2013

Share a Post on Facebook Page using Scribe and Java

As a second Part of my earlier post, I will now demonstrate how you can Share a Post on a Facebook Page using Scribe and Java.

The pre-requisites/setup is the same as mentioned in the first part. i.e.

  • Create a Facebook App and get App ID & App Secret
  • Initialize Scribe’s OAuthService using above information
  • Get Short Lived Access Tokens and then exchange it a Long Lived Access Token – Note that these tokens are the Facebook App’s Tokens

    Token accessToken;

    //facebook app's short-lived access token
    //accessToken = getFbAppShortLivedAccessToken(oAuthService);
    //accessToken = new Token("CAAF3yH4PHBkBAO4mTp8sgngVkNgQxAebc1xt4O64qeOqlzxiI7vyJpM8Ml7VAIKROHPJB5IgDEgi0ShfWIkrnuMirmEm0UjuYFSrRlaURj9YWEWWKLrBQN5vrjFkid4JPMMYsewEcODKe73dp3LYA2JeHld8ZAJc1EkLZCr3HNdYLprSJF", "");

    //facebook app's long-lived access token
    //accessToken = getFbAppLongLivedAccessToken(oAuthService, accessToken);
    accessToken = new Token("CAAF3yH4PHBkBAKUwtBB5SAEreaLN2uVDRI48Q5LhAEHn2kUKaCyDcUO1y8ZBobqFccBx7QDdIWDd4gKJcQpZCYMAIy7P5KIKRBrvzuliJpjUJW18QUU3ijk4NMqROZAPmmrHqf24PufYNK9R26vRn9X7suDtuSze3eKvh5zSrZADZAkZCZARHan9ZAyWZBZBKvhWUZD", "");

  • You will also have to get the Short and Long Lived Access Tokens for the Facebook Page, on to which you want to share a post

    Token pageAccessToken;

    //facebook page's short-lived access token
    //pageAccessToken = getFbPageShortLivedAccessToken(oAuthService, accessToken);
    //pageAccessToken = new Token("CAAF3yH4PHBkBAMzY4Tyi5nyzhckF2DZC0V3ZBWjd5orLwZCw2Xv6lZBhCxsB29HCwPKdF8iMPgqmdurK9ZB2vmL7wPHlrWxagZA329QZBrnwkswZAMPZCDTvL5xcfCAvmZCTQXe6kS5ZAbUIELd1TeqB0pbjmkYh6w6kTNxtvRCSnAtDWOLMeP7qvpPMFXP21JFzToZD", "");

    //facebook page's long-lived access token
    //pageAccessToken = getFbPageLongLivedAccessToken(oAuthService, pageAccessToken);
    pageAccessToken = new Token("CAAF3yH4PHBkBAOSP9vZA0ZA876psVlRIfl1kQ4wdZBRm6M2nCx6Ru9eurBGzcx1zfLtBDZC2EFnGSNWuukwLpmgVHil57oXiZBLYRoWl0h8DcE8XSpAGvcxOumJrZBHZAEEFjZA1jrDVZCJu8ZBLZBQUqwKll0Ngy4EZCiglCYGSTj9NbOkuyX8S6vQl", "");

Finally:

OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/" + FB_PAGE_NAME + "/feed");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
String message = "test message - " + sdf.format(new Date());
request.addBodyParameter("message", message);
String link = "
http://codeoftheday.blogspot.com/";
request.addBodyParameter("link", link);
request.addBodyParameter(ACCESS_TOKEN, pageAccessToken.getToken());
oAuthService.signRequest(accessToken, request);
Response response = request.send();

Note that we have used accessToken, Facebook App’s Access Token, to sign the request as usual. And, we are passing the pageAccessToken, Facebook Page’s Access Token, as a parameter of our request. This will ensure the Facebook Page Impersonation, such that the Facebook Page’s name and icon will be displayed as the Sharer. If you don’t pass pageAccessToken as a parameter than the Facebook App’s name and icon will be displayed as the Sharer.

/**
* Share a Post on Facebook Page using Scribe and Java - http://codeoftheday.blogspot.com/2013/09/share-post-on-facebook-page-using.html
*/
package com.smhumayun.codeoftheday.PostToFacebookPageUsingScribeExample;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FacebookApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;
public class PostToFacebookPageUsingScribeExample {
private static String FB_APP_KEY = "012345678901234";
private static String FB_APP_SECRET = "01234567890123456789012345678901";
private static String FB_PAGE_NAME = "H1bWorkVisaUsa";
private static String ACCESS_TOKEN = "access_token";
private static String FB_GRAPH_API = "https://graph.facebook.com/";
private static OAuthService getOAuthService()
{
return new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(FB_APP_KEY)
.apiSecret(FB_APP_SECRET)
.callback("http://www.smhumayun.com/")
.scope("publish_stream")
.build();
}
@SuppressWarnings("UnusedDeclaration")
private static Token getFbAppShortLivedAccessToken(OAuthService oAuthService)
{
Token fbAppShortLivedAccessToken;
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = oAuthService.getAuthorizationUrl(null);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize this program here:");
System.out.println(authorizationUrl);
//open authorizationUrl in your browser and the you will be redirected to your call back url containing 'code'
//something like this: http://www.smhumayun.com/?code=AQBAFNRNKyxjaSf1....ONXVc#_=_
//copy only the value of 'code' and paste it on the console of this program as an input
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(new Scanner(System.in).nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
fbAppShortLivedAccessToken = oAuthService.getAccessToken(null, verifier);
System.out.println("Got the Access Token!");
System.out.println("Facebook App's Short-Lived Access Token = " + fbAppShortLivedAccessToken.getToken());
System.out.println();
return fbAppShortLivedAccessToken;
}
@SuppressWarnings("UnusedDeclaration")
private static Token getFbAppLongLivedAccessToken(OAuthService oAuthService, Token fbAppShortLivedAccessToken)
{
return getLongLivedAccessToken("Facebook App", oAuthService, fbAppShortLivedAccessToken);
}
private static Token getLongLivedAccessToken(String tokenName, OAuthService oAuthService, Token shortLivedAccessToken)
{
return getAccessToken(tokenName + "'s Long-Lived Access Token"
, FB_GRAPH_API + "oauth/" + ACCESS_TOKEN + "?grant_type=fb_exchange_token"
+ "&client_id=" + FB_APP_KEY + "&client_secret=" + FB_APP_SECRET
+ "&fb_exchange_token=" + shortLivedAccessToken.getToken()
, oAuthService, shortLivedAccessToken);
}
private static Token getAccessToken(String tokenName, String url, OAuthService oAuthService, Token accessToken)
{
Token newAccessToken;
System.out.println("Getting the " + tokenName + "...");
OAuthRequest request = new OAuthRequest(Verb.GET, url);
oAuthService.signRequest(accessToken, request);
newAccessToken = new Token(extractAccessToken(request.send()), "");
System.out.println(tokenName + " = " + newAccessToken.getToken());
System.out.println();
return newAccessToken;
}
private static String extractAccessToken (Response response)
{
if(response != null)
{
System.out.println("response.getBody() = " + response.getBody());
String responseBody = response.getBody();
if(responseBody != null && responseBody.contains(ACCESS_TOKEN))
{
if(responseBody.contains(ACCESS_TOKEN + "="))
return responseBody.split("=")[1].trim();
else
return getValueFrom(response, ACCESS_TOKEN);
}
}
return null;
}
private static String getValueFrom (Response response, String key)
{
//determining the generic type of map
Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
//desrialize json to map
Map<String, String> responseMap = new GsonBuilder().create().fromJson(response.getBody(), typeOfMap);
return responseMap.get(key).trim();
}
@SuppressWarnings("UnusedDeclaration")
private static Token getFbPageShortLivedAccessToken(OAuthService oAuthService, Token accessToken)
{
return getAccessToken("Facebook Page {" + FB_PAGE_NAME + "}'s Short-Lived Access Token"
, FB_GRAPH_API + FB_PAGE_NAME + "?fields=" + ACCESS_TOKEN
, oAuthService, accessToken);
}
@SuppressWarnings("UnusedDeclaration")
private static Token getFbPageLongLivedAccessToken(OAuthService oAuthService, Token fbPageShortLivedAccessToken)
{
return getLongLivedAccessToken("Facebook Page {" + FB_PAGE_NAME + "}", oAuthService, fbPageShortLivedAccessToken);
}
private static void postOnFacebookPage(OAuthService oAuthService, Token accessToken, Token pageAccessToken)
{
OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/" + FB_PAGE_NAME + "/feed");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
String message = "test message - " + sdf.format(new Date());
request.addBodyParameter("message", message);
String link = "http://codeoftheday.blogspot.com/";
request.addBodyParameter("link", link);
request.addBodyParameter(ACCESS_TOKEN, pageAccessToken.getToken());
oAuthService.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getCode());
String responseBody = response.getBody();
System.out.println(responseBody);
}
public static void main(String[] args)
{
OAuthService oAuthService = getOAuthService();
Token accessToken;
//facebook app's short-lived access token
//accessToken = getFbAppShortLivedAccessToken(oAuthService);
//accessToken = new Token("CAAF3yH4...dYLprSJF", "");
//facebook app's long-lived access token
//accessToken = getFbAppLongLivedAccessToken(oAuthService, accessToken);
accessToken = new Token("CAAF3yH4...WUZD", "");
Token pageAccessToken;
//facebook page's short-lived access token
//pageAccessToken = getFbPageShortLivedAccessToken(oAuthService, accessToken);
//pageAccessToken = new Token("CAAF3yH4...ToZD", "");
//facebook page's long-lived access token
//pageAccessToken = getFbPageLongLivedAccessToken(oAuthService, pageAccessToken);
pageAccessToken = new Token("CAAF3yH4...6vQl", "");
postOnFacebookPage(oAuthService, accessToken, pageAccessToken);
}
}

No comments:

Post a Comment