CI框架开发新浪微博登录接口源码完整版
CI框架开发新浪微博登录接口源码完整版
发布时间:2016-12-29 来源:查字典编辑
摘要:首先来看下流程:流程原理:1.通过code获得access_token通过授权,并获取用户的信息(包括用户u_id)(这个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写进去,代码如下:

复制代码 代码如下:

<?php

$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,代码:

复制代码 代码如下:

<?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文件(名字你可以自己取),代码:

复制代码 代码如下:

<?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');//这个类是本项目的用户登录类,本贴不提供原代码,因为不同的项目,需求不同,可根据你项目需求可以自己封装

$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 "<script>alert('您的账号未激活,请去邮箱激活!');location='/login/index';</script>";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 "<script>alert('登录成功!');location='/user_center'</script>";die();

}else{//用户第三方表没有记录,询问用户是否在平台有过帐号,没有跳转注册,有跳转登录

$this->session->set_userdata('sina_id',$arr['id']);

echo "<script>if(!confirm('是否在平台注册过用户?')){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); // 绑定

}

//保存

//在注册控制器里,用户信息写入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文件,代码:

复制代码 代码如下:

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

保存

说明:这是个图片按钮,图片你可在官网下载,下载地址: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 ='';

$url = '';

$str ='';

$code = $_REQUEST['code'];

$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='off'>";

$str .="<input type='hidden' name='code' value='{$code}'>";

$str .="</form>

</body>

</html>

<script type="text/javascript">

document.getElementById('form').submit();

</script>";

echo $str;

保存

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

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新php教程学习
热门php教程学习
编程开发子分类