search
HomeBackend DevelopmentPHP TutorialCI framework development Sina Weibo login interface full version source code_PHP tutorial

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>CI framework development Sina Weibo login interface full version source code_PHP tutorial

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
主板aafp是什么接口主板aafp是什么接口Aug 29, 2022 am 10:50 AM

主板上的aafp是音频接口;该接口的功能是启用前面板的“3.5mm”插孔,起到传输音频的作用,aafp跳线基本上由两个部分组成,一部分是固定在主板、硬盘等设备上的,由两根或两根以上金属跳针组成,另一部分是跳线帽,是一个可以活动的组件,外层是绝缘塑料,内层是导电材料,可以插在跳线针上。

cha fan表示什么风扇cha fan表示什么风扇Sep 15, 2022 pm 03:09 PM

“cha fan”表示的是机箱风扇;“cha”是“chassis”的缩写,是机箱的意思,“cha fan”接口是主板上的风扇供电接口,用于连接主板与机箱风扇,可以配合温度传感器反馈的信息进行智能的转速调节、控制噪音。

ioioi是什么接口ioioi是什么接口Aug 31, 2022 pm 04:50 PM

ioioi是指COM接口,即串行通讯端口,简称串口,是采用串行通信方式的扩展接口。COM接口是指数据一位一位地顺序传送;其特点是通信线路简单,只要一对传输线就可以实现双向通信(可以直接利用电话线作为传输线),从而大大降低了成本,特别适用于远距离通信,但传送速度较慢。

link/act是什么接口link/act是什么接口Feb 23, 2023 pm 04:14 PM

link/act是物理数据接口;交换机上的link/act指示灯表示线路是否连接或者活动的状态;通常Link/ACT指示灯用来观察线路是否激活或者通畅;一般情况下,若是线路畅通,则指示灯长亮,若是有数据传送时,则指示灯闪烁。

sata6g是什么接口sata6g是什么接口Sep 14, 2022 am 11:46 AM

sata6g是数据传输速度为“6G/s”的sata接口;sata即“Serial ATA”,也就是串行ATA,是主板接口的名称,现在的硬盘和光驱都使用sata接口与主板相连,这个接口的规格目前已经发展到第三代sata3接口。

鼠标插在主机哪个接口鼠标插在主机哪个接口Sep 13, 2022 pm 03:50 PM

鼠标插在主机的串口接口、PS/2接口或USB接口上。串行接口是最古老的鼠标接口,是一种9针或25针的D型接口,将鼠标接到电脑主机串口上就能使用。PS/2接口是1987年IBM公司推出的鼠标接口,是一种鼠标和键盘的专用接口,是一种6针的圆型接口。USB接口,是一种高速的通用接口,具有非常高的数据传输率,且支持热插拔。

dc接口是什么意思dc接口是什么意思Aug 24, 2022 am 10:47 AM

dc接口是一种为转变输入电压后有效输出固定电压接口的意思;dc接口是由横向插口、纵向插口、绝缘基座、叉形接触弹片、定向键槽组成,两只叉型接触弹片定位在基座中心部位,成纵横向排列互不相连,应用于手机、MP3、数码相机、便携式媒体播放器等产品中。

pump fan是什么接口pump fan是什么接口Jun 25, 2021 pm 02:55 PM

pump fan是散热风扇接口。主板上的风扇接口有cpu fun、sys fun、pump fun,对于一般普通用户来说区别不大,一般接哪个都行,而pump fun上的电流更大一点,用于接功率大一点的水冷风扇头。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),