103 lines
2.9 KiB
PHP

<?php
namespace Extend\Detection;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use App\Model\BasicDetectionOrgan;
use App\Utils\Log;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Context\ApplicationContext;
use Psr\Container\ContainerInterface;
use \Hyperf\Config\config;
/**
* 对接检测所
*/
class Base
{
#[Inject]
protected ContainerInterface $container;
#[Inject]
protected Client $client;
protected string $app_id;
protected string $secret; // 秘钥
protected string $request_url; // 请求地址
public function __construct(string $detection_organ_id)
{
$this->container = ApplicationContext::getContainer();
$this->client = $this->container->get(Client::class);
// 获取检测机构数据
$params = array();
$params['detection_organ_id'] = $detection_organ_id;
$basic_detection_organ = BasicDetectionOrgan::getOne($params);
if (!empty($basic_detection_organ)){
if (!empty($basic_detection_organ['app_id'])){
$this->app_id = $basic_detection_organ['app_id'];
}
if (!empty($basic_detection_organ['app_secret'])){
$this->secret = $basic_detection_organ['app_secret'];
}
$app_env = config("app_env","dev");
if ($app_env == "dev"){
if (!empty($basic_detection_organ['request_dev_url'])){
$this->request_url = $basic_detection_organ['request_dev_url'];
}
}else{
if (!empty($basic_detection_organ['request_prod_url'])){
$this->request_url = $basic_detection_organ['request_prod_url'];
}
}
}
}
/**
* 请求封装
* @param string $sign
* @param $path
* @param array $arg 请求参数
* @return array
* @throws GuzzleException
*/
protected function httpRequest(string $sign,$path,array $arg = []): array
{
$option = [
"headers" => [
"source" => $sign
]
];
if (!empty($option)){
$arg = array_merge($arg,$option);
}
// 打印使用
$l = $arg;
unset($l['json']['pictureOfDetectionTube']);
Log::getInstance("请求参数")->info(json_encode($l,JSON_UNESCAPED_UNICODE));
$response = $this->client->post($path, $arg);
if ($response->getStatusCode() != '200'){
// 请求失败
throw new BusinessException($response->getBody()->getContents());
}
$body = json_decode($response->getBody(),true);
if (empty($body)){
// 返回值为空
throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
}
return $body;
}
}