2022-11-07 16:29:37 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Service\Wechat;
|
|
|
|
|
|
|
|
use App\Exception\BusinessException;
|
|
|
|
use App\Helper\Curl;
|
|
|
|
use App\JsonRpc\UserExternalServiceInterface;
|
|
|
|
use Hyperf\Config\Annotation\Value;
|
|
|
|
use Hyperf\Di\Annotation\Inject;
|
|
|
|
|
2022-11-08 11:38:31 +08:00
|
|
|
/**
|
|
|
|
* 微信授权处理服务层
|
|
|
|
*/
|
2022-11-07 16:29:37 +08:00
|
|
|
class AuthService
|
|
|
|
{
|
2022-11-08 11:38:31 +08:00
|
|
|
/**
|
|
|
|
* 考勤系统小程序APPID
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
2022-11-07 16:29:37 +08:00
|
|
|
#[Value("app.wechat_punch_card_appid")]
|
|
|
|
protected string $appid;
|
|
|
|
|
2022-11-08 11:38:31 +08:00
|
|
|
/**
|
|
|
|
* 考勤系统小程序APPSecret
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
2022-11-07 16:29:37 +08:00
|
|
|
#[Value("app.wechat_punch_card_secret")]
|
|
|
|
protected string $secret;
|
|
|
|
|
2022-11-08 11:38:31 +08:00
|
|
|
/**
|
|
|
|
* 用户中心对外RPC服务
|
|
|
|
*
|
|
|
|
* @var UserExternalServiceInterface
|
|
|
|
*/
|
2022-11-07 16:29:37 +08:00
|
|
|
#[Inject]
|
|
|
|
protected UserExternalServiceInterface $userExternalService;
|
|
|
|
|
2022-11-08 11:38:31 +08:00
|
|
|
/**
|
|
|
|
* 微信通过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']);
|
|
|
|
}
|
|
|
|
|
|
|
|
return ['openid' => $result['data']['openid']];
|
|
|
|
}
|
|
|
|
}
|