khyzd/hyperf-api-client

apiClient

Installs: 44

Dependents: 0

Suggesters: 0

Security: 0

pkg:composer/khyzd/hyperf-api-client

v3.0.2 2025-12-23 05:38 UTC

This package is auto-updated.

Last update: 2025-12-27 09:00:59 UTC


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;
            }
        );
    }

}