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

第一步

创建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;
    }


}

转载于:https://my.oschina.net/u/130894/blog/895882

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值