Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Facebook SDK for Unity - Plus Windows Phone 8

Discussion in 'Windows' started by zeezeezee, Dec 17, 2013.

  1. mechanicals59

    mechanicals59

    Joined:
    Aug 6, 2014
    Posts:
    7
    How can i use Authentication through browser in case the user does not have the Facebook Application already installed and also does not want to install the Facebook Application. Really need help on this.
     
  2. kennt

    kennt

    Joined:
    Feb 21, 2014
    Posts:
    1
    @zeezeezee
    I met a very thorny issue, I hope you can help me.
    If the Facebook application has been installed on the Windows Phone, press Login button in the game and logged in. In this case, the game crashes occasionally.It has two exception callback on function named "RootFrame_NavigationFailed" and "Application_UnhandledException" in class APP of package Windows Phone, and the call the other excetion :

    Unhandled exception "System.Reflection.TargetInvocationException" type of place in System.Windows.ni.dll

    Additional information: Exception has been thrown by the target of an invocation.
     
  3. mechanicals59

    mechanicals59

    Joined:
    Aug 6, 2014
    Posts:
    7
    How do I Add request permission for getting user's friends. Currently I am getting request for user_profile and email. How and where to add the user_friends request.permissions. Thanks !!!
     
  4. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    @jojo665 - I haven't managed to get it working 100% yet. You basically need to extend the SDK to include a FacebookWin8 (or what ever you want to call it) rather than the FacebookWP8 and use a WebAuthenticationBroker to make the facebook call. As I say, I've not had it working in Unity yet, I got it working in a basic Windows Store app, but not had time to go back to it for a while to finish it off. When I do get it all working which I'll be doing in a few weeks, I can give some more advice then.

    @mechanicals59 - There was a way of doing web authentication in an older version of the plugin, but Zee updated it with the single sign on only. I possibly have the old library somewhere as I think he's removed it from his bit bucket account - its a bit of a pain to get going, and I'm not sure if both can be integrated together. Also, I get friends in my access token by calling: FB.Login("email,publish_actions", LoginCallback); I believe friends are publicly available, so you don't need special permissions to access them.
     
  5. latas

    latas

    Joined:
    Oct 9, 2013
    Posts:
    149
    Hi everyone, trying to make work the facebook SDK with Windows Phone 8, I comment here my notes.
    I followed the instructions and I could make it work.
    I was able to do post, and in fact I did my implementation for several games.
    But it is truth there is a bug that make the game crashes some times.
    When?

    Well, there are 3 ways the authentication can follow when it begins.
    First way. It happens when you never approved the application. That way doesn't crash. You approve the application and after some button touches in the facebook app your game is resumed and you back to your game without issue.

    Second way. It happens when once you approved your app, you run the game, and your authentication token is still valid ( not expired ) and then the authentication happens in background and your app keeps on running without any resume or quit. This works well.

    Third way. This is when the app crashes. Your app is already approved for using with facebook, you run your game, and the last authentication token has expired. Then your app quits, facebook app is launched, authentication procedure happens without user interaction and then it resumes trying to go your game again. Then sometimes, other not, the game crashes.

    What happens different here than the other ways? In my guess only app launches and resumes speed. So I did my best trying to not accessing GameObjects directly from my facebook controller in Callbacks, or at least conditioning them with a null check before using it. In that way, by the way it look it works.

    But I'm pretty sure that maybe only helps to crash a little bit less, but the main problem is not there.

    Any idea?
     
  6. BlackPanda

    BlackPanda

    Joined:
    Jan 24, 2014
    Posts:
    78
    I'm building an WP 8.1 app. I don't have a WMAppManifest file, but a Package.appxmanifest file. Can anyone tell me what are all the changes that I should make after building the VS project?
     
  7. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,722
    You need to enable the correct capabilities in the manifest.
     
  8. BlackPanda

    BlackPanda

    Joined:
    Jan 24, 2014
    Posts:
    78
    Yes I already did that. I had enabled Internet(Client & Server). But a null reference exception is thrown in the method FacebookWP8.Init() while the condition if(FacebookWP8.AccessToken.Length > 0) is checked. So the facebook login is not working too.

    I want to know how I can edit the manifest file so that I can provide the details of product IDs as mentioned in the first post. I believe that's how I got this error???
     
    Last edited: Oct 9, 2014
  9. BlackPanda

    BlackPanda

    Joined:
    Jan 24, 2014
    Posts:
    78
    How can I add <Extension> in Package.appxmanifest file in WP8.1??
     
  10. mechanicals59

    mechanicals59

    Joined:
    Aug 6, 2014
    Posts:
    7
    Hi, I am facing a scenario...If i go to the Facebook Login through this SDK and then instead of Logging In I press back button to go back to my App. I get a NullRefrence Exception. Any ideas or if anybody has faced this before.
     
  11. kevine711

    kevine711

    Joined:
    Sep 7, 2014
    Posts:
    3
    Has anybody got this working with the Facebook SDK 6.0? It looks like the graph 2.0 is going to be mandatory starting in April 2015. Also, I'm unclear about the "real" and "fake" stuff. Is there a clear process/guide to follow?

    Any help is appreciated!
     
    BlackPanda likes this.
  12. zoolax

    zoolax

    Joined:
    Apr 18, 2013
    Posts:
    19
    How can I set and post scores as a saving method?
     
  13. BDCJR

    BDCJR

    Joined:
    Apr 25, 2013
    Posts:
    19
    Hey guys I encounter other strange error! After I complete all the steps below, I got this error "App Not Setup. The developers of this app have not set up this app properly for Facebook Login." when I try to login from the game on the WP8 device. But my game is already published on PlayStore and AppStore and the facebook app works without problems.

    P.S. I set up a new Windows App on facebook developers console and I paste the store ID (without dashes) and in WMAppManifest.xaml

    Someone encounter the same problem?
     
  14. myaug

    myaug

    Joined:
    Jul 3, 2014
    Posts:
    1
    A week ago, my game worked well with this package but now it raise error. I've found that FB just released a new Facebook SDK for Unity on 01/28/2015. It seem this is problem.
    I've upgraded to new SDK but still not solve it, error return from Init() function.
     
  15. layinka

    layinka

    Joined:
    Jun 26, 2013
    Posts:
    6
    Please, is there anyway to reach facebook?
    Please tell facebook to release or implement their sdk for unity for WP too, its affecting a lot of people
     
  16. Nerosam

    Nerosam

    Joined:
    Jul 23, 2013
    Posts:
    40
    I second this...its an epic shame one needs to scream at a developers ear for windows8/wp8 support...especially if they are huge and acquiring other companies with spare change
     
  17. cs_gwl

    cs_gwl

    Joined:
    Apr 20, 2014
    Posts:
    1
    @BDCJR --- I am facing the same issue as you are facing...I have seen the comments on stackoverflow.com for this type of error and the resolution was to make app public in facebook.
    In my case my app is already published in facebook and still getting the error "App Not Setup. The developers of this app have not set up this app properly for Facebook Login."
    I have setup my app as WP app in facebook, updated my manifest file as described in the comments but still could not make it work...

    Any solution...???
     
  18. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Wouldn't surprise me if this is something to do with the new Facebook requirements. They don't have a way of authorising a Windows Phone app yet, so I'm thinking this may not be possible any more. I'm currently updating our games to the latest SDK and I'll let you know how I get on in regards to Windows Phone.

    As others have said, its about time Facebook got their SDK in order and added Windows Phone. Its been in beta on their site for well over a year and we don't even have a beta SDK we can use. Not very good!
     
  19. Nerosam

    Nerosam

    Joined:
    Jul 23, 2013
    Posts:
    40
    Update: I ran into this video that explains how the "AndContinue" methods are going away in windows 10 so we can use one single method; the Async methods that already exists on windows 8/8.1 api. Check it out at


    Hi peeps,

    I managed to get something working.

    Here is some of the main code that directly calls on WebAuthenticationBroker:-

    Code (CSharp):
    1. static bool isTryingToRegister { get; set; }
    2. private static string _FbToken;
    3. public static string response;
    4. static bool isLoggedIn { get; set; }
    5. static private string AppID { get { return "000000000000000000"; } }
    6. static private Uri callback { get; set; }
    7. static private string permissions { get { return "public_profile, user_friends, email, publish_actions, user_photos"; } }
    8. public static System.Action<object> AuthSuccessCallback;
    9. public static System.Action<object> AuthFailedCallback;
    10. public static string fbToken
    11. {
    12. get
    13. {
    14. return _FbToken;
    15. }
    16. }
    17.  
    18. static Uri loginUrl
    19. {
    20. get
    21. {
    22. return new Uri(String.Format("https://www.facebook.com/v2.0/dialog/oauth/?client_id={0}&display=popup&response_type=token&redirect_uri={1}&scope={2}",
    23. AppID,
    24. callback,
    25. permissions));
    26. }
    27. }
    28.  
    29. public static IEnumerator _Run_ConnectWithFacebook()
    30. {
    31. yield return new WaitForEndOfFrame();
    32.  
    33. #if UNITY_EDITOR
    34. UnityDebugAuthentication();
    35. #endif
    36. #if NETFX_CORE
    37. WindowsStoreAuthenticate();
    38. #endif
    39.  
    40. }
    41. #if NETFX_CORE
    42. static void WindowsStoreAuthenticate()
    43. {
    44. #if UNITY_WP_8_1 && !UNITY_EDITOR
    45. AuthSuccessCallback = _Run_ConnectWithFacebook_SuccessResponse;
    46. AuthFailedCallback = _Run_ConnectWithFacebook_FailedResponse;
    47. UnityEngine.WSA.Application.InvokeOnUIThread(
    48. () =>
    49. {
    50. callback = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
    51. WebAuthenticationBroker.AuthenticateAndContinue(loginUrl, callback, null, WebAuthenticationOptions.None);
    52. }, true);
    53. #endif
    54. #if UNITY_METRO_8_1 && !UNITY_EDITOR
    55. AuthSuccessCallback = _Run_ConnectWithFacebook_SuccessResponse;
    56. AuthFailedCallback = _Run_ConnectWithFacebook_FailedResponse;
    57. UnityEngine.WSA.Application.InvokeOnUIThread(
    58. async () =>
    59. {
    60. callback = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
    61. WebAuthenticationResult authResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, loginUrl);
    62. }, true);
    63. #endif
    64. }
    65. #endif
    Note how I use WebAuthenticationBroker.AuthenticateAndContinue for windows phone and WebAuthenticationBroker.AuthenticateAsync for windows 8. This is necessary for their respective platforms. You may want to look into getting the WebAuthenticationBroker which is a Microsoft class that works on WP8 and WSA (im guessing you are aiming for WSA, so am I):-

    https://msdn.microsoft.com/library/...cationbroker.aspx?f=255&MSPPError=-2147217396

    You will also need to build a c# project in unity so you can implement part 2 of it which includes handling when the token details are returned to the app. Here is my code sample of App.xaml.cs which was inspired by https://msdn.microsoft.com/en-us/library/dn631755.aspx:-

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using System.Linq;
    5. using System.Runtime.InteropServices.WindowsRuntime;
    6. using Windows.ApplicationModel;
    7. using Windows.ApplicationModel.Activation;
    8. using Windows.Foundation;
    9. using Windows.Foundation.Collections;
    10. using Windows.UI.Core;
    11. using Windows.UI.ViewManagement;
    12. using Windows.UI.Xaml;
    13. using Windows.UI.Xaml.Controls;
    14. using Windows.UI.Xaml.Controls.Primitives;
    15. using Windows.UI.Xaml.Data;
    16. using Windows.UI.Xaml.Input;
    17. using Windows.UI.Xaml.Media;
    18. using Windows.UI.Xaml.Navigation;
    19. using UnityPlayer;
    20. using Template.Common;
    21. using Windows.Security.Authentication.Web;
    22. // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
    23.  
    24. namespace Template
    25. {
    26. /// <summary>
    27. /// Provides application-specific behavior to supplement the default Application class.
    28. /// </summary>
    29. sealed partial class App : Application
    30. {
    31. private WinRTBridge.WinRTBridge _bridge;
    32. private AppCallbacks appCallbacks;
    33. #if UNITY_WP_8_1
    34. public ContinuationManager continuationManager { get; private set; }
    35. #endif
    36. /// <summary>
    37. /// Initializes the singleton application object. This is the first line of authored code
    38. /// executed, and as such is the logical equivalent of main() or WinMain().
    39. /// </summary>
    40. public App()
    41. {
    42. this.InitializeComponent();
    43. appCallbacks = new AppCallbacks();
    44. appCallbacks.RenderingStarted += RemoveSplashScreen;
    45.  
    46. #if UNITY_WP_8_1
    47. this.Suspending += OnSuspending;
    48. continuationManager = new ContinuationManager();
    49. #endif
    50. }
    51.  
    52. /// <summary>
    53. /// Invoked when application is launched through protocol.
    54. /// Read more - http://msdn.microsoft.com/library/windows/apps/br224742
    55. /// </summary>
    56. /// <param name="args"></param>
    57. protected override void OnActivated(IActivatedEventArgs args)
    58. {
    59. #if UNITY_WP_8_1
    60.  
    61. var continuationEventArgs = args as IContinuationActivatedEventArgs;
    62. if (continuationEventArgs != null)
    63. {
    64.  
    65. ContinueWebAuthentication(args as WebAuthenticationBrokerContinuationEventArgs);
    66. return;
    67. //}
    68. }
    69. #endif
    70. string appArgs = "";
    71. Windows.ApplicationModel.Activation.SplashScreen splashScreen = null;
    72. switch (args.Kind)
    73. {
    74. case ActivationKind.Protocol:
    75. ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
    76. splashScreen = eventArgs.SplashScreen;
    77. appArgs += string.Format("Uri={0}", eventArgs.Uri.AbsoluteUri);
    78. break;
    79. }
    80. InitializeUnity(appArgs, splashScreen);
    81. }
    82.  
    83.  
    84. #if UNITY_WP_8_1
    85. public void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
    86. {
    87. WebAuthenticationResult result = args.WebAuthenticationResult;
    88.  
    89. if (result.ResponseStatus == WebAuthenticationStatus.Success)
    90. {
    91. string responseData = result.ResponseData.Substring(result.ResponseData.IndexOf("access_token"));
    92. String[] keyValPairs = responseData.Split('&');
    93. string access_token = null;
    94. string expires_in = null;
    95. for (int i = 0; i < keyValPairs.Length; i++)
    96. {
    97. String[] splits = keyValPairs[i].Split('=');
    98. switch (splits[0])
    99. {
    100. case "access_token":
    101. access_token = splits[1]; //you may want to store access_token for further use. Look at Scenario5 (Account Management).
    102. break;
    103. case "expires_in":
    104. expires_in = splits[1];
    105. break;
    106. }
    107. }
    108.  
    109. AppCallbacks.Instance.UnityActivate(Window.Current.CoreWindow, CoreWindowActivationState.CodeActivated);
    110. AppCallbacks.Instance.InvokeOnAppThread(() =>
    111. {
    112. // back to Unity
    113. //function to call or variable that accepts the access token
    114. }, false);
    115. //OutputToken(result.ResponseData.ToString());
    116. //await GetFacebookUserNameAsync(result.ResponseData.ToString());
    117. }
    118. else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
    119. {
    120. //OutputToken("HTTP Error returned by AuthenticateAsync() : " + result.ResponseErrorDetail.ToString());
    121. AppCallbacks.Instance.InvokeOnAppThread(() =>
    122. {
    123. // back to Unity
    124. //function to call indicating something went wrong
    125. }, false);
    126. }
    127. else if(result.ResponseStatus == WebAuthenticationStatus.UserCancel)
    128. {
    129. //OutputToken("Error returned by AuthenticateAsync() : " + result.ResponseStatus.ToString());
    130. AppCallbacks.Instance.InvokeOnAppThread(() =>
    131. {
    132. // back to Unity
    133. //function to call indicating something went wrong
    134. }, false);
    135. }
    136.  
    137. }
    138. #endif
    139.  
    140. /// <summary>
    141. /// Invoked when application is launched via file
    142. /// Read more - http://msdn.microsoft.com/library/windows/apps/br224742
    143. /// </summary>
    144. /// <param name="args"></param>
    145. protected override void OnFileActivated(FileActivatedEventArgs args)
    146. {
    147. string appArgs = "";
    148. Windows.ApplicationModel.Activation.SplashScreen splashScreen = null;
    149.  
    150. splashScreen = args.SplashScreen;
    151. appArgs += "File=";
    152. bool firstFileAdded = false;
    153. foreach (var file in args.Files)
    154. {
    155. if (firstFileAdded) appArgs += ";";
    156. appArgs += file.Path;
    157. firstFileAdded = true;
    158. }
    159.  
    160. InitializeUnity(appArgs, splashScreen);
    161. }
    162.  
    163. /// <summary>
    164. /// Invoked when the application is launched normally by the end user. Other entry points
    165. /// will be used when the application is launched to open a specific file, to display
    166. /// search results, and so forth.
    167. /// </summary>
    168. /// <param name="args">Details about the launch request and process.</param>
    169. protected override void OnLaunched(LaunchActivatedEventArgs args)
    170. {
    171. InitializeUnity(args.Arguments, args.SplashScreen);
    172. }
    173.  
    174. private void InitializeUnity(string args, Windows.ApplicationModel.Activation.SplashScreen splashScreen)
    175. {
    176. #if UNITY_WP_8_1
    177. ApplicationView.GetForCurrentView().SuppressSystemOverlays = true;
    178. #pragma warning disable 4014
    179. StatusBar.GetForCurrentView().HideAsync();
    180. #pragma warning restore 4014
    181. #endif
    182.  
    183. appCallbacks.SetAppArguments(args);
    184. Frame rootFrame = Window.Current.Content as Frame;
    185.  
    186. // Do not repeat app initialization when the Window already has content,
    187. // just ensure that the window is active
    188. if (rootFrame == null && !appCallbacks.IsInitialized())
    189. {
    190. var mainPage = new MainPage(splashScreen);
    191. Window.Current.Content = mainPage;
    192. Window.Current.Activate();
    193.  
    194. // Setup scripting bridge
    195. _bridge = new WinRTBridge.WinRTBridge();
    196. appCallbacks.SetBridge(_bridge);
    197.  
    198. #if !UNITY_WP_8_1
    199. appCallbacks.SetKeyboardTriggerControl(mainPage);
    200. #endif
    201.  
    202. appCallbacks.SetSwapChainPanel(mainPage.GetSwapChainPanel());
    203. appCallbacks.SetCoreWindowEvents(Window.Current.CoreWindow);
    204. appCallbacks.InitializeD3DXAML();
    205. }
    206.  
    207. Window.Current.Activate();
    208.  
    209. #if UNITY_WP_8_1
    210. SetupLocationService();
    211. #endif
    212. }
    213.  
    214. private void RemoveSplashScreen()
    215. {
    216. // This will fail if you change main window class
    217. // Make sure to adjust accordingly if you do something like this
    218. MainPage page = (MainPage)Window.Current.Content;
    219. page.RemoveSplashScreen();
    220. }
    221.  
    222. #if UNITY_WP_8_1
    223. // This is the default setup to show location consent message box to the user
    224. // You can customize it to your needs, but do not remove it completely if your application
    225. // uses location services, as it is a requirement in Windows Store certification process
    226. private async void SetupLocationService()
    227. {
    228. if (!appCallbacks.IsLocationCapabilitySet())
    229. {
    230. return;
    231. }
    232.  
    233. const string settingName = "LocationContent";
    234. bool userGaveConsent = false;
    235.  
    236. object consent;
    237. var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
    238. var userWasAskedBefore = settings.Values.TryGetValue(settingName, out consent);
    239.  
    240. if (!userWasAskedBefore)
    241. {
    242. var messageDialog = new Windows.UI.Popups.MessageDialog("Can this application use your location?", "Location services");
    243.  
    244. var acceptCommand = new Windows.UI.Popups.UICommand("Yes");
    245. var declineCommand = new Windows.UI.Popups.UICommand("No");
    246.  
    247. messageDialog.Commands.Add(acceptCommand);
    248. messageDialog.Commands.Add(declineCommand);
    249.  
    250. userGaveConsent = (await messageDialog.ShowAsync()) == acceptCommand;
    251. settings.Values.Add(settingName, userGaveConsent);
    252. }
    253. else
    254. {
    255. userGaveConsent = (bool)consent;
    256. }
    257.  
    258. if (userGaveConsent)
    259. { // Must be called from UI thread
    260. appCallbacks.SetupGeolocator();
    261. }
    262. }
    263. #endif
    264. /// <summary>
    265. /// Invoked when Navigation to a certain page fails
    266. /// </summary>
    267. /// <param name="sender">The Frame which failed navigation</param>
    268. /// <param name="e">Details about the navigation failure</param>
    269. void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
    270. {
    271. throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
    272. }
    273.  
    274. /// <summary>
    275. /// Invoked when application execution is being suspended. Application state is saved
    276. /// without knowing whether the application will be terminated or resumed with the contents
    277. /// of memory still intact.
    278. /// </summary>
    279. /// <param name="sender">The source of the suspend request.</param>
    280. /// <param name="e">Details about the suspend request.</param>
    281. private async void OnSuspending(object sender, SuspendingEventArgs e)
    282. {
    283. var deferral = e.SuspendingOperation.GetDeferral();
    284. await SuspensionManager.SaveAsync();
    285. deferral.Complete();
    286. }
    287. }
    288. }

    You will also need the ContinuationManager.cs class and the SuspensionManager.cs class but mainly for WP8.1 Universal. This isnt needed for W8.1 and so you should ensure that you are using #defines to keep them within their own contexts

    If you want, instead of calling on WebAuthenticationBroker, you could call on the facebook app directly but I don't know of all the details. You can read up on that on facebook's website https://developers.facebook.com/docs/facebook-login/login-for-windows-phone. That method isnt recommended incase the user doesn't have it installed.

    Long (rushed) story short, call WebAuthenticationBroker, handle the continuation Event in OnActivated event to catch the WebAuthenticationBrokerContinuationEventArgs object coming through and use the data however you see fit. Be sure to use the following if you want to call any code in the unity side. Note that you can directly access the c# code from App.xaml.cs:-

    Code (CSharp):
    1. AppCallbacks.Instance.InvokeOnAppThread(() =>
    2. {
    3. // back to Unity
    4. //your code here
    5. }, false);
    Also note that this is mainly to get the access token. Once we have that, we can make basic WWW calls directly to facebook and get data back from it. The data will be returned as a JSON format (ps this is such an awesome clean format!) you can use the .NET json library to serialize it into a class. I use http://json2csharp.com/ to convert any example output into a class which I just parse into the json library.
     
    Last edited: Mar 27, 2015
  20. KirillAndrushko

    KirillAndrushko

    Joined:
    Aug 11, 2014
    Posts:
    1
    Hello, i using this plugin. My game good work on android. But when i run it on WP8 i have a problem.
    My app start and i click to FB login button. Then run facebook app and i enter my email and password. My game crashed when i return to it
     
  21. dean0

    dean0

    Joined:
    Mar 7, 2014
    Posts:
    10
    Thank you Nerosam!

    Yes apparently WebAuthenticationBroker.AuthenticateAndContinue can only be called on the UI thread. Else you can look forward to some completely inexplicable exception.
     
  22. Ersin

    Ersin

    Joined:
    Oct 25, 2012
    Posts:
    13
  23. layinka

    layinka

    Joined:
    Jun 26, 2013
    Posts:
    6
    Hi Nerosam.
    Please can you just help with a small guide to show how all this can be put together and used?
    Thanks, i will be very grateful.
     
  24. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Right, I got all this working for Windows Phone now. Took a bit of messing around, but its really not so bad. This is updated to use Graph V2.2.

    I'll include the updated source and compiled DLL for anyone that wants to use it. Just follow the same instructions at the start of the thread, but replace the Facebook DLL in the WP8 folder with the one in Real and the Facebook DLL in the Plugins Folder with the Fake one.

    This only really works for login (as did the original) so if you need posting support, might be better using Ersin's plugin, but if login is alls you need, you should be fine with this. I won't be able to offer too much support with this as its just updating whats already there for the April deadline - but I'll see what I can do.

    Alan
     

    Attached Files:

  25. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    @Nerosam - that looks great! I've been really eager to get my game onto WP8.1 rather than being stuck with 8, but Facebook has been the thing holding it back. I might look into this at some point and try to update this plugin further to support WP8.1 and Windows. :D
     
  26. Carwashh

    Carwashh

    Joined:
    Jul 28, 2012
    Posts:
    760
    Hey @kujo,

    I don't suppose you've had the chance to look at this and add support for WP8.1/ WSA?
     
    Last edited: May 13, 2015
  27. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    @Carwashh I made a start in implementing what Nerosam looked suggested, and got it working on a basic windows store app, but had problems when this was added to Unity. I get some kind of null reference exception within the WebAuthenticationBroker that I haven't managed to trace yet.

    @Nerosam, have you had this working in Unity?
     
  28. thelightofwinter

    thelightofwinter

    Joined:
    Dec 10, 2014
    Posts:
    8
    when using plugin in unity 5.x, I receive compile error:
    ArgumentException: The Assembly mscorlib.Extensions is referenced by FacebookWinPhone8 ('Assets/Plugins/WP8/FacebookWinPhone8.dll'). But the dll is not allowed to be included or could not be found.

    Any idea to fix it? Thanks a lot.
     
  29. Nerosam

    Nerosam

    Joined:
    Jul 23, 2013
    Posts:
    40
    Hi sorry ive been crazy busy with work. Yeah its working in my unity builds for windows store 8.1 builds and windows phone store 8.1. I figured it might be easy to sus it out from my previous post but here is some extra info:-

    The function i created _Run_ConnectWithFacebook() initiates the facebook authentication call:-

    Code (CSharp):
    1. public static IEnumerator _Run_ConnectWithFacebook()
    2. {
    3. yield return new WaitForEndOfFrame();
    4.  
    5. #if UNITY_EDITOR
    6. UnityDebugAuthentication();
    7. #endif
    8. #if NETFX_CORE
    9. WindowsStoreAuthenticate();
    10. #endif
    11. #if UNITY_IOS || UNITY_ANDROID
    12.         iOSAndroidAuthenticate();
    13. #endif
    14.  
    15. }
    So depending on what platform my project is set to, it will call the relevant function. My iOSAndroidAuthenticate() function calls the official facebook api:-

    Code (CSharp):
    1.     public static void iOSAndroidAuthenticate()
    2.     {
    3.         string auth = null;
    4.         FB.Init (SetInit, OnHideUnity, auth);
    5.     }
    6.  
    7.     public static void SetInit()
    8.     {
    9.         FB.Login (permissions, _Run_ConnectWithFacebookiOS_Response);
    10.     }
    11.  

    The above code actually works in the editor as it should if the platform is set to iOS or Android which can be good for testing.

    UnityDebugAuthentication() Doesnt do any thing special. In my case I:-

    • Set the _FbToken to the fbtoken to a manually obtained token from the fb api
    • Call the function that I want it to call such as show a message box
     
  30. Nerosam

    Nerosam

    Joined:
    Jul 23, 2013
    Posts:
    40
    I personally try to avoid any WP8 plugins and ensure I use Metro/WSA plugins instead. Those are universal project compatible from my experience
     
  31. Carwashh

    Carwashh

    Joined:
    Jul 28, 2012
    Posts:
    760
  32. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Finally - Been waiting for MS to releasing something semi official for this. Going to look at implementing it. I wouldn't imagine it would be too difficult to get it working.
     
  33. psykojello2

    psykojello2

    Joined:
    Jul 19, 2013
    Posts:
    37
    @kujo if you get it working in Unity, please do share!

    And just in case I get to it first - can folks give me suggestions on how I would call this from Unity? Should I make a plugin? Or should I use the library directly in Unity?
     
  34. BrokenAngel

    BrokenAngel

    Joined:
    Mar 24, 2013
    Posts:
    92
    I had been implement it , but when run the project and call the method FBSession.ActiveSession , I got this error :

    Requested Windows runtime type "Facebook.FBSession" is not registered.

    Does anyone got this bug ?
     
  35. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    @psykojello2 Not something I've had chance to look at yet, but I'd imagine you'd need to create a plugin wrapper for it at the very least.
     
  36. pokeking

    pokeking

    Joined:
    May 13, 2015
    Posts:
    42
    I seted up the FB SDK, and i tested the example. It shared on FB, but it share directly, not show a panel with some sentences like in android o_O. It didn't need allowance to share on FB or not, and player won't like, so how can i make somethings like press share FB button, then it show a panel to write some words, and decide to post on FB or not ;)
    sorry for my English, still training:p
     
  37. sonxoans2

    sonxoans2

    Joined:
    Apr 17, 2015
    Posts:
    25
    Hi,
    how to get list my friends???
     
  38. BonyYousuf

    BonyYousuf

    Joined:
    Aug 22, 2013
    Posts:
    110
    Is there a way to use this with windows 10 universal app?
     
  39. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Ok - I've managed to get login working with the new SDK from Microsoft on the post above from @Carwashh. It works great and I can FINALLY release a universal 8.1 app. I don't know if this will just work out of the box for Win10, and I don't have any devices to test this out, so I'll have to wait and see I guess!

    I've also updated it so that it works with the new Facebook 7 SDK for Unity 5.2. I'm still in testing and stuff with it at the moment, so I'm not really in a position to release instructions on how to use this yet, but I might see if I can put something together when I have some time


    @BrokenAngel - Have you managed to fix your issue?
     
    Carwashh likes this.
  40. BonyYousuf

    BonyYousuf

    Joined:
    Aug 22, 2013
    Posts:
    110
    @kujo could you please share you how you have managed to do this? I am new with windows development. My game runs with facebook on web player and android just fine. :)
     
  41. Carwashh

    Carwashh

    Joined:
    Jul 28, 2012
    Posts:
    760
    This pleases me greatly! Looking forward to seeing your solution, will be extremely grateful if you manage to get time to post it!
     
  42. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    I can give a rough outline of how I've done it and possibly post a more detailed guide later with full code. I don't want to post the code yet because its still largely untested, I only finished the Windows version last night and got a successful login.

    I've got a solution file with 4 class libraries in it, two basic fake for WP8.1 and Win8.1 in .NET 3.5 and two actual class libraries for both platforms.

    You need to download the WinSDK from the link (I created mine as a submodule in git, just for ease later) and add the two project files into the solution. Reference the FacebookWP8.1 in the WP class library and the FacebookWin8.1 in the Win class library.

    If you look in the samples for the WinSDK, I basically followed the Login example they gave, with a few modifications.

    Here's the login method:

    Code (csharp):
    1.  
    2. public static void Login(IEnumerable<string> permissions)
    3. {
    4.  
    5. _permissions = permissions;
    6.  
    7. LoginAsyc();
    8. }
    9.  
    10. private static async void LoginAsyc()
    11. {
    12. FBSession sess = FBSession.ActiveSession;
    13.  
    14. FBResult result = null;
    15. CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    16. {
    17. result = await sess.LoginAsync(BuildPermissions());
    18.  
    19.  
    20. if (WasAppPermissionRemovedByUser(result))
    21. {
    22. await sess.LogoutAsync();
    23. }
    24. else if (ShouldRerequest(result))
    25. {
    26. await TryRerequest(false);
    27. }
    28. else if (result.Succeeded)
    29. {
    30. IsLoggedIn = true;
    31. }
    32. });
    33. }
    As sess.LoginAsync needs to be done on the UI thread, you need to use the dispatcher otherwise it'll fail. The rest of that code is in the Login example.

    That's pretty much it for how to make the DLLs, I'll come back to how to return the data to Unity in a moment. You need to put the exact same code into your Win81 class library as well. Its a bit annoying that I couldn't make this a universal library, but the WinSDK hasn't been implemented as portable DLL's so its not possible.

    Another annoying part is that these DLL's also can't be compiled for any CPU, so you need to build it twice, once in ARM and the other in x86/Win32.

    To bring those into Unity, they need to be in the following folders. The ones outside the WSA folder are your Fake DLLs, the others are your specific CPU builds.

    DLLS.PNG

    For each of them, you need to set them similar to the following:
    settings.PNG

    Notice to SDK setting as well. The Win81 version needs to be be SDK81.

    So, the rest of the implementation comes in Unity. Download the latest SDK from Facebook and have that installed. You need to duplicate the 3 classes that Facebook has for iOS or Android and change them to your WP81 and Win81 versions. They are in the Facebook->Scripts->Mobile.

    So - the getting back into Unity that I mentioned. Because the login needs to happen on the UI thread, you need to either dispatch back into Unity, but that requires more code being one in the exported project. So instead of that, I followed what zeezeezee did and basically sit and wait. The check is done in the IsLoggedIn static bool inside of the DLL that gets set when a success is returned.

    So, I did it as follows:

    Win81Facebook.cs

    Code (csharp):
    1.  
    2. public override void LogInWithReadPermissions(
    3. IEnumerable<string> permissions,
    4. FacebookDelegate<ILoginResult> callback)
    5. {
    6. int callbackID = this.AddCallback(callback);
    7. FacebookWin81.Login(permissions);
    8.  
    9. FBGameObject.WaitForLogin(callbackID);
    10. }
    11.  
    12. public override void LogInWithPublishPermissions(
    13. IEnumerable<string> permissions,
    14. FacebookDelegate<ILoginResult> callback)
    15. {
    16. int callbackID = this.AddCallback(callback);
    17. FacebookWin81.Login(permissions);
    18. FBGameObject.WaitForLogin(callbackID);
    19. }
    the FBGameObject is the one you have created. I set up a reference in it, so I can do a coroutine as follows:

    Win81FacebookGameObject:

    Code (csharp):
    1.  
    2. public void WaitForLogin(int callbackId)
    3. {
    4. StartCoroutine(CheckLoginLoop(callbackId));
    5. }
    6.  
    7. private IEnumerator CheckLoginLoop(int callbackId)
    8. {
    9. while (true)
    10. {
    11. yield return new WaitForSeconds(1);
    12. if (FacebookWin81.IsLoggedIn)
    13. {
    14. string jsonResult = FacebookWin81.GetLoggedOnDetails(callbackId);
    15. OnLoginComplete(jsonResult);
    16. break;
    17. }
    18. }
    19. }
    20.  
    The GetLoggedOnDetails is in the DLL again:

    Code (csharp):
    1.  
    2. public static string GetLoggedOnDetails(int callbackid=-1)
    3. {
    4. FBAccessTokenData data = FBSession.ActiveSession.AccessTokenData;
    5.  
    6. StringBuilder builder = new StringBuilder();
    7.  
    8. builder.Append("{");
    9.  
    10. builder.AppendFormat("\"{0}\":\"{1}\",", "access_token", data.AccessToken);
    11. builder.AppendFormat("\"{0}\":\"{1}\",", "user_id", FBSession.ActiveSession.User.Id);
    12. builder.AppendFormat("\"{0}\":\"{1}\",", "expiration_timestamp", data.ExpirationDate);
    13. builder.AppendFormat("\"{0}\":\"{1}\",", "permissions", string.Join(",", data.GrantedPermissions.Values));
    14. builder.AppendFormat("\"{0}\":\"{1}\",", "declined_permissions", string.Join(",", data.DeclinedPermissions.Values));
    15. if(callbackid>-1)
    16. builder.AppendFormat("\"{0}\":\"{1}\",", "callback_id", callbackid.ToString());
    17.  
    18. builder.AppendFormat("\"{0}\":\"{1}\"", "platform", "wp81");
    19. builder.Append("}");
    20.  
    21. return builder.ToString();
    22. }
    23.  
    I built the JSON manually because of conflicts I had with Newtonsoft.JSON in my own project, but its fairly simple, so I just made it manually.

    And the rest is essentially handled by the main Facebook SDK.

    Quite a long post, but I hope that gets you started at least.

    As I say, when I get more testing and some more of the Facebook features added in. At the moment, you need to log in every time, it doesn't remember that you've done it before. SO I've still got quite a bit of work to do on it yet. But once thats working and tested, I'll post some more.
     
    Last edited: Sep 29, 2015
    Carwashh likes this.
  43. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Oh - something I forgot - When you produce your build from Unity, you need to add in both FacebookSDK projects again into your exported VS solution, otherwise it won't compile
     
  44. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    Got an auto login working today, but it needed some additional methods adding into the WinSDK... going to see if I can speak with the devs and get it added in properly, else I'll have to release the code with my own custom version, which I'd rather avoid.
     
  45. Carwashh

    Carwashh

    Joined:
    Jul 28, 2012
    Posts:
    760
    @kujo - Haven't had chance to take a look and follow your instructions yet, hopefully this weekend.

    Why can't Windows be as easy/ simple as other platforms? =/
     
  46. kujo

    kujo

    Joined:
    Aug 19, 2013
    Posts:
    106
    I know - its so annoying. I don't know why its just not part of the full Facebook SDK by now. its been in beta for years now on their site... one day... maybe with Windows Phone 10 if that ever gets released? Fingers crossed
     
    Carwashh likes this.
  47. Carwashh

    Carwashh

    Joined:
    Jul 28, 2012
    Posts:
    760
    @kujo - I'm afraid I'm a bit of a beginner when it comes to anything outside of Unity, so I'm going to have some questions!

    Starting with...
    When I add the references, they have a yellow triangle over them (as seen in the screenshot). Assuming I've setup everything prior to that correctly, how do I fix this issue?


    Also,

    - Do the FacebookWin81 and FacebookWP81 class libraries need to be .NET 3.5? If I change them to .NET 3.5 the references Microsoft.CSharp and System.Net.Http also get yellow triangles.

    - I am unable to select ARM or x86/x64 in platform target for my two class libraries. For the imported FBWinSDK.WindowsPhone I can select Win32 or ARM and FBWinSDK.Windows I can select Win32, x64 and ARM.

    Have I setup the project correctly? I went File -> New -> Project -> Templates/ Visual C# -> Class Library.

    If I create a class library from Templates/ Visual C#/ Windows then use Windows 8.1 or Windows Phone 8.1 I don't get yellow triangles and can select ARM/ x86/ x64 for build platform ... so I'm assuming that is what I need to do there.

    But are these two the ones to change to .NET 3.5?

    - When I C&P your login code into my class, I get loads of red lines... I think I need 'using Facebook' but it's not showing up to add.
     
    Last edited: Oct 3, 2015
  48. optimus-primeixii

    optimus-primeixii

    Joined:
    Sep 11, 2014
    Posts:
    1
    #kujo can you give me an example about login facebook window phone in unity game. Thanks.
     
  49. Zynpo

    Zynpo

    Joined:
    May 29, 2014
    Posts:
    16
    I cannot find this SDK anymore. Links are dead. Does anyone know where I can get Facebook access for Windows/Windows Phone?
     
  50. Carwashh

    Carwashh

    Joined:
    Jul 28, 2012
    Posts:
    760