Connect facebook login to firebase in unity - facebook

I want in my unity game with firebase facebook login when user login through facebook there user name, email & profile picture save in firebase.
I tried from firebase unity login auth docs but i cant get any thing from there.
On there docs to difficult to understand for beginners.
using UnityEngine;
using Facebook.Unity;
using UnityEngine.UI;
using Firebase.Auth;
public class FacebookManager : MonoBehaviour
{
public Text userIdText;
private FirebaseAuth mAuth;
private void Awake()
{
if (!FB.IsInitialized)
{
FB.Init();
}
else
{
FB.ActivateApp();
}
}
public void LogIn()
{
FB.LogInWithReadPermissions(callback:OnLogIn);
}
private void OnLogIn(ILoginResult result)
{
if (FB.IsLoggedIn)
{
AccessToken tocken = AccessToken.CurrentAccessToken;
userIdText.text = tocken.UserId;
Credential credential =FacebookAuthProvider.GetCredential(tocken.UserId);
}
else
{
Debug.Log("Login Failed");
}
}
public void accessToken(Credential firebaseResult)
{
FirebaseAuth auth = FirebaseAuth.DefaultInstance;
if (!FB.IsLoggedIn)
{
return;
}
auth.SignInWithCredentialAsync(firebaseResult).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInWithCredentialAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
return;
}
FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
}
}
Please help me i am beginner in coding

Image
tocken.UserId This is wrong. Use tocken.TokenString . This will solve your problem. :)

Related

Invalid Credential When Sign In Facebook SDK To Firebase/Unity

I try to implement Facebook Authentication on my Unity project. So, after experimenting a few things i could make the Email Authentication works fine. But, when i tried to implement the Facebook Authentication it said "Invalid Credential". Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using Facebook.Unity;
public class facebookAuth : MonoBehaviour
{
private void Awake() {
FB.Init(initCallBack,OnUnityHide);
}
void initCallBack(){
if(!FB.IsInitialized)
FB.ActivateApp();
}
void OnUnityHide(bool show){
if(show)
FB.ActivateApp();
}
public void facebookLogin(){
if(FB.IsLoggedIn){
FB.LogOut();
}
var perms = new List<string>(){"email","public_profile"};
FB.LogInWithReadPermissions(perms,facebookResult);
}
void facebookResult(ILoginResult result){
if(FB.IsLoggedIn){
AccessToken token = result.AccessToken;
Credential credential = FacebookAuthProvider.GetCredential(token.TokenString);
firebaseFacebook(credential);
}
}
void firebaseFacebook(Credential token){
FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(token).ContinueWith(task=>{
if(task.IsCanceled){
Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
errorMessage("Canceled : ",(AuthError)e.ErrorCode);
}
if(task.IsFaulted){
Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
errorMessage("Faulted : ",(AuthError)e.ErrorCode);
}
Debug.Log(task.Result.DisplayName + " " + task.Result.UserId);
});
}
void errorMessage(string str, AuthError error)
{
string msg = error.ToString();
print(str+msg);
}
}
Your code looks correct to my reading. Make sure Facebook is enabled in the Firebase Console and the proper credentials have been filled out:
(I forget this all the time, especially if I have to enter things like the App Secret).
If this doesn't help, it would be useful to have any additional logging (or a copy of the error message) if possible.
--Patrick

Facebook Login with Unity 5 - Always return me Graph API Error: Bad request

I just start write my first game with unity.
I Created on facebook app - in games category.
I downloaded Facebook idk and added to unity.
I changed app id in Facebook settings.
Now I tried my code:
public class LoginScript : MonoBehaviour {
public string resultstr { get; set; }
public Text LableResult { get; set; }
List<string> perms = new List<string> (){"public_profile", "email", "user_friends"};
// Use this for initialization
void Start () {
LableResult = gameObject.GetComponent<Text> ();
LableResult.text = "Test";
if (!FB.IsInitialized) {
// Initialize the Facebook SDK
FB.Init (InitCallback, OnHideUnity);
} else {
// Already initialized, signal an app activation App Event
FB.ActivateApp ();
}
}
private void InitCallback ()
{
if (FB.IsInitialized) {
// Signal an app activation App Event
FB.ActivateApp ();
// Continue with Facebook SDK
// ...
} else {
Debug.Log ("Failed to Initialize the Facebook SDK");
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
// Update is called once per frame
void Update () {
}
private void AuthCallback (ILoginResult result)
{
if (FB.IsLoggedIn) {
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log (aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log (perm);
}
} else {
Debug.Log ("User cancelled login");
}
}
// On Facebook login button
public void OnFacebook ()
{
FB.LogInWithReadPermissions (perms, AuthCallback);
}
}
But I'm ALWAYS getting in Result:
Graph Api Error: 400 Bad request
And callback_id 2 (sometimes I've seen 3)
Login I try in Mock window with token from facebook.
I tried deploy on iPhone - and game just crashed when I click on login button
Please to close this topic. I fixed it. It was my fail )) (Used app token instead user token )) (Happends)))))
The same thing happened to me!
Remember to check the user token part, which won't be set by default!

