How to do a login with Facebook [Unity]

  1. Setup a Unity project with the Gamedonia SDK by following these steps.

  2. Create an app in the Facebook Developers Portal. In your Facebook app Dashboard, go to Settings and click on Add Platform to add Android or iOS.

  3. Configurate your Facebook app and your Unity project for Android or iOS as described in this guide.

In Unity:

  1. Initialize the Facebook plugin with this line:
    void Awake() {
     FacebookBinding.Init("<your-facebook-app-id>");
    }
    
  2. Create a variable to store the read permissions we want the user to grant us:
    private static string [] READ_PERMISSIONS = new string[] {"read_stream", "read_friendlists"};

  3. Add this call on a button that will act as custom Facebook login button:
    FacebookBinding.OpenSessionWithReadPermissions(READ_PERMISSIONS, OnFacebookOpenSession);

  4. Create the callback for the openSession call:

    //Callback handler for the OpenSession call
    void OnFacebookOpenSession(bool success, bool userCancelled, string message)
    {
     if (success) {
     //Now that we have a valid session we have an accessToken but we still need the user fbuid so we call the graph api to get it.
     FacebookBinding.RequestWithGraphPath("/me",null,"GET",OnFacebookMe);
     } else {
          Debug.Log("Unable to open session with Facebook");
     }
    }
    
  5. Add the callback for the "/me" call to the Facebook API Graph, where we authenticate the user (create & login):

    private void OnFacebookMe(IDictionary data) {
     //Extract some needed data from the Facebook response to the Graph API
     string fbUserId = data ["id"] as string;
     string fbUserName = data ["name"] as string;
     Debug.Log ("AccessToken: " + FacebookBinding.GetAccessToken() + " fbuid: " + fbUserId);
     //Setup a map with the Facebook credentials to call Gamedonia Login process. Map key names are very important take care.
     Dictionary<string,object> facebookCredentials = new Dictionary<string,object> ();
     facebookCredentials.Add("fb_uid",fbUserId);
     facebookCredentials.Add("fb_access_token",FacebookBinding.GetAccessToken());
     //Authenticate method will do the job of registering and login the user to be able to start working with Gamedonia!
     GamedoniaUsers.Authenticate (Gamedonia.CredentialsType.FACEBOOK,facebookCredentials, OnFacebookLogin);
    }
    
  6. Create a callback for the login result:

    void OnFacebookLogin (bool success) {
     if (success) {
          Debug.Log("Login worked!!");
          //TODO Put your login success behavior here.
     }else { 
          Debug.Log("Login failed");
    }
    }
    
    For a more detailed guide follow this Facebook Login Tutorial.

More info here: Facebook integration guide