120 lines
		
	
	
		
			4.2 KiB
		
	
	
	
		
			PHP
		
	
	
			
		
		
	
	
			120 lines
		
	
	
		
			4.2 KiB
		
	
	
	
		
			PHP
		
	
	
<?php
 | 
						|
namespace app\controller\api;
 | 
						|
 | 
						|
use app\exception\RepositoryException;
 | 
						|
use app\model\Account;
 | 
						|
use app\repository\AccountRepository;
 | 
						|
use app\service\File;
 | 
						|
use app\service\Jwt;
 | 
						|
use app\service\wx\WechatApplets;
 | 
						|
use app\validate\User as UserValidate;
 | 
						|
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
 | 
						|
use Exception;
 | 
						|
use think\response\Json;
 | 
						|
 | 
						|
class User extends Base
 | 
						|
{
 | 
						|
    protected $noNeedLogin = [
 | 
						|
        'login',
 | 
						|
        'test',
 | 
						|
    ];
 | 
						|
 | 
						|
    /**
 | 
						|
     * 登录  成功返回token及用户信息
 | 
						|
     *
 | 
						|
     * @return Json
 | 
						|
     * @throws InvalidConfigException
 | 
						|
     */
 | 
						|
    public function login(): Json
 | 
						|
    {
 | 
						|
        $params = [
 | 
						|
            'code'          => $this->request->param('code', ''),
 | 
						|
            'nick_name'     => $this->request->param('nickName', ''),
 | 
						|
            'avatar_url'    => $this->request->param('avatarUrl', ''),
 | 
						|
            'gender'        => $this->request->param('gender', 0),
 | 
						|
        ];
 | 
						|
 | 
						|
        $validate = new UserValidate();
 | 
						|
        if (!$validate->scene('wx_applets')->check($params)) {
 | 
						|
            return $this->json(4000, $validate->getError());
 | 
						|
        }
 | 
						|
        $minApp = WechatApplets::getInstance();
 | 
						|
        $jsCode = $params['code'];
 | 
						|
        $wxUser = $minApp->auth->session($jsCode);
 | 
						|
 | 
						|
        if (isset($wxUser['errcode']) && $wxUser['errcode'] != 0) {
 | 
						|
            return $this->json(4001, $wxUser['errcode'].';'.$wxUser['errmsg'] ?? '登录失败');
 | 
						|
        }
 | 
						|
        // $wxUser success has [session_key, openid, unionid]
 | 
						|
        // 有效期2小时
 | 
						|
        $wxUser['expire_time'] = time() + 7200;
 | 
						|
        $wxUser['session_key'] = $wxUser['session_key'] ?? '';
 | 
						|
        $openID                = $wxUser['openid'] ?? '';
 | 
						|
 | 
						|
        if (empty($openID)) {
 | 
						|
            return $this->json(4002, '登录失败');
 | 
						|
        }
 | 
						|
 | 
						|
        try {
 | 
						|
            $repo       = AccountRepository::getInstance();
 | 
						|
            $account    = $repo->findByOpenID($openID);
 | 
						|
            $nowDate    = date('Y-m-d H:i:s');
 | 
						|
 | 
						|
            if (!$account) {
 | 
						|
                // 自动注册
 | 
						|
                $account = $repo->create([
 | 
						|
                    'user_code'         => createUuid(), // 用户UUID
 | 
						|
                    'open_id'           => $openID,
 | 
						|
                    'create_time'       => $nowDate,
 | 
						|
                    'login_time'        => $nowDate,
 | 
						|
                    'type'              => Account::type_consumer, // 默认为普通消费者
 | 
						|
                    'state'             => Account::state_default,
 | 
						|
                    'nick_name'         => $params['nick_name'] ?: generateDefaultNickName(),
 | 
						|
                    'avatar_url'        => $params['avatar_url'] ?: Account::DEFAULT_AVATAR,
 | 
						|
                    'gender'            => $params['gender'],
 | 
						|
                ]);
 | 
						|
 | 
						|
            } else {
 | 
						|
                $updateData     = [
 | 
						|
                    'login_time'  => $nowDate,
 | 
						|
                ];
 | 
						|
 | 
						|
                // 更新资料
 | 
						|
                $modifyStringList = ['nick_name', 'avatar_url'];
 | 
						|
                foreach ($modifyStringList as $modifyKey) {
 | 
						|
                    if (isset($params[$modifyKey]) && !empty($params[$modifyKey])) {
 | 
						|
                        $updateData[$modifyKey] = $params[$modifyKey];
 | 
						|
                    }
 | 
						|
                }
 | 
						|
 | 
						|
                $repo->update($updateData, ['id' => $account['id']]);
 | 
						|
                $account = $repo->findById($account['id']);
 | 
						|
            }
 | 
						|
 | 
						|
        } catch (RepositoryException | Exception $e) {
 | 
						|
            return $this->json(4003, '登录失败!'.$e->getMessage());
 | 
						|
        }
 | 
						|
 | 
						|
        $account = $account->toArray();
 | 
						|
        $account['avatar_url'] = File::convertCompleteFileUrl($account['avatar_url']);
 | 
						|
        $jwtData = [
 | 
						|
            'user_id'       => $account['id'],
 | 
						|
            'user_code'     => $account['user_code'],
 | 
						|
            'open_id'       => $openID,
 | 
						|
            'session_key'   => $wxUser['session_key'],
 | 
						|
            'expire_time'   => $wxUser['expire_time'],
 | 
						|
        ];
 | 
						|
 | 
						|
 | 
						|
        $data   = [
 | 
						|
            'avatar'        => File::convertCompleteFileUrl($account['avatar_url']),
 | 
						|
            'nickName'      => $account['nick_name'],
 | 
						|
            'token'         => Jwt::generate($jwtData),
 | 
						|
            'userType'      => $account['type'],
 | 
						|
            'userTypeDes'   => Account::accountTypeDescList()[$account['type']] ?? '游客',
 | 
						|
        ];
 | 
						|
        return $this->json(0, 'success', $data);
 | 
						|
    }
 | 
						|
 | 
						|
 | 
						|
} |