Xamarin.Auth: Using Facebook oauth, how to redirect to my app?

I've just started using Xamarin.Auth and I want to enable Facebook login via oauth.
Here is my config:
public static string ClientId = "client id";
public static string ClientSecret = "client secret";
public static string Scope = "email";
public static string AuthorizeUrl = "https://m.facebook.com/dialog/oauth";
public static string RedirectUrl = "https://www.facebook.com/connect/login_success.html";
public static string AccessTokenUrl = "https://m.facebook.com/dialog/oauth/token";
Code for initiating the authentication:
public class AuthenticationPageRenderer : PageRenderer
{
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear (animated);
var auth = new OAuth2Authenticator (
Constants.ClientId,
Constants.ClientSecret,
Constants.Scope,
new Uri (Constants.AuthorizeUrl),
new Uri (Constants.RedirectUrl),
new Uri (Constants.AccessTokenUrl)
);
auth.Completed += OnAuthenticationCompleted;
PresentViewController (auth.GetUI (), true, null);
}
async void OnAuthenticationCompleted (object sender, AuthenticatorCompletedEventArgs e)
{
Debug.WriteLine ("AUTH Completed!");
if (e.IsAuthenticated) {
}
}
}
Seems to work fine, but instead of redirecting the user to https://www.facebook.com/connect/login_success.html, I want to redirect him back to my app again. Any help much appreciated!
Best,
Sascha
You can "redirect back" to your app again by simply invoking your own method to display the app's page you want to show to your user like this.
async void OnAuthenticationCompleted (object sender, AuthenticatorCompletedEventArgs e)
{
Debug.WriteLine ("AUTH Completed!");
if (e.IsAuthenticated) {
//invoke the method that display the app's page
//that you want to present to user
App.SuccessfulLoginAction.Invoke();
}
}
In your App.cs
public static Action SuccessfulLoginAction
{
get
{
return new Action(() =>
{
//show your app page
var masterDetailPage = Application.Current.MainPage as MasterDetailPage;
masterDetailPage.Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(MainPage)));
masterDetailPage.IsPresented = false;
});
}
}
Assuming that MainPage is the page you wanted to show after successful login. I am using Xamarin.Forms with MasterDetailPage to display pages in my example which maybe different from your app but the concept is the same.
Just call DismissViewController (true, null) in your OnAuthenticationCompleted method. Or use the async equivalent:
async void OnAuthenticationCompleted(object sender, AuthenticatorCompletedEventArgs e)
{
Debug.WriteLine("AUTH Completed!");
await DismissViewControllerAsync(true);
if (e.IsAuthenticated)
{
}
}

facebook login with unity jumping to first scene in editor

