109 lines
3.1 KiB
PHP

<?php
namespace Extend\Ca;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
/**
* 四川ca云证书+电子签章
*/
class Ca
{
#[Inject]
protected ContainerInterface $container;
#[Inject]
protected Client $client;
public function __construct(){
$this->container = ApplicationContext::getContainer();
$this->client = $this->container->get(Client::class);
}
// 获取云证书
public function getCloudCert(array $data){
$option = [
'form_params' => [
'entityId' => $data['user_id'], // 用户唯一标识,由业务系统定义
'entityType' => "Personal",// 用户类型,可选值[Personal/Organizational]
'pin' => $data['user_id'], // 证书PIN码
'cardNumber' => $data['card_num'], // 证件号码(个人身份证;企业统一社会信用代码)
]
];
try {
$response = $this->httpRequest(config("ca.api_url") . '/cloud-certificate-service' . '/api/cloudCert/open/V2/cert/offlineAuthCertEnroll', $option);
if (empty($response)){
// 返回值为空
throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
}
return $response;
} catch (GuzzleException $e) {
throw new BusinessException($e->getMessage());
}
}
/**
* 获取签名
* @param array $data
* @return string
*/
protected function getSign(array $data): string
{
$data = implode('&',$data['form_params']);
return hash_hmac("sha1",$data,config("ca.secret"));
}
/**
* 封装公共请求
* @param string $path
* @param array $arg
* @return mixed
* @throws GuzzleException
*/
public function httpRequest(string $path,array $arg = []): mixed
{
$option = [
"headers" => [
"app_id" => config("ca.app_id"),
"signature" => $this->getSign($arg)
],
];
$arg = array_merge($arg,$option);
dump($path);die;
dump($arg);die;
$response = $this->client->post($path, $arg);
dump(1);
if ($response->getStatusCode() != '200'){
// 请求失败
throw new BusinessException($response->getBody()->getContents());
}
dump(2);
$body = json_decode($response->getBody(),true);
dump($body);die;
if (empty($body)){
// 返回值为空
throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
}
if ($body['result_code'] != 0){
// 请求失败
if (!empty($body['result_msg'])){
throw new BusinessException($body['result_msg']);
}
throw new BusinessException(HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR));
}
return $body['body'];
}
}