Dev.../>

github第三方登录

PHP 2018-11-01 浏览(2018 评论(0

注册github application

首先登录github账号,进入settings->Developer Settings 创建你的New OAuth App

第一:进入Settings

图片描述

第二:进入Developer Settings

图片描述

第三:创建:New OAuth App

图片描述

代码部分:

client_id和client_secret改成自己的就可以了

//登录
public function actionGithubLogin(){
        $redirect_uri = "http://www.hxinq.com/site/callback";
        $client_id = "xxxxxxxxxxxx";
        $_url = "https://github.com/login/oauth/authorize?client_id=".$client_id."&state=1&redirect_uri=".$redirect_uri;
        $this->redirect($_url);
        //echo "<pre>";
        //print_r($result);exit;
}

//回调
public function actionCallback()
{
    $code = $_GET['code'];
    $client_id = "xxxxxxxxxx";
    $client_secret = "xxxxxxxxxxxxxxxxxxxxxxxx";
    $_url = "https://github.com/login/oauth/access_token?client_id=".$client_id."&client_secret=".$client_secret."&code=".$code;
    $result = file_get_contents($_url);
    $data = [];
    parse_str($result,$data);//字符串解析到变量
    $access_token = $data['access_token'];
    if($access_token){
            $info_url = "https://api.github.com/user?access_token=".$access_token;
            $res = json_decode($this->curl($info_url));
            echo "<pre>";
            print_r($res);exit;
    }else{
            $this->redirect("http://www.hxinq.com");
    }

}


//CURL 设置请求头和响应头(github API接口需要)
public function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        // 设置请求头, 有时候需要,有时候不用,看请求网址是否有对应的要求
        $header[] = "Content-type: application/x-www-form-urlencoded";
        $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        // 返回 response_header, 该选项非常重要,如果不为 true, 只会获得响应的正文
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 是否不需要响应的正文,为了节省带宽及时间,在只需要响应头的情况下可以不要正文
        curl_setopt($ch, CURLOPT_NOBODY, false);
        // 使用上面定义的$user_agent
        curl_setopt($ch, CURLOPT_USERAGENT,$user_agent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        curl_setopt($ch, CURLOPT_URL, $url);
        $res =  curl_exec($ch);
        // 获得响应结果里的:头大小
        //$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        // 根据头大小去获取头信息内容
        //$header = substr($res, 0, $headerSize);
        curl_close($ch);
        return $res;
}

打赏

如果此文对你有所帮助,请随意打赏鼓励作者^_^

黄信强博客