色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

CI框架開發(fā)新浪微博登錄接口源碼完整版

首先來看下流程:
流程原理:
     1.通過code獲得access_token通過授權(quán),并獲取用戶的信息(包括用戶u_id)(這個(gè)u_id在后面的第三方登錄表里面叫sina_id,那個(gè)表是需要自己建的)
     2.查詢第三方登錄表,如果不存在用戶sina_id,分2種情況,一:用戶在平臺(tái)已經(jīng)有帳號(hào),這時(shí)需要把平臺(tái)(比如:平臺(tái)的用戶表是:user_reg)用戶id綁定到第三方登錄表(比如是:third_login表),然后就讓客戶登錄;
                                                          二:用戶在平臺(tái)沒有帳號(hào),跳轉(zhuǎn)至注冊(cè)頁面注冊(cè),注冊(cè)的同時(shí),信息寫入uer_reg表,同時(shí)也把用戶sina_id寫入第三方登錄表進(jìn)行綁定;
     3.查詢第三方登錄表(third_login),如果存在用戶sina_id,再查詢用戶表(user_reg),如果郵箱已經(jīng)激活,就直接登錄,如果沒有激活,提示用戶去郵箱激活帳號(hào)。

下面開始詳講步驟:
第一步:申請(qǐng)App key和App secret申請(qǐng)地址:http://open.weibo.com/ 在頁面點(diǎn)擊網(wǎng)站接入WEB,進(jìn)去申請(qǐng)就好了,通過后會(huì)得到App Key 和 App Secret如下:
App Key:1428003339
App Sercet:f1c6177a38b39f764c76a1690720a6dc
回調(diào)地址:http://test.com/callback.php

說明:申請(qǐng)下來后,那你的這個(gè)新浪帳號(hào)就是測(cè)試帳號(hào),你在開發(fā)的時(shí)候可以用這個(gè)帳號(hào)來調(diào)試,其他帳號(hào)是無法登錄,無法返回信息的。開發(fā)前,最好上官網(wǎng)看下開發(fā)流程,流程是最重要的。只要思路理清楚了,剩下就是用代碼實(shí)現(xiàn)你的所思所想。

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

第三步:代碼
1.建立一個(gè)第三方登錄表,以便存儲(chǔ)第三方登錄的信息(新浪是u_id,QQ是openid,他們都是唯一的,用來標(biāo)識(shí)用戶,我們根據(jù)這個(gè)來存儲(chǔ)):

復(fù)制代碼 代碼如下:
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 = '第三方登錄表'

說明:平臺(tái)返回的是u_id,他是用戶的唯一標(biāo)識(shí),我把他存為sina_id,user_id是關(guān)聯(lián)平臺(tái)用戶表user_reg的id的,user_reg表我這里不列出,你可以按實(shí)際項(xiàng)目需求來建表,推薦的操作工具有phpmyadmin,MySQL Workbench,操作方便。
如果你只需要做新浪登錄接口,那可以把qq_id這個(gè)字段去掉。

2.寫配置文件,在application下新建一個(gè)文件sina_conf.php,把剛申請(qǐng)到的App Key 和 App Secret寫進(jìn)去,代碼如下:

復(fù)制代碼 代碼如下:
<?php
$config["sina_conf"] = array(
    "App_Key" => '1428003339',
    "App_Secret" =>'f1c6177a38b39f764c76a1690720a6dc',
    "WB_CALLBACK_URL" => 'http://test.com/callback.php'
);

保存

3.oauth認(rèn)證類,把剛下載下來的saetv2.ex.class.php文件復(fù)制到application/libraries下。
說明:這是非常重要的類,登錄,授權(quán),獲取用戶信息都要用到這個(gè)類中的方法,沒他就沒法玩下去了,原封不動(dòng)的粘到application/libraries下。

4.寫新浪微博登錄類(QQ登錄也可用,我這里QQ登錄的也封裝在一起了,就算只做新浪登錄接口,也不影響),在application/models下建一個(gè)文件third_login_model.php,代碼:

復(fù)制代碼 代碼如下:
<?php
/**
 * Description of third_login_model
 *第三方接口授權(quán),登錄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';//本項(xiàng)目用戶表
        $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,實(shí)現(xiàn)授權(quán)完成,然后獲取用戶信息
      * @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 ) ;//完成授權(quán)
      } 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 : 第三方登錄用戶記錄結(jié)果集
      */
    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 : 第三方登錄用戶記錄結(jié)果集
      */
    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 : 第三方登錄用戶記錄結(jié)果集
      */
    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;
    }
}

保存
說明:這個(gè)code是由入口文件callback.php傳過來的,第7步會(huì)有他的詳細(xì)代碼。
現(xiàn)在配置文件,model,數(shù)據(jù)表都有了,接下來就是控制器和視圖文件了。

5.寫登錄控制器  在application/controllers下,建立login.php文件(名字你可以自己取),代碼:

復(fù)制代碼 代碼如下:
<?php   if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Description of index
 * @author victory
 */
