Twitter第三方登錄
Laravel PHP7.3
默認(rèn)已經(jīng)注冊開發(fā)者賬號 并拿到第三方登錄的key
這里推薦購買國外郵箱注冊(國外信息注冊),國內(nèi)郵箱注冊很容易被封
前端登錄界面首頁
<li class="sc-tw">
<a class="animate" href="?twitter_login">
<img src="/images/login-btn-tw.png" alt="Twitter" title="Login With Twitter">
</a>
</li>
@if(isset($twitteruid))
<script type="text/javascript">
window.onload=function(){
var twitteruid = '{!!$twitteruid!!}';
var twitter = '{!!$twitter!!}';
if(twitteruid){
$.post('/ajax/SocilaAuthLogin',{
data:{userdata:twitter,type:'twitterLogin'},
},function(data){
var data=JSON.parse(data);
art.dialog({
title:'{{$LANG['PUBLIC']['TIPS']}}',
icon: data['icon'],
content:data['tips'],
okVal:'ok'
});
window.location.reload();
});
}
}
</script>
@endif
通過get方式后端調(diào)用twitter登錄界面
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use App\Http\Models\Website\TwitterThirdLogin;
use Route;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use App\Http\Models\Website\Basesite;
use Illuminate\Support\Facades\Input;
use Storage;
class HomeController extends Controller
{
public function signin(request $request){
//已登錄用戶跳轉(zhuǎn)登錄和注冊頁時跳轉(zhuǎn)首頁
if(isset($this->data['member']['memberId'])){
return redirect("/");
}
if (isset($_GET['twitter_login'])){
$twitter_third_login = new TwitterThirdLogin();
$result = $twitter_third_login->bind();
}
if(isset($_SESSION['twitter_userid'])){
$twitter['userid'] = $_SESSION['twitter_userid'];
$twitter['username'] = $_SESSION['twitter_username'];
$twitter['twitter_user_email'] = $_SESSION['twitter_user_email'];
$this->data['twitter']=json_encode($twitter,true);
$this->data['twitteruid']=$_SESSION['twitter_userid'];
}
return view('u7buy.signin')
->with($this->data);
}
}
加入twitter主要功能塊兒
<?php
// +----------------------------------------------------------------------
// | TWITTER第三方登陸
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 All rights reserved.
// +----------------------------------------------------------------------
// | Author: HueyYao
// +----------------------------------------------------------------------
//----------------------------------
// Twitter第三方登陸
//----------------------------------
namespace App\Http\Models\Website;
class TwitterThirdLogin
{
private $consumerKey = 'XXXXXXXXX';//key
private $consumerSecret = 'XXXXXXXXX';//Secretkey
//打開綁定界面
function bind(){
$time = time();
$oauth_consumer_key = $this->consumerKey;
$oauth_nonce=$time . rand();
$oauth_signature_method="HMAC-SHA1";
$oauth_timestamp=$time;
$oauth_version="1.0";
//請求方法,必需全部大寫。
$httpMethod = 'GET';
//url,必需全部小寫。
$url = 'https://twitter.com/oauth/request_token';
//參數(shù),此次請求中的除了oauth_signature以外的所有參數(shù)按照字母順序升序排列,如果參數(shù)名相同,那么按照參數(shù)值的字母順序升序排列。
$params = "oauth_consumer_key={$oauth_consumer_key}&oauth_nonce={$oauth_nonce}&oauth_signature_method={$oauth_signature_method}&oauth_timestamp={$oauth_timestamp}&oauth_version={$oauth_version}";
//簽名串(text)的構(gòu)成:HttpMethod&url&參數(shù)。(一定是先各自urlencode后再用‘&’相連起來)
$signature_text = urlencode($httpMethod) . '&' . urlencode($url) . '&' . urlencode($params);
$key = $this->consumerSecret . '&' ;
$oauth_signature = $this->get_signature($signature_text, $key);
$oauth_signature = urlencode($oauth_signature);
$httpHeader = [
'Authorization: OAuth ' .
'oauth_consumer_key='.$oauth_consumer_key .
',oauth_nonce='.$oauth_nonce .
',oauth_signature_method='.$oauth_signature_method .
',oauth_timestamp='.$oauth_timestamp .
',oauth_version='.$oauth_version .
',oauth_signature='.$oauth_signature
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
if (false === $ret) {
$ret = curl_errno($ch);
}
curl_close($ch);
$oautoken = $ret;
//判斷是否未獲取到ret的值
//跳轉(zhuǎn)授權(quán)
$url2 = 'https://api.twitter.com/oauth/authorize?'.$oautoken;
echo "<script language='javascript' type='text/javascript'>";
echo "window.location.href = '$url2'";
echo "</script>";
}
//獲取用戶信息,返回用戶的id和name以及授權(quán)token
function userInfo($oauth_token,$oauth_verifier){
$time = time();
$oauth_consumer_key = $this->consumerKey;
$oauth_nonce=$time . rand();
$oauth_signature_method="HMAC-SHA1";
$oauth_timestamp=$time;
$oauth_version="1.0";
//請求方法,必需全部大寫。
$httpMethod = 'GET';
//url,必需全部小寫。
$url = 'https://api.twitter.com/oauth/access_token?';
//參數(shù),此次請求中的除了oauth_signature以外的所有參數(shù)按照字母順序升序排列,如果參數(shù)名相同,那么按照參數(shù)值的字母順序升序排列。
$params = "oauth_consumer_key={$oauth_consumer_key}&oauth_nonce={$oauth_nonce}&oauth_signature_method={$oauth_signature_method}&oauth_timestamp={$oauth_timestamp}&oauth_verifier={$oauth_verifier}&oauth_token={$oauth_token}&oauth_version={$oauth_version}";
$signature = $url.$params;
//簽名串(text)的構(gòu)成:HttpMethod&url&參數(shù)。(一定是先各自urlencode后再用‘&’相連起來)
$signature_text = urlencode($httpMethod) . '&' . urlencode($url) . '&' . urlencode($params);
$key = $this->consumerSecret . '&' ;
$oauth_signature = $this->get_signature($signature_text, $key);
$oauth_signature = urlencode($oauth_signature);
$httpHeader = [
'Authorization: OAuth ' .
'oauth_consumer_key='.$oauth_consumer_key .
',oauth_nonce='.$oauth_nonce .
',oauth_signature_method='.$oauth_signature_method .
',oauth_timestamp='.$oauth_timestamp .
',oauth_verifier='.$oauth_verifier .
',oauth_token='.$oauth_token .
',oauth_version='.$oauth_version .
',oauth_signature='.$oauth_signature
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
if (false === $ret) {
$ret = curl_errno($ch);
}
curl_close($ch);
$result_arr = explode("&",$ret);
$oauth_token = str_replace('oauth_token=','',$result_arr['0']);
$oauth_token_secret = str_replace('oauth_token_secret=','',$result_arr['1']);
$twitter_userid = str_replace('user_id=','',$result_arr['2']);
$twitter_username = str_replace('screen_name=','',$result_arr['3']);
$userEmail = $this->userInfoDetails($oauth_token,$oauth_token_secret,$twitter_userid,$twitter_username);
$rets['ret'] = $ret;
$rets['userEmail'] = $userEmail;
return $rets;
}
//獲取用戶詳細信息,包括頭像和發(fā)布的twitter文章和郵箱等信息,目前取郵箱
function userInfoDetails($oauth_token,$oauth_token_secret,$twitter_userid,$twitter_username){
$oauth_access_token = $oauth_token;
$oauth_access_token_secret = $oauth_token_secret;
$consumer_key = $this->consumerKey;
$consumer_secret = $this->consumerSecret;
$twitter_timeline = "statuses/retweets_of_me"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
$account = "account/verify_credentials";// account/verify_credentials account/settings
$endLine = $account;
//create request
//When set to true email will be returned in the user objects as a string. If the user does not have an email address on their account, or if the email address is not verified, null will be returned.————————include_email = true
$request = array(
'screen_name'=> $twitter_username,
'count' => '3',
'include_email'=>'true'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method'=> 'HMAC-SHA1',
'oauth_token'=> $oauth_access_token,
'oauth_timestamp'=> time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = $this->buildBaseString("https://api.twitter.com/1.1/$endLine.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
//發(fā)送請求
$header = array($this->buildAuthorizationHeader($oauth), 'Expect:');
$options = array(
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/$endLine.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
//對返回數(shù)據(jù)進行解碼成數(shù)組形式
$userInfoDetails = json_decode($json,true);
//取出數(shù)組中需要的郵箱信息并返回
$userEmail = $userInfoDetails['email'];
return $userEmail;
}
//加密算法
function get_signature($str, $key){
$signature = "";
if (function_exists('hash_hmac')){
$signature = base64_encode(hash_hmac("sha1", $str, $key, true));
}else{
$blocksize = 64;
$hashfunc = 'sha1';
if (strlen($key) > $blocksize)
{
$key = pack('H*', $hashfunc($key));
}
$key = str_pad($key,$blocksize,chr(0x00));
$ipad = str_repeat(chr(0x36),$blocksize);
$opad = str_repeat(chr(0x5c),$blocksize);
$hmac = pack(
'H*',$hashfunc(
($key^$opad).pack(
'H*',$hashfunc(
($key^$ipad).$str
)
)
)
);
$signature = base64_encode($hmac);
}
return $signature;
}
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
}
此處已經(jīng)調(diào)用打開twitter界面并輸入賬號登錄 完成這些操作后 twitter按照后臺設(shè)置的回調(diào)鏈接進行訪問
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use App\Http\Models\Website\TwitterThirdLogin;
use Route;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use App\Http\Models\Website\Basesite;
use Illuminate\Support\Facades\Input;
use Storage;
class HomeController extends Controller
{
public function c2c_twitter_login(request $request){
$LANG=$this->data['LANG'];
$LANG=$this->inclueLang($LANG,'signin');
$LANG=$this->inclueLang($LANG,'signup');
$LANG=$this->inclueLang($LANG,'game');
$this->data['LANG']=$LANG;
$oauth_token=$_GET["oauth_token"];
$oauth_verifier=$_GET["oauth_verifier"];
$twitter_third_login = new TwitterThirdLogin();
$result = $twitter_third_login->userInfo($oauth_token,$oauth_verifier);
$result_arr = explode("&",$result['ret']);
$_SESSION['twitter_userid'] = str_replace('user_id=','',$result_arr['2']);
$_SESSION['twitter_username'] = str_replace('screen_name=','',$result_arr['3']);
$_SESSION['twitter_user_email'] = $result['userEmail'] ?? '';
//已登錄用戶跳轉(zhuǎn)登錄和注冊頁時跳轉(zhuǎn)首頁
if(isset($this->data['member']['memberId'])){
return redirect("/member/my-info.html");
}else{
return redirect("/signin.html");
}
}
}