`
曾越明
  • 浏览: 11481 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

基于Ci 框架下qq,新浪第三方登录

    博客分类:
  • php
阅读更多
qq配置文件
路径:application/config/isetting/qq_setting.php
   <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

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

    $config['inc_info'] = array(
        array (
                'appid' => '101091040',
                'appkey' => '7cb031049f2c900fea809424e614a968',
                'callback' => '此为绑定的url/qqcallback.php'
              ),
        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',
              )
    );

根目录下的,qqcallback.php
    <?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//新浪微博登录回调入口文件,将路径转移到login/callback方法里,并将code值传过去
$code ='';
$state='';
$url = '';
$str ='';
$code = $_REQUEST['code'];
$state = $_REQUEST['state'];
$url  = "/login/qqcallback";
//die('ssss');
$str = "<!doctype html>
<html>
<head>
<meta charset=\"UTF-8\">
<title>自动跳转</title>
</head>
<body>";
$str .="<form action=\"{$url}\" method=\"post\" id=\"form\" autocomplete='off'>";
$str .="<input type='hidden' name='code' value='{$code}'>";
$str .="<input type='hidden' name='state' value='{$state}'>";
$str .=" <!--<p><input type='submit' value='go'/></p> -->
        </form>
        </body>
        </html>
    <script type=\"text/javascript\">
document.getElementById('form').submit();
    </script>";
echo $str;

login控制器下的qqcallback方法
    public function qqcallback(){
            header("content-type: text/html; charset=utf-8");
            $this->load->library('tencent/oauth','oauth');
           
            $this->load->model("user_reg_model","user_reg");
            $code = $_REQUEST['code'];
            $state = $_REQUEST['state'];
            $CI = &get_instance();
            $CI->config->load('isetting/qq_setting');
            $setting = $CI->config->item('inc_info');
            $appid = $setting[0]['appid'];
            $arr =array();
            $arr = $this->oauth->qq_callback($code,$state,$appid);
           // echo "<pre>";print_r($arr);die();
           
            $res = $this->third->select_third(array("qq_id"=>$arr['openid']));
            if(!empty($res)){
                $user_info = $this->user_reg->user_detect(array("id"=>$res['user_id']));
                if($user_info['status']){
                    echo "<script>alert('您登陆的账号还未激活');location='/login/index';</script>";die();
                }
                $datas = $this->third->select_user_qqname($arr['openid']);
    //            echo "<pre>";print_r($datas);die();
                $uname = $datas['username'];
                $password = $datas['password'];
                $this->load->model("login_model","login");
                $this->login->validation($uname,$password);
                echo "<script>alert('登录成功!');location='/user_center'</script>";die();
            }else{
                $this->session->set_userdata('qq_id',$arr['openid']);
                echo "<script>if(!confirm('是否在平台注册过用户?')){location='/register/index'}else{location='/login'};</script>";
            }    
        }

models下的模型
    <?php

/**
* Description of third_login_model
*新浪接口授权及登录model
* @author
*/
class third_login_model extends CI_Model{
    //put your code here
    private $sina=array();
    private $qq  =array();
    private $users ='';
    private $third='';
    public function __construct() {
        parent::__construct();
//        $this->l = DIRECTORY_SEPARATOR;
        $this->load->database();  
        $this->load->library('session');
        include_once APPPATH."/libraries"."/saetv2.ex.class.php";
        $this->third =  $this->db->dbprefix.'_third_login';
        $this->users = $this->db->dbprefix.'_user_reg';
        $this->config->load("sina_conf");
        $this->sina= $this->config->item("sina_conf");
       
    }
   
    /**
      * @uses : 新浪微博登录
      * @param :
      * @return : $sina_url----登录地址
      */
    public function sina_login(){
        $obj = new SaeTOAuthV2($this->sina['App_Key'],$this->sina['App_Secret']);
        $sina_url = $obj->getAuthorizeURL( $this->sina['WB_CALLBACK_URL'] );
        return $sina_url;
    }
   
    /**
      * @uses : 登录后,通过返回的code值,获取token,实现授权完成,然后获取用户信息
      * @param : $code
      * @return : $user_message--用户信息
      */
    public function sina_callback($code){
      $obj = new SaeTOAuthV2($this->sina['App_Key'],$this->sina['App_Secret']);
      if (isset($code)) {
  $keys = array();
  $keys['code'] = $code;
  $keys['redirect_uri'] = $this->sina['WB_CALLBACK_URL'];
  try {
$token = $obj->getAccessToken( 'code', $keys ) ;//完成授权
  } catch (OAuthException $e) {
}
      }
      $c = new SaeTClientV2($this->sina['App_Key'], $this->sina['App_Secret'], $token['access_token']);
      $ms =$c->home_timeline();
      $uid_get = $c->get_uid();//获取u_id
      $uid = $uid_get['uid'];
      $user_message = $c->show_user_by_id($uid);//获取用户信息
      return $user_message;
    }
   
    /**
      * @uses : 查询第三方登录表
      * @param : $where
      * @return : 第三方登录用户记录结果集
      */
    public function select_third($where) {
        $result = false;
        $this->db->select();
        $this->db->from($this->third);
        $this->db->where($where);
        $query = $this->db->get();
        if($query){
            $result = $query->row_array();
        }
        return $result;
    }
   
    /**
      * @uses : sina查询用户表和第三方登录表
      * @param : $where
      * @return : 第三方登录用户记录结果集
      */
    public function select_user_name($where) {
        $field ="user.id,user.password,user.username,utl.*";
        $sql = "select {$field} from {$this->third} as utl "
                ." left join {$this->users} as user on user.id=utl.user_id"
                . " where utl.sina_id={$where}";
        $query = $this->db->query($sql);
        $result = $query->row_array();
        return $result;
    }
   
    /**
      * @uses : qq查询用户表和第三方登录表
      * @param : $where
      * @return : 第三方登录用户记录结果集
      */
    public function select_user_qqname($where) {
        $field ="user.id,user.password,user.username,utl.*";
        $sql = "select {$field} from {$this->third} as utl "
                ." left join {$this->users} as user on user.id=utl.user_id"
                . " where utl.qq_id='{$where}'";
        $query = $this->db->query($sql);
        $result = $query->row_array();
        return $result;
    }
   
//    public function insert_third($datas){
//        if (!is_array($datas)) show_error ('wrong param');
//        $res ='';
//        $res = $this->db->insert($this->third, $datas);
//        return $res;
//    }
//   
//    public function up_third($datas) {
//       
//    }
   
    public function binding_third($datas) {
        if (!is_array($datas)) show_error ('wrong param');
        if($datas['sina_id']==0 && $datas['qq_id']==0)  return;
       
        $resa ='';
        $resb ='';
        $resa = $this->select_third(array("user_id"=>$datas['user_id']));
        $temp =array(
            "user_id"=>$datas['user_id'],
            "sina_id"=>$resa['sina_id']!=0 ? $resa['sina_id'] : $datas['sina_id'],
            "qq_id"  => $resa['qq_id']!=0 ? $resa['qq_id'] : $datas['qq_id'],
        );
        if($resa){
            $resb = $this->db->update($this->third, $temp,array("user_id"=>$datas['user_id']));
        }else{
            $resb = $this->db->insert($this->third,$temp);
        }
        if($resb) {
            $this->session->unset_userdata('sina_id');
            $this->session->unset_userdata('qq_id');
        }
        return $resb;
    }
}

libraries/tencent/oauth.php在下载附件中

新浪配置文件
application/config/sina_conf.php
    <?php

$config["sina_conf"] = array(   //测试机
    "App_Key" => '1498005339',
    "App_Secret" =>'f1c6277a38b39f764c76a1190750a6dc',
    "WB_CALLBACK_URL" => 'http://.../callback.php'
);

根目录下的回调地址 callback.php

<?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//新浪微博登录回调入口文件,将路径转移到login/callback方法里,并将code值传过去
$code ='';
$url = '';
$str ='';
$code = $_REQUEST['code'];
$url  = "/login/callback";

$str = "<!doctype html>
<html>
    <head>
<meta charset=\"UTF-8\">
<title>自动跳转</title>
    </head>
<body>";
$str .="<form action=\"{$url}\" method=\"post\" id=\"form\" autocomplete='off'>";
$str .="<input type='hidden' name='code' value='{$code}'>";
$str .="</form>
        </body>
        </html>
        <script type=\"text/javascript\">
       document.getElementById('form').submit();
        </script>";
echo $str;

请求的方法

    //流程原理:
    // 1.通过code获得access_token通过授权,并获取用户的信息(包括用户u_id)
    // 2.查询第三方登录表,如果存在用户id,查询用户表,如果邮箱已经激活,就直接登录,如果没有激活,提示用户去邮箱激活帐号
    // 3.查询第三方登录表,如果不存在用户id,分2种情况,一:用户在平台已经有帐号了,这时需要把平台user_reg用户id绑定到第三方登录表,然后就让客户登录
    //   二:如果用户在平台没有帐号,跳转至注册页面注册,注册的同时,信息写入uer_reg表,同时也把用户id写入第三方登录表进行绑定
    public function callback(){
        header("content-type: text/html; charset=utf-8");
        $this->load->model("user_reg_model","user_reg");
        $code = $_REQUEST['code'];//code值由入口文件callback.php传过来
        $arr =array();
        $arr = $this->third->sina_callback($code);//通过授权并获取用户信息(包括u_id)
        $res = $this->third->select_third(array("sina_id"=>$arr['id']));
        if(!empty($res)){
            $user_info = $this->user_reg->user_detect(array("id"=>$res['user_id']));
            if($user_info['status']){
                echo "<script>alert('您登陆的账号还未激活');location='/login/index';</script>";die();
            }
            $datas = $this->third->select_user_name($arr['id']);
//            echo "<pre>";print_r($datas);die();
            $uname = $datas['username'];
            $password = $datas['password'];
            $this->load->model("login_model","login");
            $this->login->validation($uname,$password);
            echo "<script>alert('登录成功!');location='/user_center'</script>";die();
        }else{
            $this->session->set_userdata('sina_id',$arr['id']);
            echo "<script>if(!confirm('是否在平台注册过用户?')){location='/register/index'}else{location='/login'};</script>";
        }    
    }




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics