Twitter第三方登录

Twitter第三方登录

Laravel PHP7.3

默认已经注册开发者账号 并拿到第三方登录的key

这里推荐购买国外邮箱注册(国外信息注册),国内邮箱注册很容易被封

前端登录界面首页

<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方式后端调用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){
        //已登录用户跳转登录和注册页时跳转首页
        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';
         
        //参数,此次请求中的除了oauth_signature以外的所有参数按照字母顺序升序排列,如果参数名相同,那么按照参数值的字母顺序升序排列。
        $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)的构成:HttpMethod&url&参数。(一定是先各自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的值

        //跳转授权
        $url2 = 'https://api.twitter.com/oauth/authorize?'.$oautoken;

        echo "<script language='javascript' type='text/javascript'>"; 
        echo "window.location.href = '$url2'"; 
        echo "</script>"; 
     
    }

    //获取用户信息,返回用户的id和name以及授权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?';

        //参数,此次请求中的除了oauth_signature以外的所有参数按照字母顺序升序排列,如果参数名相同,那么按照参数值的字母顺序升序排列。
        $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)的构成:HttpMethod&url&参数。(一定是先各自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;

    }

    //获取用户详细信息,包括头像和发布的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;
        //发送请求
        $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);
        //对返回数据进行解码成数组形式
        $userInfoDetails = json_decode($json,true);
        //取出数组中需要的邮箱信息并返回
        $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;
    }   

    
}

此处已经调用打开twitter界面并输入账号登录 完成这些操作后 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 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'] ?? '';
        //已登录用户跳转登录和注册页时跳转首页
        if(isset($this->data['member']['memberId'])){
            return redirect("/member/my-info.html");
        }else{
            return redirect("/signin.html");
        }   
 }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容