您的位置:永利集团登录网址 > 计算机教学 > Thinkphp 实现QQ一键登录的例子

Thinkphp 实现QQ一键登录的例子

2019-10-03 18:11

1.到QQ互联上申请APP ID、应用程式 KEY。地址: 详细注方法这里不再赘述。
亟需小心能够写七个这里的回调地址要求和您布置文件中的一致:

项目中碰着的多规格异步查询及数码分页难点,做了数11回尝试,最后虽指标达到,但。。。。。希望能有越来越好的管理格局

首先来看下流程:
流程原理:
     1.通过code获得access_token通过授权,并收获顾客的新闻(包涵顾客u_id)(这个u_id在背后的第三方登入表里面叫sina_id,那多个表是索要团结建的)
     2.询问第三方登陆表,假诺不真实顾客sina_id,分2种状态,一:客商在凉台已经有帐号,那时急需把阳台(举个例子:平台的客户表是:user_reg)客户id绑定到第三方登入表(比方是:third_login表),然后就让客商登陆;
                                                          二:客商在凉台未有帐号,跳转至注册页面注册,注册的还要,音讯写入uer_reg表,同期也把客商sina_id写入第三方登陆表进行绑定;
     3.询问第三方登入表(third_login),倘诺存在顾客sina_id,再查询客商表(user_reg),借使邮箱已经激活,就直接登陆,若无激活,提醒客商去邮箱激活帐号。

3.QQHelper.class.php那几个文件请放到ThinkPhp宗旨报中 路线为:ThinkphpExtendLibraryORGNetQQHelper.class.php,此文件为QQ登入的中坚类。

基于 tp框架

上面开端详讲步骤:
率先步:申请App key和App secret申请地址: 在页面点击网址接入WEB,进去申请就好了,通过后会得到App Key 和 App Secret如下:
App Key:1428003339
App Sercet:f1c6177a38b39f764c76a1690720a6dc
回调地址:

4.配置一下配置文件如下:
//网站url路径
define ( 'WEBSITE_URL', '' );
//应用ID 这几个是在     申请
define ( 'APP_ID', ********* );
//应用KEY  这么些是在     申请
define ( 'APP_KEY', '****9676d9bec3bf0f0d53ff4ff6****' );
//QQ登入回调地址
define ( 'APP_LOGIN_CPATH', WEBSITE_URL . '/Login/qq_login_cb' );//这里的渠道要和QQ互联上的回调接口一致
//绑定QQ回调地址
define ( 'APP_BIND_CPATH', WEBSITE_URL . '/Index/qq_bc' );//这里的路径要和QQ互联上的回调接口一致
//诉求顾客授权时向客商展现的可进行授权的列表
define ( 'APP_SCOPE', 'get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo' );
//图片是不是本地化
define ( 'AVATAR_LOCAL', false );

 

证实:申请下来后,这您的这一个天涯论坛帐号就是测验帐号,你在支付的时候能够用那些帐号来调整,别的帐号是力所不及登入,不可能回去音讯的。开垦前,最佳上官方网站看下开荒流程,流程是最根本的。只要思路理清楚了,剩下正是用代码实现您的所思所想。

//Session设置
define ( 'SES_TOKEN_NAME', 'qq_token' ); //token名称
define ( 'SES_OPENID_NAME', 'qq_openid' ); //QQ用户的openid名称
define ( 'SES_STATE_NAME', 'qq_state' );// 状态名称

1、html页面代码

第二步:下载SDK,下载php版的,下载地址(官方网站):

