C#/수업내용

2020.08.20. 수업내용 - Firebase 연동 (1)

dev_sr 2020. 8. 20. 18:08

GPGS 연동했던 프로젝트 그대로 씀

적으면서 한게 아니라서 기억나는 대로 써서 두서 없음

 

파이어베이스 unity sdk 다운받고 

dotnet4 에서 

 

 

이거 두개 임포트함

 

Unity에서 Google Play 게임 서비스를 사용하여 인증  |  Firebase

Google Play 게임 서비스를 사용하여 Firebase 및 Unity로 개발된 Android 게임에 플레이어가 로그인하도록 할 수 있습니다. Firebase를 통한 Google Play 게임 서비스 로그인을 사용하려면 우선 Google Play 게임��

firebase.google.com

이거 보고 하면 되는데 대부분 과정은 이미 GPGS연결하면서 선행함

하라는 대로 하고 플레이콘솔에서 앱 연결하면 파이어베이스에 프로젝트가 생기는데

 

플레이 콘솔에서 서비스 -> 파이어 베이스 연결하기? 사용하기? 눌러주면 파이어베이스에

기존 APP 프로젝트가 또 생기므로 (API에 Web Application도 생김) 

그냥 이렇게 파이어베이스 프로젝트 생성하는 게 좋을 듯

 

 

 

 

 

연결된 앱에서 상단에 다른앱 연결을 눌러서 웹을 추가해주는데

url 적는 곳에 파이어베이스의 authentication -> sign - in method 아래에 승인된 도메인 부분의 firebaseapp.com으로 끝나는 것을 넣어줌

 

 

 

저장하고 넘어가려고 하면 오류 날거임

위에 노란 박스가 생기는데 선택 눌러서 연결할 프로젝트? 선택해주면 넘어감

 

 

연결된 앱에 이렇게 나와야함

 

 

 

서비스를 눌렀을 땐 이렇게 안드로이드, 웹 둘다 불이 켜져야함

 

 

 

web application이 api에 생성됐으면 그거 ID랑 클라이언트 보안 비밀을 play 게임에 넣어줌

 

 

 

 

 

구글 플레이 콘솔 앱서명 부분의 sha-1로 끝나는 거 두개다 순서대로 sha 인증서 지문에 넣어줌

저기서 패키지 이름이랑 구글 build setting의 패키지 이름이랑 같아야함

안그러면 bundle id 맞추라고 유니티 안에서 팝업창 계속 뜨고 난리남

 

 

 

json 파일 다운받고 unity Asset 폴더 안에 넣어줌 (파이어베이스 설정이 뭐 바뀔때마다 다운받아서 넣어줘야함)

 

 

 

 

파이어베이스->통합-> googlePlay 에 연결된 앱이 해당되는게 나오는 지 확인 해야함

 

 

 ★★구글 플레이 콘솔에서 꼭 출시를 눌러줘야함
(릴리즈x, 변경사항을 출시한다는 의미)

 

 

GPGSManager에서 Init 부분만 가져다 씀

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using GooglePlayGames.OurUtils;

public class GPGSManager
{
    private static GPGSManager instance;

    private GPGSManager() { }

    public static GPGSManager GetInstance()
    {
        if(GPGSManager.instance==null)
        {
            GPGSManager.instance = new GPGSManager();
        }
        return GPGSManager.instance;

    }

    public void Init()
    {
        PlayGamesClientConfiguration conf = new PlayGamesClientConfiguration.Builder()
            .RequestServerAuthCode(false /* Don't force refresh */)
            .Build();

        PlayGamesPlatform.InitializeInstance(conf);
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
    }

    public void SignIn(System.Action<SignInStatus> onComplete)
    {
        //CanPromptOnce
        // If automatic sign-in is not successful,
        //they will be prompted to sign in manually with an interactive sign-in screen

        //CanPromptAlways -> 항상 보여줌

        PlayGamesPlatform.Instance.Authenticate(SignInInteractivity.CanPromptAlways, (result) =>
         {
             onComplete(result);
         });
    }

    public void SignOut()
    {
        PlayGamesPlatform.Instance.SignOut();
    }

    public string GetUserName()
    {
        return Social.localUser.userName;
    }

    public void GetUserImage(System.Action<Texture2D> onComplete)
    {
        PlayGamesHelperObject.RunCoroutine(this.LoadImage(() =>
            {
                var texture = Social.localUser.image;

                onComplete(texture);
            }));
    }

    private IEnumerator LoadImage(System.Action onComplete)
    {
        yield return new WaitUntil(() => Social.localUser.image != null);

        onComplete();
    }

}

 

 

이게 메인이고 여기서 로그인, 로그 아웃함

text에서 authCode 찍어봄

 

파이어베이스에 연결이 제대로 안되면

로그인도 안되고 (구글 로그인 연결 나오고 좀 로딩 돌다가 사라짐..)

PlayGamesPlatform.Instance.GetServerAuthCode(); -> 이 부분이 계속 null 이 나와서 버그남

 

using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public class FirebaseTest : MonoBehaviour
{
    public Button signInBtn;
    public Button signOutBtin;

    public Text text;


    private Firebase.Auth.FirebaseAuth auth;
    // Start is called before the first frame update
    void Start()
    {
        GPGSManager.GetInstance().Init();

        this.signInBtn.onClick.AddListener(() =>
        {
            this.SignIn();
        });

        this.signOutBtin.onClick.AddListener(() =>
        {
            this.SingOut();
        });


    }

    public void SignIn()
    {

        Social.localUser.Authenticate((bool success) => {
            // handle success or failure
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            Debug.LogFormat("=============================>authCode:{0}",authCode);
            this.text.text = authCode;
            this.auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
            Firebase.Auth.Credential credential =
                Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode);
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
                if (task.IsCanceled)
                {
                    Debug.LogError("SignInWithCredentialAsync was canceled.");
                    return;
                }
                if (task.IsFaulted)
                {
                    Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                    return;
                }

                Firebase.Auth.FirebaseUser newUser = task.Result;
                Debug.LogFormat("User signed in successfully: {0} ({1})",
                    newUser.DisplayName, newUser.UserId);

               Firebase.Auth.FirebaseUser user = auth.CurrentUser;
                if (user != null)
                {
                    string playerName = user.DisplayName;

                    // The user's Id, unique to the Firebase project.
                    // Do NOT use this value to authenticate with your backend server, if you
                    // have one; use User.TokenAsync() instead.
                    string uid = user.UserId;
                }

            });
        });
    }

    public void SingOut()
    {
        if (this.auth != null)
        {
            this.auth.SignOut();
        }
    }
}

결과
로그인이 된 뒤 authcode를 전달받은 것을 확인할 수 있었음