当前位置:   article > 正文

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

ci框架接口访问

本帖内容较多,大部分都是源码,要修改的地方只有一个,其他只要复制过去,就可以完美运行。本帖主要针对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登录页面登录,如果要上线,要用到别的功能,可在这几个文件上填代码就行了。

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

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号