2020-05-08

NodeJS 後端取得 Google Play Games 玩家資訊


玩家在 Android 裝置登入 Google Play Games 之後可以取得 Server Auth Code (參照 這裡),後端可利用 Server Auth Code 取得玩家的 Access Token,再由 Access Token 取得玩家資訊 (取得玩家資訊的 API 參照 這裡)。

底下是 NodeJS 利用 Server Auth Code 取得 Access Token 的實作 :
var querystring =require('querystring')
var https =require('https')

var post_data =querystring.stringify({
  grant_type:'authorization_code',
  code:/*CLIENT 給的 SERVER AUTH CODE*/,
  client_id:/*Google API Console 取得的 client id*/,
  client_secret:/*Google API Console 取得的 client secret*/,
  redirect_uri:'',
})

var post_options ={
  host:'oauth2.googleapis.com',
  port:443,
  path:'/token',
  method:'POST',
  headers:{
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(post_data)
  }
}

var post_req =https.request(post_options, (res)=>{
  res.setEncoding('utf8')
  var body =''
  res.on('data', (chunk)=>{
    body +=chunk
  })
  res.on('end', ()=>{
    console.log(body)
  })
})
post_req.write(post_data)
post_req.end()

執行之後應該會顯示類似內容 :
{
  "access_token": "ya29.a0Ae4lvC3sSLZwqGO8iSHsnzErS_GbBc021o9Q3FhDV_bb0mu3ukKF-_D5bf1xtvIWTFEAZLRODhlfdxetMrUEfQtt5jqhsH8oUrBlGll575VnLND_WGovv98y_tzVhceh6Ti42qrpdO9A6vKtWUGaHeOtxSb71KgP0U8",
  "expires_in": 3599,
  "refresh_token": "1//0es-vhoIE4URRCgYIARAAGA4SNwF-L9IrM22Sj9e2zM-SJpjgocfM4wcYhF2i8rRossKhSxCGj1nDEVy7BmSeWGmhl4",
  "scope": "https://www.googleapis.com/auth/games_lite",
  "token_type": "Bearer"
}

有了 access_token 就可以用來取得玩家資訊 :
var player_id ='玩家的 ID'
var api_key ='Google API Console 取得的 API Key'
var get_options ={
  host:'www.googleapis.com',
  port:443,
  path:'/games/v1/players/'+player_id+'?key='+api_key,
  method:'GET',
  headers:{
    Authorization: 'Bearer '+access_token,
    Accept: 'application/json'
  }
}
var get_req =https.request(get_options, (res)=>{
  res.setEncoding('utf8')
  var body =''
  res.on('data', (chunk)=>{
    body+=chunk
  })
  res.on('end', ()=>{
    console.log(body)
  })
})
get_req.end()

範例程式裡提到的 Client ID, Client Secret 和 API Key 可以由 Google API Console 取得,參考如下圖 :


其中 A. 是 API Key,C. 下載的 JSON 檔案裡包含 Client ID/ Client Secret,這裡要注意的是 B. OAuth 用戶端 ID 的類型是網路應用程式。

0 意見 :

張貼留言