CI Framework Develops Full Source Version of Sina Weibo Login Interface

  • 2021-06-28 11:46:23
  • OfStack

First, look at the process:
Process Principle:
1. Obtain access_from codetoken authorizes and obtains user information (including user u_id (this u_id is called sina_in the subsequent third-party login formid, that table needs to be built by yourself)
2. Query the third party login table if user sina_does not existid, there are two cases, 1: the user already has an account number in the platform, when you need to put the platform (for example, the user table of the platform is: user_reg) User id is bound to a third-party login table (for example, third_login table), and then let the customer log in;
2: User has no account number on the platform, jump to the registration page to register, and write the information to uer_while registeringThe reg table also puts the user sina_id writes to the third party login table for binding;
3. Query the third party login table (third_login), if user sina_existsid, then query the user table (user_reg), if the mailbox is activated, log in directly, if not, prompt the user to go to the mailbox to activate the account number.

Start with the steps below:
Step 1: Apply for App key and App secret application addresses: http://open.weibo.com/Access WEB by clicking on the website on the page. You will get App Key and App Secret as follows:
App Key:1428003339
App Sercet:f1c6177a38b39f764c76a1690720a6dc
Callback address: http://test.com/callback.php

Note: After you apply, your Sina account number is the test account number. You can debug with this account when you develop it. Other accounts can not be logged in and information can not be returned.Before development, it is best to go to the official website to see the development process, which is the most important.As long as the idea is clear, the rest is to use code to achieve what you think.

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

Step 3: Code
1. Establish a third-party login form to store third-party login information (Sina is u_id, QQ are openid, they are the only ones to identify users, and we store them according to 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 = ' No. 3 Party Login Form '

Description: Platform returns u_id, he is the user's only identification, I save him as sina_id, user_id is the associated platform user table user_id of reg, user_reg table I do not list here, you can build the table according to actual project requirements, the recommended operating tools are phpmyadmin, MySQL Workbench, easy to operate.
If you only need Sina login interface, you can add qq_id is removed.

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


<?php
$config["sina_conf"] = array(
    "App_Key" => '1428003339',
    "App_Secret" =>'f1c6177a38b39f764c76a1690720a6dc',
    "WB_CALLBACK_URL" => 'http://test.com/callback.php'
);

Preservation

3.oauth certified class, copy the newly downloaded saetv2.ex.class.php file to application/libraries.
Description: This is a very important class, login, authorization, access to user information are all used in this class of methods, he can not play without it, stick to the original application/libraries.

4. Write the Sina Weibo Login Class (QQ login is also available, I encapsulate the QQ login here, even if it is only the Sina login interface), and build a file under application/models third_login_model.php, code:


<?php
/**
 * Description of third_login_model
 * No. 3 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';// No. 3 Party Login Form 
        $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 login, return by code Value, get token To complete the authorization and obtain 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();// Obtain u_id
      $uid = $uid_get['uid'];
      $user_message = $c->show_user_by_id($uid);// Get user information 
      return $user_message;
    }

    /**
      * @uses :  Query No. 3 Party Login Form 
      * @param : $where
      * @return :  No. 3 Party logon 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--- Query user tables and 3 Party Login Form 
      * @param : $where
      * @return :  No. 3 Party logon user record result set 
      */
    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 tables and 3 Party Login Form 
      * @param : $where
      * @return :  No. 3 Party logon 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 :  And 3 Party Login Table Information Binding 
      * @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');// Cancellation 
            $this->session->unset_userdata('qq_id');// Cancellation 
        }
        return $resb;
    }
}

Preservation
Description: This code was passed from the entry file callback.php, with its detailed code in step 7.
Now that you have the configuration file, model, and the data table, you will have the controller and view files.

5. Write the login controller under application/controllers to create the login.php file (name you can take it yourself), code:


<?php   if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 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']);//激活后,把信息写入用户表和第3方登录表
            $uname = $datas['username'];//username,password都是user_reg表的字段,user_reg数据表的构建本帖也不提供,因为每个项目都不1样,需要根据实际项目来
            $password = $datas['password'];
            $this->load->model("login_model","login");
            $this->login->validation($uname,$password);//validation方法是登录的主要方法,这里主要是在登录的时候,将用户信息写入第3方登录表,下面仅提供写入第3方登录表的代码
            echo "<script>alert('登录成功!');location='/user_center'</script>";die();
        }else{//用户第3方表没有记录,询问用户是否在平台有过帐号,没有跳转注册,有跳转登录
            $this->session->set_userdata('sina_id',$arr['id']);
            echo "<script>if(!confirm('是否在平台注册过用户?')){location='/register/index'}else{location='/login'};</script>";
        }     
    }
    public function login_validation(){
      //第3方登录用户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);  // 绑定
}

//保存

     //在注册控制器里,用户信息写入user_reg表,同时也把sina_id写入third_login表,我这里只展示第3方登录接口用户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);
    }
}

Preservation

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


<html>
<head>
    <meta content="text/html; charset=utf-8">
    <title> Sina Weibo Login Interface </title>
</head>
<body>
     <div><a href="<?=$sina_url?>"><img src="http://images.cnblogs.com/weibo_login.png" width="110"  /></a></div>
</body>
</html>

Preservation
Description: This is a picture button, picture you can download on the official website, download address: http://open.weibo.com/widget/loginbutton.php

7. Callback address
In the first step of the configuration file, the callback address was set: http://test.com/callback.php. Where does this callback.php go? It needs to be at the same level as the entry index.php, which is also at the same level as application.The new file callback.php is created in the starting directory.Code:


<?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.
 */
// Sina Weibo Logon Callback Entry File, Transfer Path to login/callback Method, and code Value Passed 
$code ='';
$url = '';
$str ='';
$code = $_REQUEST['code'];
$url  = "/login/callback";
$str = "<!doctype html>
<html>
    <head>
    <meta charset=\"UTF-8\">
    <title> automatic skip </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;

Preservation

At this time, when you access the index.php file with your browser, you will see a login button that logs in with your Weibo account number. Clicking the button will jump to the Weibo login page. If you enter your user name password for Sina Weibo, he will do different things.The specific process I mentioned above.


Related articles: