{"id":13220,"date":"2014-04-28T17:02:17","date_gmt":"2014-04-28T11:32:17","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=13220"},"modified":"2014-04-28T20:40:24","modified_gmt":"2014-04-28T15:10:24","slug":"facebook-oauth-for-fetching-page-token","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/facebook-oauth-for-fetching-page-token\/","title":{"rendered":"Facebook Oauth for fetching page token"},"content":{"rendered":"<p><a href=\"http:\/\/en.wikipedia.org\/wiki\/OAuth\">OAuth<\/a> is a secure mechanism to access facebook.<\/p>\n<p>To access facebook in your grails application you need to create a facebook app, go to <a href=\"https:\/\/developers.facebook.com\/\">https:\/\/developers.facebook.com<\/a>, click on Apps dropdown, further click on &#8216;Create a new App&#8217;.<\/p>\n<p>Ensure that you register the URL of you application with the Facebook app you have setup.<\/p>\n<p>Save your apiKey and secretKey provided by Facebook.<\/p>\n<p>We are going to use <a href=\"https:\/\/github.com\/fernandezpablo85\/scribe-java\/\">Scribe<\/a> java library for Oauth authentication.<\/p>\n<p>Add this to your BuildConfig.groovy for integrating Scribe.<\/p>\n<p>[java]<\/p>\n<p>compile &#8216;org.scribe:scribe:1.3.5&#8217;<\/p>\n<p>[\/java]<\/p>\n<p>Create a controller, lets call it Demo Controller and define some variables in it.<\/p>\n<p>[java]<\/p>\n<p>class DemoController {<br \/>\n     String apiKey = \u201cxxxxxxxxxxxxxxx\u201d<br \/>\n     String secretKey = &quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br \/>\n     String baseUrl = &quot;https:\/\/graph.facebook.com\/&quot;;<br \/>\n     String callbackUrl = \u201c\/demo\/action2\u201d \/\/ link to the callback url of your application<br \/>\n     String fbUserToken \/\/ we will get value for this later<br \/>\n     String pageToken \/\/ we will get value for this later<br \/>\n}<\/p>\n<p>[\/java]<\/p>\n<p>Now create an action using which we will initiate the Oauth flow<\/p>\n<p>[java]<\/p>\n<p>def index() {<br \/>\n     OAuthService service = new ServiceBuilder()<br \/>\n             .provider(FacebookApi.class)<br \/>\n             .apiKey(apiKey)<br \/>\n             .apiSecret(secretKey)<br \/>\n             .scope(&quot;manage_pages,read_insights&quot;)<br \/>\n             .callback(grailsApplication.config.grails.serverURL + callbackUrl)<br \/>\n             .build();<br \/>\n     String authUrl = service.getAuthorizationUrl(null);<br \/>\n     redirect(url: authUrl.toURL())<br \/>\n}<br \/>\n[\/java]<\/p>\n<p>This action will initiate a call to Facebook Oauth and user will be redirected to a facebook login page. Upon successful authentication, the user will be redirected to the callback url of your application as specified by you. (\/demo\/action2 in this case).<\/p>\n<p>Here you will receieve authorization code in params. Which you can use to generate a short term token.<\/p>\n<p>[java]<br \/>\ndef action2() {<br \/>\n     OAuthService service = new ServiceBuilder()<br \/>\n                       .provider(FacebookApi.class)<br \/>\n                       .apiKey(apiKey<br \/>\n                       .apiSecret(secretKey)<br \/>\n                       .scope(&quot;manage_pages,read_insights&quot;)<br \/>\n                       .callback(grailsApplication.config.grails.serverURL + callbackUrl)<br \/>\n                       .build();<br \/>\n     Verifier v = new Verifier(params.code);<br \/>\n     Token accessToken = service.getAccessToken(null, v); \/\/ returns short term token for FB User<br \/>\n     fbUserToken = getLongTermUserToken(accessToken.token) \/\/ returns long term token for FB User which is valid for 2 months.<br \/>\n     pageToken = getPageToken(longTermToken) \/\/ returns the long term token for the facebook page which has no expiry.<br \/>\n}<br \/>\n[\/java]<\/p>\n<p>Now we have a access token, using which we can make calls to facebook on behalf of user, however, this is only a short term token valid for period of about 10 mins. We can get a long term token using :<\/p>\n<p>[java]<\/p>\n<p>fbUserToken = getLongTermUserToken(accessToken.token)  \/\/ returns long term token for FB User which is valid for 2 months.<\/p>\n<p>String getLongTermUserToken(String accessToken) {<br \/>\n     String url = baseUrl + &quot;oauth\/access_token?grant_type=fb_exchange_token&amp;client_id=${apiKey}&amp;client_secret=${apiSecret}&amp;fb_exchange_token=${accessToken}&quot;<br \/>\n     URL longTermUrl=new URL(url)<br \/>\n     String response = longTermUrl.text<br \/>\n     String longTermToken = extractLongTermToken(response)<br \/>\n     if (!longTermToken) {<br \/>\n          throw new Exception(&quot;Some good exception while fetching Long term Token&quot;)<br \/>\n     }<br \/>\n     return longTermToken<br \/>\n}<\/p>\n<p>String extractLongTermToken(String response) {<br \/>\n      List list = response.tokenize(&quot;&amp;&quot;)<br \/>\n      String result = &quot;&quot;<br \/>\n      list.each { String s -&gt;<br \/>\n           if (s.startsWith(&quot;access_token&quot;)) {<br \/>\n           result = s.tokenize(&quot;=&quot;).last()<br \/>\n        }<br \/>\n     }<br \/>\n     return result<br \/>\n}<br \/>\n[\/java]<\/p>\n<p>Now we have a long term token, which is valid for about 2 months. However to retrieve page information of a page managed by user, we need another token known as page token. To get page token :<\/p>\n<p>[java]<\/p>\n<p>String getPageToken(String longTermToken) {<br \/>\n     String url = baseUrl + &quot;me\/accounts?access_token=${longTermToken}&quot;<br \/>\n     URL pageTokenUrl=new URL(url)<br \/>\n     String dataString = pageTokenUrl.text<br \/>\n     JSONObject data = JSON.parse(dataString)<br \/>\n     Map response = data as Map<br \/>\n     String pageToken = extractPageToken(response)<br \/>\n     if (!pageToken) {<br \/>\n          throw new Exception(&quot;Some good exception while fetching Page Token&quot;)<br \/>\n     }<br \/>\n     return pageToken<br \/>\n}<\/p>\n<p>String extractPageToken(Map response) {<br \/>\n     String pageToken = &#8221;<br \/>\n     response.data.each {<br \/>\n         if (it.id == pageId) {<br \/>\n              pageToken = it.access_token<br \/>\n         }<br \/>\n     }<br \/>\n     return pageToken<br \/>\n}<\/p>\n<p>[\/java]<\/p>\n<p>Notice that we are using long term access token to get the page token. A page token fetched using long term access token has no expiry date. Now we can use this page token to fetch information for the page like page insights etc.<\/p>\n<p>Hope it helps.<\/p>\n<p>Mansi Arora<\/p>\n<p>mansi[at]ntelligrape[dot]com<\/p>\n","protected":false},"excerpt":{"rendered":"<p>OAuth is a secure mechanism to access facebook. To access facebook in your grails application you need to create a facebook app, go to https:\/\/developers.facebook.com, click on Apps dropdown, further click on &#8216;Create a new App&#8217;. Ensure that you register the URL of you application with the Facebook app you have setup. Save your apiKey [&hellip;]<\/p>\n","protected":false},"author":79,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":9},"categories":[7],"tags":[703,4840,770,1413,1414],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/13220"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/79"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=13220"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/13220\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=13220"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=13220"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=13220"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}