5.php代码
    1.commonAction.class.php代码
    class CommonAction extends Action
    {
        public function _initialize() {
            header("Content-Type:text/html; charset=utf-8");
            header('Content-Type:application/json; charset=utf-8');
            $systemConfig = include WEB_ROOT . 'Common/systemConfig.php';
            $this->assign("site", $systemConfig);
           
           
            if(empty($_SESSION['info']['username']))
            {
                if(empty($_SESSION['qq_openid']))
                {
                    $L="<li><a href=".$systemConfig['WEB_ROOT']."Register/index>注册</a></li>";
                    $L.="<li><a href='javascript:void(0);' id='login'>登录</a></li>";
                    $L.="<li><a href='".$systemConfig['WEB_ROOT']."Login/qq_login'><img src='".$systemConfig['WEB_ROOT']."/Public/home/images/qq_login.png'/></a></li>";
                }else{
                    if($_SESSION['info']['bind']=="N")
                    {   
                        $L="<li><a href='".$systemConfig['WEB_ROOT']."Login/loginout'>退出</a></li>";
                        $L.="<li><a href='".$systemConfig['WEB_ROOT']."Center/index'>会员中央</a></li>";
                        $L.="<li><a href='".$systemConfig['WEB_ROOT']."Index/readtemplate?source=bind_uname'>请绑定客户名</a></li>";
                        $L.="<li>".$_SESSION['info']['nickname']."</li>";
                        $L.="<li><img src='".$_SESSION['info']['avatar']."' style='width:30px;'/></li>";   
                    }else{
                        $L="<li><a href='".$systemConfig['WEB_ROOT']."Login/loginout'>退出</a></li>";
                        $L.="<li><a href='".$systemConfig['WEB_ROOT']."Center/index'>会员中央</a></li>";
                        //$L.="<li><a href='/Index/readtemplate?source=bind_uname'>请绑定顾客名</a></li>";
                        $L.="<li>".$_SESSION['info']['nickname']."</li>";
                        $L.="<li><img src='".$_SESSION['info']['avatar']."' style='width:30px;'/></li>";
                    }
                }

<div class="h_cityName1">

第三步:代码
1.一贫如洗一个第三方登入表,以便存储第三方登入的音讯(和讯是u_id,QQ是openid,他们都是独一的,用来标记客户,大家依据那个来存款和储蓄):

            }else{
                $L="<li><a href='".$systemConfig['WEB_ROOT']."Login/loginout'>退出</a></li>";
                if(empty($_SESSION['info']['open_id']))
                {
                    $L.="<li><a href='".$systemConfig['WEB_ROOT']."Index/qq_bind'>绑定QQ号</a></li>";   
                }else{
                    $L.="<li><a href=".$systemConfig['WEB_ROOT']."Index/qq_unbind'>解绑QQ号</a></li>";
                }
                   
               
                $L.="<li><a href='".$systemConfig['WEB_ROOT']."Center/index'>会员宗旨</a></li>";
                $L.="<li>您好:".$_SESSION['info']['username']."</li>";
            }
            $this->assign("L", $L);       
        }

  <div class="h_cityName11">

复制代码 代码如下:

    }

<span>省</span>

CREATE TABLE IF NOT EXISTS `third_login` (
  `user_id` INT(6) NOT NULL,
  `sina_id` BIGINT(16) NULL,
  `qq_id` varchar(64) NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC),
  INDEX `sina_id` (`sina_id` ASC),
  INDEX `index4` (`qq_id` ASC))
