在網站上使用 Discord 登入
網頁工程師 • HTML、CSS、PHP | 了解更多請前往 https://haer0248.me/about-me

撰寫語言:PHP (Hypertext Preprocessor)
本文需要:Discord Bot
建立教學:建立屬於自己的-discord-bot

需要以下兩個資料,這篇將會使用 733372339034783814 (client id)與 jZj-dgH4Lq60SaQjBWerORvNpZOjfvD_ (token) 當作範例。
文章撰寫完畢後移除

請注意:這個 token 可以讓其他人存取機器人,請不要外流。

撰寫前請注意:請將您的登入網址輸入到 Discord Developers Portal 頁面的 OAuth2 中的 Redirects,完成後記得保存

程式碼

<?php
ini_set('max_execution_time', 300);
session_start();

define('OAUTH2_CLIENT_ID', '733372339034783814'); //請輸入自己的 CLIENT ID
define('OAUTH2_CLIENT_SECRET', 'jZj-dgH4Lq60SaQjBWerORvNpZOjfvD_'); //請輸入自己的 CLIENT SECRET
define('LOGIN_URL', 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); //自動取得登入網址,需要變更請自行變更

$authorizeURL = 'https://discord.com/api/oauth2/authorize';
$tokenURL = 'https://discord.com/api/oauth2/token';
$apiURLBase = 'https://discord.com/api/users/@me/guilds';

if(get('action') == 'login') {

  $params = array(
    'client_id' => OAUTH2_CLIENT_ID,
    'redirect_uri' => LOGIN_URL,
    'response_type' => 'code',
    'scope' => 'identify guilds'
  );

  header('Location: https://discord.com/api/oauth2/authorize' . '?' . http_build_query($params));
  die();
}

if(get('code')) {
  $token = apiRequest($tokenURL, array(
    "grant_type" => "authorization_code",
    'client_id' => OAUTH2_CLIENT_ID,
    'client_secret' => OAUTH2_CLIENT_SECRET,
    'redirect_uri' => LOGIN_URL,
    'code' => get('code')
  ));
  $logout_token = $token->access_token;
  $_SESSION['access_token'] = $token->access_token;
  header('Location: ' . $_SERVER['PHP_SELF']);
}

if(session('access_token')) {
  $user = apiRequest($apiURLBase);
  echo '<h3>已登入</h3>';
  echo '<h4>歡迎, ' . $user->username . '</h4>';
  echo '<pre>';
    print_r($user);
  echo '</pre>';
  echo '<p><a href="?action=logout">登出</a></p>';
} else {
  echo '<p><a href="?action=login">登入</a></p>';
}

if(get('action') == 'logout') {
  session_destroy();
  header('Location: ' . $_SERVER['PHP_SELF']);
}

function apiRequest($url, $post=FALSE, $headers=array()) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  $response = curl_exec($ch);


  if($post)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

  $headers[] = 'Accept: application/json';

  if(session('access_token'))
    $headers[] = 'Authorization: Bearer ' . session('access_token');

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($ch);
  return json_decode($response);
}

function get($key, $default=NULL) {
  return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}

function session($key, $default=NULL) {
  return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}

?> 

想要測試看看嗎?

https://tools.haer0248.me/discord-login.php