首頁  >  文章  >  後端開發  >  關於CI框架開發新浪微博登入介面的源碼分析

關於CI框架開發新浪微博登入介面的源碼分析

不言
不言原創
2018-06-14 14:58:371841瀏覽

這篇文章主要介紹了關於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

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


第二步:下載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寫進去

,程式碼如下:

<?php
$config["sina_conf"] = array(
    "App_Key" => &#39;1428003339&#39;,
    "App_Secret" =>&#39;f1c6177a38b39f764c76a1690720a6dc&#39;,
    "WB_CALLBACK_URL" => &#39;http://test.com/callback.php&#39;
);
儲存
3.

oauth認證類,把剛下載下來的saetv2.ex.class.php檔案複製到application/libraries下。

說明:這是非常重要的類,登錄,授權,獲取用戶資訊都要用到這個類中的方法,沒他就沒法玩下去了,原封不動的粘到application/libraries下

4.

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

<?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 =&#39;&#39;;
    private $third=&#39;&#39;;
    public function __construct() {
        parent::__construct();
//        $this->l = DIRECTORY_SEPARATOR;
        $this->load->database();   
        $this->load->library(&#39;session&#39;);
        include_once APPPATH."/libraries"."/saetv2.ex.class.php";
        $this->third =  $this->db->&#39;third_login&#39;;//第三方登录表
        $this->users = $this->db->&#39;user_reg&#39;;//本项目用户表
        $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[&#39;App_Key&#39;],$this->sina[&#39;App_Secret&#39;]);
        $sina_url = $obj->getAuthorizeURL( $this->sina[&#39;WB_CALLBACK_URL&#39;] );
        return $sina_url;
    }

    /**
      * @uses : 登录后,通过返回的code值,获取token,实现授权完成,然后获取用户信息
      * @param : $code
      * @return : $user_message--用户信息
      */
    public function sina_callback($code){
      $obj = new SaeTOAuthV2($this->sina[&#39;App_Key&#39;],$this->sina[&#39;App_Secret&#39;]);
      if (isset($code)) {
      $keys = array();
      $keys[&#39;code&#39;] = $code;
      $keys[&#39;redirect_uri&#39;] = $this->sina[&#39;WB_CALLBACK_URL&#39;];
      try {
        $token = $obj->getAccessToken( &#39;code&#39;, $keys ) ;//完成授权
      } catch (OAuthException $e) {
    }
      }
      $c = new SaeTClientV2($this->sina[&#39;App_Key&#39;], $this->sina[&#39;App_Secret&#39;], $token[&#39;access_token&#39;]);
      $ms =$c->home_timeline();
      $uid_get = $c->get_uid();//获取u_id
      $uid = $uid_get[&#39;uid&#39;];
      $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=&#39;{$where}&#39;";
        $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 (&#39;wrong param&#39;);
        if($datas[&#39;sina_id&#39;]==0 && $datas[&#39;qq_id&#39;]==0)  return;

        $resa =&#39;&#39;;
        $resb =&#39;&#39;;
        $resa = $this->select_third(array("user_id"=>$datas[&#39;user_id&#39;]));
        $temp =array(
            "user_id"=>$datas[&#39;user_id&#39;],
            "sina_id"=>$resa[&#39;sina_id&#39;]!=0 ? $resa[&#39;sina_id&#39;] : $datas[&#39;sina_id&#39;],
            "qq_id"  => $resa[&#39;qq_id&#39;]!=0 ? $resa[&#39;qq_id&#39;] : $datas[&#39;qq_id&#39;],
        );
        if($resa){
            $resb = $this->db->update($this->third, $temp,array("user_id"=>$datas[&#39;user_id&#39;]));
        }else{
            $resb = $this->db->insert($this->third,$temp);
        }
        if($resb) {
            $this->session->unset_userdata(&#39;sina_id&#39;);//注销
            $this->session->unset_userdata(&#39;qq_id&#39;);//注销
        }
        return $resb;
    }
}

儲存

說明:這個code是由入口檔案callback.php傳過來的,第7步會有他的詳細程式碼。 現在設定文件,model,資料表都有了,接下來就是控制器和視圖檔案了。

5.

寫入登入控制器  在application/controllers下,建立login.php檔案(名字你可以自己取),

程式碼:

<?php   if ( ! defined(&#39;BASEPATH&#39;)) exit(&#39;No direct script access allowed&#39;);
/**
 * Description of index
 * @author victory
 */
class Login extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model(&#39;login_model&#39;,&#39;login&#39;);//这个类是本项目的用户登录类,本贴不提供原代码,因为不同的项目,需求不同,可根据你项目需求可以自己封装
        $this->load->model("third_login_model","third");
        $this->load->library(&#39;session&#39;);
    }
    public function index() {
        header("content-type: text/html; charset=utf-8");
        $this->load->model("third_login_model","third");//加载新浪登录接口类
        $datas[&#39;sina_url&#39;] = $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[&#39;code&#39;];//code值由入口文件callback.php传过来
        $arr =array();
        $arr = $this->third->sina_callback($code);//通过授权并获取用户信息(包括u_id)
        $res = $this->third->select_third(array("sina_id"=>$arr[&#39;id&#39;]));
        if(!empty($res)){//用户已有帐号记录,先判断帐号是否激活
            $user_info = $this->user_reg->user_detect(array("id"=>$res[&#39;user_id&#39;]));//查询用户表邮箱状态,user_detect方法就是查询用户信息的方法,上面也说了,login_model.php这个类本贴不提供,需要大家自己去封装。
            if($user_info[&#39;status&#39;]){//根据status的状态判断用户帐号是否激活,user_reg表中的字段status,1为未激活,0为已激活
                echo "<script>alert(&#39;您的账号未激活,请去邮箱激活!&#39;);location=&#39;/login/index&#39;;</script>";die();
            }
            $datas = $this->third->select_user_name($arr[&#39;id&#39;]);//激活后,把信息写入用户表和第三方登录表
            $uname = $datas[&#39;username&#39;];//username,password都是user_reg表的字段,user_reg数据表的构建本帖也不提供,因为每个项目都不一样,需要根据实际项目来
            $password = $datas[&#39;password&#39;];
            $this->load->model("login_model","login");
            $this->login->validation($uname,$password);//validation方法是登录的主要方法,这里主要是在登录的时候,将用户信息写入第三方登录表,下面仅提供写入第三方登录表的代码
            echo "<script>alert(&#39;登录成功!&#39;);location=&#39;/user_center&#39;</script>";die();
        }else{//用户第三方表没有记录,询问用户是否在平台有过帐号,没有跳转注册,有跳转登录
            $this->session->set_userdata(&#39;sina_id&#39;,$arr[&#39;id&#39;]);
            echo "<script>if(!confirm(&#39;是否在平台注册过用户?&#39;)){location=&#39;/register/index&#39;}else{location=&#39;/login&#39;};</script>";
        }     
    }
    public function login_validation(){
      //第三方登录用户id ,sina_id,qq_id的记录增改
        $third_info =array(
            "user_id" => $user_ser[&#39;id&#39;],
            "sina_id" => $this->session->userdata(&#39;sina_id&#39;),
            "qq_id"   =>$this->session->userdata(&#39;qq_id&#39;),
        );
        if($third_info[&#39;sina_id&#39;]||$third_info[&#39;qq_id&#39;])    $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(&#39;session&#39;);
    }
    public function reg() {
          $haha =array(
                      "user_id" => $rs,
                      "sina_id" => $this->session->userdata(&#39;sina_id&#39;),
                      "qq_id"   =>$this->session->userdata(&#39;qq_id&#39;),
                      );
            if($haha[&#39;sina_id&#39;]||$haha[&#39;qq_id&#39;])    $this->third->binding_third($haha);
    }
}
儲存

6.

檢視檔案安排新浪微博登入按鈕,在application/view下建立index.php檔案
,程式碼:

<html>
<head>
    <meta content="text/html; charset=utf-8">
    <title>新浪微博登录接口</title>
</head>
<body>
     <p><a href="<?=$sina_url?>"><img src="http://images.cnblogs.com/weibo_login.png" width="110"  /></a></p>
</body>
</html>
###儲存###說明:這是圖片按鈕,圖片你可在官網下載,下載網址:http://open.weibo.com/widget/loginbutton.php###

7.回调地址
前面在第1步配置文件文件的时候,设置了回调地址:http://test.com/callback.php ,那这个callback.php放在什么地方呢,它需要放在和入口index.php同级的位置,它和application也是同级的。所在在开始的目录下新建文件callback.php。代码:

<?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 =&#39;&#39;;
$url = &#39;&#39;;
$str =&#39;&#39;;
$code = $_REQUEST[&#39;code&#39;];
$url  = "/login/callback";
$str = "<!doctype html>
<html>
    <head>
    <meta charset=\"UTF-8\">
    <title>自动跳转</title>
    </head>
<body>";
$str .="<form action=\"{$url}\" method=\"post\" id=\"form\" autocomplete=&#39;off&#39;>";
$str .="<input type=&#39;hidden&#39; name=&#39;code&#39; value=&#39;{$code}&#39;>";
$str .="</form>
        </body>
        </html>
        <script type=\"text/javascript\">
           document.getElementById(&#39;form&#39;).submit();
        </script>";
echo $str;

保存

这个时候,你用浏览器访问index.php文件的时候,会看到一个用微博帐号登录的登录按钮,点击按钮,会跳转到微博登录页面,要你输入新浪微博用户名密码,他会做不同的操作。具体流程我在上面也说过了。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何使用CodeIgniter开发实现支付宝接口调用

以上是關於CI框架開發新浪微博登入介面的源碼分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn