User.php
3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Db;
use think\Validate;
use fast\Http;
/**
* 个人中心
*/
class User extends Api
{
protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
protected $noNeedRight = '*';
public function _initialize()
{
parent::_initialize();
}
/**
* @ApiTitle (小程序登录)
* @ApiSummary (小程序登录)
* @ApiMethod (POST)
* @ApiRoute (/api/user/login)
* @ApiParams (name="code", type="string", required=true, description="小程序code")
* @ApiParams (name="nickname", type="string", required=true, description="小程序昵称")
* @ApiParams (name="avatar", type="string", required=true, description="小程序头像")
* @ApiReturn({
"code": 1,
"msg": "登录成功",
"time": "1553839125",
"data": {
"token": "677afb39-1a4f-4492-84d3-0bcf32016b8a",//token
"user_id": 27,//用户id
"createtime": 1553839125,//登录时间
"expiretime": 1556431125,//token失效时间
"expires_in": 2592000//token失效剩余时间(单位s)
"openid": 1485212522522//openid
})
*/
public function login(){
if($this->request->isPost()){
//小程序配置
$config = config('verify.raw');
//小程序传递数据,包含昵称,头像,code
$raw_data = $this->request->post();
//验证表数据
$rule = config('verify.user');
$validate = new Validate($rule['rule'],$rule['msg']);//
if (!$validate->check($raw_data)) {
$this->error($validate->getError());
}
$params = [
'appid' => $config['app_id'],
'secret' => $config['secret'],
'js_code' => $raw_data['code'],
'grant_type' => 'authorization_code'
];
$result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
if ($result['ret']) {
$json = (array)json_decode($result['msg'], true);
if (isset($json['openid'])) {
$result = [
'openid' => $json['openid'],
'nickname' => $raw_data['nickname'],
'avatar' => $raw_data['avatar']
];
$ret = $this->auth->login($result);
if ($ret) {
$data = $this->auth->getUserinfo();
$this->success('登录成功', $data);
}else {
$this->error($this->auth->getError());
}
} else {
$this->error("登录失败",$json);
}
}
}else{
$this->error('请求方式错误');
}
}
/**
* @ApiTitle (首页)
* @ApiSummary (首页)
* @ApiMethod (POST)
* @ApiRoute (/api/user/index)
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
* @ApiReturn ({
'code':'1',
'msg':'返回成功'
})
*/
public function index()
{
$data = Db::name('video')
->field('id,thumbnail')
->order('id desc')
->limit('1')
->find();
$this->success('SUCCESS',$data);
}
}