Files
lgp-admin-plus-api/app/Service/wx/WxAuthService.php
LQ bcf54c2727 初始化
缺陷:主题配色需要优化整体的同风格
2026-08-14 23:21:21 +08:00

72 lines
2.5 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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 是服务端自签的(见 WxTokenServicesession_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,
];
}
}