hyperf-gateway/app/Service/User/WechatAuthService.php

122 lines
2.9 KiB
PHP
Raw Normal View History

2022-11-07 16:29:37 +08:00
<?php
2022-11-17 10:14:12 +08:00
namespace App\Service\User;
2022-11-07 16:29:37 +08:00
2022-11-17 10:14:12 +08:00
use App\Constants\Wechat\AuthErrorCode;
2022-11-07 16:29:37 +08:00
use App\Exception\BusinessException;
use App\Helper\Curl;
use App\JsonRpc\UserExternalServiceInterface;
use Hyperf\Config\Annotation\Value;
use Hyperf\Di\Annotation\Inject;
2022-11-17 10:14:12 +08:00
use Phper666\JWTAuth\JWT;
use Psr\SimpleCache\InvalidArgumentException;
2022-11-07 16:29:37 +08:00
/**
* 微信授权处理服务层
*/
2022-11-17 10:14:12 +08:00
class WechatAuthService
2022-11-07 16:29:37 +08:00
{
/**
* 考勤系统小程序APPID
*
* @var string
*/
2022-11-07 16:29:37 +08:00
#[Value("app.wechat_punch_card_appid")]
protected string $appid;
/**
* 考勤系统小程序APPSecret
*
* @var string
*/
2022-11-07 16:29:37 +08:00
#[Value("app.wechat_punch_card_secret")]
protected string $secret;
/**
* 用户中心对外RPC服务
*
* @var UserExternalServiceInterface
*/
2022-11-07 16:29:37 +08:00
#[Inject]
protected UserExternalServiceInterface $userExternalService;
2022-11-17 10:14:12 +08:00
/**
* JWT认证组件
*
* @var JWT
*/
#[Inject]
protected JWT $jwt;
/**
* 微信通过code获取session信息请求地址
*
* @var string
*/
2022-11-07 16:29:37 +08:00
protected string $wechat_auth_url = 'https://api.weixin.qq.com/sns/jscode2session';
/**
* 通过微信授权新建用户
*
* @param string $code
* @return array
*/
public function codeToOpenID(string $code) : array
{
$url = $this->wechat_auth_url . '?' . http_build_query([
'appid' => $this->appid,
'secret' => $this->secret,
'js_code' => $code,
'grant_type' => 'authorization_code'
]);
$result = Curl::get($url);
$res = $this->userExternalService->wechatNewUser($result['data']['openid']);
if (!$res['code'] !== 200) {
throw new BusinessException($res['code'], $res['msg']);
}
2022-11-17 10:14:12 +08:00
if (empty($res['data']['user'])) {
throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL);
}
$user_data = [
'user_id' => $res['data']['user']['user_id'],
'nickname' => $res['data']['user']['user_nickname'],
'openid' => $res['data']['user']['user_openid']
];
try {
$token = $this->jwt->getToken('default', $user_data);
} catch (InvalidArgumentException) {
// TODO 记录日志
throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL);
}
return [
'token' => $token->toString(),
'exp' => $this->jwt->getTTL($token->toString())
];
}
/**
* 刷新token
*
* @return array
*/
public function refreshToken() : array
{
try {
$token = $this->jwt->refreshToken();
} catch (InvalidArgumentException) {
// TODO 记录日志
throw new BusinessException(AuthErrorCode::CODE_TO_AUTH_FAIL);
}
return [
'token' => $token->toString(),
'exp' => $this->jwt->getTTL($token->toString())
];
2022-11-07 16:29:37 +08:00
}
}