# 使用Google第三方登入取得個人資訊 | javaScript範例 以下示範使用javascript取得第三方登入的個人資訊 1. 請先至[Google Cloud 申請憑證](https://console.cloud.google.com/apis/credentials),建立一組OAuth 2.0 用戶端 ID。 > 詳細申請教學可輸入關鍵字 "Google Cloud OAuth 2.0 申請教學" 上網尋找,網上有很多資源這裡就不多做說明。 完成申請可看到下圖: ![1710944821364](https://hackmd.io/_uploads/ry9IGudC6.jpg) 2. 接著開啟專案,輸入下方程式 > 在專案中插入meta標籤,用戶端編號就是上方步驟您申請的OAuth 2.0。[color=#DD4B25] ```html <meta name="google-signin-client_id" content="貼上您的用戶端編號"> ``` <br/> > 引入Google Sign-In(GSI)的客戶端程式庫CDN。[color=#DD4B25] ```html <script src="https://accounts.google.com/gsi/client" async defer></script> ``` > 加上登入 html 元素,此為官方預設範例。data-client_id 一樣貼上您的用戶端編號。[color=#DD4B25] ```html <div id="g_id_onload" data-client_id="貼上您的用戶端編號" data-callback="handleCredentialResponse"> </div> <div class="g_id_signin" data-type="standard"></div> ``` > 接著,在 script 區塊中輸入以下函式,該函式用於解析 callback 返回的憑證(credential)值中 JWT 的 payload 資訊。[color=#F7E025] ```javascript function decodeJwtResponse(token) { const parts = token.split('.'), payload = parts[1], decodedPayload = JSON.parse(atob(payload)); return decodedPayload; } ``` - 若想詳細察看憑證回傳了哪些內容,可到[jwt.io](https://jwt.io/)做查看,複製 credential 的值貼到網站上 Encoded 區塊即可。 > 當使用者成功登入並授權後,Google 會回傳憑證(credential),接著 decodeJwtResponse()接收 response.credential 作為參數解碼JWT資訊,並將解碼後的資訊儲存在 responsePayload ,最後輸出到控制台,以下範例舉例一些常見的資訊。[color=#F7E025] ```javascript function handleCredentialResponse(response) { const responsePayload = decodeJwtResponse(response.credential); console.log(` 照片 ${ responsePayload.picture } 全名 ${ responsePayload.name } 姓氏 ${ responsePayload.family_name } 名字 ${ responsePayload.given_name } 信箱 ${ responsePayload.email } 發行者 ${ responsePayload.iss } `); } ``` 3. 可在控制台看到以下結果: ![1710946413818](https://hackmd.io/_uploads/BkeFOOdR6.jpg) 自從Chrome 將於 2024 年第 1 季淘汰第三方 Cookie後,第三方登入取得資訊與CDN引用有些不同,留下紀錄供各位參考。 > 參考來源 > [FedCM說明](https://developers.google.com/privacy-sandbox/3pcd/fedcm?hl=zh-tw) > [處理憑證回應](https://developers.google.com/identity/gsi/web/guides/handle-credential-responses-js-functions?hl=zh-tw) > [Google 登入遷移](https://developers.google.com/identity/gsi/web/guides/migration?hl=zh-tw)