如何实现SDK的connection和invoke方法
Source: Qeasy Cloud397 views
SDK适配器实现:连接与调用
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, array$params=[], string$method='POST') {}
public function connection() {}
}
实现连接方法
在connection()方法中,我们需要实现与目标平台的连接,尤其是需要token鉴权的平台,用于管理token。
public function connection() {
// 获取缓存中的token
$cacheKey = "{$this->connectorId}{$this->env}";
if ($token=Cache::get($cacheKey)) {
return ['status' => true, 'token' => ($this->token=$token)];
}
// 请求新的token
try {
$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'],
]);
if (($arr=json_decode((string)$response->getBody(), true))['code'] == 0) {
Cache::put($cacheKey, ($this->$token=$arr['tenant_access_token']), ($arr['expire']-100));
return ['status'=>true,'token'=>$arr['tenant_access_token']];
}
return ['status'=>false,'error'=>'Token获取失败'];
} catch (\Exception$e) {
return ['status'=>false,'error'=>$e.getMessage()];
}
}
实现接口调用方法
invoke()方法用来实现具体接口的调用逻辑。
public function invoke(string$api,array$params=[],string$method='POST') {
try{
// 构建请求URL和签名
url="{$this->$host}$api";
headers=[
'accesstoken'=>$this->$token,
'sign'=>$generateSign($params),
'Content-Type'=>'application/json'
];
// 根据请求方式发送请求
if (strtoupper($method)==='GET') {
response=$client.get(url,['query'=>$params,'http_errors'=>false,'headers'=>$headers]);
} else {
response=$client.post(url,['body'=>json_encode(params),'http_errors'=>false,'headers'=>$headers]);
}
// 处理响应结果
body=(string)$response.getBody();
arr=json_decode(body,true);
return arr;
} catch (\Exception$e) {
return ['status'=>false,'error'=>$e.getMessage()];
}
}
protected function generateSign(array$params): string{
jsonStr=json_encode(params).$login['appKey'];
return md5(jsonStr);
}
以上代码展示了如何通过SDK实现与目标平台的连接以及接口调用。通过合理地管理和使用Token,我们可以确保与平台的通信安全可靠。
Copyright Notice
The article "如何实现SDK的connection和invoke方法" is original content owned by 广东轻亿云软件科技有限公司. Reposting, quoting, copying or mirroring is strictly prohibited without written authorization. Please contact us for authorization and credit the author and source (including the original link) prominently.