原创 适配器SDK实现:连接与调用方法详解

发布时间:
更新时间:
浏览次数:161
评论数:0

如何实现适配器SDK中的connection和invoke方法

要构建一个适配器SDK以连接和调用指定的软件平台,需要引用并实例化适配器类,并在实例化过程中传递基本连接参数给SDK构造方法。

namespace Adapter\PlatformName\SDK;

class PlatformNameSDK {
    protected $connectorId = 'connectorId';
    protected $env = '';
    protected $host = '';
    protected $login = [
        'appKey' => 'xxxxxx',
        'appSecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    ];
    protected $token = null;
    protected $client = \GuzzleHttp\Client::class;

    public function __construct($connectorId, $params, string $env = '') {
        $this->connectorId = $connectorId;
        $this->host = $params['host'];
        $this->login = $params;
        $this->env = $env;
        $this->client = new \GuzzleHttp\Client();
    }

    public function invoke(string $api, $params = [], $method = 'POST') {}

    public function connection() {}
}

实现connection方法

connection()方法主要用于连接到目标平台并获取token,特别是对于需要token鉴权的平台,这个方法负责管理token的获取和缓存。

public function connection() {
    $cacheKey = $this->connectorId . $this->env;
    $token = Cache::get($cacheKey);

    if ($token) {
        $this->token = $token;
        return ['status' => true, 'token' => $token];
    }

    $url = $this->host . '/open-apis/auth/v3/tenant_access_token/internal';
    $response = $this->client->post($url, [
        'form_params' => $this->login,
        'headers' => ['Content-Type' => 'application/json;charset=utf-8']
    ]);

    $body = $response->getBody();
    $arr = json_decode((string)$body, true);

    if ($arr['code'] == 0) {
        $this->token = $arr['tenant_access_token'];
        Cache::put($cacheKey, $this->token, $arr['expire'] - 100);
    }

    return $arr;
}

实现invoke方法

invoke()方法用于实现具体接口的调用。

public function invoke(string $api, $params = [], $method = 'POST') {
    $url = $this->host . $api;
    $sign = $this->generateSign($params);
    $headers = [
        'accesstoken' => $this->token,
        'sign' => $sign,
        'Content-Type' => 'application/json'
    ];

    if (strtolower($method) === 'get') {
        $response = $this->client->get($url, [
            'query' => $params,
            'http_errors' => false,
            'headers' => $headers
        ]);
    } else {
        $response = $this->client->post($url, [
            'body' => json_encode($params),
            'http_errors' => false,
            'headers' => $headers
        ]);
    }

    $body = (string) $response->getBody();
    return json_decode($body, true);
}

protected function generateSign($params) {
    $jsonStr = json_encode($params) . $this->login['appKey'];
    return md5($jsonStr);
}

这个实现展示了如何用PHP的GuzzleHttp\Client来处理HTTP请求,如何生成签名,以及如何管理token缓存。