使用 JavaScript 實作 Facebook 登入

前置作業

首先,前往 Meta 開發者平台,建立一個應用程式。例如:

  • 應用程式名稱:post-bot-auth
  • 新增使用案例:「使用 Facebook 登入,驗證用戶並索取資料」
  • 商家:「我還不想連結商家資產管理組合」

完成後,點選「建立應用程式」按鈕。

建立專案

建立專案。

1
2
mkdir facebook-auth-example
cd facebook-auth-example

初始化專案。

1
npm init

安裝依賴套件。

1
npm i -D live-server

新增 .gitignore 檔。

1
node_modules/

修改 package.json 檔,添加一個 dev 啟動腳本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "facebook-auth-example",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "live-server"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"live-server": "^1.2.2"
}
}

啟動服務。

1
npm run dev

使用 ngrok 指令,啟動一個 HTTP 代理伺服器。

1
ngrok http 8080

設定

回到 Meta 開發者平台,在「使用案例」頁面,點選「自訂」按鈕。進到「自訂使用案例」頁面,點選「設定」按鈕。

設置以下:

檢查

設置以下,點選「檢查 URI」按鈕。

如果成功,會顯示「此重新導向 URI 對此應用程式有效」。

快速入門

點選「快速入門」頁籤,點選「網站」按鈕,查看如何設定 Facebook JavaScript SDK 到網站。

實作

新增 index.html 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="info" ></div>
<button id="login">Login</button>
<button id="logout" hidden>Logout</button>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: "9368643076536346",
cookie: true,
version: "v22.0",
});
FB.AppEvents.logPageView();
};

(function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
})(document, "script", "facebook-jssdk");

const loginElement = document.getElementById("login");
const logoutElement = document.getElementById("logout");
const infoElement = document.getElementById("info");

loginElement.addEventListener("click", function () {
FB.login(
function (response) {
if (!response.authResponse) {
console.log("User cancelled login or did not fully authorize.");
return;
}

FB.api("/me", function (response) {
infoElement.innerHTML = `Good to see you, ${response.name}.`;
});

logoutElement.hidden = false;
loginElement.hidden = true;
},
{
scope: "public_profile,email",
}
);
});

logoutElement.addEventListener("click", function () {
FB.logout(function () {
infoElement.innerHTML = "Goodbye!";
loginElement.hidden = false;
logoutElement.hidden = true;
});
});
</script>
</body>
</html>

前往 https://random.ngrok-free.app 瀏覽。

程式碼

參考資料