Home  >  Article  >  Backend Development  >  Sina Weibo login interface (PHP version)_PHP tutorial

Sina Weibo login interface (PHP version)_PHP tutorial

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

Full version of Sina Weibo login interface under CI framework
Note: This post is only suitable for CI framework. Functional implementation: The login interface jumps to the link successfully, obtains the user information (including the most important u_id) successfully, connects the user to the local platform, stores the information after the user logs in successfully, and designs the third-party login table of the local database. In short, the interface process has been completed. I have notes on almost every key step to explain in detail.

First, let’s take a look at the process:
Principle of the process:
1. Obtain the access_token through code, authorize it, 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 user sina_id does not exist, There are two situations: one: the user already has an account on the platform. In this case, the user ID of the platform (for example: the user table of the platform is: user_reg) needs to be bound to the third-party login table (for example: third_login table), and then the Customer login;                                Register on the registration page. At the same time of registration, 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. Defined;
3. Query the third-party login table (third_login). If the user sina_id exists, then query the user table (user_reg). If the email has been activated, log in directly. If it is not activated, prompt the user Go to your email to activate your account.
The following steps will be explained in detail:

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. After passing, you will get the App Key and App Secret as follows: App Key: 1428003339
App Sercet: f1c6177a38b39f764c76a1690720a6dc
Callback address: http://test.com/callback.php
Instructions: After applying, then you This Sina account is 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:
Code1. 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 the user. We store it based on this):
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 , it 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 build the table according to actual project requirements. The recommended operating tool is phpmyadmin. ,MySQL Workbench, easy to operate.

If you only need to create a 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:

$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 .
Explanation: 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 anymore. Stick it intact. under application/libraries.

4. Write the 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). Create a file third_login_model.php under application/models, code:


/**
* 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();                                                                                                             ."/libraries"."/saetv2.ex.class.php";
            $this->third = $this->db->'third_login';//Third party Login table
$this->users = $this->db->'user_reg';//User table for this project
$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 ) ;//Complete authorization
} 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 the 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 : 将用户和第三方登录表信息绑定
      * @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'];//The code value is passed from the entry file callback.php
$arr =array();
        $arr = $this->third->sina_callback($code);//Get user information (including u_id) by authorizing and obtaining user information (including u_id)
                $res = $this->third- >select_third(array("sina_id"=>$arr['id']));
If(!empty($res)){//The user already has an account record, first Determine whether the account is activated
                   $user_info = $this->user_reg->user_detect(array("id"=>$res['user_id']));//Query the user table For mailbox status, the user_detect method is a method for querying user information. As mentioned above, the login_model.php class is not provided in this post and needs to be encapsulated by yourself.
If($user_info['status']){//Determine whether the user account is activated based on the status of the status. The field status in the user_reg table, 1 means not activated, 0 means activated
echo "<script>alert('Your account is not activated, please go to your email to activate it!');location='/login/index';</script>";die();
                                                                                                                                                                                    ​Enter the user table and third-party login table
$uname = $datas['username'];//username and password are both fields of the user_reg table. The construction of the user_reg data table is not provided in this post. , because every project is different, it needs to be determined according to the actual project >model ("login_model", "login"); The main purpose here is to write user information into the third-party login table when logging in. The following only provides the code for writing into the third-party login table
                                                                                                                                           echo "<script>alert('Login successful! ');location='/user_center'</script>";die();
              }else{//The user’s third-party table has no record, and asks the user whether he has an account on the platform. No jump registration, there are jump login
$ this-& gt; session-& gt; set_userdata ('sina_id', $ arr ['id']); >                echo "<script>if(!confirm('Have you ever registered a user on the platform? ')){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'],
            "sina_id" => $this->session ->userdata('sina_id'),
               "qq_id"                                                                                                          );

if($third_info['sina_id']||$third_info['qq_id']) $this->third->binding_third($third_info); // Binding
}
 
Save


     //在注册控制器里,用户信息写入user_reg表,同时也把sina_id写入third_login表,我这里只展示第三方登录接口用户id存入数据表的代码
class Register extends CI_Controller {

    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);
    }
}
保存

6.视图文件布置新浪微博登录按钮,在application/view下建立index.php文件,代码:


   
    新浪微博登录接口


    





Save
Description: 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. So where should this callback.php 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:


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



< Title & gt; automatic jump & lt;/title & gt;
& lt;/head & gt;
& lt; ";
$ STR .="
";
$str .="";
$str .="


                                                                                                                                                              .getElementById('form').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 your Weibo account. Click the button and you will be redirected. Go to the Weibo login page and ask you to enter your Sina Weibo username and password, and it will perform different operations. I have also mentioned the specific process above.

This post is for reference only and does not involve any commercial scope.
If you want to reprint, please indicate the source and original address, thank you!

If there is something wrong or something that can be improved, please point it out in the comments below, thank you!


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

www.bkjia.com

true

TechArticleFull version of Sina Weibo login interface under CI framework Note: This post is only suitable for CI framework. Function implementation: The login interface jump link is successful, the user information (including the most important u_id) is successfully obtained,...
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