Home Backend Development PHP Tutorial 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

Jul 13, 2016 am 10:29 AM
ci interface

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard Mar 12, 2024 pm 04:34 PM

When we assemble the computer, although the installation process is simple, we often encounter problems in the wiring. Often, users mistakenly plug the power supply line of the CPU radiator into the SYS_FAN. Although the fan can rotate, it may not work when the computer is turned on. There will be an F1 error "CPUFanError", which also causes the CPU cooler to be unable to adjust the speed intelligently. Let's share the common knowledge about the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard. Popular science on the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard 1. CPU_FANCPU_FAN is a dedicated interface for the CPU radiator and works at 12V

Common programming paradigms and design patterns in Go language Common programming paradigms and design patterns in Go language Mar 04, 2024 pm 06:06 PM

As a modern and efficient programming language, Go language has rich programming paradigms and design patterns that can help developers write high-quality, maintainable code. This article will introduce common programming paradigms and design patterns in the Go language and provide specific code examples. 1. Object-oriented programming In the Go language, you can use structures and methods to implement object-oriented programming. By defining a structure and binding methods to the structure, the object-oriented features of data encapsulation and behavior binding can be achieved. packagemaini

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

Solution to NotImplementedError() Solution to NotImplementedError() Mar 01, 2024 pm 03:10 PM

The reason for the error is in python. The reason why NotImplementedError() is thrown in Tornado may be because an abstract method or interface is not implemented. These methods or interfaces are declared in the parent class but not implemented in the child class. Subclasses need to implement these methods or interfaces to work properly. How to solve this problem is to implement the abstract method or interface declared by the parent class in the child class. If you are using a class to inherit from another class and you see this error, you should implement all the abstract methods declared in the parent class in the child class. If you are using an interface and you see this error, you should implement all methods declared in the interface in the class that implements the interface. If you are not sure which

Application of interfaces and abstract classes in design patterns in Java Application of interfaces and abstract classes in design patterns in Java May 01, 2024 pm 06:33 PM

Interfaces and abstract classes are used in design patterns for decoupling and extensibility. Interfaces define method signatures, abstract classes provide partial implementation, and subclasses must implement unimplemented methods. In the strategy pattern, the interface is used to define the algorithm, and the abstract class or concrete class provides the implementation, allowing dynamic switching of algorithms. In the observer pattern, interfaces are used to define observer behavior, and abstract or concrete classes are used to subscribe and publish notifications. In the adapter pattern, interfaces are used to adapt existing classes. Abstract classes or concrete classes can implement compatible interfaces, allowing interaction with original code.

Insight into Hongmeng system: actual function measurement and usage experience Insight into Hongmeng system: actual function measurement and usage experience Mar 23, 2024 am 10:45 AM

As a new operating system launched by Huawei, Hongmeng system has caused quite a stir in the industry. As a new attempt by Huawei after the US ban, Hongmeng system has high hopes and expectations. Recently, I was fortunate enough to get a Huawei mobile phone equipped with Hongmeng system. After a period of use and actual testing, I will share some functional testing and usage experience of Hongmeng system. First, let’s take a look at the interface and functions of Hongmeng system. The Hongmeng system adopts Huawei's own design style as a whole, which is simple, clear and smooth in operation. On the desktop, various

What is the difference between interfaces and abstract classes in PHP? What is the difference between interfaces and abstract classes in PHP? Jun 04, 2024 am 09:17 AM

Interfaces and abstract classes are used to create extensible PHP code, and there is the following key difference between them: Interfaces enforce through implementation, while abstract classes enforce through inheritance. Interfaces cannot contain concrete methods, while abstract classes can. A class can implement multiple interfaces, but can only inherit from one abstract class. Interfaces cannot be instantiated, but abstract classes can.

Inner class implementation of interfaces and abstract classes in Java Inner class implementation of interfaces and abstract classes in Java Apr 30, 2024 pm 02:03 PM

Java allows inner classes to be defined within interfaces and abstract classes, providing flexibility for code reuse and modularization. Inner classes in interfaces can implement specific functions, while inner classes in abstract classes can define general functions, and subclasses provide concrete implementations.

See all articles