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

48 lines
1.2 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
{
#[Value("app.wechat_punch_card_appid")]
protected string $appid;
#[Value("app.wechat_punch_card_secret")]
protected string $secret;
#[Inject]
protected UserExternalServiceInterface $userExternalService;
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']];
}
}