淘寶開放平臺很多API需要授權後才能使用。
授權的時候就需要一個回調地址。
通過回調,我們可以獲取保用用戶名,淘寶ID,過期時間等資料,方便後續開發。
製作授權頁面
這裏我們直接修改welcome的index方法,代碼如下:
public function index()
{
$tbnick = get_cookie('taobao_user_nick');
$etime = get_cookie('expire_time');
$tbserid = get_cookie('taobao_user_id');
$session = get_cookie('access_token' );
$data = array(
'taobao_user_nick' => $tbnick,
'expire_time' => $etime,
'taobao_user_id' => $tbserid,
'access_token' => $session
);
$this->load->view('welcome_message',$data);
}
模板代碼,由於頁面簡單,用pure的CSS框架。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A layout example with a side menu that hides on mobile, just like the Pure website.">
<title>大華軟件授權</title>
<link rel="stylesheet" href="/static/css/pure-min.css" integrity="sha384-" crossorigin="anonymous">
<!--[if lte IE 8]>
<link rel="stylesheet" href="/static/css/layouts/side-menu-old-ie.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="/static/css/layouts/side-menu.css">
<!--<![endif]-->
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function getoauth() {
$.ajax({
//幾個參數需要注意一下
type: "POST",//方法類型
dataType: "json",//服務端接收的數據類型
url: "http://vipapi.dahuariji.com/index.php/welcome/getoauth" ,//url
data: $('#form1').serialize(),
success: function (result) {
console.log(result);//打印服務端返回的數據(調試用)
if (result.id > 0) {
//alert("SUCCESS");
$("#td1").html(decodeURIComponent(result.taobao_user_nick));
$("#td2").html(result.expire_time);
$("#td3").html(result.taobao_user_id);
$("#td4").html(result.access_token);
}
},
error : function() {
alert("異常!");
}
});
}
/**
* 時間戳轉化爲年 月 日 時 分 秒
* number: 傳入時間戳
* format:返回格式,支持自定義,但參數必須與formateArr裏保持一致
*/
function formatTime(number,format) {
var formateArr = ['Y','M','D','h','m','s'];
var returnArr = [];
var date = new Date(number * 1000);
returnArr.push(date.getFullYear());
returnArr.push(formatNumber(date.getMonth() + 1));
returnArr.push(formatNumber(date.getDate()));
returnArr.push(formatNumber(date.getHours()));
returnArr.push(formatNumber(date.getMinutes()));
returnArr.push(formatNumber(date.getSeconds()));
for (var i in returnArr)
{
format = format.replace(formateArr[i], returnArr[i]);
}
return format;
}
//數據轉化
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
</script>
</head>
<body>
<div id="layout">
<!-- Menu toggle -->
<a href="#menu" id="menuLink" class="menu-link">
<!-- Hamburger icon -->
<span></span>
</a>
<div id="menu">
<div class="pure-menu">
<a target="_blank" class="pure-menu-heading" href="http://www.dahuariji.com/?from=vipapi">大華日記</a>
<ul class="pure-menu-list">
<li class="pure-menu-item"><a href="#" class="pure-menu-link">Home</a></li>
<li class="pure-menu-item"><a href="#" class="pure-menu-link">About</a></li>
<li class="pure-menu-item menu-item-divided pure-menu-selected">
<a href="#" class="pure-menu-link">Services</a>
</li>
<li class="pure-menu-item"><a href="#" class="pure-menu-link">Contact</a></li>
</ul>
</div>
</div>
<div id="main">
<div class="header">
<h1>大華軟件授權</h1>
<h2>大華軟件的使用導引,大華軟件一般需要到這裏授權</h2>
</div>
<div class="content">
<h2 class="content-subhead">如何使用</h2>
<p>
由於大華很多軟件都是調用淘寶開放平臺的API,而這需要您的授權。授權過程非常簡單,點擊授權鏈接登錄即可自動保存。
<a href="https://oauth.taobao.com/authorize?response_type=code&client_id=25307802&redirect_uri=http://vipapi.dahuariji.com/index.php/welcome/oauth&state=vipapi&view=web" alt="點擊給我授權">點擊給我授權</a>,
授權後請記住您的<code>淘寶數字ID</code>。
</p>
<h2 class="content-subhead">忘記淘寶數字ID或授權過期怎麼辦</h2>
<p>
我們將在下面給您提供查詢接口,只需要輸入淘寶賬號,或您重新授權一次。授權有效期一個月。如果授權失敗,請重新授權。
</p>
<h2 class="content-subhead">查詢結果</h2>
<form class="pure-form" method="post" onsubmit="return false" action="#" id="form1">
<fieldset>
<input class="pure-input-1-2" type="text" name="tbnick" placeholder="淘寶用戶名">
<button type="submit" class="pure-button pure-button-primary" onclick="getoauth()">查詢</button>
</fieldset>
</form>
<table class="pure-table" id = "table1">
<thead>
<tr>
<th>#</th>
<th>淘寶用戶名</th>
<th>過期時間</th>
<th>淘寶數字ID</th>
<th>session</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="td1"><?=$taobao_user_nick?></td>
<td id="td2"><?php echo date('Y-m-d H:i:s', $expire_time/1000); ?></td>
<td id="td3"><?=$taobao_user_id?></td>
<td id="td4"><?=$access_token?></td>
</tr>
</tbody>
</table>
<p>如果名字裏含有亂七八糟的字符查不到,別查了,重新授權下吧。</p>
</div>
</div>
</div>
<script src="/static/js/ui.js"></script>
</body>
</html>
拼接授權鏈接
上面的頁面,主要是爲了方面用戶操作,同時爲了友好顯示,把用戶授權後的信息又給保存了下來。
https://oauth.taobao.com/authorize?response_type=code&client_id=25307802&redirect_uri=http://vipapi.dahuariji.com/index.php/welcome/oauth&state=vipapi&view=web
處理回調內容
用戶正常授權後,我們取回所需要的內容。
public function oauth()
{
$url = 'https://oauth.taobao.com/token';
$postfields = array('grant_type' => 'authorization_code',
'client_id' => '你的appkey',
'client_secret' => '你的appkey',
'code' => $_GET['code'],
'redirect_uri' => 'http://vipapi.dahuariji.com/index.php/welcome/oauth');
$post_data = '';
foreach ($postfields as $key => $value) {
$post_data .= "$key=" . urlencode($value) . "&";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//指定post數據
curl_setopt($ch, CURLOPT_POST, true);
//添加變量
curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data, 0, -1));
$output = curl_exec($ch);
curl_close($ch);
$j = json_decode($output);
$tbnick = $j->taobao_user_nick;
$etime = $j->expire_time;
$openuid = $j->taobao_open_uid;
$tbserid = $j->taobao_user_id;
$session = $j->access_token;
$data = array(
'taobao_user_nick' => $tbnick,
'expire_time' => $etime,
'taobao_open_uid' => $openuid,
'taobao_user_id' => $tbserid,
'access_token' => $session
);
if ($session) {
set_cookie('taobao_user_nick',$tbnick,2592000);
set_cookie('expire_time',$etime,2592000);
set_cookie('taobao_user_id',$tbserid,2592000);
set_cookie('access_token' , $session,2592000);
//入庫
$querys = $this->users_model->get_user($tbserid);
if ($querys->num_rows() == 1)
{
$query = $this->users_model->update_user($data);
}
else
{
$query = $this->users_model->insert_user($data);
}
//
}
//$this->load->view('welcome_show',$data);
//跳轉到額新頁面展示
redirect("http://vipapi.dahuariji.com/index.php/welcome/showuid/".$tbserid);
}
這裏爲了顯示簡單點,跳轉到新的頁面,簡單的顯示了下。
public function showuid()
{
$uid = $this->uri->segment(3);
$data =array('uid' => $uid);
$this->load->view('welcome_show',$data);
}
數據庫的基本操作,增刪改查
public function get_user_by_name($taobao_user_nick)
{
$query = $this->db->get_where('usertoken', array('taobao_user_nick' => $taobao_user_nick), 0,1);
return $query;
}
public function get_user($taobao_user_id)
{
$query = $this->db->get_where('usertoken', array('taobao_user_id' => $taobao_user_id), 0,1);
return $query;
}
public function insert_user($data)
{
return $this->db->insert('usertoken', $data);
}
public function update_user($data)
{
return $this->db->replace('usertoken', $data);
}
這樣一個基本的session授權管理就做好了。