Skip to main content

Sign in with Google

OAuth 2.0 based Google login web authentication method. Compatible with both iOS and Android.

How It Works

Android:

  1. Select Google account in external browser (or Chrome Custom Tabs)
  2. Receive id_token via Deep Link
  3. Call account registration (SocialSignIn) or member conversion (SocialChange) API with token

iOS:

  1. Display in-app authentication session via ASWebAuthenticationSession
  2. Receive id_token via OnGoogleAuthCallback method
  3. Call account registration (SocialSignIn) or member conversion (SocialChange) API with token

Unity Implementation

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class GoogleSignin : MonoBehaviour
{
private string HOST_PLAYNANOO_OAUTH2REDIRECT = "https://www.playnanoo.com/oauth2redirect.html";
private string OAUTH2REDIRECT_SCOPE = "openid email profile";
private string clientId = "Your Google Client Id";

void Start()
{
Application.deepLinkActivated += OnDeepLink;
}

private void OnDeepLink(string url)
{
string token = ExtractIdToken(url);
if (!string.IsNullOrEmpty(token))
{
SendTokenToServer(token);
}
}

private string ExtractIdToken(string url)
{
// query parameter(?) 또는 fragment(#)에서 id_token 추출
string paramString = null;

if (url.Contains("?"))
{
paramString = url.Split('?')[1];
}
else if (url.Contains("#"))
{
paramString = url.Split('#')[1];
}

if (string.IsNullOrEmpty(paramString)) return null;

string[] parts = paramString.Split('&');
foreach (var p in parts)
{
if (p.StartsWith("id_token="))
return p.Substring("id_token=".Length);
}
return null;
}

public void Sign_in_with_Google()
{
string nonce = Guid.NewGuid().ToString("N");

string authUrl = "https://accounts.google.com/o/oauth2/v2/auth"
+ "?client_id=" + clientId
+ "&redirect_uri=" + HOST_PLAYNANOO_OAUTH2REDIRECT
+ "&response_type=id_token"
+ "&scope=" + Uri.EscapeDataString(OAUTH2REDIRECT_SCOPE)
+ "&nonce=" + nonce
+ "&prompt=select_account"
+ "&login_hint="; // 빈 값으로 자동 로그인 방지

// 외부 브라우저에서 열기 (403 disallowed_useragent 방지)
OpenURLInExternalBrowser(authUrl);
}

private void OpenURLInExternalBrowser(string url)
{
if (Application.platform == RuntimePlatform.Android)
{
try
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
using (AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", "android.intent.action.VIEW"))
using (AndroidJavaClass uri = new AndroidJavaClass("android.net.Uri"))
{
intent.Call<AndroidJavaObject>("setData", uri.CallStatic<AndroidJavaObject>("parse", url));
intent.Call<AndroidJavaObject>("addFlags", 0x10000000); // FLAG_ACTIVITY_NEW_TASK
intent.Call<AndroidJavaObject>("addCategory", "android.intent.category.BROWSABLE");

try
{
intent.Call<AndroidJavaObject>("setPackage", "com.android.chrome");
currentActivity.Call("startActivity", intent);
}
catch
{
intent.Call<AndroidJavaObject>("setPackage", null);
currentActivity.Call("startActivity", intent);
}
}
}
catch
{
Application.OpenURL(url);
}
}
else
{
Application.OpenURL(url);
}
}

//인증 완료 시 토큰 받는 메소드.
private void SendTokenToServer(string token)
{
//toten 값으로 SocialChange 또는 SocialSignIn 진행.
//SocialChange(token, PN_ACCOUNT_GOOGLE);
// or
//SocialSignIn(token, PN_ACCOUNT_GOOGLE);
}

//계정 전환 예시. SocialChange
public void SocialChange(string token, string accountType)
{
}

public void SocialSignIn(string token, string accountType)
{
}
}

OAuth 2.0 Parameters

ParameterValueDescription
client_idIssued from Google Cloud ConsoleOAuth web client ID
redirect_urihttps://www.playnanoo.com/oauth2redirect.htmlRedirect URL after authentication
response_typeid_tokenRequest OpenID Connect ID token
scopeopenid email profileUser information scope to request
nonceGuid.NewGuid()Random string to prevent replay attacks
promptselect_accountForce account selection display
Environment Settings Required

Before using Sign in with Google, you must complete the following settings by referring to the Google Environment Settings documentation:

  • Issue OAuth 2.0 client ID from Google Cloud Console
  • Configure Android/iOS Deep Link
  • Register redirect URI

How to Use

1. Start Google Login

Sign_in_with_Google();

An external browser opens and the user selects a Google account.

After authentication is complete, call the PlayNANOO API with the id_token received in the SendTokenToServer method:

New Login (SocialSignIn)

public void SocialSignIn(string token, string accountType)
{
// 구글 계정으로 처음 로그인
//accountType : PN_ACCOUNT_GOOGLE
}

Member Conversion (SocialChange)

public void SocialChange(string token, string accountType)
{
// 비회원에서 구글 회원으로 전환
//accountType : PN_ACCOUNT_GOOGLE
}
References

Platform-Specific Callback Handling

Android

  • Receives callbacks via DeepLink.
  • Register a callback method on the Application.deepLinkActivated event.
  • If the Chrome Custom Tabs library is included, the browser opens in an in-app overlay form.
  • If the library is not present, it opens in an external Chrome browser and returns to the app via deep link after authentication.

iOS

  • Uses ASWebAuthenticationSession to open an authentication session within the app.
  • Register a callback with SetGoogleAuthCallback and it will be called upon authentication completion.
void Start()
{
Plugin plugin = Plugin.GetInstance();

// iOS Google OAuth 콜백 등록
plugin.SetGoogleAuthCallback((result) =>
{
if (result.StartsWith("error:"))
{
Debug.LogError("[GoogleOAuth] iOS Auth Error: " + result);
return;
}

// result는 콜백 URL 전체 (예: {game_id}://#id_token=xxx&...)
// ※ mygame:// scheme은 deprecated 되었습니다. PlayNANOO 콘솔에 등록된 Game ID를 scheme으로 사용합니다.
string token = ExtractIdToken(result);
if (!string.IsNullOrEmpty(token))
{
// 토큰으로 SocialSignIn 또는 SocialChange 호출
}
});
}

private string ExtractIdToken(string url)
{
if (!url.Contains("#")) return null;
string fragment = url.Split('#')[1];
string[] parts = fragment.Split('&');
foreach (var p in parts)
{
if (p.StartsWith("id_token="))
return p.Substring("id_token=".Length);
}
return null;
}