Development of Sina Weibo login interface source code in CI framework full version _ PHP Tutorial

Source: Internet
Author: User
The full version of the source code of the Sina Weibo login interface developed by the CI framework. First, let's take a look at the following process: Process principle: 1. get access_token through code and get user information (including user u_id) by means of authorization (this u_id is called in the third-party login table following this process first:
Process principle:
1. get access_token through code and obtain user information (including user u_id) through authorization (this u_id is called sina_id in the third-party login table that is created by yourself)
2. query the third-party logon table. if the user sina_id does not exist, there are two types of situations: 1. if the user already has an account on the platform, you need to set the platform (for example, the platform user table is user_reg) bind the user ID to a third-party login table (for example, the third_login table), and then let the customer log on;
2. if you do not have an account on the platform, go to the registration page to register the account. when you register the account, write the information to the uer_reg table and write the user sina_id to the third-party logon table for binding;
3. query the third-party logon table (third_login). If the user sina_id exists, query the user table (user_reg). if the email address is activated, log on directly. if the email address is not activated, prompt the user to go to the mailbox to activate the account.

The detailed steps are as follows:
Step 1: Apply for App key and App secret application address: http://open.weibo.com/click on the page to access the WEB site, go in to apply for it, after the App Key and App Secret will be obtained as follows:
App Key: 1428003339
App Sercet: f1c6177a38b39f764c76a1690720a6dc
Callback address: http://test.com/callback.php

Note: After the application is completed, your Sina account is the test account. you can use this account for debugging during development. Other accounts cannot log on and cannot return information. Before development, it is best to go to the official website to check the development process. The process is the most important. As long as the thinking is clear, the rest is to use code to implement what you think.

Step 2: Download the SDK and php version (official website): Release.

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 all unique, used to identify the user, we store according to this ):

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 table'

Note: The platform returns the u_id, which is the unique identifier of the user. I save it as sina_id. the user_id is the id of the user_reg table associated with the platform user table. the user_reg table is not listed here, you can create tables based on actual project requirements. we recommend that you use phpmyadmin and MySQL Workbench for easy operations.
If you only need to perform the Sina login interface, you can remove the qq_id field.

2. write the configuration file, create a file sina_conf.php under the application, and write the applied App Key and App Secret into the file. the code is as follows:

The code is as follows:


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

Save

3. copy the downloaded saetv2.ex. class. php file to application/libraries.
Note: This is a very important class. methods in this class are used for logon, authorization, and user information retrieval. without such methods, you cannot play with them. they are stuck to application/libraries.

4. write Sina Weibo login class (QQ login is also available, and QQ login here is also encapsulated together, even if only Sina login interface is used, it will not be affected ), create a file third_login_model.php under application/models. 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'; // third-party login table
$ This-> users = $ this-> db-> 'User _ reg '; // user table of this project
$ This-> config-> load ("sina_conf ");
$ This-> sina = $ this-> config-> item ("sina_conf ");

}

/**
* @ Uses: Sina Weibo logon
* @ Param:
* @ Return: $ sina_url ---- logon 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 on, get the token through the returned code value, implement 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 _ url'] = $ 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 the third-party logon 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 --- query the user table and third-party login table
* @ 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 the 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 table 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'); // logout
$ This-> session-> unset_userdata ('qq _ id'); // cancel
}
Return $ resb;
}
}

Save
Note: This code is sent from the callback. php file at the entrance. his detailed code will be available in step 1.
Now the configuration file, model, and data table are available, and the controller and view file are available.

5. write the logon controller and create the login. php file under application/controllers (you can obtain the name by yourself). The code is as follows:

The code is as follows:


/**
* 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 logon class of the project. The original code is not provided in this post, different projects have different requirements and can be encapsulated by yourself according to your project requirements.
$ 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 the Sina logon interface class
$ Datas ['sina _ url'] = $ this-> third-> sina_login (); // call the sina_login method in the class
$ This-> load-> view ("index. php", $ datas); // retrieves the view file and transmits data

}

Public function callback (){
Header ("content-type: text/html; charset = utf-8 ");
$ This-> load-> model ("user_reg_model", "user_reg ");
$ Code = $ _ REQUEST ['code']; // The code value is transmitted from the callback. php file.
$ Arr = array ();
$ Arr = $ this-> third-> sina_callback ($ code); // obtain user information (including u_id) through authorization)
$ Res = $ this-> third-> select_third (array ("sina_id" => $ arr ['id']);
If (! Empty ($ res) {// The 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 the mailbox status of the user table, the user_detect method is used to query user information. as mentioned above, the login_model.php class is not provided and needs to be encapsulated by everyone.
If ($ user_info ['status']) {// determines whether the user account is activated based on the status. in the user_reg table, the field status, 1 is inactive, and 0 is activated.
Echo "script" alert ('Your account is not activated, please go to the mailbox to activate it! '); Location ='/login/index'; script "; die ();
}
$ Datas = $ this-> third-> select_user_name ($ arr ['id']); // after activation, the information is written to the user table and third-party login table.
$ Uname = $ datas ['username']; // username and password are all fields in the user_reg table. this post is not provided for building the user_reg data table because each project is different, depends on the actual project.
$ Password = $ datas ['password'];
$ This-> load-> model ("login_model", "login ");
$ This-> login-> validation ($ uname, $ password); // The validation method is the main method for logging on. here, it is mainly used when logging on, write user information to the third-party login table. the following code only writes to the third-party login table.
Echo "script alert ('logon successful! '); Location ='/user_center 'script "; die ();
} Else {// The user's third-party table does not have a record. ask if the user has an account on the platform, no jump registration, or a jump logon.
$ This-> session-> set_userdata ('sina _ id', $ arr ['id']);
Echo "script" if (! Confirm ('have you registered a user on the platform? ') {Location ='/register/index'} else {location = '/login'}; script ";
}
}

Public function login_validation (){
// Add and modify records of third-party login user IDs, sina_id, and 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); // bind
}

// Save


// In the registration controller, the user information is written to the user_reg table, and the sina_id is also written to the third_login table. here I only show the code for saving the user ID of the third-party login interface to the data table.
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, create index. php file under application/view, code:

The code is as follows:





Sina Weibo logon interface


">




Save
(This is an image button, pictures you can download on the official website,: http://open.weibo.com/widget/loginbutton.php)

7. callback address
Before in step 2 configuration file, set the callback address: http://test.com/callback.php, that callback. where should php be placed? it needs to be placed with the entry index. php and application are at the same level. Create the callback. php file in the starting directory. 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 ="



Automatic jump

";
$ Str. ="


Related Article

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.