ENGINE = MyISAM
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin
COMMENT = '第三方登入表'

    2.完结QQ登入代码 LoginAction 都需接二连三 CommonAction
    class LoginAction extends CommonAction {

<ul class="h_publicB" id="province_id" name="province_id" >

评释:平台重临的是u_id,他是客商的独步天下标记,小编把她存为sina_id,user_id是涉及平台客商表user_reg的id的,user_reg表笔者那边不列出,你能够按实际项目供给来建表,推荐的操作工具备phpmyadmin,MySQL Workbench,操作方便。
譬喻你只需求做新浪登陆接口,那能够把qq_id那个字段去掉。

        private $user;
        private $qqHelper;
       
        function _initialize() {
            $this->user = M('Member');
            import ('ORG.Net.QQHelper');
            $this->qqHelper = new QQHelper ();
        }
       
        //QQ登录
        public function qq_login()
        {
            $this->qqHelper->login ( APP_ID, APP_SCOPE, APP_LOGIN_CPATH );
        }
       
        //QQ登入的回调
        function qq_login_cb() {
            $this->qqHelper->callback ( APP_LOGIN_CPATH );
            $this->qqHelper->get_openid ();
           
            //先去数据库中查找openid存在不
            $temp_data = $this->user->where(array('open_id' => $_SESSION [SES_OPENID_NAME]))->find();
           
            if (empty($temp_data['open_id'])) {
                //声明该QQ还未有在本站登陆过
                $userInfo = json_decode ( $this->qqHelper->get_user_info (), true );
                $data ['open_id'] = $_SESSION [SES_OPENID_NAME];
                $data ['nickname'] = $userInfo ['nickname'];
                $data ['avatar'] = $userInfo ['figureurl_2'];
                $data ['login_ip'] = get_client_ip();
                $data ['login_time'] = time();
                $data ['reg_date'] = time();
                $this->user->add ( $data );
                //将消息写入session
                $temp_data = $this->user->where(array('uid' => $this->user->getLastInsID()))->find();
                $_SESSION['info']=$temp_data;
            } else {
                $_SESSION['info']=$temp_data;
            }
            $this->redirect ('Index/index');
        }
       
        //退出
        public function loginout()
        {
            unset($_SESSION['info']);
            session_destroy();
            $this->redirect('Index/index');
        }
    }

<volist name="list" id="vo">

2.写配置文件,在application下新建二个文书sina_conf.php,把刚申请到的App Key 和 App Secret写进去,代码如下:

    3.QQ号与本地顾客绑定 IndexAction 都需再而三 CommonAction
   
    class IndexAction extends CommonAction {

<if condition="$areaId eq $vo.areaId">

复制代码 代码如下:

        private $user;
        private $qqHelper;
       
        function _initialize() {
            parent::_initialize();
            $this->user = M ( 'Member' );
            import ('ORG.Net.QQHelper');
            $this->qqHelper = new QQHelper ();
        }   
       
        /**QQ登录**/
       
        //绑定客户名 指利用QQ登入的客户,还不曾本站帐号和密码
        function bind_uname() {
            $data ['username'] = $_POST ['uname'];
            $data ['pwd'] = MD5(MD5($_POST ['pwd']));
            $data ['bind'] = 'Y';
           
            $map ['open_id'] = $_SESSION [SES_OPENID_NAME]; //QQ的openid            

<li value="{$vo.areaId}" onclick="sendData(this,'province_id')"  >{$vo.areaName}</li>

<?php
$config["sina_conf"] = array(
    "App_Key" => '1428003339',
    "App_Secret" =>'f1c6177a38b39f764c76a1690720a6dc',
    "WB_CALLBACK_URL" => ''
);

            //查找该openid是或不是曾经绑定过客户名从未
            $stat = $this->user->where ( $map )->find ();
            if ($stat ['username'] != '' || $stat ['username'] != null) {
                $this->error ( '你曾经绑定过顾客名,请不要再绑定啦' );
            }
           
            $res = $this->user->where ( $map )->save ( $data );
            //更新session
            $_SESSION['info']['bind']='Y';
           
            if ($res) {
                $this->success ( '绑定客户成功');
            } else {
                $this->error ( '绑定失利' );
            }
        }
       
        //绑定QQ号 首要是由此本站注册的顾客
        function qq_bind() {
            //先去看清该帐号是不是绑定过QQ号
            $map ['open_id'] = $_SESSION [SES_OPENID_NAME];
            $res = $this->user->where ( $map )->find ();
            if ($res != null) {
                $this->error ( '您曾经绑定了QQ帐号了,假若要转移请先祛除绑定!' );
            }
            $this->qqHelper->login ( APP_ID, APP_SCOPE, APP_BIND_CPATH ); //注意这里的回调地址和登入的回调地址分裂
        }
       
        //绑定QQ号 的回调地址
        function qq_bc() {
            $tmp_ses = $_SESSION [SES_OPENID_NAME]; //保存在此之前的Sesion 制止Session被遮住
            $this->qqHelper->callback ( APP_BIND_CPATH ); //注意这里的回调地址和登陆的回调地址分歧
            $this->qqHelper->get_openid ();
            $userInfo = json_decode ( $this->qqHelper->get_user_info (), true );
           
            //先要去看清那一个QQ号是还是不是曾经绑定过帐号没有
            $res = $this->user->where ( array ('open_id' => $_SESSION [SES_OPENID_NAME] ) )->find ();
            if ($res != null) {
                $_SESSION [SES_OPENID_NAME] = $tmp_ses;
                $this->error ( '该QQ号已经绑定过帐号了,请勿再度绑定', /esoxue.php );
            }
            $map['uid'] = $_SESSION['info']['uid'];
            $data ['open_id'] = $_SESSION [SES_OPENID_NAME];
            $data ['avatar'] = $userInfo ['figureurl_2'];
            $data ['bind'] = 'Y';
            $stat = $this->user->where ( $map )->save ( $data );
            if ($stat > 0) {
                $this->success ( '绑定QQ号成功!', /esoxue.php );
            } else {
                $this->error ( '绑定QQ失败', /esoxue.php );
            }
        }
       
        //解绑QQ号
        function qq_unbind() {
            $map ['uid'] = $_SESSION['info']['uid'];
            $data ['open_id'] = '';
            $res = $this->user->where ( $map )->save ( $data );
            if ($res > 0) {
                $this->success ( '解绑成功!', /esoxue.php );
            } else {
                $this->error ( '解绑退步', /esoxue.php );
            }
        }
       
        //读模板
        function readtemplate() {
            $dotpl = $_GET ['source'];
           
            if ($dotpl == 'bind_uname') {
                $this->display ( 'bind_uname' );
            }
        }
       
        /**QQ登录**/
       
    }

