Quantcast
Viewing all articles
Browse latest Browse all 577

2023 使用 Google 新版 API 取得使用者個人資訊﹍實作範例

Image may be NSFW.
Clik here to view.
之前寫的「使用 Google People API 取得使用者生日、性別等多種個人資訊」,因為「Google 更新登入 API 及相關模組」,官方公告在 2023/3/31 舊版程式碼會失效,連帶也使能夠取得 Google 帳號個人資訊的 People API 必須更新程式碼。 由於變動相當大,例如原本使用的 gapi.auth2 模組將被 google.accounts.oauth2 模組取代,載入 API 的方式也差別很大,直接更新上一篇原文可能會造成相當大的混亂,乾脆重新寫一篇。因此關於 Google People API 的介紹、測試方法請看上一篇,本篇直接提供新版操作流程及範例程式碼。 (圖片出處: pixabay.com)

一、準備動作

操作 API 之前需要先建立 Google API 專案,如果還沒建立過的話,請完成以下流程:

二、程式碼範例

以下使用「Bootstrap 按鈕」、jQuery 處理點擊按鈕,作為範例程式碼: <!--jQuery--> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <!--Bootstrap--> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <!--登入、登出按鈕--> <button id="google_login" class="btn btn-large btn-primary">GOOGLE 登入</button> <button id="google_logout" class="btn btn-large btn-warning">GOOGLE 登出</button> <p /> <p>目前狀態:</p> <div id="persoanl_info">尚未授權</div> <script> var client_id = "5432xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", apiKey = "AIzaxxxxxxxxxxxxxxxxxxxxxx", scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/user.gender.read https://www.googleapis.com/auth/user.birthday.read", personFields = "names,emailAddresses,photos,genders,birthdays", discovery_doc = "https://www.googleapis.com/discovery/v1/apis/people/v1/rest", resourceName = "people/me", $persoanl_info = $("#persoanl_info"), tokenClient; loadApi(); // 載入 google api function loadApi() { // 載入 gapi $.getScript("https://apis.google.com/js/api.js", function() { gapi.load("client", function() { gapi.client.init({ apiKey: apiKey, discoveryDocs: [discovery_doc], }); }); }); // 載入 gsi $.getScript("https://accounts.google.com/gsi/client", function() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: client_id, scope: scope, callback: signIn_callback, error_callback: error_callback }); }); // 登入後 callback function signIn_callback(res) { // 登入失敗時 if (res.error !== undefined) { console.log(res.error); $persoanl_info.html(res.error); } // 登入成功後 if (res && res.access_token) { // 顯示帳號資訊 listAccountInfo(); } } // 捕捉非 OAuth 錯誤 或是在傳回 OAuth 回應前遭到關閉 function error_callback(res) { console.log(res); $persoanl_info.html(res.message); } // 顯示帳號資訊 function listAccountInfo() { // 呼叫 people api 取得資料 gapi.client.people.people.get({ "resourceName": resourceName, "personFields": personFields, }).then(function(res) { // 顯示資料 var result = res.result, errorMessage = "請重新登入, 並勾選生日及性別!", html = "", id, name, imgUrl, email, gender, birthday, birthdayStr; // 沒有勾選生日、性別時 if (!result.genders || !result.birthdays) { alert(errorMessage); $persoanl_info.html(errorMessage); return; } id = result.resourceName.split("/")[1]; name = result.names[0].displayName; imgUrl = result.photos[0].url; email = result.emailAddresses[0].value; gender = result.genders[0].formattedValue; birthday = result.birthdays[1].date; birthdayStr = birthday.year + "-" + birthday.month + "-" + birthday.day; html += "ID: " + id + "<br/>"; html += "暱稱: " + name + "<br/>"; html += "頭像:<img style='width: 40 px;' src='" + imgUrl + "'/><br/>"; html += "email:" + email + "<br/>"; html += "性別:" + gender + "<br/>"; html += "生日:" + birthdayStr + "<br/>"; $persoanl_info.html(html); }); } } // 點擊登入按鈕 $("#google_login").click(function() { // 進動畫 $persoanl_info.html("<img src='https://lh5.googleusercontent.com/-EyVZ0f8J0qQ/UCeEG7aa8nI/AAAAAAAADtY/9sXw53XkYXM/s512/indicator-light.gif' /> <span>請稍後...</span>"); if (gapi.client.getToken() === null) { // 未登入則彈出登入視窗 tokenClient.requestAccessToken(); } else { // 已登入則不彈出視窗 tokenClient.requestAccessToken({ prompt: "" }); } }); // 點擊登出按鈕 $("#google_logout").click(function() { var token = gapi.client.getToken(); if (token !== null) { google.accounts.oauth2.revoke(token.access_token); gapi.client.setToken(""); // 登出後的動作 $persoanl_info.html("已登出"); } }); </script>紅字字串參數請特別注意以下說明:
  • client_id:請置換為前面「處理 OAuth 憑證」流程取得的「用戶端 ID」
  • apiKey:請置換為前面「取得 Google API 金鑰流程」取得的「API 金鑰」字串
  • scope:請參考上一篇「一、People API 說明」填入需要的 scope 授權,每個網址字串用空格隔開
  • personFields:請參考上一篇「一、People API 說明」填入想取得的個人資料項目,每個項目用小寫逗號隔開
  • 範例程式碼請放在前面「處理 OAuth 憑證」流程設定的網站才能執行

三、DEMO 效果展示

以下為範例程式碼的執行效果,可進行操作並注意對應狀態的顯示資訊:
目前狀態:
尚未授權
更多 Google 相關文章:

Viewing all articles
Browse latest Browse all 577

Trending Articles