android - 如果我在 Android 中使用 Games.API,如何获取服务器的访问 token ?

标签 android api google-play-services

在我的 Android 游戏中,我使用 Google 服务获取成就并保存游戏数据。我的 Google Api 客户端:

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(StartActivity.this)
                .addOnConnectionFailedListener(StartActivity.this)
                .addApi(Games.API).addScope(Games.SCOPE_GAMES)
                .addApi(Drive.API).addScope(Drive.SCOPE_APPFOLDER)
                .setViewForPopups(findViewById(android.R.id.content))
                .build();

现在我需要在我的服务器上使用 google 授权。我阅读了谷歌文档(https://developers.google.com/identity/sign-in/android/start)并尝试实现这一点。我将 .addApi(Auth.GOOGLE_SIGN_IN_API, geo) 添加到我的 google api 客户端。如果我使用此 Api,那么我可以获得 idToken 以在服务器端进行验证。但是我收到错误消息“Auth.GOOGLE_SIGN_IN_API 不能与 Games.API 一起使用”。搜索互联网,我发现我应该只使用 Games.API。我如何在 Google 开发者博客 ( http://android-developers.blogspot.ru/2016/01/play-games-permissions-are-changing-in.html ) 上找到的,这段代码很好:

GetServerAuthCodeResult result = Games.getGamesServerAuthCode(gac, clientId).await();  
if (result.isSuccess()) {  
    String authCode = result.getCode();  
    // Send code to server.  
}

GetServerAuthCodeResultgetGamesServerAuthCode 已弃用。 result.getCode() 总是为我返回 null。有什么方法既可以获取服务器端身份验证 token ,又可以使用 Games.API 获取成就?

最佳答案

解决此问题的关键在于玩家在设备上通过身份验证后: 获取授权码以发送到您的后端服务器:

GetServerAuthCodeResult result =
Games.getGamesServerAuthCode(gac, clientId).await();
if (result.isSuccess()) {
    String authCode = result.getCode(); 
        // Send code to server.
}

在服务器上,通过向 https://www.googleapis.com/oauth2/v4/token 发送 RPC 来交换 token 接收到的授权码。将授权码交换为访问 token 。
您必须提供服务器客户端 ID、服务器客户端密码(在您创建服务器客户端 ID 时在开发人员控制台中列出)和授权代码。查看更多详情 here

获得访问 token 后,将使用访问 token 通过以下方式检索玩家 ID:www.googleapis.com/games/v1/applications//verify/。在 header 中传递身份验证 token ,如下所示:Authorization: OAuth

响应值将包含用户的玩家 ID。这是用于该用户的正确玩家 ID。此访问 token 可用于根据需要进行额外的服务器到服务器调用。

关于android - 如果我在 Android 中使用 Games.API,如何获取服务器的访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39145354/

相关文章:

android - 运行程序的主要功能

android - "ActionBarDrawerToggle"什么时候显示它的 "openDrawerContentDescRes"和 "closeDrawerContentDescRes"字符串?

android - 100% 唤醒我的设备的正确方法?

android - Proguard NoClassDefFoundError

android - 更改 Android 中的证书

ruby-on-rails - Rails RESTful API + 对仅允许 GET/POST 的客户端的支持 - 这可能吗?

javascript - 如何在 TideSdk 应用程序中去除窗口类似窗口的边框?

java - 是否有用于分析 yourkit 快照(内存/cpu)的 API?

android - 找不到类 com.google.android.gms.analytics.GoogleAnalytics

android - 如何将相机移动到 android 中的 google maps v2 中的特定标记