網頁使用第三方登入服務-Line

寫在前面

新年愉快~
過完西元年,很快的又要迎接農曆年,趕緊在放假前把還沒更新的Line登入筆記補上。

跟前兩篇一樣,截圖的部分可能會與實做的內容,在名稱上有些微的調整,但實在懶得重新截圖了,
請各位看倌不要介意,斟酌參考,以下正題:

Line 相關文件

官方文件
申請開發者帳號

參考文件-30天教你如何玩弄 Line bot API

參考文件-每天五分鐘 LINE API 輕鬆上手

註冊應用程式

* 需先申請開發者帳號

  • 建立頻道

  • 選擇服務-line login

  • 填完基本資料可以拿到client_id, secret

程式碼參考

  • 產生登入連結

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <?php

    // 從config 取出client_id
    $channel_id = cfg('system.line-client-id');
    $redirect_url = urlencode("your_redirect_url");
    $state = $this->random_string(); // 與google 登入時存的state 類似,用來比對是同一次的request

    // 將資訊存起來,不管是存資料庫還是Session, 之後需要比對
    $this->set('Line-Login', ['state' => $state]); // 各框架使用Session 的語法稍有不同,僅供參考

    // 組登入按鈕的url
    $url = "https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id={$client_id}&redirect_uri={$redirect_url}&state={$state}&scope=profile%20openid&nonce=09876xyz";

    // 網址丟到畫面上,塞進line 登入的按鈕
    echo $url
  • callback

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
<?php

// 取出先前存的state 比對是否相同
$state = $this->get('Line-Login');

if (!$state || $state !== @$_GET['state']) {
echo ('error: login-failed'];
}

// config 中取出channel資訊
$client_id = cfg('system.line-client-id');
$client_secret = cfg('system.client-secret');

$redirect_url = 'your_redirect_url';
$token_url = 'https://api.line.me/oauth2/v2.1/token';

//--

$context = [
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query([
'grant_type' => 'authorization_code',
'code' => @_GET['code'],
'redirect_uri' => $redirect_url,
'client_id' => $client_id,
'client_secret' => $client_secret,
]),
],
];

// call line api 取得 access_token
$response = file_get_contents($token_url, false, stream_context_create($context));

if ($response) {
$response = json_decode($response, true);
}

$token = @$response['access_token'];

if (!$token) {
echo ('error: invalid-access-token'];
}

// call line api 取得使用者資訊

$context = [
'http' => [
'header' => "Authorization: Bearer {$token}",
],
];

$profile_url = 'https://api.line.me/v2/profile';

$profile = file_get_contents($profile_url, false, stream_context_create($context));

if ($profile) {
$profile = json_decode($profile, true);
}

echo '<pre>';
print_r($profile);
exit;

結語

目前台灣大多數的網站,較常見的第三方登入 Google, Facebook, Line 的操作方式都介紹完了,
反覆再提醒一次,第三方登入無法像各網站註冊一樣,取得相對完整的會員資料,又或者是取得的資料可信度不高,
例如姓名只能當作nickname, mail 只有google可以真的發信到此信箱,因此使用上並不一定真的方便,
唯一取代的就是登入時會員可以不用輸入帳號密碼。因此,若是會員資料對開發的網站來說相對不重要(例如notion),
則快速登入是吸引會員註冊的一大利器;反之若會員資料很重要(如購物商城必要時需要可以聯絡得到會員),則第三方登入
只能快速建立帳號,並且在日後登入時取代輸入帳號密碼,但註冊時必要填入的資訊仍需要透過指定流程要求會員輸入(如結帳前需先完善資料等等)。