如何快速接入 GitHub 登陸

liaohui5發表於2019-05-31

接入github的好處

  1. 一鍵登入,使用者體驗好(只針對程式設計師來說)
  2. 申請簡單,如果是要申請QQ登陸或者微博登陸(一頓驗證猛如虎,身份證拍照,打電話..各種各種)
  3. 使用簡單,利於學習

登陸github 並註冊一個 oauth app

  1. 找到 settings
    settings

  2. developer settings
    developer settings

  3. new oauth app
    image.png

  4. 獲取 client_idclient_secret 填寫應用資訊
    client_id client_secret

  5. 完善資訊
    注意這個 application namecalback URL 選項,後面請求可能用得到

image.png

官方文件

https://developer.github.com/apps/building...

開發接入

  • 接入github第三發登入分為以下幾步
    1. 將使用者匯入 github登陸授權頁面
    2. (如果使用者同意授權) => github 會返回到建立 OAuth app 時填寫的 callback URL 填寫的連結並攜帶一個 code 引數
    3. 使用這個 code 引數加上 你的 client_id client_secret 去獲取 access_token
    4. 使用 access_token 去調取 github 提供的介面 獲取使用者資訊

程式碼

/**
 * 傳送請求(也可以直接使用guzzle)
 *
 * @param string $url      請求地址
 * @param array $data      請求資料
 * @param array $headers   請求頭
 * @return string|array
 */
function sendRequest($url, $data = [], $headers = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if (!empty($data)) {
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $response = curl_exec($ch) ? curl_multi_getcontent($ch) : '';
    curl_close($ch);
    return $response;
}

// 如果使用者同意登陸, github 就會返回到 callback.php 並攜帶一個code引數
// 此時只需要使用這個 code 去獲取 access_token, 然後在使用 access_token 獲取使用者資訊
$url        = "https://github.com/login/oauth/access_token";
$app_id     = "your github oauth app client_id";
$app_secret = "your github oauth app client_secret";

// 組合請求引數
$code   = $_GET['code'];
$params = [
    'client_id'     => $app_id,
    'client_secret' => $app_secret,
    'code'          => $code,
];

// 傳送請求並獲取響應資訊
$response = sendRequest($url, $params, ['Accept: application/json']);
$response = json_decode($response, true);

// 如果有響應資訊, 說明請求成功
if (!empty($response['access_token'])) {
    // 請求成功,使用 access_token 獲取使用者資訊
    $access_token = $response['access_token'];
    $url = "https://api.github.com/user";

    // 傳送請求,調取github API 獲取使用者資訊
    $userInfo =  sendRequest($url,[],[
        "Accept: application/json",
        "User-Agent: ilearn",  // 此處(ilearn)是填寫應用名稱 或者 github使用者名稱
        "Authorization:token {$access_token}"
    ]);

    exit($userInfo);
}

// 如果登陸失敗就列印錯誤資訊
echo "<p>登陸失敗</p></pre>";
var_dump($response);
exit("</pre>");

如果不想自己寫,也可以使用這個大神寫的擴充套件包

https://github.com/overtrue/laravel-social...

最後

如果你真的想學習如何接入的話, 就自己動手敲程式碼試一遍,別人的始終是別人的,

紙上得來終覺淺,絕知此事要恭行

在這裡順便吐槽一下,微博登入,qq登入,對於開發者來說,使用者體驗極差, 註冊一個賬號真的是費勁,文件寫的我感覺比看英文文件還困難...

相關文章