需要填写重定向地址, 与之后代码中重定向地址要相同
# 一个点击跳转的按钮即可
/** * 登录/注册 */ public function signin(Request $request) { $type = $request->get('type'); if ($type == 'twitter') { // 生成跳转到twitter授权页面的url, 重定向到授权页面 $twitterModel = New NewTwitterLogin() $uri = $twitterModel->createOauthLink(); return redirect()->away($url); } } /** * twitter 回调接口 */ public function callBackTwitter() { // 获取重定向链接中的code $code = $request->get('code'); $twitter = new NewTwitterLogin(); // 用code 获取 access_token $token = $twitter->getAccessToken($code); // 用 access_token 获取用户信息 $userInfo = $twitter->getUserInfo($token); // 处理自己的登录/注册逻辑 }
private $key = '*****'; private $secret = '*********'; // oauth 2.0 使用 private $clientId = '********'; private $clientSecret = '*******'; private $redirect_uri = '*****' // 重定向url // 创建链接 public function createOauthLink() { $url = "https://twitter.com/i/oauth2/authorize?response_type=code&client_id={$this->clientId}&redirect_uri={$this->redirect_uri}&scope=users.read%20tweet.read&state=twitter&code_challenge=challenge&code_challenge_method=plain"; return $url; } /** * 获取access_token * * @param string code 登录授权后返回用户code */ public function getAccessToken($code) { $url = 'https://api.twitter.com/2/oauth2/token'; // Authorization Basic $basic = base64_encode($this->clientId . ':' . $this->clientSecret); $header = [ "Content-Type: application/x-www-form-urlencoded", "Authorization: Basic $basic", ]; $data = [ 'code' => $code, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->redirect_uri, 'code_verifier' => 'challenge', ]; $data = http_build_query($data); $res = $this->curlMethod($url, $header, $data); return $res['access_token']; } /** * 获取用户信息 */ public function getUserInfo($token) { $uri = 'https://api.twitter.com/2/users/me'; $header = [ "Authorization: Bearer $token", ]; $res = $this->curlMethod($uri, $header, [], 'GET'); return $res['data']; } public function curlMethod($uri, $header, $data = [], $method = 'POST', $json = true) { $curl = curl_init(); if ($data && is_array($data) && $json) { $data = json_encode($data); } curl_setopt_array($curl, array( CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, // CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => $header, )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); return json_decode($response, true); } }