You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity桌面游戏PlayFab集成Google登录:获取Server Auth Code方法咨询

解决Unity PlayFab Google登录中Server Auth Code的获取问题

要获取PlayFab LoginWithGoogleAccountRequest 所需的Server Auth Code,核心是调整Google OAuth2授权流程,明确指定access_type=offline参数,并手动处理授权码的获取(而非直接获取AccessToken)。以下是具体实现步骤和代码:

关键前提

  1. 确保你在Google Cloud控制台创建的OAuth客户端是桌面应用类型,而非Web应用(桌面应用无需手动配置回调URL,默认支持本地回调)。
  2. 已导入Google OAuth2相关库(Google.Apis.Auth.OAuth2、Google.Apis.Util.Store等)。

完善GetServerAuthCode函数

替换你的空实现,使用GoogleAuthorizationCodeFlow和LocalServerCodeReceiver来获取授权码:

using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;

public class LoginManager: MonoBehaviour
{
    // 替换为你的Google OAuth客户端ID和密钥
    private const string GoogleClientId = "YOUR_GOOGLE_CLIENT_ID";
    private const string GoogleClientSecret = "YOUR_GOOGLE_CLIENT_SECRET";

    // 异步获取Server Auth Code(避免阻塞Unity主线程)
    async Task<string> GetServerAuthCodeAsync()
    {
        string[] scopes = { "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" };

        // 创建授权流实例
        var authFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = GoogleClientId,
                ClientSecret = GoogleClientSecret
            },
            Scopes = scopes,
            DataStore = new FileDataStore("PlayFabGoogleAuth") // 可选:用于持久化令牌信息
        });

        // 使用本地服务器接收授权码(桌面应用标准方式)
        var codeReceiver = new LocalServerCodeReceiver();
        // 生成授权URL,必须指定access_type=offline才能获取Server Auth Code
        var authUrl = authFlow.CreateAuthorizationCodeRequest(codeReceiver.RedirectUri)
            .SetAccessType("offline")
            .SetPrompt("consent") // 强制用户确认授权,确保每次获取新的授权码(可选,第一次授权后可移除)
            .Build();

        // 打开系统浏览器让用户完成Google登录授权
        Process.Start(new ProcessStartInfo(authUrl.ToString()) { UseShellExecute = true });

        // 等待用户授权完成,接收返回的授权码
        var codeResult = await codeReceiver.ReceiveCodeAsync(CancellationToken.None);
        return codeResult.Code;
    }

    // 修改登录方法为异步调用
    async void LoginUsingGoogle()
    {
        try
        {
            string serverAuthCode = await GetServerAuthCodeAsync();
            var loginRequest = new LoginWithGoogleAccountRequest
            {
                CreateAccount = true,
                ServerAuthCode = serverAuthCode
            };
            PlayFabClientAPI.LoginWithGoogleAccount(loginRequest, OnLoginUsingThirdPartySuccess, OnLoginUsingThirdPartyFailure);
        }
        catch (System.Exception ex)
        {
            Debug.LogError("获取Google授权码失败: " + ex.Message);
        }
    }

    private void OnLoginUsingThirdPartySuccess(LoginResult result)
    {
        Debug.Log("Google登录PlayFab成功: " + result.PlayFabId);
        // 后续逻辑
    }

    private void OnLoginUsingThirdPartyFailure(PlayFabError error)
    {
        Debug.LogError("Google登录PlayFab失败: " + error.ErrorMessage);
    }
}

核心说明

  • access_type=offline:这是获取Server Auth Code的必要参数,告诉Google需要返回可用于服务器端交换令牌的授权码。
  • LocalServerCodeReceiver:Google提供的桌面应用授权码接收方案,会启动一个本地HTTP服务器,监听Google授权后的回调请求,自动获取授权码。
  • 异步处理:使用async/await避免阻塞Unity主线程,防止游戏界面卡顿。
  • 授权码的一次性:Server Auth Code只能使用一次,每次登录都需要重新获取,不能缓存重用。

额外注意事项

  1. 在PlayFab控制台的「设置 > 登录方法」中,启用Google登录并填入对应的Google客户端ID和密钥。
  2. 测试时确保设备能正常访问Google授权页面(需翻墙环境)。
  3. 若要优化用户体验,可在打开浏览器时添加提示,告诉用户需完成Google登录授权后返回游戏。

内容的提问来源于stack exchange,提问作者Mubarak Almehairbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:45:00