Unity 接入Firebase第三方登录(Apple、Facebook、Google)

一、 Firebase接入

1. SDK下载

官方网址: firebase官网
在这里插入图片描述

图片中1为demo地址,2为SDK包

2. 接入准备工作

在这里插入图片描述
此为firebase的unity包,根据自身需求接入对应的,对应关系如下
在这里插入图片描述

3. firebase初始化
public class FireBase : MonoBehaviour
{
    Firebase.FirebaseApp app;
    Firebase.Auth.FirebaseAuth auth;

    private bool firebaseInitialized;

    // Start is called before the first frame update
    IEnumerator Start()
    {
        InitializeFirebaseAndStart();
        while (!firebaseInitialized)
        {
            yield return null;
        }
        auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
    }

	// 初始化firebase
    void InitializeFirebaseAndStart()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
        {
            var dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                firebaseInitialized = true;
                Debug.Log("firebase Initialized");
            }
            else
            {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
                // Application.Quit();
            }
        });
    }
}
4. 登录接入文档

在此介绍三种第三方登录,根据官方文档提示,Apple、Google、Facebook 都需要再接入sdk获取token,然后使用firebase的验证获取firebase的token。

二、 Google 登录接入

注意:本文介绍的是google登录,而非google-play-game登录

1. 插件介绍

在此推荐一个插件 google-signin,地址为: google-signin

打包测试,Android测试成功,但是iOS会报如下错误
在这里插入图片描述

官方推荐是使用老版本,地址如下:https://github.com/googlesamples/google-signin-unity/issues/102,可供参考

因为我使用的sdk都是新版本,在此选择升级,升级后的地址如下
地址:使用google 6.0.0 以上版本地址

2. 初始化
 GoogleSignIn.Configuration = new GoogleSignInConfiguration
 {
     RequestIdToken = true,
     // Copy this value from the google-service.json file.
     // oauth_client with type == 3
     //填入在配置谷歌项目SHA1值时给你的Client ID
     WebClientId = " "
 };
3. 登录请求
 public void GoogleLogin()
 {
     Debug.Log("Enter Google Script Login Method");
     Task<GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();

     signIn.ContinueWithOnMainThread(task =>
     {
         if (task.IsCanceled)
         {
             Debug.Log("task.IsCanceled");
         }
         else if (task.IsFaulted)
         {
             Debug.Log("task.IsFaulted = " + task.Exception.Message);
         }
         else
         {
             var idToken = ((Task<GoogleSignInUser>)task).Result.IdToken;
             Debug.Log("idToken = " + idToken);
             Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(idToken, null);
             CredentialSigin(credential);
         }
     });

 }
4. firebase 登录验证

三种登录方式都用此方法验证

public void CredentialSigin(Credential credential)
{
   auth.SignInWithCredentialAsync(credential).ContinueWith(async authTask =>
   {
       if (authTask.IsCanceled)
       {
           Debug.Log("authTask.IsCanceled");
       // if (LoginResultManager.Instance != null)
       //     LoginResultManager.Instance.OpenLoginResult(false);
       // signInCompleted.SetCanceled();
       }
       else if (authTask.IsFaulted)
       {
           Debug.Log("authTask.IsFaulted");
       // if (LoginResultManager.Instance != null)
       //     LoginResultManager.Instance.OpenLoginResult(false);
       // signInCompleted.SetException(authTask.Exception);
       }
       else
       {
       // signInCompleted.SetResult(((Task<FirebaseUser>)authTask).Result);
           Firebase.Auth.FirebaseUser newUser = authTask.Result;
           Debug.Log(String.Format("User Login Successful : {0} ({1})", newUser.DisplayName, newUser.UserId));

           var token = await newUser.TokenAsync(true);
           Debug.Log("Firebase Token = " + token);

           // 访问服务器

           action_fbToken?.Invoke(token);

       }
   });
}

三、FaceBook 登录接入

1. 插件介绍

在这里插入图片描述
地址:facebook

2. 接入设置

导入相关unity包后,根据下图所示填入信息
在这里插入图片描述

