Skip to content

Commit

Permalink
API 万能签名
Browse files Browse the repository at this point in the history
  • Loading branch information
Tinywan committed Sep 4, 2016
1 parent 2062384 commit d26da38
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 54 deletions.
71 changes: 17 additions & 54 deletions Backend/Api/Controller/IndexController.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,64 +5,27 @@

class IndexController extends Controller
{
public function index()
{
$model = M('Category'); // return Object
// Mysql CONCAT()函数用于将多个字符串连接成一个字符串
$result = $model->field("*,concat(path,',',id) as paths")->order('path')->select();
foreach ($result as $key => $v) {
$result[$key]['name'] = str_repeat('   ', $v['level']) . $v['name'];
}
$this->categorys = $result;
$this->display();
}

/**
* 添加一个新分类
* API 接口的签名方式
* 【1】key 双方约定的公钥
* 【2】password
* 【3】uniqueId
* 【4】username
* 【5】time()
* 【6】加密方式(顺序):MD5(password+uniqueId+username+time()+key)
*/
public function addCategory()
public function sign()
{
$data['pid'] = I('post.pid');
$data['name'] = I('post.name');
// 实例化一个数据表
$model = M('Category');
// 判断是否是顶级分类
if (!empty($data['name']) && $data['pid'] != 0) {
$path = $model->field('path')->find($data['pid']);
//思路,先添加后修改
$data['path'] = $path['path'];
// substr_count() 函数计算子串在字符串中出现的次数
$data['level'] = substr_count($path['path'], ',');
// 在TP中 $data['pid'] = I('post.pid') 会返回当前插入的id
$resultId = $model->add($data); // return add id
$update['id'] = $resultId;
$update['path'] = $path['path'] . ',' . $resultId;
$update['level'] = $data['level'] + 1;
$updateResult = $model->save($update);
if (!$updateResult) {
return $this->error('添加一个新分类失败');
} else {
return $this->success('添加一个新分类成功', U('Index/index'));
}
} elseif (!empty($data['name']) && $data['pid'] == 0) {
$data['path'] = $data['pid'];
$data['level'] = 1;
// 在TP中 $data['pid'] = I('post.pid') 会返回当前插入的id
$resultId = $model->add($data); // return add id
$update['id'] = $resultId;
$update['path'] = $data['path'] . ',' . $resultId;
$updateResult = $model->save($update);
if (!$updateResult) {
return $this->error('添加一个新分类失败');
} else {
return $this->success('添加一个新分类成功', U('Index/index'));
}
} else {
return $this->error('添加一个新分类失败');
$key = C('API_SECRET_KEY'); //公钥
$password = $_POST['password'];
$uniqueId = $_POST['uniqueId'];
$username = $_POST['username'];
$time = $_POST['time']; // 这里时间必须和和服务器的时间匹配
$sign = $_POST['sign'];
$serverSign = md5($password.$uniqueId.$username.$time.$key);
if($serverSign != $sign){
echo '签名失败';
}
}

public function test(){
echo 'category test';
}
}
5 changes: 5 additions & 0 deletions Backend/Common/Conf/api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php
return array(
'API_SECRET_KEY' => 'https://tinywan.github.io/',
);
?>

0 comments on commit d26da38

Please sign in to comment.