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

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!

Related

Is it possible to track app installs using the Facebook Unity SDK without logging the user into Facebook?

I am trying to setup a Facebook marketing campaign with the objective being to track app installs. Facebook recommends using their SDK to get accurate information about app installs, but I don't want to prompt the user to login to Facebook in my app. Is it possible to have the Facebook SDK track app installs without users logging in? According to Facebook their API automatically tracks app installs but it seems that in their initialization script called mainmenu.cs requires a Facebook login to occur.
What I did was basically create a persistent game object in my first scene and attached this code to it. I based this code off of Facebook's example https://developers.facebook.com/docs/app-events/unity but added some additional checks so FB.Init() would not be called twice. I also added a coroutine that would wait to activate an event until FB.Init() is done since FB.Init() is an asynchronous function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Facebook.Unity;
public class FacebookTracker : MonoBehaviour {
private static FacebookTracker instance;
private bool initCalled;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
} else
{
Destroy(gameObject);
}
if (FB.IsInitialized == false && initCalled == false)
{
FB.Init();
initCalled = true;
}
}
private void OnApplicationPause(bool pause)
{
Debug.Log("OnApplicationPause = " + pause);
if (pause == false)
{
if (FB.IsInitialized == true)
{
FB.ActivateApp();
} else
{
if (initCalled == false)
{
FB.Init();
initCalled = true;
}
StartCoroutine(ActivateEvent());
}
}
}
private IEnumerator ActivateEvent()
{
yield return new WaitUntil(() => FB.IsInitialized == true);
Debug.Log("Facebook Activate Event Logged");
FB.ActivateApp();
}
}

Connect facebook login to firebase in unity

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. :)

Facebook publish_actions aproved but grantedScope shows publish_actions only for me

I'm having an interesting issue.
My FB Canvas game is in dev mode and i have gotten my publish_actions approval. When launch my game in the browser i get the list of grantedScopes when logged into my account it lists publish_actions correctly and everything works, but when one of my testers (i have given the person the tester roll in the fb dev console.) Loads up the game then it does not list publish_actions under their grantedScopes.
Am i doing something wrong?
Do I need to request of the user to accept this new permission somehow?
here is my fblogin code
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using UnityEngine.UI;
using System;
public class FBLogin : MonoBehaviour {
void Awake()
{
FB.Init (SetInit, OnHideUnity);
}
private void SetInit()
{
Debug.Log ("FB Init done.");
if (FB.IsLoggedIn)
{
Debug.Log ("FB Logged In.");
}else{
Debug.Log("FB NOT Logged In.");
}
}
private void OnHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale = 0;
}else{
Time.timeScale = 1;
}
}
public void FBlogin ()
{
var perms = new List<string>(){"public_profile", "email",};
FB.LogInWithPublishPermissions(perms, AuthCallback);
}
private void AuthCallback (ILoginResult result)
{
Debug.Log(result.RawResult);
if (FB.IsLoggedIn)
{
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");
}
}
}
Thanks guys.
The permissions you are requesting are not publish permissions, they are read permissions. You will need to use
FB.LogInWithReadPermissions(new List<String>(){"public_profile", "email"}, AuthCallback)
to log in with the requested read permissions. Once your callback fires, you will need to submit a second request:
FB.LogInWithPublishPermissions(new List<String>(){"publish_actions"}, AuthCallback)
You cannot combine read and publish permissions on the same request dialog to the end user. Rather than open two dialogs back to back, it is considered best practice to hold off on requesting the publish permissions until the user actually attempts to publish something from within your app.

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. :)