3. 初始化
public void InitializeFacebook()
{
    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;
    }
}
4. 登录请求
public void FacebookLogin()
{
    if (FB.IsInitialized)
    {
        var perms = new List<string>() { "public_profile", "email" };
        FB.LogInWithReadPermissions(perms, AuthCallback);
    }
    else
    {
        Debug.Log("Not Init");
    }

}

private void AuthCallback(ILoginResult result)
{
    if (result.Error != null)
    {
        Debug.Log("Error: " + result.Error);
    }
    else
    {
        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: " + aToken.UserId);
            // Print current access token's granted permissions
            foreach (string perm in aToken.Permissions)
            {
                Debug.Log("perm: " + perm);
            }
            var idToken = aToken.TokenString;

            Credential credential = Firebase.Auth.FacebookAuthProvider.GetCredential(idToken);
            CredentialSigin(credential);
        }
        else
        {
            Debug.Log("User cancelled login");
        }
    }
}
5. firebase登录验证

同Google登录接入的第四步

四、 Apple登录接入

1. 插件介绍

推荐使用此插件,此插件也是官方文档中提到的插件
在这里插入图片描述
GitHub地址: Sign in with Apple Unity Plugin

2. 接入设置

根据文档添加后处理文件
在这里插入图片描述

3. 初始化
private IAppleAuthManager _appleAuthManager;

void InitializeApple()
{
    if (AppleAuthManager.IsCurrentPlatformSupported)
    {
        // Creates a default JSON deserializer, to transform JSON Native responses to C# instances
        var deserializer = new PayloadDeserializer();
        // Creates an Apple Authentication manager with the deserializer
        this._appleAuthManager = new AppleAuthManager(deserializer);
    }
}

void Update()
{
    // Updates the AppleAuthManager instance to execute
    // pending callbacks inside Unity's execution loop
    if (this._appleAuthManager != null)
    {
        this._appleAuthManager.Update();
    }
}
4. 登录请求
public void AppleLogin()
{
    var rawNonce = GenerateRandomString(32);
    var nonce = GenerateSHA256NonceFromRawNonce(rawNonce);
    var loginArgs = new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName, nonce);

    this._appleAuthManager.LoginWithAppleId(
        loginArgs,
        credential =>
        {
        // Obtained credential, cast it to IAppleIDCredential
            var appleIdCredential = credential as IAppleIDCredential;
            if (appleIdCredential != null)
            {
            // Apple User ID
            // You should save the user ID somewhere in the device
                var userId = appleIdCredential.User;
                Debug.Log("app userId = " + userId);
            // PlayerPrefs.SetString(AppleUserIdKey, userId);

            // Email (Received ONLY in the first login)
                var email = appleIdCredential.Email;
                Debug.Log("app email = " + email);

            // Full name (Received ONLY in the first login)
                var fullName = appleIdCredential.FullName;
                Debug.Log("app fullName = " + fullName);

            // Identity token
                var identityToken = Encoding.UTF8.GetString(
                    appleIdCredential.IdentityToken,
                    0,
                    appleIdCredential.IdentityToken.Length);

                Debug.Log("app identityToken = " + identityToken);

            // Authorization code
                var authorizationCode = Encoding.UTF8.GetString(
                    appleIdCredential.AuthorizationCode,
                    0,
                    appleIdCredential.AuthorizationCode.Length);

                Debug.Log("app authorizationCode = " + authorizationCode);

            // And now you have all the information to create/login a user in your system

                Credential FirebaseCredential = Firebase.Auth.OAuthProvider.GetCredential("apple.com", identityToken, rawNonce, authorizationCode);
                CredentialSigin(FirebaseCredential);
            }

        },
        error =>
        {
            var authorizationErrorCode = error.GetAuthorizationErrorCode();
            Debug.LogWarning("Sign in with Apple failed " + authorizationErrorCode.ToString() + " " + error.ToString());

        });
}
5. firebase登录验证

同Google登录接入的第四步

五、结语

希望大家都可以成功接入,有任何问题欢迎评论区提问。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>