初始化
缺陷:主题配色需要优化整体的同风格
This commit is contained in:
71
app/Service/wx/WxAuthService.php
Normal file
71
app/Service/wx/WxAuthService.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service\wx;
|
||||
|
||||
use App\BaseApp\BaseWxService;
|
||||
use App\Models\business\ListModel;
|
||||
use App\Models\business\WxUserModel;
|
||||
use App\Service\business\SerialNoService;
|
||||
|
||||
/**
|
||||
* 小程序登录
|
||||
*
|
||||
* 返回的 token 是服务端自签的(见 WxTokenService),session_key 只写库不外发。
|
||||
*/
|
||||
class WxAuthService extends BaseWxService
|
||||
{
|
||||
protected bool $needLogin = false;
|
||||
|
||||
private const DEFAULT_AVATAR = 'http://qiniu.boerman.top/b_2010f38d40d7d4426787b9131020e2a3.png';
|
||||
|
||||
/**
|
||||
* code 登录:老用户更新 session_key,新用户建档并送一份默认清单
|
||||
*/
|
||||
public function login(array $params): array
|
||||
{
|
||||
$code = trim((string) ($params['code'] ?? ''));
|
||||
if ($code === '') {
|
||||
$this->utils->errorThrow('缺少 code');
|
||||
}
|
||||
$credentials = WxMiniService::getInstance()->jscode2session($code);
|
||||
$openId = (string) $credentials['openid'];
|
||||
$now = time();
|
||||
|
||||
$user = WxUserModel::where('open_id', $openId)->first();
|
||||
if (empty($user)) {
|
||||
$userId = WxUserModel::insertGetId([
|
||||
'open_id' => $openId,
|
||||
'session_key' => (string) ($credentials['session_key'] ?? ''),
|
||||
'avatar' => $params['avatar'] ?? self::DEFAULT_AVATAR,
|
||||
'nick_name' => $params['nick_name'] ?? '微信用户',
|
||||
'phone' => '',
|
||||
'created_at' => $now,
|
||||
]);
|
||||
if (empty($userId)) {
|
||||
$this->utils->errorThrow('用户创建失败');
|
||||
}
|
||||
ListModel::insert([
|
||||
'list_no' => SerialNoService::getInstance()->generate(SerialNoService::PREFIX_LIST, 'list', 'list_no'),
|
||||
'user_id' => $userId,
|
||||
'name' => '默认清单',
|
||||
'remark' => '系统默认生成的清单',
|
||||
'created_at' => $now,
|
||||
]);
|
||||
} else {
|
||||
$userId = (int) $user['id'];
|
||||
WxUserModel::where('id', $userId)->update([
|
||||
'session_key' => (string) ($credentials['session_key'] ?? ''),
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
$userInfo = WxUserModel::where('id', $userId)->with('enterprise')->first();
|
||||
$userInfo = $userInfo ? $userInfo->toArray() : [];
|
||||
unset($userInfo['session_key']);
|
||||
|
||||
return [
|
||||
'token' => WxTokenService::getInstance()->issue((int) $userId, (string) ($credentials['app_code'] ?? '')),
|
||||
'user_info' => $userInfo,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user