hyperf-gateway/app/Service/Wechat/AuthService.php

71 lines
1.6 KiB
PHP

<?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;
/**
* 微信授权处理服务层
*/
class AuthService
{
/**
* 考勤系统小程序APPID
*
* @var string
*/
#[Value("app.wechat_punch_card_appid")]
protected string $appid;
/**
* 考勤系统小程序APPSecret
*
* @var string
*/
#[Value("app.wechat_punch_card_secret")]
protected string $secret;
/**
* 用户中心对外RPC服务
*
* @var UserExternalServiceInterface
*/
#[Inject]
protected UserExternalServiceInterface $userExternalService;
/**
* 微信通过code获取session信息请求地址
*
* @var string
*/
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']];
}
}