CI框架 QQ接口(第三方登录接口PHP版)

本帖内容较多,大部分都是源码,要修改的地方只有一个,其他只要复制过去,就可以完美运行。本帖主要针对CI框架,不用下载SDK,按我下面的步骤,建文件,复制代码就可以了。10分钟不要,接口就可完成。
第一步:申请APP ID,APP KEY,申请地址:http://connect.opensns.qq.com/
验证通过后:会得到APP ID,APP KEY。这是你用个文件把这些信息保持下来,免得用的时候有要上网去查,记录在本地记事本里,方便,用的时候打开就可以。如下:
APP ID:101091331
APP KEY:7cb032049f2c900fea509424e614a979
回调地址:http://test.com

第二步:如果你的系统没有安装curl,请先安装curl。
怎么知道本地系统是否安装了curl呢,方法如下:
1.在web服务器目录( Ubuntu下的通常为 /var/www )新建crul.php文件
2.编辑文件,键入下面一行代码:
  <?php phpinfo(); ?>
3.保存文件
4.打开浏览器,浏览该网页。(例如:http://localhost/curl.php)
5.搜索"curl",如果没搜到就证明没安装curl。

下面是安装方法:
打开终端,输入下面的命令:
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
再重启apache:
sudo /etc/init.d/apache2 restart
这样curl就安装好了,打开你刚才的那个页面,搜一下curl,就可以看到了curl了,这表示已经安装成功,很简单吧。

如果还是没有,编辑你的php.ini文件,我的phpini.php文件在/etc/php5/apache2/php.ini,估计你的也差不多是在这个位置,去找找看,找到后,打开这个文件,在最后加上一行:
extension=curl.so

保存文件后重启Apache服务器,再打开页面,就会出现curl了。

第三步:代码
注:腾讯提供了SDK,可以在官网下载:下载地址:http://wiki.connect.qq.com/sdk%E4%B8%8B%E8%BD%BD,如果不是CI框架,估计下载下来就可以用了,CI框架调用规则不同,所以要做修改,如果是CI框架下开发QQ登录接口,就不用下载SDK了,用我下面的代码,下面正式上代码,完整的代码。

代码步骤:
1.打开application/config/constants.php文件
写入如下代码:
/*qq登陆*/
define('GET_AUTH_CODE_URL', "https://graph.qq.com/oauth2.0/authorize");
define('GET_ACCESS_TOKEN_URL' , "https://graph.qq.com/oauth2.0/token");
define('GET_OPENID_URL' , "https://graph.qq.com/oauth2.0/me");
保存

2.打开application文件夹,在application下新建一个文件夹isetting,在isetting下建一个qq_setting.php文件,
打开qq_setting.php文件,输入如下代码:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
     * @qq互联配置信息
     * 默认开启get_user_info模块
     * **/

$config['inc_info'] = array(
        array (
                'appid' => '101091331',
                'appkey' => '7cb032049f2c900fea509424e614a979',
                'callback' => 'http://test.com'
              ),
        array (
                'get_user_info' => '1',
                'add_topic' => '0',
                'add_one_blog' => '0',
                'add_album' => '0',
                'upload_pic' => '0',
                'list_album' => '0',
                'add_share' => '0',
                'check_page_fans' => '0',
                'add_t' => '0',
                'add_pic_t' => '0',
                'del_t' => '0',
                'get_repost_list' => '0',
                'get_info' => '0',
                'get_other_info' => '0',
                'get_fanslist' => '0',
                'get_idollist' => '0',
                'add_idol' => '0',
                'del_idol' => '0',
                'get_tenpay_addr' => '0',
              )
    );
保存
说明:你需要把appid,appkey对应的键值修改成你刚刚申请的appid,appkey值,callback为回调地址(所谓回调地址就是登录成功后,返回到哪个页面),callback的值写你申请的时候做验证的那个地址。

3.打开application下的libraries文件,新建一个文件夹tencent,在tencent里面新建一个文件oauth.php,打开这个文件,复制下面的代码进去:

<?php

class Oauth
    {
         /**
        * combineURL
        * 拼接url
        * @param string $baseURL   基于的url
        * @param array  $keysArr   参数列表数组
        * @return string           返回拼接的url
        */
        
        private $APIMap;
        
        public function __construct() {
            /*以下部分为获取第三方qq登陆资料*/
        //初始化APIMap
        /*
         * 加#表示非必须,无则不传入url(url中不会出现该参数), "key" => "val" 表示key如果没有定义则使用默认值val
         * 规则 array( baseUrl, argListArr, method)
         */
        $this->APIMap = array(
        
            
            /*                       qzone                    */
            "add_blog" => array(
                "https://graph.qq.com/blog/add_one_blog",
                array("title", "format" => "json", "content" => null),
                "POST"
            ),
            "add_topic" => array(
                "https://graph.qq.com/shuoshuo/add_topic",
                array("richtype","richval","con","#lbs_nm","#lbs_x","#lbs_y","format" => "json", "#third_source"),
                "POST"
            ),
            "get_user_info" => array(
                "https://graph.qq.com/user/get_user_info",
                array("format" => "json"),
                "GET"
            ),
            "add_one_blog" => array(
                "https://graph.qq.com/blog/add_one_blog",
                array("title", "content", "format" => "json"),
                "GET"
            ),
            "add_album" => array(
                "https://graph.qq.com/photo/add_album",
                array("albumname", "#albumdesc", "#priv", "format" => "json"),
                "POST"
            ),
            "upload_pic" => array(
                "https://graph.qq.com/photo/upload_pic",
                array("picture", "#photodesc", "#title", "#albumid", "#mobile", "#x", "#y", "#needfeed", "#successnum", "#picnum", "format" => "json"),
                "POST"
            ),
            "list_album" => array(
                "https://graph.qq.com/photo/list_album",
                array("format" => "json")
            ),
            "add_share" => array(
                "https://graph.qq.com/share/add_share",
                array("title", "url", "#comment","#summary","#images","format" => "json","#type","#playurl","#nswb","site","fromurl"),
                "POST"
            ),
            "check_page_fans" => array(
                "https://graph.qq.com/user/check_page_fans",
                array("page_id" => "314416946","format" => "json")
            ),
            /*                    wblog                             */

"add_t" => array(
                "https://graph.qq.com/t/add_t",
                array("format" => "json", "content","#clientip","#longitude","#compatibleflag"),
                "POST"
            ),
            "add_pic_t" => array(
                "https://graph.qq.com/t/add_pic_t",
                array("content", "pic", "format" => "json", "#clientip", "#longitude", "#latitude", "#syncflag", "#compatiblefalg"),
                "POST"
            ),
            "del_t" => array(
                "https://graph.qq.com/t/del_t",
                array("id", "format" => "json"),
                "POST"
            ),
            "get_repost_list" => array(
                "https://graph.qq.com/t/get_repost_list",
                array("flag", "rootid", "pageflag", "pagetime", "reqnum", "twitterid", "format" => "json")
            ),
            "get_info" => array(
                "https://graph.qq.com/user/get_info",
                array("format" => "json")
            ),
            "get_other_info" => array(
                "https://graph.qq.com/user/get_other_info",
                array("format" => "json", "#name", "fopenid")
            ),
            "get_fanslist" => array(
                "https://graph.qq.com/relation/get_fanslist",
                array("format" => "json", "reqnum", "startindex", "#mode", "#install", "#sex")
            ),
            "get_idollist" => array(
                "https://graph.qq.com/relation/get_idollist",
                array("format" => "json", "reqnum", "startindex", "#mode", "#install")
            ),
            "add_idol" => array(
                "https://graph.qq.com/relation/add_idol",
                array("format" => "json", "#name-1", "#fopenids-1"),
                "POST"
            ),
            "del_idol" => array(
                "https://graph.qq.com/relation/del_idol",
                array("format" => "json", "#name-1", "#fopenid-1"),
                "POST"
            ),
            /*                           pay                          */

"get_tenpay_addr" => array(
                "https://graph.qq.com/cft_info/get_tenpay_addr",
                array("ver" => 1,"limit" => 5,"offset" => 0,"format" => "json")
            )
        );
        
        }

//登陆
         public function check_login()
         {
             if(isset($_SESSION['qq']['state']) && $_GET['state'] && ($_SESSION['qq']['state'] == $_GET['state']))
             {
                 return 'true';
             }
             else
             {
                 return 'false';
             }
         }

public function qq_login()
        {
            $CI = &get_instance();
            $CI->config->load('isetting/qq_setting');
            $setting = $CI->config->item('inc_info');
            $appid = $setting[0]['appid'];
            $callback = $setting[0]['callback'];
            $scope = '';
            foreach ($setting[1] as $key=>$val)
            {
                if($val === '1')
                {
                    $scope .= $key . ',';
                }
            }
            $scope = trim(rtrim($scope,','));

//-------生成唯一随机串防CSRF攻击
            $state = md5(uniqid(rand(), TRUE));
            $_SESSION['qq']['state'] = $state;

//-------构造请求参数列表
            $keysArr = array(
                "response_type" => "code",
                "client_id" => $appid,
                "redirect_uri" => $callback,
                "state" => $state,
                "scope" => $scope
            );
            $login_url =  $this->combineURL(GET_AUTH_CODE_URL, $keysArr);
            header("Location:$login_url");
        }
        
        //callback回调方法
        public function qq_callback()
        {
            $CI = &get_instance();
            $CI->config->load('isetting/qq_setting');
            $setting = $CI->config->item('inc_info');
            $state = $_SESSION['qq']['state'];
            //--------验证state防止CSRF攻击
            if($_GET['state'] != $state){
                echo "<script>alert('QQ第三方登陆失败');</script>";
                redirect('/login','location',301);
            }

//-------请求参数列表
            $keysArr = array(
                "grant_type" => "authorization_code",
                "client_id" => $setting[0]['appid'],
                "redirect_uri" => $setting[0]['callback'],
                "client_secret" => $setting[0]['appkey'],
                "code" => $_GET['code']
            );

//------构造请求access_token的url
            $token_url = $this->combineURL(GET_ACCESS_TOKEN_URL, $keysArr);
            $response = $this->get_contents($token_url);

$params = array();
            parse_str($response, $params);

$_SESSION['qq']['access_token'] = $params["access_token"];
            
            $access_token = $params["access_token"];
            $openid= $this->get_openid();
            
            //进入主页
            //获取用户信息
            $_data = $this->qq_get_user($access_token,$openid);
            
            redirect('/','location',301);
        }
    
        //注销
        public function qq_logout()
        {
            
        }
        
        
        public function combineURL($baseURL,$keysArr){
            $combined = $baseURL."?";
            $valueArr = array();

foreach($keysArr as $key => $val){
                $valueArr[] = "$key=$val";
            }

$keyStr = implode("&",$valueArr);
            $combined .= ($keyStr);

return $combined;
        }
        
        /**
         * get_contents
         * 服务器通过get请求获得内容
         * @param string $url       请求的url,拼接后的
         * @return string           请求返回的内容
         */
          public function get_contents($url)
          {
            if (ini_get("allow_url_fopen") == "1") {
                $response = file_get_contents($url);
            }else{
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_URL, $url);
                $response =  curl_exec($ch);
                curl_close($ch);
            }

//-------请求为空
            if(empty($response)){
                echo "<script>alert('QQ第三方登陆失败');</script>";
                redirect('/login','location',301);
            }
            return $response;
        }
        
        public function get_openid()
        {

//-------请求参数列表
            $keysArr = array(
                "access_token" => $_SESSION['qq']['access_token']
            );

$graph_url = $this->combineURL(GET_OPENID_URL, $keysArr);
            $response = $this->get_contents($graph_url);

//----检测错误是否发生
            if(strpos($response, "callback") !== false)
            {

$lpos = strpos($response, "(");
                $rpos = strrpos($response, ")");
                $response = substr($response, $lpos + 1, $rpos - $lpos -1);
            }

$user = json_decode($response);
            //------记录openid
            $_SESSION['qq']['openid'] = $user->openid;
            return $user->openid;
        }
        
        
        
        
        
        /**
        * _call
        * 魔术方法,做api调用转发
        * @param string $name    调用的方法名称
        * @param array $arg      参数列表数组
        * @since 5.0
        * @return array          返加调用结果数组
        */
        public function __call($name,$arg){
        //如果APIMap不存在相应的api
        if(empty($this->APIMap[$name])){
            echo "<script>alert('获取资料出错');</script>";
            redirect('/login','location',301);
        }

//从APIMap获取api相应参数
        $baseUrl = $this->APIMap[$name][0];
        $argsList = $this->APIMap[$name][1];
        $method = isset($this->APIMap[$name][2]) ? $this->APIMap[$name][2] : "GET";

if(empty($arg)){
            $arg[0] = null;
        }

//对于get_tenpay_addr,特殊处理,php json_decode对\xA312此类字符支持不好
        if($name != "get_tenpay_addr"){
            $response = json_decode($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
            $responseArr = $this->objToArr($response);
        }else{
            $responseArr = $this->simple_json_parser($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
        }

//检查返回ret判断api是否成功调用
        if($responseArr['ret'] == 0){
            return $responseArr;
        }else{
            echo "<script>alert('第三方登陆失败')</script>";
            redirect('/','location',301);
        }

}
    
    //调用相应api
    private function _applyAPI($arr, $argsList, $baseUrl, $method){
        $pre = "#";
        $keysArr = $this->keysArr;

$optionArgList = array();//一些多项选填参数必选一的情形
        foreach($argsList as $key => $val){
            $tmpKey = $key;
            $tmpVal = $val;

if(!is_string($key)){
                $tmpKey = $val;

if(strpos($val,$pre) === 0){
                    $tmpVal = $pre;
                    $tmpKey = substr($tmpKey,1);
                    if(preg_match("/-(\d$)/", $tmpKey, $res)){
                        $tmpKey = str_replace($res[0], "", $tmpKey);
                        $optionArgList[$res[1]][] = $tmpKey;
                    }
                }else{
                    $tmpVal = null;
                }
            }

//-----如果没有设置相应的参数
            if(!isset($arr[$tmpKey]) || $arr[$tmpKey] === ""){

if($tmpVal == $pre){//则使用默认的值
                    continue;
                }else if($tmpVal){
                    $arr[$tmpKey] = $tmpVal;
                }else{
                    if($v = $_FILES[$tmpKey]){

$filename = dirname($v['tmp_name'])."/".$v['name'];
                        move_uploaded_file($v['tmp_name'], $filename);
                        $arr[$tmpKey] = "@$filename";

}else{
                        $this->error->showError("api调用参数错误","未传入参数$tmpKey");
                    }
                }
            }

$keysArr[$tmpKey] = $arr[$tmpKey];
        }
        //检查选填参数必填一的情形
        foreach($optionArgList as $val){
            $n = 0;
            foreach($val as $v){
                if(in_array($v, array_keys($keysArr))){
                    $n ++;
                }
            }

if(! $n){
                $str = implode(",",$val);
                $this->error->showError("api调用参数错误",$str."必填一个");
            }
        }

if($method == "POST"){
            if($baseUrl == "https://graph.qq.com/blog/add_one_blog") $response = $this->urlUtils->post($baseUrl, $keysArr, 1);
            else $response = $this->urlUtils->post($baseUrl, $keysArr, 0);
        }else if($method == "GET"){
            $response = $this->urlUtils->get($baseUrl, $keysArr);
        }

return $response;

}
    
    //php 对象到数组转换
    private function objToArr($obj){
        if(!is_object($obj) && !is_array($obj)) {
            return $obj;
        }
        $arr = array();
        foreach($obj as $k => $v){
            $arr[$k] = $this->objToArr($v);
        }
        return $arr;
    }
    
    //简单实现json到php数组转换功能
    private function simple_json_parser($json){
        $json = str_replace("{","",str_replace("}","", $json));
        $jsonValue = explode(",", $json);
        $arr = array();
        foreach($jsonValue as $v){
            $jValue = explode(":", $v);
            $arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
        }
        return $arr;
    }

}

保存
说明:这段代码复制不过就行,不用做任何改动。这个是最核心的代码,代码比较多,但是功能代码就这些了,想想,在自己的网站上,别人用qq帐号就可以登录了,都不用注册,多方便啊,是吧,这样一想这些代码也不算多了。

4.建控制器。打开application下的controllers文件夹,在controllers下新建一个文件qq.php,打开qq.php,复制下面代码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    /*
     * @ qq登陆 注销 消息获取等
     * @author
     */
    class QQ extends CI_Controller
    {
       
        public function __construct() {
            parent::__construct();
            session_start();
            $this->load->helper('url');
            //error_reporting(0);
            /*qq登陆*/
           $this->load->library('tencent/oauth','oauth');
        }
        
        public function index()
        {   
            //验证是登陆还是回调
            if($this->oauth->check_login() === 'false')
            {
                $this->oauth->qq_login();
            }
            else
            {
                $this->oauth->qq_callback();
            }
                
        }     
    }

保存
说明:这段代码不用做修改。

5.放置登录按钮,点击用QQ帐号登录按钮,跳转到QQ登录页面登录。
在你的登录页面放按钮的位置,写入:
<div><a href="/qq"><img src="http://images.cnblogs.com/qq_login.png" width="110" /></a></div>

保存
说明:样式你可自己调整,图片按钮可以从官网下载,地址:http://wiki.connect.qq.com/%E8%A7%86%E8%A7%89%E7%B4%A0%E6%9D%90%E4%B8%8B%E8%BD%BD#2.QQ.E7.99.BB.E5.BD.95.E6.A1.86.E6.A0.87.E5.87.86.E6.A0.B7.E5.BC.8F

到这里,QQ第三方登录接口就OK了,你打开你的登录页面,点击QQ登录的图片按钮,它会转到QQ登录页面登录,如果要上线,要用到别的功能,可在这几个文件上填代码就行了。

申明:
本帖仅供学习参考,不涉及任何商业范围,如有冒犯,敬请原谅!
如有不对的地方,或者可以改良的地方,请回复指点,受教受教!

QQ登录接口(第三方登录接口)的更多相关文章

  1. 拾人牙慧篇之———QQ微信的第三方登录实现

    一.写在前面 关于qq微信登录的原理之流我就不一一赘述了,对应的官网都有,在这里主要是展示我是怎么实现出来的,看了好几个博客,有的是直接复制官网的,有的不知道为什么实现不了.我只能保证我的这个是我实现 ...

  2. Yii2 使用 QQ 和 Weibo 第三方登录源码

    我们社区在 yii2-authclient 多次升级后,登录异常.一直想寻求一种通用的方法,尽量不重写 OAuth2, BaseOAuth 以及 OAuthToken 类, 所以本次直接在 initU ...

  3. 使用OAuth2.0协议的github、QQ、weibo第三方登录接入总结

    目录 第三方接入总结 OAuth2.0介绍 github OAuth2.0登录接入 国内第三方应用商SDK使用 微博SDK 腾讯QQ SDK passport.js插件使用 安装 相关中间件.路由 返 ...

  4. Android 实现微信QQ分享以及第三方登录

    集成准备 在微信开放平台创建移动应用,输入应用的信息,包括移动应用名称,移动应用简介,移动应用图片信息,点击下一步,选择Android 应用,填写信息提交审核. 获取Appkey 集成[友盟+]SDK ...

  5. 实现QQ、微信、新浪微博和百度第三方登录(Android Studio)

    前言: 对于大多数的APP都有第三方登录这个功能,自己也做过几次,最近又有一个新项目用到了第三方登录,所以特意总结了一下关于第三方登录的实现,并拿出来与大家一同分享: 各大开放平台注册账户获取AppK ...

  6. Android 实现QQ、微信、新浪微博和百度第三方登录

    前言: 对于大多数的APP都有第三方登录这个功能,自己也做过几次,最近又有一个新项目用到了第三方登录,所以特意总结了一下关于第三方登录的实现,并拿出来与大家一同分享: 各大开放平台注册账户获取AppK ...

  7. 基于Vue、Springboot网站实现第三方登录之QQ登录,以及邮件发送

    基于Vue.Springboot实现第三方登录之QQ登录 前言 一.前提(准备) 二.QQ登录实现 1.前端 2.后端 1.application.yml 和工具类QQHttpClient 2.QQL ...

  8. dedecms织梦第三方登录插件-QQ登录、微博登录、微信登录

    织梦程序集成第三方QQ登录.微博登录.微信登录,获取QQ.微博.微信,并存储至数据库,一键注册为网站会员,不用再次填写绑定信息,方便粘贴用户更强. 织梦第三方登录效果 第三方登录插件特点 1.所有文件 ...

  9. 第三方登录 ----转载自简书,作者 <<碧霄问鼎>>

    这几天遇到一个需求:做第三方登录和分享.遇到了一些坑,把整个过程整理记录下来,方便他人,同时也捋一下思路. 当时考虑过把每个平台的SDK下载下来,一个一个弄,一番取舍后决定还是用ShareSDK.这里 ...

  10. CI框架 QQ接口(第三方登录接口PHP版)

    本帖内容较多,大部分都是源码,要修改的地方只有一个,其他只要复制过去,就可以完美运行.本帖主要针对CI框架,不用下载SDK,按我下面的步骤,建文件,复制代码就可以了.10分钟不要,接口就可完成.第一步 ...

随机推荐

  1. Power of Cryptography

    //只用一行核心代码就可以过的天坑题目............= = 题目: Description Current work in cryptography involves (among othe ...

  2. OGG问题 ORA-01403的处理办法

    认识logdump分析工具及常用命令:http://book.51cto.com/art/201202/319253.htm http://www.killdb.com/2012/09/01/gold ...

  3. python 基础干货 01

    赋值的实现 a = 'abc' 1. 在内存中创建了'abc'字符串; 2. 在内存中创建了一个名为 a 的变量, 并把它指向刚才创建的'abc', 也就是a中保存着字符串的地址. b = a, 创建 ...

  4. github pages简易指南

    在我之前的博客用Octopress在Github pages上写博客(博客园上,github pages上)中介绍了怎么在Github Pages上写博客,今天发现了一个很不错的github page ...

  5. Cookie案例分析

    一.案例- 显示用户上次访问的时间 当用户第一次访问该页面的时候提示:你好,你是第一次访问本页面,当前时间为:2016-11-3 22:10:30 第n次访问该页面时:欢迎回来,你上次访问的时间是:2 ...

  6. Gamma校正及其OpenCV实现

    參考:[1]http://www.cambridgeincolour.com/tutorials/gamma-correction.htm [2]http://en.wikipedia.org/wik ...

  7. [Node.js] Exporting Modules in Node

    In this lesson, you will learn the difference between the exports statement and module.exports. Two ...

  8. Linux下设置最大文件打开数nofile及nr_open、file-max

    在开发运维的时候我们常常会遇到类似“Socket/File: Can’t open so many files”,“无法打开更多进程”,或是coredump过大等问题,这些都可以设置资源限制来解决.今 ...

  9. 字符集详解 ------------------------ UNICODE +UTF8

    http://my.oschina.net/goldenshaw/blog?catalog=3294521 http://my.oschina.net/goldenshaw/blog?catalog= ...

  10. Linux系统调优1

    Linux在进行系统调优的时候,首先要考虑整个操作系统的结构,然后针对各个部分进行优化,下面展示一个Linux系统的各个组成部分: 有上图可以看出,我们可以调整的有应用程序,库文件,内核,驱动,还有硬 ...