简体   繁体   中英

Posting on Page with facebook4j

Is there a way of how to post on facebook page wall? From tutorials is just showing how to get info about page. I wan to be able to post on public page(not my own but One that customer has admin rights).

I also tried using app solution and I succesfully got OAuthAppAccessToken, but it's not enough.

An active access token must be used to query information about the current user.

Is there some tutorial? because most people just want to get like and comments from pages.

Option 1 (get token via tools)

This option requires manual entering and copying generated tokens via graph api tools. I am not going to cover this option much because these two links obtaining facebook page access token the 4 step program and Post to Facebook Page wall using RestFB api are covering it pretty well.


Option 2 (one button solution)

Now this is pretty automated solution which (if you are like me) you want. Since I couldn't tell my client: "Go here, copy this, gimme this and stuff...". I needed to do most user friendly solution. In the end I implemented FB login button and simple ajax call that will get long lived page access token. With this token, our app can post on his page automatically when some event occurs. Using the obtaining facebook page access token the 4 step program tutorial here is the solution:

  1. Make your application https://developers.facebook.com/apps/ (you may need to add website platform and make it live).
  2. In dashboard retrieve app id and app secret.
  3. Implement log in button on your website. A great info about this can be found here fb login for web . Code snippet there is all you need, just replace app id with your app id.
  4. Add scopes in login-button so we can obtain pages as well have permissions to do publish actions.

<fb:login-button scope="public_profile,email,manage_pages,publish_actions" onlogin="checkLoginState();"> </fb:login-button>

  1. In login button you can see function that is called every time when login is invoked. In this function we can get response from FB with tokens and info we need about our user (in this case it's really just token we need). Following javascript code sends user token (short lived) via ajax, to our server.

    function checkLoginState() { FB.getLoginStatus(function (response) { statusChangeCallback(response); }); } function statusChangeCallback(response) { if (response.status === 'connected') { getLongLivedToken(response.authResponse.accessToken); } } function getLongLivedToken(access) { var data = { ${fbParam}: acces }; $.post( '${fbUrl}', data, function (INFO) { console.log("done"); }, 'text' ); }

  2. The next step is server side one. At the moment we receive token, we need to convert it to long lived one.

      String url = "https://graph.facebook.com/oauth/access_token"; String charset = "UTF-8"; String grandType = "fb_exchange_token"; String query = String.format("grant_type=%s&client_id=%s&client_secret=%s&fb_exchange_token=%s", URLEncoder.encode(grandType, charset), URLEncoder.encode(Constants.FACEBOOK_APP_ID, charset), URLEncoder.encode(Constants.FACEBOOK_APP_SECRET, charset), URLEncoder.encode(shortToken, charset)); HttpsURLConnection con = (HttpsURLConnection) new URL(url + "?" + query).openConnection(); InputStream ins = con.getInputStream(); InputStreamReader isr = new InputStreamReader(ins); BufferedReader in = new BufferedReader(isr); String inputLine; String result = ""; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); result += inputLine; } in.close(); String[] params = result.split("&"); Map<String, String> map = new HashMap<String, String>(); for (String param : params) { String name = param.split("=")[0]; String value = param.split("=")[1]; map.put(name, value); } String longToken=map.get("access_token"); 
  3. Now the last step we need to obtain access token for page we want to post at. From this point on we can use facebook4j.

      Facebook facebook = new FacebookFactory().getInstance(); facebook.setOAuthAppId(Constants.FACEBOOK_APP_ID, Constants.FACEBOOK_APP_SECRET); facebook.setOAuthAccessToken(new AccessToken(longToken)); try { String pageToken = null; for (Account a : facebook.getAccounts()) { if (a.getName().toLowerCase().contains("nameOfPage")) { pageToken = a.getAccessToken(); } } 
  4. PROFIT: with this token we can post on desired page:

     PostUpdate post = new PostUpdate(new URL("http://priklad.sk")) .picture(new URL("http://priklad.sk/obrazcok/testik.png")) .name("priklad") .caption("priklad") .message("priklad") .description("priklad"); try { if (pageToken != null) { facebook.setOAuthAccessToken(new AccessToken(id)); facebook.postFeed(post); Input.addInfoAnnotation(req, "sysAdminTools.annotation.fb.ok"); } } catch (FacebookException ex) { Logger.getLogger(EditAdPreviewServlet.class.getName()).log(Level.SEVERE, null, ex); } 

Side note : This solution is not meant to be used as a page spammer. User needs to be informed what events will trigger posting on his page. If user wants to reduce/remove permissions he can do in FB settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM