新浪微博登入介面(PHP版)_PHP教程

來源:互聯網
上載者:User
CI架構下 新浪微博登入介面完整版
說明:本貼只適合CI架構。功能實現:登入介面跳轉連結成功,擷取使用者資訊(包括最重要的u_id)成功,將使用者於本地平台串連起來,使用者登入成功後資訊的儲存,本機資料庫第三方登入表的設計。總之介面流程已全部完成。每個關鍵步驟我幾乎都有注釋,講解詳細。

首先來看下流程:
流程原理:
1.通過code獲得access_token通過授權,並擷取使用者的資訊(包括使用者u_id)(這個u_id在後面的第三方登入表裡面叫sina_id,那個表是需要自己建的)
2.查詢第三方登入表,如果不存在使用者sina_id,分2種情況,一:使用者在平台已經有帳號,這時需要把平台(比如:平台的使用者表是:user_reg)使用者id綁定到第三方登入表(比如是:third_login表),然後就讓客戶登入;
二:使用者在平台沒有帳號,跳轉至註冊頁面註冊,註冊的同時,資訊寫入uer_reg表,同時也把使用者sina_id寫入第三方登入表進行綁定;
3.查詢第三方登入表(third_login),如果存在使用者sina_id,再查詢使用者表(user_reg),如果郵箱已經啟用,就直接登入,如果沒有啟用,提示使用者去郵箱啟用帳號。

下面開始詳講步驟:
第一步:申請App key和App secret申請地址:http://open.weibo.com/ 在頁面點擊網站接入WEB,進去申請就好了,通過後會得到App Key 和 App Secret如下:
App Key:1428003339
App Sercet:f1c6177a38b39f764c76a1690720a6dc
回調地址:http://test.com/callback.php

說明:申請下來後,那你的這個新浪帳號就是測試帳號,你在開發的時候可以用這個帳號來調試,其他帳號是無法登入,無法返回資訊的。開發前,最好上官網看下開發流程,流程是最重要的。只要思路理清楚了,剩下就是用代碼實現你的所思所想。

第二步:下載SDK,下載php版的,下載地址(官網):http://code.google.com/p/libweibo/downloads/list,下載下來有5個檔案,其中一個是saetv2.ex.class.php,我只需要這個檔案。

第三步:代碼
1.建立一個第三方登入表,以便儲存第三方登入的資訊(新浪是u_id,QQ是openid,他們都是唯一的,用來標識使用者,我們根據這個來儲存):
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 = '第三方登入表'

說明:平台返回的是u_id,他是使用者的唯一標識,我把他存為sina_id,user_id是關聯平台使用者表user_reg的id的,user_reg表我這裡不列出,你可以按實際項目需求來建表,推薦的操作工具有phpmyadmin,MySQL Workbench,操作方便。
如果你只需要做新浪登入介面,那可以把qq_id這個欄位去掉。


2.寫設定檔,在application下建立一個檔案sina_conf.php,把剛申請到的App Key 和 App Secret寫進去,代碼如下:

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

儲存

3.oauth認證類,把剛下載下來的saetv2.ex.class.php檔案複製到application/libraries下。
說明:這是非常重要的類,登入,授權,擷取使用者資訊都要用到這個類中的方法,沒他就沒法玩下去了,原封不動的粘到application/libraries下。

4.寫新浪微博登入類(QQ登入也可用,我這裡QQ登入的也封裝在一起了,就算只做新浪登入介面,也不影響),在application/models下建一個檔案third_login_model.php,代碼:


/**
* Description of third_login_model
*第三方介面授權,登入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 : 新浪微博登入
* @param :
* @return : $sina_url----登入地址
*/
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 : 登入後,通過返回的code值,擷取token,實現授權完成,然後擷取使用者資訊
* @param : $code
* @return : $user_message--使用者資訊
*/
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 : 查詢第三方登入表
* @param : $where
* @return : 第三方登入使用者記錄結果集
*/
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---查詢使用者表和第三方登入表
* @param : $where
* @return : 第三方登入使用者記錄結果集
*/
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 : 將使用者和第三方登入表資訊綁定
* @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 "";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 "";die();
}else{//使用者第三方表沒有記錄,詢問使用者是否在平台有過帳號,沒有跳轉註冊,有跳轉登入
$this->session->set_userdata('sina_id',$arr['id']);
echo "";
}
}

public function login_validation(){
//第三方登入使用者id ,sina_id,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); // 綁定
}

儲存


//在註冊控制器裡,使用者資訊寫入user_reg表,同時也把sina_id寫入third_login表,我這裡只展示第三方登入介面使用者id存入資料表的代碼
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);
}
}
儲存

6.視圖檔案布置新浪微博登入按鈕,在application/view下建立index.php檔案,代碼:



新浪微博登入介面


">



儲存
說明:這是個圖片按鈕,圖片你可在官網下載,下載地址:http://open.weibo.com/widget/loginbutton.php

7.回調地址
前面在第1步設定檔檔案的時候,設定了回調地址:http://test.com/callback.php ,那這個callback.php放在什麼地方呢,它需要放在和入口index.php同級的位置,它和application也是同級的。所在在開始的目錄下建立檔案callback.php。代碼:


/*
* 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.
*/
//新浪微博登入回調入口檔案,將路徑轉移到login/callback方法裡,並將code值傳過去
$code ='';
$url = '';
$str ='';
$code = $_REQUEST['code'];
$url = "/login/callback";

$str = "



自動跳轉

";
$str .="


";
echo $str;

儲存

這個時候,你用瀏覽器訪問index.php檔案的時候,會看到一個用微博帳號登入的登入按鈕,點擊按鈕,會跳轉到微博登入頁面,要你輸入新浪微博使用者名稱密碼,他會做不同的操作。具體流程我在上面也說過了。

本貼僅供參考學習,不涉及任何商業範圍。
如要轉載,請說明來源和原文地址,謝謝!
如有不對,或者可以改良之處,請在下方評論指出,謝謝!

http://www.bkjia.com/PHPjc/777154.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/777154.htmlTechArticleCI架構下 新浪微博登入介面完整版 說明:本貼只適合CI架構。功能實現:登入介面跳轉連結成功,擷取使用者資訊(包括最重要的u_id)成功,...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.