qingjian/app/controller/api/Login.php

86 lines
2.5 KiB
PHP
Raw Normal View History

2021-08-06 18:50:55 +08:00
<?php
namespace app\controller\api;
use app\service\{Tool};
use app\validate\{User as Vuser};
use think\facade\Db;
use think\exception\ValidateException;
use app\model\{User};
use think\Exception;
use think\facade\Config;
//登录
class Login extends Base
{
protected function initialize()
{
parent::initialize();
}
/**
* 获取openid
*/
public function getOpenId()
{
Config::load('extra/wechat', 'wechat');
$config = config('wechat');
$code = $this->request->param('code/s');
$appId = $config["appId"];//appid
$appSecret = $config["appSecret"];//appsecret
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $appSecret . '&js_code=' . $code . '&grant_type=authorization_code';
$datas = json_decode(Tool::httpRequest($url, "get"), true);
//返回状态
if (isset($datas["openid"])) {
return $this->json(0, "ok", $datas);
}
return $this->json(1, "null");
}
/**
* 小程序用户登录 创建用户或更新用户信息
*/
public function wechatMiniLogin()
{
$data = [];
$data['openid'] = $this->request->post('openid/s');//微信用户openid
$data['headimgurl'] = $this->request->post('avatarUrl/s');//微信头像
$data['nickname'] = $this->request->post('nickName/s');//用户昵称
try {
validate(Vuser::class)->check($data);
} catch (ValidateException $e) {
return $this->json(1, "异常请求");
}
$user = User::getByOpenid($data['openid']);
$time = time();
$token_close_time = $time + User::TokenCloseTime;
$data["login_ip"] = $this->request->ip();
$data["last_login"] = $time;
$data["token_close_time"] = $token_close_time;
$data["token"] = md5($data["openid"] . $time . randomStr(1, 16));
Db::startTrans();
try {
//如果没有注册过 就添加
if (!empty($user)) {
User::create($data);
} else {
User::updateById($user['id'], $data);
}
//提交事务
Db::commit();
return $this->json(0, "ok", [
"token" => $data["token"],
]);
} catch (Exception $e) {
Db::rollback();
return $this->json(2, $e->getMessage());
}
}
}