Unity access Firebase third-party login (Apple, Facebook, Google)

1. Firebase access

1. SDK download

Official website: firebase official website
insert image description here

In the picture, 1 is the demo address, and 2 is the SDK package

2. Access preparations

insert image description here
This is the unity package of firebase, access the corresponding one according to your own needs, the corresponding relationship is as follows
insert image description here

3. firebase initialization
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. Log in to access documents

Here are three third-party logins. According to the official documentation, Apple, Google, and Facebook all need to access the SDK to obtain tokens, and then use firebase verification to obtain firebase tokens.

2. Google login access

Note: This article describes google login, not google-play-game login

1. Plug-in introduction

A plug-in google-signin is recommended here, the address is: google-signin

Packaging test, Android test is successful, but iOS will report the following error
insert image description here

The official recommendation is to use the old version, the address is as follows: https://github.com/googlesamples/google-signin-unity/issues/102, for reference

Because the sdk I use is a new version, I choose to upgrade here. The address after the upgrade is as follows
Address: use google 6.0.0 or above address

2. Initialization
 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. Login request
 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 login authentication

All three login methods use this method to verify

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);

       }
   });
}

3. Facebook login access

1. Plug-in introduction

insert image description here
Address: facebook

2. Access Settings

After importing the relevant unity package, fill in the information as shown in the figure below
insert image description here

3. Initialization
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. Login request
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 login authentication

The fourth step of logging in with Google

4. Apple login access

1. Plug-in introduction

It is recommended to use this plugin, which is also the plugin GitHub address mentioned in the official documentation
insert image description here
: Sign in with Apple Unity Plugin

2. Access Settings

Added post-processing files according to the docs
insert image description here

3. Initialization
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. Login request
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 login authentication

The fourth step of logging in with Google

V. Conclusion

I hope everyone can successfully access, if you have any questions, please ask in the comment area.

Guess you like

Origin blog.csdn.net/weixin_56130753/article/details/128290955