Sunday, May 15, 2011

Facebook Login on Google App Engine(Java)

In this blog i will explain how you can use facebook login on your google app engine java application and how to publish on logged in user's facebook wall.

Frameworks/libraries i will be using are
1) Google App Engine Java
2) facebook-java-api(V 3.0.2)
3) Spring MVC(You can easily avoid it if you want to)

First thing i should warn you this facebook-java-api is not being supported actively so if you get into trouble you may find bit bit difficult to find a solution. But i hope using this tutorial you may not hit to any problem

Create Facebook Login Url
Login Url should be in the following Format
http://www.facebook.com/login.php?api_key=<Your Facebook Api Key1>&connect_display=popup&v=1.0&next=<Callback Url after user login and authorize app2>&cancel_url=<Callback Url after user do not login or do not authorize app3>&fbconnect=true&return_session=true&session_key_only=true&req_perms=<permissions4>
1 Your facebook application API key. For more information visit Facebook Developer
2 Your site's url after login at facebook is succesfull and user authorize your application to use his/her data.
e.g. http://www.yoursite.com/logindone
3 Your site's url after user declined to login at facebook or do not authorize your application to use his/her data.
e.g. http://www.yoursite.com/loginerror
4 Kind of information you want to access on behalf of User. Click here for more info on permission.

Once your url is ready, either directly display it on your html or hide it behind proxy url(using redirect on server side code).
Using Sprice MVC(annotaion based you can write login function as follows)


@RequestMapping(value = "/login", method = RequestMethod.GET)
 public String login(@RequestParam("op") String provider,@RequestParam("target") String target,HttpServletRequest request,Model model){
 String redirectUrl = null;
 try{
     String uri = request.getRequestURI();
     String requestUrl = request.getRequestURL().toString();
     int ind = requestUrl.lastIndexOf(uri);
     String serverName = requestUrl.substring(0, ind);
     //using provider param you can use many other logins like google etc but this example is only for facebook
     request.getSession().setAttribute("target", target);
     String returnUrl = serverName+"/logindone";
         redirectUrl="http://www.facebook.com/login.php?api_key=1102257e0b87a111b12ec1c3d04f6b6b&connect_display=popup&v=1.0&next="+returnUrl+"&cancel_url="+returnUrl+"&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,email,offline_access";
     return "redirect:"+redirectUrl;
 }



Call back url implementation
Using Sprice MVC(annotaion based you can write function as follows)

@RequestMapping(value = "/logindone", method = RequestMethod.GET)
    public String logindone(HttpServletRequest request,Model model) throws AppException{
        String target = (String)request.getSession().getAttribute("target");// save your site url in session when you are going to Login url, so that you can send user back to site url where he clicked on Login url
        try{
                JSONObject facebookCode = new JSONObject(request.getParameter("session"));
                String sessionKey = facebookCode.getString("session_key");
                FacebookJsonRestClient jsonRestClient = new FacebookJsonRestClient("API_KEY", "SECRET",sessionKey);
                long userUid = jsonRestClient.users_getLoggedInUser();
                JSONArray userInfoArray = (JSONArray)jsonRestClient.fql_query("select first_name,last_name,username, email,sex from user where uid = me()");

                String emailId = (String)userInfoArray.getJSONObject(0).get("email");
                String firstName = (String)userInfoArray.getJSONObject(0).get("first_name");
                String lastName = (String)userInfoArray.getJSONObject(0).get("last_name");
                String sex = (String)userInfoArray.getJSONObject(0).get("sex");
 //Now you can publish this on Facebook if you want to. Just brag about your site on facebook :)
                    try{
                        Attachment attachment = new Attachment();
                        attachment.setCaption(loggedInApplUser.getFirstName()+ " has joined MySite.com to Do Something");
                        attachment.setDescription("My Site is fastest growing website in my frield in India.");
                        AttachmentMedia media = new AttachmentMediaImage("http://cdn1.iconfinder.com/data/icons/locationicons/building.png","http://www.mysite.com");
                        attachment.setMedia(media);
                        jsonRestClient.stream_publish(loggedInApplUser.getFirstName()+ " has joined mysite.com to do something", 
                                attachment, null, null, null);
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
        return "redirect:"+target;
    }



2 comments:

  1. Thank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we provide Java course in Chennai at Fita.

    ReplyDelete
  2. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Java Training in Chennai

    ReplyDelete