class Login extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('login_model','login');//這個(gè)類是本項(xiàng)目的用戶登錄類,本貼不提供原代碼,因?yàn)椴煌捻?xiàng)目,需求不同,可根據(jù)你項(xiàng)目需求可以自己封裝
        $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();//調(diào)用類中的sina_login方法
        $this->load->view("index.php",$datas);//調(diào)取視圖文件,并傳入數(shù)據(jù)

     }

    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);//通過授權(quán)并獲取用戶信息(包括u_id)
        $res = $this->third->select_third(array("sina_id"=>$arr['id']));
        if(!empty($res)){//用戶已有帳號(hào)記錄,先判斷帳號(hào)是否激活
            $user_info = $this->user_reg->user_detect(array("id"=>$res['user_id']));//查詢用戶表郵箱狀態(tài),user_detect方法就是查詢用戶信息的方法,上面也說了,login_model.php這個(gè)類本貼不提供,需要大家自己去封裝。
            if($user_info['status']){//根據(jù)status的狀態(tài)判斷用戶帳號(hào)是否激活,user_reg表中的字段status,1為未激活,0為已激活
                echo "<script>alert('您的賬號(hào)未激活,請(qǐng)去郵箱激活!');location='/login/index';</script>";die();
            }
            $datas = $this->third->select_user_name($arr['id']);//激活后,把信息寫入用戶表和第三方登錄表
            $uname = $datas['username'];//username,password都是user_reg表的字段,user_reg數(shù)據(jù)表的構(gòu)建本帖也不提供,因?yàn)槊總€(gè)項(xiàng)目都不一樣,需要根據(jù)實(shí)際項(xiàng)目來
            $password = $datas['password'];
            $this->load->model("login_model","login");
            $this->login->validation($uname,$password);//validation方法是登錄的主要方法,這里主要是在登錄的時(shí)候,將用戶信息寫入第三方登錄表,下面僅提供寫入第三方登錄表的代碼
            echo "<script>alert('登錄成功!');location='/user_center'</script>";die();
        }else{//用戶第三方表沒有記錄,詢問用戶是否在平臺(tái)有過帳號(hào),沒有跳轉(zhuǎn)注冊(cè),有跳轉(zhuǎn)登錄
            $this->session->set_userdata('sina_id',$arr['id']);
            echo "<script>if(!confirm('是否在平臺(tái)注冊(cè)過用戶?')){location='/register/index'}else{location='/login'};</script>";
        }    
    }

    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);  // 綁定
}

//保存


     //在注冊(cè)控制器里,用戶信息寫入user_reg表,同時(shí)也把sina_id寫入third_login表,我這里只展示第三方登錄接口用戶id存入數(shù)據(jù)表的代碼
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文件,代碼:

復(fù)制代碼 代碼如下:
<html>
<head>
    <meta content="text/html; charset=utf-8">
    <title>新浪微博登錄接口</title>
</head>
<body>
     <div><a href="<?=$sina_url?>"><img src="http://images.cnblogs.com/weibo_login.png" width="110"  /></a></div>
</body>
</html>

保存
說明:這是個(gè)圖片按鈕,圖片你可在官網(wǎng)下載,下載地址:http://open.weibo.com/widget/loginbutton.php

7.回調(diào)地址
前面在第1步配置文件文件的時(shí)候,設(shè)置了回調(diào)地址:http://test.com/callback.php ,那這個(gè)callback.php放在什么地方呢,它需要放在和入口index.php同級(jí)的位置,它和application也是同級(jí)的。所在在開始的目錄下新建文件callback.php。代碼:

復(fù)制代碼 代碼如下:
<?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.
 */
//新浪微博登錄回調(diào)入口文件,將路徑轉(zhuǎn)移到login/callback方法里,并將code值傳過去
$code ='';
$url = '';
$str ='';
$code = $_REQUEST['code'];
$url  = "/login/callback";

$str = "<!doctype html>
<html>
    <head>
    <meta charset=/"UTF-8/">
    <title>自動(dòng)跳轉(zhuǎn)</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;

保存

這個(gè)時(shí)候,你用瀏覽器訪問index.php文件的時(shí)候,會(huì)看到一個(gè)用微博帳號(hào)登錄的登錄按鈕,點(diǎn)擊按鈕,會(huì)跳轉(zhuǎn)到微博登錄頁面,要你輸入新浪微博用戶名密碼,他會(huì)做不同的操作。具體流程我在上面也說過了。

php技術(shù)CI框架開發(fā)新浪微博登錄接口源碼完整版,轉(zhuǎn)載需保留來源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 额敏县| 仙居县| 呼伦贝尔市| 娄底市| 广水市| 芷江| 桂平市| 鲜城| 霍州市| 华宁县| 吉木萨尔县| 廉江市| 余江县| 临清市| 镇江市| 南汇区| 敦煌市| 达州市| 马鞍山市| 灵丘县| 巴马| 柳河县| 鄢陵县| 惠水县| 仪征市| 当涂县| 三亚市| 岳阳市| 澜沧| 华池县| 开原市| 绍兴县| 吉林市| 鄂伦春自治旗| 门头沟区| 阿瓦提县| 堆龙德庆县| 什邡市| 安溪县| 灵武市| 留坝县|