Home  >  Article  >  Backend Development  >  CI framework development Sina Weibo login interface full version source code_PHP tutorial

CI framework development Sina Weibo login interface full version source code_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:29:151196browse

First let’s look at the process:
Principle of the process:
1. Obtain the access_token through code and obtain authorization, and obtain the user’s information (including user u_id) (this u_id is called sina_id in the third-party login table later) , that table needs to be built by yourself)
2. Query the third-party login table. If the user sina_id does not exist, there are two situations. One: the user already has an account on the platform. In this case, the platform (for example: the platform The user table is: user_reg) The user id is bound to the third-party login table (for example: third_login table), and then the customer is allowed to log in; , the information is written into the uer_reg table, and the user sina_id is also written into the third-party login table for binding;
3. Query the third-party login table (third_login), if the user sina_id exists, then query the user table (user_reg), if If the email address has been activated, just log in directly. If it is not activated, the user will be prompted to go to the email address to activate the account.

Let’s start with the detailed steps:

Step 1: Apply for App key and App secret. Application address: http://open.weibo.com/ Click on the website to access the WEB, go in and apply, and pass You will get the App Key and App Secret as follows:
App Key: 1428003339
App Sercet: f1c6177a38b39f764c76a1690720a6dc
Callback address: http://test.com/callback.php

Note: After applying, your Sina account will be a test account. You can use this account to debug during development. Other accounts cannot log in and return information. Before development, it is best to check the development process on the official website. The process is the most important. As long as the ideas are clear, the rest is to use code to realize what you want.

Step 2: Download the SDK, download the php version, download address (official website): http://code.google.com/p/libweibo/downloads/list, there are 5 files downloaded, one of which is saetv2 .ex.class.php, I only need this file.

Step 3: Code

1
. Create a third-party login table to store third-party login information (Sina is u_id, QQ is openid, they are both unique and used to identify users, We store it based on this):

Copy code The code is as follows:
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 = 'Third-party login form'

Note: The platform returns u_id, which is the unique identifier of the user. I save it as sina_id. user_id is the id associated with the platform user table user_reg. I will not list the user_reg table here. You can follow the actual project requirements. To create a table, the recommended operating tools are phpmyadmin and MySQL Workbench, which are easy to operate.

If you only need to create the Sina login interface, you can remove the qq_id field.

2.

Write the configuration file, create a new file sina_conf.php under application, and write the App Key and App Secret you just applied for . The code is as follows:

Copy code The code is as follows:
$config["sina_conf"] = array(
"App_Key" => '1428003339',
"App_Secret" =>'f1c6177a38b39f764c76a1690720a6dc',
"WB_CALLBACK_URL" => 'http://test.com/callback. php'
);

Save

3.

oauth authentication class, copy the saetv2.ex.class.php file you just downloaded to application/libraries. Note: This is a very important class. Login, authorization, and obtaining user information all use the methods in this class. Without it, you can’t play. Stick it intact under application/libraries
.

4.

Write a Sina Weibo login class (QQ login is also available, and the QQ login here is also packaged together. Even if I only make the Sina login interface, it will not affect it), and build one under application/models File third_login_model.php, code:

Copy code The code is as follows:

/**
* Description of third_login_model
*Third-party interface authorization, login 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");

    }

    /**
* @uses: Sina Weibo login
* @param:
* @return: $sina_url----Login address
*/
    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: After logging in, obtain the token through the returned code value, complete the authorization, and then obtain the user information
* @param: $code
* @return: $user_message--user information
*/
    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: Query third-party login table
* @param: $where
* @return: Third-party login user record result set
*/
    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---Query user table and third-party login table
* @param: $where
* @return: Third-party login user record result set
*/
    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;
    }

   
    /**
* @uses: Bind user and third-party login form information
* @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;

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

保存
说明:这个code是由入口文件callback.php传过来的,第7步会有他的详细代码。
现在配置文件,model,数据表都有了,接下来就是控制器和视图文件了。

5.写登录控制器  在application/controllers下,建立login.php文件(名字你可以自己取),代码:

复制代码 代码如下:

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

public function __construct() {
parent::__construct();
$this->load->model('login_model','login');//这个类是本项目的用户登录类,本贴不提供原代码,因为不同的项目,需求不同,可根据你项目需求可以自己封装
        $this->load->model("third_login_model","third");
        $this->load->library('session');
    }

    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);//调取视图文件,并传入数据

     }

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

public function login_validation(){
//Record additions and modifications of third-party login user id, sina_id, qq_id
$third_info =array(
"user_id" => $user_ser['id' ;, ; >}

//Save


//In the registration controller, user information is written into the user_reg table, and sina_id is also written into the third_login table. Here I only show the code for storing the third-party login interface user id in the data table
class Register extends CI_Controller {

public function __construct() {

parent::__construct();
$this->load->library('session');
}

public function reg() {

                                                                                                                                                                                                                                                          ​ id'),
" qq_id" =>$this->session->userdata('qq_id'),
                                                                              ->third->binding_third($haha);
}
}



Save

6.
View file layout Sina Weibo login button, create index.php file
under application/view, code:

Sina Weibo login interface

< ;div>

SaveNote: This is a picture button. You can download the picture from the official website. Download address: http://open.weibo.com/widget/loginbutton.php 7.Callback address
When configuring the file in step 1, we set the callback address: http://test.com/callback.php, then put this callback.php Where should it be placed? It needs to be placed at the same level as the entry index.php. It is also at the same level as application. Create a new file callback.php in the starting directory. Code:




Copy code

The code is as follows:

/*
* 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.
*/
//Sina Weibo login callback entry file, transfer the path to the login/callback method, and pass the code value
$code = '';
$url = '';
$str ='';
$code = $_REQUEST['code'];
$url = "/login/callback";

$str = "



Auto Jump

";
$str .="

";
$str .="";
$str . = .submit();
             ";
echo $str;



Save
At this time, when you use the browser to access the index.php file, you will see a login button to log in with a Weibo account. Click the button and it will jump to the Weibo login page, asking you to enter your Sina Weibo user password, he will perform different operations. I have also mentioned the specific process above.

http://www.bkjia.com/PHPjc/777637.html

www.bkjia.com

http: //www.bkjia.com/PHPjc/777637.htmlTechArticleFirst let’s look at the process: Process principle: 1. Obtain the access_token through code, authorize it, and obtain the user’s information ( Including user u_id) (This u_id is called in the third-party login table later...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP pseudo-static (url rewrite mod_rewrite rewrite)_PHP tutorialNext article:PHP pseudo-static (url rewrite mod_rewrite rewrite)_PHP tutorial

Related articles

See more