<else />

保存

在header中输出{$L} header 是满含文件

<li value="{$vo.areaId}" onclick="sendData(this,'province_id')"  >{$vo.areaName}</li>

3.oauth认证类,把刚下载下来的saetv2.ex.class.php文件复制到application/libraries下。
证实:那是可怜关键的类,登陆,授权,获取顾客音信都要用到这几个类中的方法,没他就没有办法玩下去了,未有丝毫退换的粘到application/libraries下。

6.数据库在你的会员中增多如下字段:
nickname、avatar、open_id、bind

</if>

4.写和讯博客园登入类(QQ登陆也可用,小编那边QQ登入的也封装在共同了,就算只做腾讯网登入接口,也不影响),在application/models下建叁个文件third_login_model.php,代码:

CREATE TABLE IF NOT EXISTS `lw_member` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(20) DEFAULT NULL COMMENT '客户小名',
  `pwd` char(32) DEFAULT NULL COMMENT '密码',
  `avatar` varchar(100) DEFAULT NULL COMMENT '客户头像',
  `login_ip` varchar(15) DEFAULT NULL COMMENT '登录ip',
  `login_time` int(17) DEFAULT NULL COMMENT '登陆时间',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `open_id` varchar(32) NOT NULL,
  `bind` enum('N','Y') NOT NULL DEFAULT 'N',
  PRIMARY KEY (`uid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='网址前台会员表' AUTO_INCREMENT=6 ;

</volist>

复制代码 代码如下:

绑定本地客户模板代码:
        <form action="{:U('Index/bind_uname')}" method="POST">
            <p style="margin:0;text-align:right;margin-right:10px;cursor: pointer;" ></p>
            <h1>绑定客户</h1>
            <p> </p>
            <p><input type="text" name="uname" class="input" placeholder="请输入用户名"/></p>
            <p> </p>
            <p><input type="password" name="pwd" class="input" placeholder="请输入密码"/></p>
            <p> </p>
            <p><input type="submit" name="submit" value="绑 定" class="submit"/></p>
        </form>
一时演示地址:
以上全数代码可依照真实意况改变。需求潜心:QQ登陆必要CURL的支撑

   </ul>

<?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->'third_login';//第三方登陆表
        $this->users = $this->db->'user_reg';//本项目顾客表
        $this->config->load("sina_conf");
        $this->sina= $this->config->item("sina_conf");

</div>

    }

<div class="h_cityName11 h_cityList">

    /**
      * @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;
    }

<span>市</span>

    /**
      * @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;
    }

<ul class="h_publicB" id="city_id" name="city_id">

    /**
      * @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;
    }

</ul>

    /*-
      * @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;
    }

</div>

    /**
      * @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;
    }

   **<div class="h_cityName11 h_areaList" >**

   
    /**
      * @uses : 将顾客和第三方登入表新闻绑定
      * @param : $datas
      * @return :
      */
    public function binding_third($datas) {
        if (!is_array($datas)) show_error ('wrong param');
        if($datas['sina_id']==0 && $datas['qq_id']==0)  return;

<span>区</span>

        $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;
    }
}

<ul class="h_publicB" id="area_id" name="area_id">

保存
证实:那些code是由入口文件callback.php传过来的,第7步会有她的详尽代码。
当今布署文件,model,数据表都有了,接下去便是调节器和视图像和文字件了。

</ul>

5.写登入调控器  在application/controllers下,建构login.php文件(名字你能够友善取),代码:

</div>

复制代码 代码如下:

</div>

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

<div class="hangye"><b>行业</b></div>

/**
 * Description of index
 * @author victory
 */
class Login extends CI_Controller {

  **<ul>**

    public function __construct() {
        parent::__construct();
        $this->load->model('login_model','login');//这么些类是本项目标客商登入类,本贴不提供原代码,因为分裂的花色,需要不一,可依据你项目供给可以团结包裹
        $this->load->model("third_login_model","third");
        $this->load->library('session');
    }

  <volist name="industry" id="industry">

    public function index() {
        header("content-type: text/html; charset=utf-8");
        $this->load->model("third_login_model","third");//加载乐乎报到接口类
        $datas['sina_url'] = $this->third->sina_login();//调用类中的sina_login方法
        $this->load->view("index.php",$datas);//调取视图像和文字件,并传播数据

   <li value="" onclick="sendData(this,'industry')" name="{$idfrom_home}" ><span >{$industry.name}</span></li>**    **

     }

   </volist>

    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']));//查询客商表邮箱状态,user_detect方法就是询问客户音信的点子,上边也说了,login_model.php那几个类本贴不提供,要求我们温馨去封装。
            if($user_info['status']){//根据status的情景决断客户帐号是不是激活,user_reg表中的字段status,1为未激活,0为已激活
                echo "<script>alert('您的账号未激活,请去邮箱激活!');location='/login/index';</script>";die();
            }
            $datas = $this->third->select_user_name($arr['id']);//激活后,把消息写入客户表和第三方登入表
            $uname = $datas['username'];//username,password都是user_reg表的字段,user_reg数据表的营造本帖也不提供,因为各种体系都不雷同,供给基于实际项目来
            $password = $datas['password'];
            $this->load->model("login_model","login");
            $this->login->validation($uname,$password);//validation方法是登录的关键方式,这里首假使在签到的时候,将客户音信写入第三方登陆表,下边仅提供写入第三方登入表的代码
            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>";
        }    
    }

   </ul>           

    public function login_validation(){
      //第三方登陆客户id ,sina_id,qq_id的记录增改
        $third_info =array(
            "user_id" => $user_ser['id'],
            "sina_id" => $this->session->userdata('sina_id'),
            "qq_id"   =>$this->session->userdata('qq_id'),
        );
        if($third_info['sina_id']||$third_info['qq_id'])    $this->third->binding_third($third_info);  // 绑定
}

</div>

//保存

<div class="search3">

     //在注册调控器里,顾客音讯写入user_reg表,同有时间也把sina_id写入third_login表,小编这里只展现第三方登入接口客户id存入数据表的代码
class Register extends CI_Controller {

        <input type="text" name="" id="companyname" value=""  placeholder="找出集团/厂家名称"/>

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
    }
    public function reg() {
          $haha =array(
                      "user_id" => $rs,
                      "sina_id" => $this->session->userdata('sina_id'),
                      "qq_id"   =>$this->session->userdata('qq_id'),
                      );
            if($haha['sina_id']||$haha['qq_id'])    $this->third->binding_third($haha);
    }
}

         <a href="#"><input type="submit" class="but1"  id="s-by-c"  onclick="sendData(this,'companyname')" value="" /></a>

保存

 

6.视图像和文字件铺排腾讯网腾讯网登陆按键,在application/view下创立index.php文件,代码:

</div>

复制代码 代码如下:

<div class="zongmu-lbbu" id="companylist">

<html>
<head>
    <meta content="text/html; charset=utf-8">
    <title>博客园今日头条登陆接口</title>
</head>
<body>
     <div><a href="<?=$sina_url?>"><img src="" width="110"  /></a></div>
</body>
</html>

<volist name="company" id="vo">

保存
证实:那是个图片按键,图片你可在官方网址下载,下载地址:

   <div class="recommend-logo" >

7.回调地址
眼前在第1步配置文件文件的时候,设置了回调地址: ,那那几个callback.php放在什么地点呢,它须要放在和入口index.php同级的岗位,它和application也是同级的。所在在早先的目录下新建文件callback.php。代码:

      <div class="fl1">

复制代码 代码如下:

<a href="{:U('Home/Company/detail?id='.$vo['id'])}">

<?php

<img src="{$uploads}{$vo.logo}" class="fl-img"/>

/*
 * 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";

<p>{$vo.name}</p>

$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;

<span class="span-add">{$vo.addreess}</span>

保存

<img src="{$home_img}qiyezongmu_03.png" class="middle-img"/><span class="span-xx">{$vo.linkman}</span>

那年,你用浏览器访问index.php文件的时候,会看见五个用知乎帐号登录的登入按键,点击开关,会跳转到网易登入页面,要你输入腾讯网腾讯网客商名密码,他会做不一致的操作。具体流程作者在地方也说过了。

<img src="{$home_img}qiyezongmu2_06.png" class="middle-img"/><span class="span-xx">{$vo.linktel}</span>

你可能感兴趣的稿子:

  • CI框架入门示例之数据库取多少总体兑现格局
  • php ci框架中加载css和js文件战败的缓和措施
  • CI框架中site_url()和base_url()的区别
  • CI框架中libraries,helpers,hooks文件夹详细表明
  • php CI框架插入一条或多条sql记录示例
  • php ci框架验证码实例深入分析
  • CI框架中cookie的操作方法剖判
  • CI框架Session.php源码深入分析
  • CI框架自动加载session现身报错的化解办法
  • 哪些消除CI框架的Disallowed Key Characters错误提示
  • CI框架源码阅读,系统常量文件constants.php的配备
  • CI框架完结框架前后端分离的方法详解

<img src="{$home_img}qiyezongmu2_03.png" class="middle-img"/><span class="span-xx"> {$vo.qqnum}</span>

</a>

</div>

  <div class="fl2">

<h3>集团主营</h3>

<p>{$vo.des}</p>

</div>

</div>

 </volist>

</div>**       **

 <div class="page" id="page">

<if condition="$arr['count'] neq 0 ">

<span>共<b>{$arr.count}</b>条记录,{$arr.p}/{$arr.Page}页</span>

{$arr.show}

<else />

<center><b>暂无数据</b></center>

</if>

 

</div>

2、jquery & ajax

<script type="text/javascript">

/*

*区域(点击省获取区,点击区获取县)

*/

function sendData(data,type){

var data1=data.value;

var name=$(data).attr('name');

   var companyname=$("#companyname").val();

var data2 =$(data).parent().attr("id");

   var aa = $(data).text();

 $(data).addClass('selectPublicA').siblings().removeClass()

/*ajax post提交再次回到区域列表 */

$.ajax({ 

url:"{:U('Home/Company/ajaxarea')}",

data:{data:data1,type:type},

type:"post",

dataType:"json",

success:function(msg){

  console.log(msg)

  if(type == 'province_id'){

  var html ='';

  $('#city_id').empty();

  $('#area_id').empty();

  for(var i=0;i<msg.length;i++){

  html += "<li value='"+msg[i].areaId+"' onclick='sendData(this,"city_id")'>"+msg[i].areaName+"</li>";

   }

  $(html).appendTo($("#city_id"));

    }else if(type == 'city_id'){

  $("#area_id").parent().css("display","block");

  var html ='';

  $('#area_id').empty();

  for(var i=0;i<msg.length;i++){

  html += "<li value='"+msg[i].areaId+"' onclick='sendData(this,"area_id")'>"+msg[i].areaName+"</li>"

  }

  $(html).appendTo($("#area_id"));

    **}**

  }

})

$.ajax({

url:"{:U('Home/Company/index')}",

data:{data:data1,type:type,name:name,companyname:companyname},

type:"post",

dataType:"json",

success:function(msg){

console.log(msg)

var html="";

var company=msg.rows;

var url=msg.url;

$('#page').empty(); 

$("#companylist").empty();

if(company != null){

for(var i=0;i<company.length;i++){

html += "<div class='recommend-logo' >"

html += "<div class='fl1'><a href='"+url[i]+"'><img src='{$uploads}"+company[i].logo+"' class='fl-img'/><p>"+company[i].name+"</p>"

html += "<span class='span-add'>"+company[i].addreess+"</span>"

html += "<img src='{$home_img}qiyezongmu_03.png' class='middle-img'/><span class='span-xx'>"+company[i].linkman+"</span>"

html += "<img src='{$home_img}qiyezongmu2_06.png' class='middle-img'/><span class='span-xx'>"+company[i].linktel+"</span>"

html += "<img src='{$home_img}qiyezongmu2_03.png' class='middle-img'/><span class='span-xx'>"+company[i].qqnum+"</span></a></div>"

html += "<div class='fl2'><h3>集团主营</h3><p>"+company[i].des+"</p></div></div>"

}

}

$(html).appendTo("#companylist");

var htmlpage="<span id='page'>共<b>"+msg.count+"</b>条记录,"+msg.p+"/"+msg.Page+"页"+msg.show+"</span>";

$(htmlpage).appendTo($("#page"));

}

})

}

</script>

 

3、PHP 页面

 

public function index(){   

        $p = I('request.p');//获取点击分页的页数

        $paging  = $p<1?1:$p;

   //==============================接收AJAX/GET传参===============//

        $areaId=I('request.data');

        $industryId=I('request.name');

        $type=I('request.type');

        $companyname=I('request.companyname');

   //==============================接收AJAX/GET传参===============//

   //==============================查询条件=====================//

        $map = array('data' => $areaId,'type'=>$type,'name'=>$industryId,'companyname'=>$companyname);

        $order='';

        if(IS_AJAX){

            if($areaId>0){//若点击省市区  该条件写入session

                 $_SESSION['areaId']=$areaId;

                 $_SESSION['type']=$type;

            }

            if($industryId >0){//若点击行当 该法规写入session

                 $_SESSION['industryId']=$industryId;

            }

            if($type == 'industry'){//若点击行业 调用session地区条件

                $areaId=$_SESSION['areaId'];

                $type=$_SESSION['type'];

             }

            if($type == 'companyname'){//若输入集团名查询 调用session 地区、行业标准

                $areaId=$_SESSION['areaId'];

                $industryId=$_SESSION['industryId'];

                $type=$_SESSION['type'];

            }

            $where= $this->get_where($areaId,$type,$industryId,$companyname);

        }else{

            //刷新页面时去掉session中标准

            $_SESSION['areaId']="";

            $_SESSION['type']='';

            $_SESSION['industryId']='';

            $where = 'ischeck = 1';

            $where .=" AND ".$this->get_where($areaId,$type,$industryId,$goodsname);

        } 

   //==============================查询条件=====================//

   //==============================查询数据=====================//

   $list =  D('Areas','Api')->getareas(100,1,'*','`parentId`=0');//全数地区列表

        $industry = D('Industry','Api')->getindustry(1000,1,'*','`status`=1 AND `isdelete`=1');//行业音讯

   $arr=$this->getData_page('Company',3,'*',$where,$order,$map);

   //==============================查询数据=====================//

         $arr['p']=$paging;

         $company=$arr['rows'];

   if(IS_AJAX){

    echo json_encode($arr);

   }else{

    $this->assign('areaId',$areaId);

            $this->assign('industryId',$industryId);

            $this->assign('company',$company);

            $this->assign('arr',$arr);

            $this->assign('list',$list['tag']);

            $this->assign('industry',$industry['tag']);//须要列表

            $this->display();  

   }

    }

    /*

     * ajax区域联合浮动

     */

 public function ajaxarea(){

        $data['parentId']=$_POST['data'];

        if($_POST['type'] == 'province_id'){

            $list =D('Areas')->getarea($data);

            echo json_encode($list);

        }else if($_POST['type'] == 'city_id'){

            $list =D('Areas')->getarea($data);

            echo json_encode($list);

        }

 

 }

/**

*询问条件管理函数

*/

public function get_where($areaId='',$type='',$industryId='',$companyname=''){

        $where = "1=1";//初始化where变量

        if ( $areaId > 0){

            $where .=" AND {$type}={$areaId}";

        }

        if ($industryId >0){

            $where .= " AND industry_id={$industryId}";

        }

        if ('' != $companyname){

            $where .=" AND `name` LIKE '%{$companyname}%'";

        }

        return $where;

    }

/**

*查询分页数据

*$model 模型名也可说是数据表名

*/

public function getData_page($model,$num='',$field='',$where='',$order ='',$map=''){

        $Model =M($model);

        $num  = ($num != '') ? $num : '10';

        $field  = ($field != '') ? $field : '*';

        if (!empty($field)){

            $Model->field($field);

        } else {

            $Model->field('*');

        }

        if (!empty($where)){

 

            $Model->where($where);

        } 

        if (!empty($order)){

            $Model->order($order);

        }else{

            unset($order);

        }

 

        $count =$Model->where($where)->count();

 

 

        if (!empty($field)){

            $Model->field($field);

        } else {

            $Model->field('*');

        }

        if (!empty($where)){

            $Model->where($where);

        } 

        if (!empty($order)){

            $Model->order($order);

        }

        $Page = new ThinkPage($count,$num);

        $Page->setConfig('prev','上一页');

        $Page->setConfig('next','下一页');

        $Page->setConfig("last",'尾页');

        $Page->setConfig('first','首页');

        $Page->rollPage = '5';

   //TP分页方法 $show 中url 拼接条件参数  点击分页条 除了传P 也会传查询条件参数

        foreach($map as $key=>$val) {

            $Page->parameter[$key]   =   urlencode($val);

        }

        $show = $Page->show();

        $offset = $Page->firstRow.','.$Page->listRows;

        $Model->limit($offset);

        $rows = $Model->select();

        $pagetotal =ceil($Page->totalRows/$num);

        $pagetotal<1 ? 1:$pagetotal;

        $arr =array('count'=>"$count",'Page'=>"$pagetotal",'show'=>"$show",'rows'=>$rows);

        return $arr;

    }

 

小结:ajax获取条件参数提交给 php,php分景况存SESSION,以确认保障下个条件查询时有所以前的条件;分页部分选择tp自带分页查询,在此基础旅长ajax提交的参数拼接到每一遍点击分页后的URL 再通过get获取就可以实现异步查询后的数据分页

 

本文由永利集团登录网址发布于计算机教学,转载请注明出处:Thinkphp 实现QQ一键登录的例子

关键词: