建議您驗證玩家,並以安全的方式將玩家的身分傳遞至後端伺服器。這可讓遊戲以安全的方式擷取玩家身分資料和其他資料,避免在透過裝置傳遞的過程中可能遭到竄改的風險。
在這個情境中,玩家成功登入後,您可以透過 Play 遊戲服務第 2 版 SDK 要求特別的一次性程式碼 (稱為伺服器驗證碼),而該用戶端會將其傳送至伺服器。然後在伺服器上交換 OAuth 2.0 憑證的伺服器驗證碼,讓伺服器用來呼叫 Google Play Games Services API。
如需在遊戲中新增登入的其他指引,請參閱在 Android 遊戲中登入。
離線存取必須採取以下步驟:
- 在 Google Play 管理中心:為遊戲伺服器建立憑證。憑證的 OAuth 用戶端類型為「網站」。
- 在 Android 應用程式中:登入時要求取得伺服器憑證的伺服器驗證碼,然後將該驗證碼傳遞至伺服器。
- 您的遊戲伺服器:以 Google 驗證服務交換 OAuth 存取憑證的伺服器驗證碼,然後用來呼叫 Play 遊戲服務 REST API。
事前準備
首先,請按照 Google Play 遊戲服務的說明,在 Google Play 管理中心新增您的遊戲,並將 Play 遊戲服務登入與您的遊戲整合。
為遊戲建立相關的伺服器端網路應用程式
Google Play 遊戲服務無法提供網路遊戲的後端支援,但是會提供 Android 遊戲伺服器的後端伺服器支援。
如果要在伺服器端應用程式中使用 Google Play 遊戲服務的 REST API,請按照以下步驟操作:
- 在 Google Play 管理中心的遊戲中,依序前往「Play Games Services」(Play 遊戲服務) >「Setup and management」(設定與管理) >「Configuration」(設定)。
- 選取「Add credential」(新增憑證),即可前往「新增憑證」頁面。選取「Games server」(遊戲伺服器) 做為憑證類型,然後繼續前往「Authorization」(授權) 區段。
- 如果遊戲伺服器已有 OAuth 用戶端 ID,請從下拉式選單中選取該 ID。儲存變更後,請繼續前往下一節。
- 如果遊戲伺服器還沒有 OAuth 用戶端 ID,則可以進行建立。
- 按一下「Create OAuth client」(建立 OAuth 用戶端),然後點選「Create OAuth Client ID」(建立 OAuth 用戶端 ID) 連結。
- 系統會引導您帶往 Google Cloud Platform 的「Create OAuth Client ID」(建立 OAuth 用戶端 ID) 頁面,為您提供遊戲相關聯的 Cloud Platform 專案。
- 填寫頁面的表單,然後按一下「Create」(建立)。請務必將應用程式類型設為網頁應用程式。
- 返回「Add credential page's Authorization」(新增憑證頁面的授權) 區段,選取新建立的 OAuth 用戶端,然後儲存變更。
取得伺服器驗證碼
如要擷取遊戲在後端伺服器取得存取權杖使用的伺服器驗證碼,:
從用戶端呼叫
requestServerSideAccess
。- 請務必使用專為遊戲伺服器註冊的 OAuth 用戶端 ID,而非 Android 應用程式的 OAuth 用戶端 ID。
- (選用) 如果遊戲伺服器需要離線存取 (使用更新權杖的長期存取權) Play 遊戲服務,則可將 forceRefreshToken 參數設為 true。
GamesSignInClient gamesSignInClient = PlayGames.getGamesSignInClient(this); gamesSignInClient .requestServerSideAccess(OAUTH_2_WEB_CLIENT_ID, /* forceRefreshToken= */ false) .addOnCompleteListener( task -> { if (task.isSuccessful()) { String serverAuthToken = task.getResult(); // Send authentication code to the backend game server to be // exchanged for an access token and used to verify the player // via the Play Games Services REST APIs. } else { // Failed to retrieve authentication code. } });
傳送 OAuth 驗證碼權杖至後端伺服器以允許進行交換,根據 Play 遊戲服務 REST API 驗證玩家 ID,然後透過遊戲進行驗證。
針對伺服器存取權杖以交換伺服器驗證碼
將伺服器驗證碼傳送至後端伺服器,以交換存取和更新憑證的權限。 使用存取權杖代表玩家呼叫 Google Play 遊戲服務 API,並視需要儲存更新權杖,在存取權杖到期時取得新的存取權杖。
下列程式碼片段示範如何使用 Java 程式設計語言實作伺服器端程式碼,以交換伺服器驗證碼以存取存取憑證。它使用 clientserverskeleton 範例應用程式:
/**
* Exchanges the authcode for an access token credential. The credential
* is the associated with the given player.
*
* @param authCode - the non-null authcode passed from the client.
* @param player - the player object which the given authcode is
* associated with.
* @return the HTTP response code indicating the outcome of the exchange.
*/
private int exchangeAuthCode(String authCode, Player player) {
try {
// The client_secret.json file is downloaded from the Google API
// console. This is used to identify your web application. The
// contents of this file should not be shared.
//
File secretFile = new File("client_secret.json");
// If we don't have the file, we can't access any APIs, so return
// an error.
if (!secretFile.exists()) {
log("Secret file : " + secretFile
.getAbsolutePath() + " does not exist!");
return HttpServletResponse.SC_FORBIDDEN;
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new
FileReader(secretFile));
// Extract the application id of the game from the client id.
String applicationId = extractApplicationId(clientSecrets
.getDetails().getClientId());
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
HTTPTransport,
JacksonFactory.getDefaultInstance(),
"https://oauth2.googleapis.com/token",
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode,
"")
.execute();
log("hasRefresh == " + (tokenResponse.getRefreshToken() != null));
log("Exchanging authCode: " + authCode + " for token");
Credential credential = new Credential
.Builder(BearerToken.authorizationHeaderAccessMethod())
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setTransport(HTTPTransport)
.setTokenServerEncodedUrl("https://www.googleapis.com/oauth2/v4/token")
.setClientAuthentication(new HttpExecuteInterceptor() {
@Override
public void intercept(HttpRequest request)
throws IOException {
}
})
.build()
.setFromTokenResponse(tokenResponse);
player.setCredential(credential);
// Now that we have a credential, we can access the Games API.
PlayGamesAPI api = new PlayGamesAPI(player, applicationId,
HTTPTransport, JacksonFactory.getDefaultInstance());
// Call the verify method, which checks that the access token has
// access to the Games API, and that the player id used by the
// client matches the playerId associated with the accessToken.
boolean ok = api.verifyPlayer();
// Call a Games API on the server.
if (ok) {
ok = api.updatePlayerInfo();
if (ok) {
// persist the player.
savePlayer(api.getPlayer());
}
}
return ok ? HttpServletResponse.SC_OK :
HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
} catch (IOException e) {
e.printStackTrace();
}
return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
從伺服器呼叫 REST API
如需可用 API 呼叫的完整說明,請參閱 Google Play 遊戲服務的 REST API。
以下是幾個實用的 REST API 呼叫範例,歡迎參考:
玩家
- 想要取得已登入玩家的 ID 和設定檔資料嗎?呼叫 Players.get 並使用
'me'
做為 ID。
朋友
請務必查看好友指南,進一步瞭解好友。
- 想要擷取玩家的好友名單嗎?呼叫 Players.list,
'friends_all'
collection
。 - 確認您是否能夠存取好友名單?呼叫
me
的 Players.get,並查看回應中的profileSettings.friendsListVisibility
欄位。
成就
請務必詳閱成就指南,其中會進一步說明各項成就。
- 想查看目前的成就清單嗎?您可以呼叫 AchievementDefinitions.list。
- 再加入 Achievements.list 呼叫,找出玩家在哪些裝置上解鎖。
- 玩家能否贏得成就?使用 Achievements.unlock 即可解鎖!
- 玩家能否取得部分成就?使用 Achievements.增量 回報進度 (以及判斷玩家是否成功解鎖)。
- 您正針對尚未正式發布的遊戲進行偵錯嗎?請嘗試透過 Management API 呼叫 Achievements.reset 或 Achievements.resetAll,將成就重設為原始狀態。
排行榜
請務必參閱排行榜指南,進一步瞭解排行榜的詳細資訊。
- 想要取得遊戲中所有計分板的清單嗎?呼叫 排行榜 s.list。
- 玩家完成遊戲了嗎?您可以將他們的分數提交至 Scores.submit,看看這是否為新的高分。
- 想要顯示排行榜嗎?從 Scores.list 取得資料並向使用者顯示。
- 使用 Scores.listWindow 尋找接近使用者最高分的分數。
- 如要進一步瞭解特定排行榜中玩家的分數 (例如,假設玩家在前 12% 的排行榜中),請呼叫 Scores.get。
- 您是否正在對遊戲進行偵錯?嘗試透過 Management API 呼叫 Scores.reset,重設特定排行榜中該玩家的所有分數