适配器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()
{
}
}
实现SDK->connection(),连接到目标平台的方法,主要针对需要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;
}
实现SDK->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 ($method === 'get' || $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 = $response->getBody();
$bodyStr = (string)$body;
$arr = json_decode($bodyStr,true);
return $arr;
}
protected function generateSign($params)
{
$jsonStr = json_encode($params).$this->login['appKey'];
return md5($jsonStr);
}