Github 创建oauth应用,并获取用户信息

原创
2017/05/09 16:26
阅读数 3K

第一步

创建GitHub的应用 : https://github.com/settings/applications/new

填写好应用名称,主页url,介绍,回调url保存即可,系统会分配给我们client_id和client_secret

第二步,写代码咯,有一点需要注意的是,获取用户信息需要带上指定的user-agent,否则接口会返回403哦

$this->curl->http_header('User-Agent', 'https://api.github.com/meta');
 

<?php

/**
 * Created by PhpStorm.
 * User: lf
 * Date: 2017/5/8
 * Time: 16:20
 */
class  Github_callback extends CI_Controller
{


    private $client_id = 'your github application client_id';
    private $client_secret = 'your github application client_secret';
    private $auth_url = 'https://github.com/login/oauth/authorize?';//授权地址
    private $token_url = 'https://github.com/login/oauth/access_token?';//获取access_token地址
    private $user_url = 'https://api.github.com/user?';//获取用户信息地址
    public function __construct()
    {
        parent::__construct();
    }

    /*
     * 发起授权demo and  授权回调
     */
    public function index()
    {
        $code = $this->input->get('code');
        if (!$code) {
            $params = ['client_id' => $this->client_id, 'scope' => 'user'];
            $jump_url = $this->auth_url . http_build_query($params);
            header('Location:' . $jump_url);
            exit;
        } else {
            $token_params = [
                'client_id' => $this->client_id,
                'client_secret' => $this->client_secret,
                'code' => $code
            ];
            $access_token_url = $this->token_url . http_build_query($token_params);
            $access_token = $this->curl_get($access_token_url);
            $user_url = $this->user_url . $access_token;
            $user_info = $this->curl_get($user_url);
            $user_data = json_decode($user_info, true);
            $this->handle_github_user($user_data);
        }
    }



    private function curl_get($url)
    {
        $this->load->library('Curl');
        $this->curl->http_header('User-Agent', 'https://api.github.com/meta');
        $resullt = $this->curl->simple_get($url);
        return $resullt;
    }


    /**
     * 处理用户逻辑/入库或者redis
     * @param $user_data
     * @return bool
     */
    private function handle_github_user($user_data)
    {

        $this->load->driver('cache', array('adapter' => 'redis'));
        $cache_key = 'github_user_id_';
        $user_info = $this->cache->get($cache_key . $user_data['id']);
        if (!$user_info && $user_data && $user_data['id']) {
            $this->cache->save($cache_key . $user_data['id'], $user_data);
        } else {
            return false;
        }
        return true;
    }


}
展开阅读全文
加载中
点击加入讨论🔥(2) 发布并加入讨论🔥
打赏
2 评论
0 收藏
0
分享
返回顶部
顶部