_php example of the main process of Sina Weibo OAuth authentication and storage

Source: Internet
Author: User
Tags oauth
There are many articles on OAuth on the web, but including the Sina itself is not covered in detail, including the verification process and the storage of validated data, so refer to the Twitter certification process to write down some detailed comment code.

Before we start, let's set up a database to hold user information, here's a basic example of Mysql:

CREATE TABLE ' oauth_users ' (  ' id ' INT (Ten) UNSIGNED not NULL auto_increment,  ' Oauth_provider ' VARCHAR,  ' Oauth_uid ' text,  ' oauth_token ' text,  ' Oauth_secret ' text,  ' username ' text,  PRIMARY KEY (' id ')) ENGINE =myisam DEFAULT Charset=utf8;

Note the two fields Oauth_token and Oauth_secret. Sina's OAuth certification requires token and Token_secret two parameters to complete the certification, so we need to reserve two fields to record them.

Then we need to do the following in turn:

Initiate an authentication application to SINAAPI registration/or login, save the relevant data in Session if the user already has an account

The OAuth-based authentication process starts with generating a web address. The user is redirected to the URL to require authentication, and after the authentication is passed, it redirects to our application server and passes the two authenticated parameters back to the URL.

Establish index.php

<?phpsession_start ();//if (Isset ($_session[' Last_key '))  header ("Location:weibolist.php"); Include_once (' Config.php '); include_once (' weibooauth.php ');//Create Sinaoauth object instance $sinaoauth = new Weibooauth (Wb_akey, wb_skey); $keys = $sinaOAuth->getrequesttoken ();//requesting authentication tokens, the parameter is the URL we'll be redirected to$ Aurl = $sinaOAuth->getauthorizeurl ($keys [' Oauth_token '], false, ' http://t.yourtion.com/sina/callback.php ');// Save to session $_session[' keys ' = $keys;? > ">use Oauth to login

Next, we need to do the following three things in this file:

Validating data in a URL
Verify token data in Session
Verify the secret data in the Session

If all the databases are legitimate, we need to create a new instance of the Sinaoauth object, which, unlike before, is going to pass the token data to the object as a parameter. After that, we should be able to get to an access token, which should be an array, and this access token is the only data we need to save.

Establish callback.php

<?phpsession_start (); include_once (' config.php '); include_once (' weibooauth.php '); if (!empty ($_GET[' oauth_ Verifier ']) &&!empty ($_session[' Keys ' [' Oauth_token ']) &&!empty ($_session[' Keys ' [' Oauth_token '] ) {//Sinaoauth object instance, note the newly added two parameters $sinaOAuth = new Weibooauth (Wb_akey, Wb_skey, $_session[' Keys '] [' Oauth_token '], $_se  ssion[' Keys ' [' Oauth_token_secret ']);  Get access token $access _token = $sinaOAuth->getaccesstoken ($_request[' oauth_verifier ');  Save the acquired access token to the Session $_session[' access_token ' = $access _token;  Get user information $user _info = $sinaOAuth->get (' account/verify_credentials ');  Print user Information mysql_connect (database_host, Database_user, Database_pssword);  mysql_select_db (Database_db_name);  Change to your database connection in config.php if (Isset ($user _info->error) or empty ($user _info[' id ')) {//Something ' s wrong, go back  To square 1 header (' Location:index.php '); } else {//Let's find the user by it ID $sql = "SELECT * FROM Oauth_users WHERE oauth_provider= ' Sina ' and oauth_uid= '. $user _info[' id '];    $query = mysql_query ($sql);    $result = Mysql_fetch_array ($query); If not, let's add it to the database if (empty ($result)) {$sql = "INSERT into Oauth_users (Oauth_provider,        Oauth_uid, username, Oauth_token, Oauth_secret) VALUES (' Sina ', ' ". $user _info[' id ']. "', '" . $user _info[' Screen_name '). "', '" .        $access _token[' Oauth_token '). "', '" . $access _token[' Oauth_token_secret ').      "')";      $query = mysql_query ($sql);      $query = mysql_query ("select * from oauth_users WHERE id =". mysql_insert_id ());    $result = Mysql_fetch_array ($query); } else {//update the Tokens $query = mysql_query ("update oauth_users SET oauth_token = '".        $access _token[' Oauth_token '). "', Oauth_secret = '".        $access _token[' Oauth_token_secret '). "' WHERE oauth_provider = ' sina ' and Oauth_uid =".    $user _info[' id ']);    } $_session[' id ']= $result [' id ']; $_session[' UsernAme ']= $result [' username '];    $_session[' Oauth_uid ']= $result [' Oauth_uid '];    $_session[' Oauth_provider ']= $result [' Oauth_provider '];    $_session[' Oauth_token ']= $result [' Oauth_token '];    $_session[' Oauth_secret ']= $result [' Oauth_secret '];  Header (' Location:update.php '); }} else{//Data incomplete, go to previous step header (' Location:index.php ');}? >

You can get the user's ID by $user _info->id, $user _info->screen_name to get the user name, and so on, other information can be obtained in the same way.

It is important to point out that oauth_verifier this returned parameter can not be reused, if the above code has correctly output the user information, you can try to re-refresh the page, you should see the page will throw an error message, because Oauth_verifier We've already used it once. To use again, you need to re-launch an authentication request to the index.php page.

User Registration

Once the user information has been obtained, we will now start to register the user information in our own database, if the user is not registered in the local database.

The database link information in the above code should be changed to your own. If the user already exists in our database, we need to update the user's tokens field, because it means that Twitter has generated a new tokens, and the tokens in the database has expired. If the user does not exist, we need to add a new record and save the relevant data in the session, and then redirect back to the update.php page.

Where the update.php code is as follows:

It is important to note that the SQL in the above code is not validated and you may have to modify it when you actually use it. Before connecting to the database, we need to verify that the user is logged in. With the user name, we can show a personalized welcome message:

<?phpinclude_once (' config.php '); include_once (' weibooauth.php '); session_start (); if (!empty ($_SESSION[') Username '])) {  //User is logged in, redirect  header (' index.php ');}? >  Authenticating with OAuth--yourtion  
 
  

Hello <?=$_session[' username ']?>

This is the main process of OAuth authentication and storage, which I hope will help you. Code Download: Sinaoauth

The above is the whole content of this article, I hope you can enjoy.

Please take a moment to share the article with your friends or leave a comment. We would be grateful for your support!

  • 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.