I am having a strange issue when trying to test the Facebook sdk(login) in Unity Editor. The login procedure works fine, but after successfully logging in (pasting the token generator) , Facebook throws me back in to my first scene instead of staying in the same scene, where the login procedure was started.
Any ideas why this is happening?
Update: Strangly enough, this only happens when "maximize on play" is enabled.
Update: Code snipet:
public class UserManager : MonoBehaviour {
public Button fbLoginButton;
public Text errorSuccessText;
public void Start() {
fbLoginButton.interactable = false;
FB.Init (OnFBInitComplete);
fbLoginButton.onClick.AddListener (() => SubmitFBInfo ());
}
private void OnFBInitComplete() {
fbLoginButton.interactable = true;
}
private void SubmitFBInfo() {
FB.Login("email,publish_actions", FBLoginCallback);
}
private void FBLoginCallback(FBResult result) {
if (FB.IsLoggedIn) {
errorSuccessText.text = "Logged In with Facebook";
}
}

Facebook: FB.apiClient TypeError: $wnd.FB.Facebook is undefined" why this error occures?

We are facing one problem with facebook.
we integrated FB in our web application, when user login through fconnect in our web application then he registered with our system(1st time only) just providing his email id.For normal user few user i/p for registration in our system
Our web-application developed in java [GWT2.0].
Problem is when FACEBOOK or normaluser login through FB in our web-application.( 1 at a time)
when user refreshes page then FB pop window Occues with message
"Debug: Exception while loading FB.apiClient TypeError: $wnd.FB.Facebook is undefined"
or sometimes $wnd.FB.Facebook.apiClient is null occures
we get above error[pop-up] message 3 times.
we used following script in html page
< script type="text/javascript" language="javascript"
src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php">
In only 1 page of our web-application i.e UserHome page where we display users info .
on that page only above error message occurs
We used following GWT Code [from Gwittit] In controller class[Singleton class ]
/**
* Function get called when all the data on first page get loaded.
*
* */
public void notifyFinishedLoadinPage() {
FacebookConnect.waitUntilStatusReady(new
RenderAppWhenReadyCallback());
}
private MyLoginCallback
loginCallback = new MyLoginCallback();
class MyLoginCallback implements LoginCallback {
public void onLogin() {
isFacebookSign = true;
fbLoggedInUserId = ApiFactory.getInstance().getLoggedInUser();
for (FacebookObserver Observer : facebookObservers) {
Observer.notifyFacebookLogin(true);
}
}
}
public void publishStream(final FacebookObserver fbObserver) {
FacebookConnect.init(FacebookConstants.FACEBOOK_API_KEY,
"xd_receiver.htm", loginCallback);
FacebookConnect.requireSession(new
AsyncCallback() {
public void onFailure(Throwable caught) {
Window.alert("Require session failed: " + caught);
GWT.log("Require session failed: " + caught, null);
}
public void onSuccess(Boolean isLoggedIn) {
if (isLoggedIn) {
for (FacebookObserver Observer :
facebookObservers) {
Observer.notifyPublishStream();
}
}
}
});
}
public void facebookConnection() {
FacebookConnect.init(FacebookConstants.FACEBOOK_API_KEY,
"xd_receiver.htm", loginCallback);
//SERVER
FacebookConnect.requireSession(new
AsyncCallback() {
public void onFailure(Throwable caught) {
GWT.log("Require session failed: " + caught, null);
}
public void onSuccess(Boolean isLoggedIn) {
if (loginCallback != null && isLoggedIn) {
loginCallback.onLogin();
} else {
//User not logged in
}
}
});
}
/**
* Fired when we know users status
*/
private class RenderAppWhenReadyCallback implements
AsyncCallback {
public RenderAppWhenReadyCallback() {
FacebookConnect.init(FacebookConstants.FACEBOOK_API_KEY,
"xd_receiver.htm", loginCallback);
//SERVER
}
public void onFailure(Throwable caught) {
Window.alert("Unable to login through Facebook: " + caught);
}
public void onSuccess(ConnectState result) {
if (result == ConnectState.connected) {
isFacebookSign = true;
for (FacebookObserver Observer : facebookObservers) {
Observer.notifyFacebookLogin(true);
}
//History.newItem(HistoryConstants.USERHOME_PAGE_HISTORY_TOKEN);
} else {
//rightSideFlexTable.clearCell(0, 0);
//rightSideFlexTable.setWidget(0, 0,
facebookPanel);
isFacebookSign = false;
}
}
};
Now we unable to found solution to this problem.
Can any one help Us to solve this problem ASAP
Hope-for the Best Co-operation
we found solution for above Question.
Facebook (login)loading requires few time.
In Our web page we fetch fb details like fb users loggedInId ,Image,etc.
so at the time of page loading we get all values null because facebook not load properly
so we get $wnd.FB.Facebook.apiClient is null or
Debug: Exception while loading FB.apiClient TypeError: $wnd.FB.Facebook is undefined"
To solve this problem we write one method which calls when user refreshes page or after facebook loading done properly.
public void notifyFacebookLogin(boolean isLogin) {
Long fbLoggedInUserId = ApiFactory.getInstance().getLoggedInUser();
if (fbLoggedInUserId != null) {
if (globalEndUserInfo == null) {
globalEndUserInfo = new EndUserInfo();
globalEndUserInfo.setFbLoggedInUserId(fbLoggedInUserId);
}
}
// code wherever we deal with FB related object
}
Now no error message display when user refreshes page or if fb takes time to loading
In this way we solve our Problem. :)