khyzd / hyperf-api-client
apiClient
v3.0.2
2025-12-23 05:38 UTC
Requires
- php: >=8.0
- hyperf/codec: ~3.0.0
- hyperf/collection: ~3.0.0
- hyperf/command: ~3.0.0
- hyperf/contract: ~3.0.0
- hyperf/framework: ~3.0.0
- hyperf/guzzle: ~3.0.0
- hyperf/http-server: ~3.0.0
Requires (Dev)
- hyperf/testing: ~3.0.0
- phpstan/phpstan: ^1.9
- swoole/ide-helper: ^5.0
README
Hyperf 分布式项目 API 客户端封装包。
安装
composer require khyzd/hyperf-api-client
说明
发布配置文件
php bin/hyperf.php vendor:publish khyzd/hyperf-api-client
使用
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
use Khyzd\HyperfApiClient\ApiClientService;
class TestController extends AbstractController
{
/**
* @Inject
* @var ApiClientService
*/
protected $apiClient;
/**
* 请求接口
* */
public function index()
{
try {
$response = $this->apiClient->postJson('/test2', [['id' => 10, 'name' => '张三']]);
var_dump($response);
} catch (\Exception $e) {
var_dump($e->getCode());
var_dump($e->getMessage());
}
}
/**
* 回调函数 方式1
* */
public function index1()
{
//验证IP白名单
if(!$this->apiClient->verifyIpWhitelist()){
return $this->apiClient->errorResponse(500, 'IP地址不在白名单中');
}
//验签
if(!$this->apiClient->verifyCurrentRequest()){
return $this->apiClient->errorResponse(500, '签名验证失败');
}
//获取请求中的业务数据
$businessData = $this->apiClient->getBusinessDataFromRequest();
//处理业务逻辑
$result = [
['id' => 10, 'name' => 'aaa'],
['id' => 11, 'name' => 'bbb']
];
//成功响应
return $this->apiClient->successResponse($result);
}
/**
* 回调函数 方式2
* */
public function index2()
{
return $this->apiClient->handleVerifyCurrentRequest(
function (array $businessData) {
//throw new \Exception('订单号不能为空', 440);
//var_dump($businessData);
$result = [
['id' => 10, 'name' => 'ccc'],
['id' => 11, 'name' => 'ddd']
];
return $result;
}
);
}
}