유니티 플레이팹 구글 로그인 Sign In with Google 간단 구현
구글 로그인 SDK 설치
GitHub - playgameservices/play-games-plugin-for-unity: Google Play Games plugin for Unity
Google Play Games plugin for Unity. Contribute to playgameservices/play-games-plugin-for-unity development by creating an account on GitHub.
github.com
구글 로그인 구현
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using PlayFab;
using PlayFab.ClientModels;
using System;
using System.Collections;
using UnityEngine;
public class PlayfabManager : MonoBehaviour
{
private string playfabId = "";
private string entityId = "";
private string entityType = "";
// UI 메시지 표시를 위한 이벤트 추가
public event Action<string> OnMessageReceived;
private void Awake()
{
#if UNITY_ANDROID
GoogleActivate();
#endif
}
// 구글 플레이 게임 서비스 초기화
private void GoogleActivate()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("profile")
.RequestServerAuthCode(false)
.Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
Debug.Log("구글 플레이 게임 서비스 초기화 완료");
}
// 구글 로그인 버튼 클릭 이벤트
public void OnClickGoogleLogin()
{
#if UNITY_ANDROID
LoginGoogleAuthenticate();
#else
SetEditorOnlyMessage("안드로이드 플랫폼에서만 사용 가능합니다");
#endif
}
// 에디터 전용 메시지 설정 (없던 함수 추가)
private void SetEditorOnlyMessage(string message)
{
Debug.Log(message);
OnMessageReceived?.Invoke(message);
}
// 구글 인증 및 PlayFab 로그인
private void LoginGoogleAuthenticate()
{
Debug.Log("구글 로그인 시도중...");
// 이미 인증된 경우 처리
if (Social.localUser.authenticated)
{
Debug.Log("이미 구글 로그인 되어있는 상태입니다.");
OnMessageReceived?.Invoke("이미 구글 로그인 되어있습니다");
// 이미 로그인되어 있다면 PlayFab에도 연결
ConnectToPlayFab();
return;
}
// 구글 인증 시도
Social.localUser.Authenticate((bool success) =>
{
if (!success)
{
Debug.Log("구글 사용자 인증 실패!");
OnMessageReceived?.Invoke("구글 로그인 실패");
return;
}
ConnectToPlayFab();
});
}
// PlayFab 연결 함수 분리 (가독성 향상)
private void ConnectToPlayFab()
{
var serverAuthCode = PlayGamesPlatform.Instance.GetServerAuthCode();
if (string.IsNullOrEmpty(serverAuthCode))
{
Debug.LogError("서버 인증 코드를 가져올 수 없습니다");
OnMessageReceived?.Invoke("인증 코드 오류 발생");
return;
}
PlayFabClientAPI.LoginWithGoogleAccount(new LoginWithGoogleAccountRequest()
{
TitleId = PlayFabSettings.TitleId,
ServerAuthCode = serverAuthCode,
CreateAccount = true,
InfoRequestParameters = new GetPlayerCombinedInfoRequestParams
{
GetPlayerProfile = true
}
},
result =>
{
Debug.Log("플레이팹 구글 로그인 성공!");
OnLoginSuccess(result);
OnMessageReceived?.Invoke("로그인 성공");
},
error =>
{
Debug.LogError("플레이팹 구글 로그인 실패: " + error.ErrorMessage);
OnMessageReceived?.Invoke("플레이팹 연결 실패");
});
}
// 구글 로그아웃
public void OnClickGoogleLogout()
{
((PlayGamesPlatform)Social.Active).SignOut();
// PlayFab에서도 로그아웃
PlayFabClientAPI.ForgetAllCredentials();
// 변수 초기화
playfabId = "";
entityId = "";
entityType = "";
Debug.Log("구글 및 PlayFab에서 로그아웃 완료");
OnMessageReceived?.Invoke("로그아웃 완료");
}
// 로그인 성공 처리
public void OnLoginSuccess(LoginResult result)
{
Debug.Log("Playfab 로그인 성공");
// 플레이어 정보 저장
playfabId = result.PlayFabId;
entityId = result.EntityToken.Entity.Id;
entityType = result.EntityToken.Entity.Type;
// 여기에 로그인 성공 후 처리를 추가할 수 있습니다
Debug.Log($"PlayFab ID: {playfabId}");
}
// 현재 로그인 상태 확인
public bool IsLoggedIn()
{
return Social.localUser.authenticated && !string.IsNullOrEmpty(playfabId);
}
}
게스트 로그인 상태에서 구글 로그인으로 전환하기
public void OnClickGoogleLink()
{
#if UNITY_ANDROID
// 이미 구글에 로그인되어 있는지 확인
if (Social.localUser.authenticated)
{
Debug.Log("이미 구글에 로그인되어 있습니다. 계정 연결을 진행합니다.");
LinkGoogleToPlayFab();
}
else
{
Debug.Log("구글 로그인 시도 중...");
// 구글 로그인 시도
Social.localUser.Authenticate((bool success) =>
{
if (success)
{
Debug.Log("구글 로그인 성공. PlayFab 계정 연결 진행 중...");
LinkGoogleToPlayFab();
}
else
{
Debug.Log("구글 로그인 실패. 계정 연결을 진행할 수 없습니다.");
OnMessageReceived?.Invoke("구글 로그인 실패");
}
});
}
#else
Debug.Log("구글 계정 연결은 안드로이드 플랫폼에서만 지원됩니다.");
OnMessageReceived?.Invoke("안드로이드 플랫폼에서만 지원됩니다");
#endif
}
// 구글 계정과 PlayFab 계정 연결 함수
private void LinkGoogleToPlayFab()
{
try
{
var serverAuthCode = PlayGamesPlatform.Instance.GetServerAuthCode();
if (string.IsNullOrEmpty(serverAuthCode))
{
Debug.LogError("서버 인증 코드를 가져올 수 없습니다.");
OnMessageReceived?.Invoke("인증 코드 오류 발생");
return;
}
LinkGoogleAccountRequest request = new LinkGoogleAccountRequest()
{
ForceLink = true,
ServerAuthCode = serverAuthCode
};
PlayFabClientAPI.LinkGoogleAccount(request,
result =>
{
Debug.Log("구글 계정 연결 성공!");
OnMessageReceived?.Invoke("구글 계정 연결 성공");
// 성공 후 추가 작업이 필요하면 여기에 구현
},
error =>
{
// 오류 코드 확인하여 세부 정보 제공
string errorDetails = error.GenerateErrorReport();
Debug.LogError("구글 계정 연결 실패: " + errorDetails);
// 이미 연결된 계정인 경우
if (error.Error == PlayFabErrorCode.AccountAlreadyLinked)
{
OnMessageReceived?.Invoke("이미 다른 계정에 연결된 구글 계정입니다");
}
// 중복 계정인 경우
else if (error.Error == PlayFabErrorCode.LinkedAccountAlreadyClaimed)
{
OnMessageReceived?.Invoke("이미 연결된 구글 계정입니다");
}
else
{
OnMessageReceived?.Invoke("계정 연결 실패: " + error.ErrorMessage);
}
});
}
catch (Exception ex)
{
Debug.LogError("구글 계정 연결 중 예외 발생: " + ex.Message);
OnMessageReceived?.Invoke("계정 연결 중 오류 발생");
}
}
플레이팹 사이트 / 추가 콘텐츠 / Google 설정
Google 앱 패키지 Id : com.xxx.xxxx
Google 앱 라이선스 키 : 구글 콘솔 / 수익 창출 설정 / 라이선스 키
플레이팹 Api 참고
Unity에서 Google Play 게임 로그인으로 PlayFab 인증 - PlayFab
Unity에서 Google Play 게임 로그인을 사용한 PlayFab 인증의 예제를 안내합니다.
docs.microsoft.com
참고할만한 글
플레이팹 Playfab 게스트 로그인 Guest Login 간단 사용법
using PlayFab; using PlayFab.ClientModels; using PlayFab.Json; using PlayFab.ProfilesModels; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Entity..
parksh3641.tistory.com
유니티 플레이팹 애플 로그인 Playfab Sign ln with Apple Login 간단 구현
애플 SDK https://github.com/lupidan/apple-signin-unity/releases/tag/v1.4.2 Release Sign in with Apple Unity Plugin v1.4.2 · lupidan/apple-signin-unity Changed Handles empty NSPersonNameComponents sent by Apple when not requesting a name, to be nil nativ
parksh3641.tistory.com