79 lines
1.9 KiB
PHP
79 lines
1.9 KiB
PHP
<?php
|
|
/**
|
|
* This service file is part of item.
|
|
*
|
|
* @author ctexthuang
|
|
* @contact ctexthuang@qq.com
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service\ServiceTrait\Api;
|
|
|
|
use App\Exception\ErrException;
|
|
use App\Lib\Log;
|
|
use GuzzleHttp\Exception\GuzzleException;
|
|
use Hyperf\Di\Annotation\Inject;
|
|
use Hyperf\Guzzle\ClientFactory;
|
|
use Psr\Container\ContainerExceptionInterface;
|
|
use Psr\Container\NotFoundExceptionInterface;
|
|
use function Hyperf\Config\config;
|
|
|
|
trait WxMiniTrait
|
|
{
|
|
/**
|
|
* 注入请求工厂类
|
|
* @var ClientFactory $clientFactory
|
|
*/
|
|
#[Inject]
|
|
protected ClientFactory $clientFactory;
|
|
|
|
/**
|
|
* 注入日志类
|
|
* @var Log
|
|
*/
|
|
#[Inject]
|
|
protected Log $log;
|
|
|
|
/**
|
|
* baseUri
|
|
* @var string
|
|
*/
|
|
protected string $BaseUri = 'https://api.weixin.qq.com';
|
|
|
|
/**
|
|
* @param string $code
|
|
* @return mixed
|
|
* @throws ContainerExceptionInterface
|
|
* @throws NotFoundExceptionInterface
|
|
*/
|
|
public function jsCodeGetOpenId(string $code): mixed
|
|
{
|
|
$url = sprintf(
|
|
'/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',
|
|
config('system.wx_appid'),
|
|
config('system.wx_secret'),
|
|
$code
|
|
);
|
|
|
|
try {
|
|
$tencentResponse = $this->clientFactory->create([
|
|
'base_uri' => $this->BaseUri,
|
|
'timeout' => 5
|
|
])->get($url);
|
|
|
|
$contents = $tencentResponse->getBody()->getContents();
|
|
|
|
$this->log->info(__class__.':微信服务器返回token信息:', [$contents]);
|
|
|
|
$res = json_decode($contents,true);
|
|
|
|
if (empty($res['errcode']) || $res['errcode'] != 0) throw new ErrException($res['errmsg'] ?? '系统繁忙');
|
|
|
|
return $res;
|
|
}catch (GuzzleException $e) {
|
|
$this->log->debug(__CLASS__.':debug:'.$e->getMessage());
|
|
throw new ErrException($e->getMessage());
|
|
}
|
|
}
|
|
} |