Sina Weibo login Interface (PHP version) _php tutorial

Source: Internet
Author: User
CI framework Sina Weibo login interface full version
Note: This post is only suitable for CI framework. Function Realization: Login interface Jump link succeeds, get user information (including most important u_id) success, connect user to local platform, store information after successful login, local database design of third party login table. In summary, the interface process has all been completed. I almost have comments on each key step, explaining the details.

first Look at the process:
Process principle:
1. Obtain Access_token through code and obtain the user's information (including user u_id) (this u_id is called sina_id in the third-party login form, which needs to be built by itself)
2. Query the third-party login form, if there is no user sina_id, in 2 cases, one: the user has an account on the platform, then need to put the platform (such as: The Platform user table is: user_reg) User ID bound to a third-party login table (such as: Third_login table), Then let the customer login;
Second: Users in the platform does not have an account, jump to register page registration, registration, the information is written to the Uer_reg table, but also the user sina_id write to a third-party login form to bind;
3. Query the third-party login form (third_login), if there is User sina_id, and then query the user table (User_reg), if the mailbox has been activated, directly login, if not activated, prompting the user to the mailbox activation account.

The following steps are described in detail:
The first step: apply for App key and app secret application address: http://open.weibo.com/in the page click website access to the Web, go into the application is good, through will get app key and app secret as follows:
App key:1428003339
App SERCET:F1C6177A38B39F764C76A1690720A6DC
callback Address: http://test.com/callback.php

Description: After the application, then your Sina account is the test account, you can use this account in the development of debugging, other accounts are unable to log in, unable to return information. Before development, the best First officer net look at the development process, the process is the most important. As long as the idea is clear, the rest is to use the code to achieve your thinking.

The second step: download the SDK, download the PHP version, download address (official website): http://code.google.com/p/libweibo/downloads/list, download down there are 5 files, One of them is saetv2.ex.class.php, and I just need this file.

Step Three: code
1. Create a third-party login form to store information about third-party logins (Sina is u_id,qq is OpenID, they are unique, used to identify the user, we store it according to this):
CREATE TABLE IF not EXISTS ' Third_login ' (
' user_id ' INT (6) is not NULL,
' sina_id ' BIGINT (+) NULL,
' qq_id ' varchar (+) 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 table '

Description: The platform returned is u_id, he is the user's unique identity, I put him as sina_id,user_id is associated Platform user table User_reg ID, user_reg table I do not list here, you can according to the actual project needs to build a table, The recommended operating tools are Phpmyadmin,mysql Workbench and easy to operate.
If you only need to do Sina login interface, that can be qq_id this field removed.


2. Write the configuration file, create a new file under Application sina_conf.php, write the app Key and app secret that you just applied to, and 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 just downloaded to application/libraries.
Description: This is a very important class, login, authorization, access to user information to use the method in this class, no he can not play down, intact stick to application/libraries under.

4. Write Sina Weibo login class (QQ login is also available, I am here QQ login also encapsulated together, even if only do Sina login interface, also do not affect), under the Application/models build a file third_login_model.php, 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 ();
$this->load->library (' Session ');
include_once APPPATH. " /libraries "." /saetv2.ex.class.php ";
$this->third = $this->db-> ' third_login ';//third-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 logging in, get token by returning the code value, implement authorization completion, and then get 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 ();//Get u_id
$uid = $uid _get[' uid '];
$user _message = $c->show_user_by_id ($uid);//Get user information
return $user _message;
}

/**
* @uses: Query third-party login form
* @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---Querying user tables and third-party login forms
* @param: $where
* @return: Third-party login 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 form and third party login form
* @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 users 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" and "= $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 ');//Logout
}
return $resb;
}
}

Save
Description: This code is transmitted by the portal file callback.php, and the 7th step will have his detailed code.
now that the configuration file, model, data table are available, then the controller and view files.

5. Write login controller under Application/controllers, build login.php file (name you can fetch by yourself), code:


/**
* Description of index
* @author Victory
*/
class Login extends Ci_controller {

Public function __construct () {
parent::__construct ();
$this->load->model (' Login_model ', ' login ');//This class is the user login class for this project, this post does not provide the original code, because different projects, different requirements, can be packaged according to your project needs
$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");//Load Sina Login Interface class
$datas [' sina_url '] = $this->third->sina_login ();//Sina_login method in the calling class
$this->load->view ("index.php", $datas);//tune the view file and pass in the data

}

Public function Callback () {
header ("content-type:text/html; Charset=utf-8 ");
$this->load->model ("User_reg_model", "User_reg");
$code = $_request[' code '];//code value is passed callback.php the entry file.
$arr =array ();
$arr = $this->third->sina_callback ($code)//authorization and obtaining user information (including u_id)
$res = $this->third->select_third (Array ("sina_id" + = $arr [' id ']));
if (!empty ($res)) {//user has an Account record, first determine whether the account is activated
$user _info = $this->user_reg->user_detect (Array ("id" + $res [' user_id ']));//query user table mailbox status, User_ Detect method is to query the user information method, above also said, login_model.php This class this paste does not provide, need everyone to package.
if ($user _info[' status ') {//depending on status state to determine if user account is active, field status,1 in User_reg table is inactive, 0 is activated
echo "";d ie ();
}
$datas = $this->third->select_user_name ($arr [' id ']);//After activation, write the information to the user table and the third-party login form
$uname = $datas [' username '];//username,password are all fields of the User_reg table, the User_reg data table is not provided, because each project is different and needs to be based on the actual project
$password = $datas [' password '];
$this->load->model ("Login_model", "Login");
$this->login->validation ($uname, $password);//validation method is the main method of login, which is mainly to write the user information to a third-party login form when logging in. Only the code that writes to the third-party login table is provided below
echo "";d ie ();
}else{//User Third party table does not have the record, asks the user whether has the account in the platform, did not jump to register, has the jump login
$this->session->set_userdata (' sina_id ', $arr [' id ']);
echo "";
}
}

Public function Login_validation () {
//third-party login user ID, sina_id,qq_id record modification
$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); Binding
}

Save


//In the registration controller, the user information is written to the User_reg table, but also sina_id written to the Third_login table, I only show the third-party login interface user ID stored in the data table code
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);
}
}
Save

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



Sina Weibo Login Interface


">



Save
Description: This is a picture button, image you can download, download address: http://open.weibo.com/widget/loginbutton.php

7. Callback Address
before the 1th step in the configuration file file, set the callback address: http://test.com/callback.php, Where is this callback.php placed, it needs to be placed in the same position as the entrance index.php, and it is similar to application. The new file callback.php is located in the starting directory. Code:


/*
* To-change the 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 over
$code = ";
$url = ";
$str = ";
$code = $_request[' code ');
$url = "/login/callback";

$str = "



Auto Jump

";
$str. = "


";
echo $str;

Save

At this time, you use a browser to access the index.php file, you will see a Weibo Account login button, click the button, will jump to the microblogging login page, you enter the Sina Weibo user name password, he will do a different operation. Specific process I have said it on the above.

this post is for informational purposes only and does not involve any commercial scope.
if you want to reprint, please explain the source and original address, thank you!
if wrong, or can be improved, please comment below, thank you!

http://www.bkjia.com/PHPjc/777154.html www.bkjia.com true http://www.bkjia.com/PHPjc/777154.html techarticle CI framework Sina Weibo login interface Full version Description: This post is only suitable for the CI framework. Function implementation: Login interface Jump link success, access to user information (including the most important u_id) success, ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.