# 第三方登入API串接(Vue版本) ## Line登入 [LINE Developers](https://developers.line.biz/zh-hant/) ### 步驟 1. 建立 Line Developers 帳號:註冊一個 Line Developers 帳號並創建一個新的 LINE Login 通道,獲得 Channel ID 和 Channel Secret。 :::spoiler 圖片解說 1. 步棸一:註冊一個商用帳號 ![](https://hackmd.io/_uploads/H12_I5vS3.png) 2. 步驟二:申請一個channel > Channel type:選擇LINE LOGIN Provider:選擇一個開發商或創間一個新的開發商 > ![](https://hackmd.io/_uploads/S1eeP9vBn.png) 3. 申請完畢即可取得Channel ID 與 Channel secret ![](https://hackmd.io/_uploads/Sk9ka5DS3.png) ![](https://hackmd.io/_uploads/HkWxT5DS3.png) ::: 2. 設定 Line 登入回調 URL:在 Line Developers 控制台中,設定允許的回調 URL,這是用戶在成功登入後重定向的網頁。 :::spoiler 圖片解說 ![](https://hackmd.io/_uploads/SJuqWswHh.png) ::: 3. 在網頁中加入 Line 登入按鈕:在網頁上,使用 Line Login 按鈕讓用戶進行登入。可以使用 Line Login 按鈕的 JavaScript SDK 或者自行設計一個按鈕,並透過 JavaScript 與 Line Login API 進行互動。 4. 處理 Line 登入回調:在回調 URL 的網頁中,接收和處理 Line Login 回傳的授權碼,並向 Line Login API 發送請求以獲取用戶的訊息。 5. 處理登入後的動作:根據需求,可以在登入後的處理中進行相應的操作,例如驗證用戶資訊、儲存登入狀態等。 :::spoiler 前端程式碼 ``` JavaScript= <template> <button class="medium_button btn_p08_user_loginType" id="lineLoginBtn" @click="openLineLogin"> <i class="fa-brands fa-line"></i> LINE </button> </template> <script setup> import { ref } from 'vue'; import axios from 'axios'; import { API_URL } from "@/config"; // yourClient_id 請設置為實際Channel ID 值 const client_id = ref('yourClient_id') // yourURI 請設置為實際Line developer 設定的重新導向網址 const redirect_uri = ref('yourURI') // yourClient_secret 請設置為實際Channel Secret 值 const client_secret = ref('yourClient_secret') // 使用者點擊登入按鈕觸發 function openLineLogin(response) { // 根據指定的 client_id、redirect_uri、scope 等參數組合出一個 LINE 登入的連結 let link = `https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=${client_id.value}&redirect_uri=${redirect_uri.value}&state=login&scope=openid%20profile`; // 將頁面重新導向到該連結 window.location.href = link; }; (async () => { try { // 使用 window.location.search 和 urlParams 獲取當前網頁 URL 中的查詢參數 const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); /* 使用 get 方法從 urlParams 實例中獲取名為 code 的參數的值。(授權碼,通常由用戶在身份驗證流程中獲得) 如果查詢字串中存在名為 code 的參數,code 變數將被賦值為該參數的值;否則,code 變數將為 null。 */ const code = urlParams.get('code'); // 使用 require 引入模組的方式引入qs模組 const qs = require('qs'); /* 使用 Axios 發送 HTTP POST 請求到指定的 URL 並指定 'Content-Type': 'application/x-www-form-urlencoded' 標頭以指示伺服器使用 URL 編碼形式解析參數 grant_type:指定授權類型為 "authorization_code" code:授權碼,這個值是從 code 變數中取得的 redirect_url:指定用戶授權完成後的重定向 URL client_id:用於識別應用程式的客戶端 ID client_secret:應用程式的客戶端密鑰 這些參數使用 qs.stringify 函式轉換為 URL 編碼的形式,以符合 "application/x-www-form-urlencoded" 的請求格式 Content-Type': 'application/x-www-form-urlencoded':指定請求的內容類型為 URL 編碼形式 */ const tokenResponse = await axios.post('https://api.line.me/oauth2/v2.1/token', qs.stringify({ grant_type: 'authorization_code', code: code, // yourURI 請設置為實際Line developer 設定的重新導向網址 redirect_uri: 'yourURI', client_id: client_id.value, client_secret: client_secret.value }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); /* 從 tokenResponse 的回應資料中取得 access_token 和 id_token。 這些欄位是從 LINE 登入 API 取得的授權資訊。 access_token 是用來作為驗證的令牌 id_token 是使用者的身份令牌。 */ const accessToken = tokenResponse.data.access_token; const idToken = tokenResponse.data.id_token; /* 使用 Axios 發送 HTTP POST 到 https://api.line.me/oauth2/v2.1/verify,驗證 id_token 以獲取包含使用者資訊的回應 id_token:用於識別使用者的身份令牌 client_id:用於識別應用程式的客戶端 ID 使用 qs.stringify 函式轉換為 URL 編碼的形式,以符合 "application/x-www-form-urlencoded" 的請求格式 Content-Type': 'application/x-www-form-urlencoded':指定請求的內容類型為 URL 編碼形式。 'Authorization': 'Bearer ' + accessToken:使用存取令牌進行身份驗證,將存取令牌放在 'Bearer ' 字符串之後。 */ const userInfoResponse = await axios.post('https://api.line.me/oauth2/v2.1/verify', qs.stringify({ id_token: idToken, client_id: client_id.value }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + accessToken } }); /* 根據需求,可以在登入後的處理中進行相應的操作,例如驗證用戶資訊、儲存登入狀態等。 */ const lineUserId = userInfoResponse.data.sub; const lineNickname = userInfoResponse.data.name; const lineAccountTypeID = 1; const response = await axios.post(`${API_URL}lineLogin.php`, { userId: lineUserId, nickname: lineNickname, accountTypeID: lineAccountTypeID }); localStorage.setItem("token", response.data.id); //window.location.reload(); } catch (error) { console.log(error); } })(); </script> ``` ::: --- ## Firebase-第三方登入-Google登入 [Firebase](https://firebase.google.com/) [npm-Firebase](https://www.npmjs.com/package/firebase) ### 步驟 1. 步驟一:掛載套件 firebase ``` npm i firebase ``` 2. 步驟二:建立 Firebase 專案 :::spoiler 圖片解說 - 建立新的專案 ![](https://hackmd.io/_uploads/H1S8iL9Sh.png) - 設置專案 - 輸入專案名稱 ![](https://hackmd.io/_uploads/S10hRLqS2.png) -選擇是否啟用Google Analytics ![](https://hackmd.io/_uploads/S1V69v9rn.png) - 設定 Google Analytics (分析),完成後建立專案 ![](https://hackmd.io/_uploads/SkwXowcSn.png) ::: 3. 步驟三:取得 Firebase SDK :::spoiler 圖片解說 - 將 Firebase 新增至應用程式,點選表示「網頁」的 icon 就會開始新增網頁應用程式 ![](https://hackmd.io/_uploads/r10tO_5S2.png) - 設定應用程式暱稱,設置完畢後點選註冊應用程式 ![](https://hackmd.io/_uploads/Bk5J9_9r2.png) - 註冊完畢後即可取得Firebase SDK,這邊可以選擇使用方式 ![](https://hackmd.io/_uploads/SyDOpO5Hn.png) ::: 4. 步驟四:撰寫程式碼 - 第一步:在vue專案中的src資料夾中建 firebaseConfig.js :::spoiler firebaseConfig.js ``` javascript= // 引入 Firebase 中的 initializeApp 函式 import { initializeApp } from 'firebase/app'; // firebaseConfig請設置為Firebase 取得 SDK const firebaseConfig = { apiKey: "yourApiKey", authDomain: "yourAuthDomain", projectId: "yourProjectId", storageBucket: "yourStorageBucket", messagingSenderId: "yourMessagingSenderId", appId: "yourAppId", measurementId: "yourMeasurementId" }; /* 透過initializeApp 函式,將 firebaseConfig 物件傳遞給它,即可初始化 Firebase 應用程式。 此函式會返回一個 Firebase 應用程式的實例,將它存儲在變數 firebaseApp 中,以便在後續的程式中使用 */ const firebaseApp = initializeApp(firebaseConfig); // 將 firebaseApp 的變數進行預設導出,在其他地方可以使用 import 進行導入 export default firebaseApp ``` ::: :::spoiler 若忘記SDK可至專案設置-您的應用程式-SDK設定和配置 查看 ![](https://hackmd.io/_uploads/SJqFMKqS2.png) ::: - 第二步:建立Google登入的component vue檔案 :::spoiler SignupGoogle.vue ```= <template> <!-- 自製google登入按鈕 --> <button class="medium_button btn_p08_user_loginType" @click="openGoogleLogin"> <i class="fa-brands fa-google"></i> GOOGLE </button> </template> <script setup> import { ref } from 'vue' import { API_URL } from "@/config"; import firebaseConfig from '../firebaseConfig'; import { getAuth, signInWithPopup, GoogleAuthProvider} from "firebase/auth"; import axios from 'axios'; firebaseConfig // getAuth():用於獲取 Firebase 的 auth 服務的實例,處理身份驗證的主要介面 const auth = getAuth(); // GoogleAuthProvider:用於提供 Google 登入的驗證提供者物件,設定相關的登入選項和參數。 const googleProvider = new GoogleAuthProvider(); const userUid = ref(); const nickname = ref(); const accountTypeID = ref(1); async function openGoogleLogin() { try { // signInWithPopup(auth, googleProvider) 函式:用於彈出 Google 登入視窗,並返回一個結果物件 const result = await signInWithPopup(auth, googleProvider); // uid:使用者的唯一識別碼 userUid.value = result.user.uid; // displayName:使用者的顯示名稱 nickname.value = result.user.displayName; // 根據需求,可以在登入後的處理中進行相應的操作,例如驗證用戶資訊、儲存登入狀態等。 const response = await axios.post(`${API_URL}googleLogin.php`, { userUid: userUid.value, nickname: nickname.value, accountTypeID: accountTypeID.value }); if (response.data.message === '登入成功') { // alert(response.data.message); } else { alert(response.data.message); } // 使用 localStorage.setItem 方法將回應中的 id 值存儲到 token 鍵中。 localStorage.setItem("token", response.data.id); //使用 window.location.reload() 重新載入頁面。 window.location.reload(); } catch (error) { console.log(error.response); alert('發生了一些錯誤,請聯絡管理員!'); window.location.reload(); } } </script> ``` ::: ###### 持續更新中! ###### 前期程式碼撰寫:張家恩,後期筆記整理:詹皓丞。 ###### 以上為自學中的筆記如有錯誤,懇請留言指正,感謝!