Files
hyperf_service/app/Service/ServiceTrait/Api/WxMiniTrait.php
2024-11-27 15:20:46 +08:00

196 lines
5.4 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\Cache\Redis\Api\ApiRedisKey;
use App\Cache\Redis\Common\CommonRedisKey;
use App\Cache\Redis\RedisCache;
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;
/**
* 注入缓存类
* @var RedisCache
*/
#[Inject]
protected RedisCache $redisCache;
/**
* baseUri
* @var string
*/
protected string $BaseUri = 'https://api.weixin.qq.com';
private string $appId = '';
private string $appSecret = '';
public function __construct()
{
$this->appId = config('system.wx_appid');
}
/**
* @return false|mixed|\Redis|string
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
protected function getAccessTokenCache(): mixed
{
$key = CommonRedisKey::getWxAccessToken();
if ($this->redisCache->exists($key)) {
return $this->redisCache->get($key) ?? '';
}
$data = $this->getAccessToken();
if (empty($data) || empty($data['access_token']) || empty($data['expires_in'])) return '';
$this->redisCache->set($key, $data['access_token'], $data['expires_in'] - 10);
return $data['access_token'];
}
/**
* 获取 access Token
* @return mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function getAccessToken(): mixed
{
$url = sprintf(
'/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
config('system.wx_appid'),
config('system.wx_secret')
);
try {
$tencentResponse = $this->clientFactory->create([
'base_uri' => $this->BaseUri,
'timeout' => 5
])->get($url);
$contents = $tencentResponse->getBody()->getContents();
$this->log->callbackLog(__class__.':微信服务器返回getAccessToken信息:'.json_encode($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());
}
}
/**
* @param string $code
* @return mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
protected 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->callbackLog(__class__.':微信服务器返回wx_login信息:'.json_encode($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());
}
}
/**
* @param string $code
* @return mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
protected function jsCodeGetPhoneNumber(string $code): mixed
{
$url = sprintf(
'/wxa/business/getuserphonenumber?access_token=%s',
$this->getAccessTokenCache()
);
$params = [
'code' => $code,
];
try {
$wxResponse = $this->clientFactory->create([
'base_uri' => $this->BaseUri,
'timeout' => 5
])->post($url,[
'headers' => [
'Content-Type' => 'application/json'
],
'body' => json_encode($params)
]);
$contents = $wxResponse->getBody()->getContents();
$this->log->callbackLog(__class__.':微信服务器返回get_phone_number信息:'.json_encode($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());
}
}
}