This article mainly introduces the source code analysis of the Sina Weibo login interface developed by the CI framework. It has a certain reference value. Now it is shared with everyone. Friends in need can refer to it.
Note: This article 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 and explain it in detail.
First let’s look at the process:
Process principle:
1. Obtain the access_token through code and obtain authorization, and obtain the user’s information (including user u_id) (this u_id is in the third-party login form behind) It's called sina_id, and you need to build that table 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 (such as : The user table of the platform 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; 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;
3. Query the third-party login table (third_login), and if the user sina_id exists, query the user table (user_reg ), if the email address has been activated, log in directly. If it is not activated, the user is 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, and just 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
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, among which One 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, used Identifies the user, we store it based on this):
1 2 3 4 5 6 7 8 9 10 11 12 | 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 = '第三方登录表'
|
Copy after login
Description: The platform returns u_id, which is the unique identifier of the user. I save it as sina_id, user_id is associated with the platform user table user_reg I will not list the id and user_reg tables here. You can build the tables according to actual project requirements. The recommended operating tools are phpmyadmin and MySQL Workbench, which are easy to operate.
If you only need to make 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:
1 2 3 4 5 6 | <?php
$config [ "sina_conf" ] = array (
"App_Key" => '1428003339',
"App_Secret" =>'f1c6177a38b39f764c76a1690720a6dc',
"WB_CALLBACK_URL" => 'http:
);
|
Copy after login
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 to 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), in application/models Create a file third_login_model.php, code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | <?php
class third_login_model extends CI_Model{
private $sina = array ();
private $qq = array ();
private $users ='';
private $third ='';
public function __construct() {
parent::__construct();
$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" );
}
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 ;
}
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();
$uid = $uid_get ['uid'];
$user_message = $c ->show_user_by_id( $uid );
return $user_message ;
}
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 ;
}
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 ;
}
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 ;
}
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 ;
}
}
|
Copy after login
Save
Description: This code is passed from the entry file callback.php, and its detailed code will be in step 7.
Now that the configuration file, model, and data table are all there, the next step is the controller and view files.
5.
Write login controller Under application/controllers, create the login.php file (you can choose the name yourself), Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | <?php if ( ! defined('BASEPATH')) exit ('No direct script access allowed');
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();
$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'];
$arr = array ();
$arr = $this ->third->sina_callback( $code );
$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']));
if ( $user_info ['status']){
echo "<script>alert('您的账号未激活,请去邮箱激活!');location='/login/index';</script>" ; die ();
}
$datas = $this ->third->select_user_name( $arr ['id']);
$uname = $datas ['username'];
$password = $datas ['password'];
$this ->load->model( "login_model" , "login" );
$this ->login->validation( $uname , $password );
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(){
$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 );
}
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 );
}
}
|
Copy after login
Save
6.
View file layout Sina Weibo login button, create index.php file under application/view, code:
1 2 3 4 5 6 7 8 9 | <html>
<head>
<meta content= "text/html; charset=utf-8" >
<title>新浪微博登录接口</title>
</head>
<body>
<p><a href= "<?=$sina_url?>" ><img src= "http://images.cnblogs.com/weibo_login.png" width= "110" /></a></p>
</body>
</html>
|
Copy after login
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.回调地址
前面在第1步配置文件文件的时候,设置了回调地址:http://test.com/callback.php ,那这个callback.php放在什么地方呢,它需要放在和入口index.php同级的位置,它和application也是同级的。所在在开始的目录下新建文件callback.php。代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php
$code ='';
$url = '';
$str ='';
$code = $_REQUEST ['code'];
$url = "/login/callback" ;
$str = "<!doctype html>
<html>
<head>
<meta charset=\"UTF-8\">
<title>自动跳转</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 ;
|
Copy after login
保存
这个时候,你用浏览器访问index.php文件的时候,会看到一个用微博帐号登录的登录按钮,点击按钮,会跳转到微博登录页面,要你输入新浪微博用户名密码,他会做不同的操作。具体流程我在上面也说过了。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
如何使用CodeIgniter开发实现支付宝接口调用
The above is the detailed content of Source code analysis on CI framework development of Sina Weibo login interface. For more information, please follow other related articles on the PHP Chinese website!