AbstractClient.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. /*
  3. * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing,
  12. * software distributed under the License is distributed on an
  13. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. * KIND, either express or implied. See the License for the
  15. * specific language governing permissions and limitations
  16. * under the License.
  17. */
  18. namespace TencentCloud\Common;
  19. use \ReflectionClass;
  20. use TencentCloud\Common\Http\HttpConnection;
  21. use TencentCloud\Common\Profile\ClientProfile;
  22. use TencentCloud\Common\Profile\HttpProfile;
  23. use TencentCloud\Common\Exception\TencentCloudSDKException;
  24. /**
  25. * 抽象api类,禁止client引用
  26. * @package TencentCloud\Common
  27. */
  28. abstract class AbstractClient
  29. {
  30. /**
  31. * @var string SDK版本
  32. */
  33. public static $SDK_VERSION = "SDK_PHP_3.0.754";
  34. /**
  35. * @var integer http响应码200
  36. */
  37. public static $HTTP_RSP_OK = 200;
  38. private $PHP_VERSION_MINIMUM = "5.6.0";
  39. /**
  40. * @var Credential 认证类实例,保存认证相关字段
  41. */
  42. private $credential;
  43. /**
  44. * @var ClientProfile 会话配置信息类
  45. */
  46. private $profile;
  47. /**
  48. * @var string 产品地域
  49. */
  50. private $region;
  51. /**
  52. * @var string 请求路径
  53. */
  54. private $path;
  55. /**
  56. * @var string sdk版本号
  57. */
  58. private $sdkVersion;
  59. /**
  60. * @var string api版本号
  61. */
  62. private $apiVersion;
  63. /**
  64. * @var HttpConnection
  65. */
  66. private $httpConn;
  67. /**
  68. * 基础client类
  69. * @param string $endpoint Deprecated, we use service+rootdomain instead
  70. * @param string $version api版本
  71. * @param Credential $credential 认证信息实例
  72. * @param string $region 产品地域
  73. * @param ClientProfile $profile
  74. */
  75. function __construct($endpoint, $version, $credential, $region, $profile=null)
  76. {
  77. $this->path = "/";
  78. $this->credential = $credential;
  79. $this->region = $region;
  80. if ($profile) {
  81. $this->profile = $profile;
  82. } else {
  83. $this->profile = new ClientProfile();
  84. }
  85. $this->getRefreshedEndpoint();
  86. $this->sdkVersion = AbstractClient::$SDK_VERSION;
  87. $this->apiVersion = $version;
  88. if (version_compare(phpversion(), $this->PHP_VERSION_MINIMUM, '<') && $profile->getCheckPHPVersion()) {
  89. throw new TencentCloudSDKException("ClientError", "PHP version must >= ".$this->PHP_VERSION_MINIMUM.", your current is ".phpversion());
  90. }
  91. $this->httpConn = $this->createConnect();
  92. }
  93. /**
  94. * 设置产品地域
  95. * @param string $region 地域
  96. */
  97. public function setRegion($region)
  98. {
  99. $this->region = $region;
  100. }
  101. /**
  102. * 获取产品地域
  103. * @return string
  104. */
  105. public function getRegion()
  106. {
  107. return $this->region;
  108. }
  109. /**
  110. * 设置认证信息实例
  111. * @param Credential $credential 认证信息实例
  112. */
  113. public function setCredential($credential)
  114. {
  115. $this->credential = $credential;
  116. }
  117. /**
  118. * 返回认证信息实例
  119. * @return Credential
  120. */
  121. public function getCredential()
  122. {
  123. return $this->credential;
  124. }
  125. /**
  126. * 设置配置实例
  127. * @param ClientProfile $profile 配置实例
  128. */
  129. public function setClientProfile($profile)
  130. {
  131. $this->profile = $profile;
  132. }
  133. /**
  134. * 返回配置实例
  135. * @return ClientProfile
  136. */
  137. public function getClientProfile()
  138. {
  139. return $this->profile;
  140. }
  141. /**
  142. * @param string $action 方法名
  143. * @param array $request 参数列表
  144. * @return mixed
  145. * @throws TencentCloudSDKException
  146. */
  147. public function __call($action, $request)
  148. {
  149. return $this->doRequestWithOptions($action, $request[0], array());
  150. }
  151. /**
  152. * @param string $action 方法名
  153. * @param array $headers 自定义headers
  154. * @param string $body content
  155. * @return mixed
  156. * @throws TencentCloudSDKException
  157. */
  158. public function call_octet_stream($action, $headers, $body) {
  159. try {
  160. $responseData = null;
  161. $options = array(
  162. "IsOctetStream" => true,
  163. );
  164. switch ($this->profile->getSignMethod()) {
  165. case ClientProfile::$SIGN_TC3_SHA256:
  166. $responseData = $this->doRequestWithTC3($action, Null, $options, $headers, $body);
  167. break;
  168. default:
  169. throw new TencentCloudSDKException("ClientError", "Invalid sign method");
  170. break;
  171. }
  172. if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
  173. throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
  174. }
  175. $tmpResp = json_decode($responseData->getBody(), true)["Response"];
  176. if (array_key_exists("Error", $tmpResp)) {
  177. throw new TencentCloudSDKException($tmpResp["Error"]["Code"], $tmpResp["Error"]["Message"], $tmpResp["RequestId"]);
  178. }
  179. return $this->returnResponse($action, $tmpResp);
  180. } catch (\Exception $e) {
  181. if (!($e instanceof TencentCloudSDKException)) {
  182. throw new TencentCloudSDKException("", $e->getMessage());
  183. } else {
  184. throw $e;
  185. }
  186. }
  187. }
  188. protected function doRequestWithOptions($action, $request, $options)
  189. {
  190. try {
  191. $responseData = null;
  192. $serializeRequest = $request->serialize();
  193. $method = $this->getPrivateMethod($request, "arrayMerge");
  194. $serializeRequest = $method->invoke($request, $serializeRequest);
  195. switch ($this->profile->getSignMethod()) {
  196. case ClientProfile::$SIGN_HMAC_SHA1:
  197. case ClientProfile::$SIGN_HMAC_SHA256:
  198. $responseData = $this->doRequest($action, $serializeRequest);
  199. break;
  200. case ClientProfile::$SIGN_TC3_SHA256:
  201. $responseData = $this->doRequestWithTC3($action, $request, $options, array(), "");
  202. break;
  203. default:
  204. throw new TencentCloudSDKException("ClientError", "Invalid sign method");
  205. break;
  206. }
  207. if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
  208. throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
  209. }
  210. $tmpResp = json_decode($responseData->getBody(), true)["Response"];
  211. if (array_key_exists("Error", $tmpResp)) {
  212. throw new TencentCloudSDKException($tmpResp["Error"]["Code"], $tmpResp["Error"]["Message"], $tmpResp["RequestId"]);
  213. }
  214. return $this->returnResponse($action, $tmpResp);
  215. } catch (\Exception $e) {
  216. if (!($e instanceof TencentCloudSDKException)) {
  217. throw new TencentCloudSDKException("", $e->getMessage());
  218. } else {
  219. throw $e;
  220. }
  221. }
  222. }
  223. private function doRequest($action, $request)
  224. {
  225. switch ($this->profile->getHttpProfile()->getReqMethod()) {
  226. case HttpProfile::$REQ_GET:
  227. return $this->getRequest($action, $request);
  228. break;
  229. case HttpProfile::$REQ_POST:
  230. return $this->postRequest($action, $request);
  231. break;
  232. default:
  233. throw new TencentCloudSDKException("", "Method only support (GET, POST)");
  234. break;
  235. }
  236. }
  237. private function doRequestWithTC3($action, $request, $options, $headers, $payload)
  238. {
  239. $endpoint = $this->getRefreshedEndpoint();
  240. $headers["Host"] = $endpoint;
  241. $headers["X-TC-Action"] = ucfirst($action);
  242. $headers["X-TC-RequestClient"] = $this->sdkVersion;
  243. $headers["X-TC-Timestamp"] = time();
  244. $headers["X-TC-Version"] = $this->apiVersion;
  245. if ($this->region) {
  246. $headers["X-TC-Region"] = $this->region;
  247. }
  248. if ($this->credential->getToken()) {
  249. $headers["X-TC-Token"] = $this->credential->getToken();
  250. }
  251. $language = $this->profile->getLanguage();
  252. if ($language) {
  253. $headers["X-TC-Language"] = $language;
  254. }
  255. $canonicalUri = $this->path;
  256. $reqmethod = $this->profile->getHttpProfile()->getReqMethod();
  257. if (HttpProfile::$REQ_GET == $reqmethod) {
  258. $headers["Content-Type"] = "application/x-www-form-urlencoded";
  259. $rs = $request->serialize();
  260. $am = $this->getPrivateMethod($request, "arrayMerge");
  261. $rsam = $am->invoke($request, $rs);
  262. $canonicalQueryString = http_build_query($rsam);
  263. $payload = "";
  264. }
  265. if (HttpProfile::$REQ_POST == $reqmethod) {
  266. if (isset($options["IsMultipart"]) && $options["IsMultipart"] === true) {
  267. $boundary = uniqid();
  268. $headers["Content-Type"] = "multipart/form-data; boundary=" . $boundary;
  269. $canonicalQueryString = "";
  270. $payload = $this->getMultipartPayload($request, $boundary, $options);
  271. } else if (isset($options["IsOctetStream"]) && $options["IsOctetStream"] === true) {
  272. $headers["Content-Type"] = "application/octet-stream";
  273. $canonicalQueryString = "";
  274. } else {
  275. $headers["Content-Type"] = "application/json";
  276. $canonicalQueryString = "";
  277. $payload = $request->toJsonString();
  278. }
  279. }
  280. if ($this->profile->getUnsignedPayload() == true) {
  281. $headers["X-TC-Content-SHA256"] = "UNSIGNED-PAYLOAD";
  282. $payloadHash = hash("SHA256", "UNSIGNED-PAYLOAD");
  283. } else {
  284. $payloadHash = hash("SHA256", $payload);
  285. }
  286. $canonicalHeaders = "content-type:".$headers["Content-Type"]."\n".
  287. "host:".$headers["Host"]."\n";
  288. $signedHeaders = "content-type;host";
  289. $canonicalRequest = $reqmethod."\n".
  290. $canonicalUri."\n".
  291. $canonicalQueryString."\n".
  292. $canonicalHeaders."\n".
  293. $signedHeaders."\n".
  294. $payloadHash;
  295. $algo = "TC3-HMAC-SHA256";
  296. // date_default_timezone_set('UTC');
  297. // $date = date("Y-m-d", $headers["X-TC-Timestamp"]);
  298. $date = gmdate("Y-m-d", $headers["X-TC-Timestamp"]);
  299. $service = explode(".", $endpoint)[0];
  300. $credentialScope = $date."/".$service."/tc3_request";
  301. $hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
  302. $str2sign = $algo."\n".
  303. $headers["X-TC-Timestamp"]."\n".
  304. $credentialScope."\n".
  305. $hashedCanonicalRequest;
  306. $skey = $this->credential->getSecretKey();
  307. $signature = Sign::signTC3($skey, $date, $service, $str2sign);
  308. $sid = $this->credential->getSecretId();
  309. $auth = $algo.
  310. " Credential=".$sid."/".$credentialScope.
  311. ", SignedHeaders=content-type;host, Signature=".$signature;
  312. $headers["Authorization"] = $auth;
  313. if (HttpProfile::$REQ_GET == $reqmethod) {
  314. $connect = $this->getConnect();
  315. return $connect->getRequest($this->path, $canonicalQueryString, $headers);
  316. } else {
  317. $connect = $this->getConnect();
  318. return $connect->postRequestRaw($this->path, $headers, $payload);
  319. }
  320. }
  321. private function getMultipartPayload($request, $boundary, $options)
  322. {
  323. $body = "";
  324. $params = $request->serialize();
  325. foreach ($params as $key => $value) {
  326. $body .= "--".$boundary."\r\n";
  327. $body .= "Content-Disposition: form-data; name=\"".$key;
  328. if (in_array($key, $options["BinaryParams"])) {
  329. $body .= "\"; filename=\"".$key;
  330. }
  331. $body .= "\"\r\n";
  332. if (is_array($value)) {
  333. $value = json_encode($value);
  334. $body .= "Content-Type: application/json\r\n";
  335. }
  336. $body .= "\r\n".$value."\r\n";
  337. }
  338. if ($body != "") {
  339. $body .= "--".$boundary."--\r\n";
  340. }
  341. return $body;
  342. }
  343. /**
  344. * @throws TencentCloudSDKException
  345. */
  346. private function getRequest($action, $request)
  347. {
  348. $query = $this->formatRequestData($action, $request, httpProfile::$REQ_GET);
  349. $connect = $this->getConnect();
  350. return $connect->getRequest($this->path, $query, []);
  351. }
  352. /**
  353. * @throws TencentCloudSDKException
  354. */
  355. private function postRequest($action, $request)
  356. {
  357. $body = $this->formatRequestData($action, $request, httpProfile::$REQ_POST);
  358. $connect = $this->getConnect();
  359. return $connect->postRequest($this->path, [], $body);
  360. }
  361. /**
  362. * @throws TencentCloudSDKException
  363. */
  364. private function formatRequestData($action, $request, $reqMethod)
  365. {
  366. $param = $request;
  367. $param["Action"] = ucfirst($action);
  368. $param["RequestClient"] = $this->sdkVersion;
  369. $param["Nonce"] = rand();
  370. $param["Timestamp"] = time();
  371. $param["Version"] = $this->apiVersion;
  372. if ($this->credential->getSecretId()) {
  373. $param["SecretId"] = $this->credential->getSecretId();
  374. }
  375. if ($this->region) {
  376. $param["Region"] = $this->region;
  377. }
  378. if ($this->credential->getToken()) {
  379. $param["Token"] = $this->credential->getToken();
  380. }
  381. if ($this->profile->getSignMethod()) {
  382. $param["SignatureMethod"] = $this->profile->getSignMethod();
  383. }
  384. $language = $this->profile->getLanguage();
  385. if ($language) {
  386. $param["Language"] = $language;
  387. }
  388. $signStr = $this->formatSignString($this->getRefreshedEndpoint(), $this->path, $param, $reqMethod);
  389. $param["Signature"] = Sign::sign($this->credential->getSecretKey(), $signStr, $this->profile->getSignMethod());
  390. return $param;
  391. }
  392. private function createConnect()
  393. {
  394. $prot = $this->profile->getHttpProfile()->getProtocol();
  395. return new HttpConnection($prot.$this->getRefreshedEndpoint(), $this->profile);
  396. }
  397. private function getConnect() {
  398. $keepAlive = $this->profile->getHttpProfile()->getKeepAlive();
  399. if (true === $keepAlive) {
  400. return $this->httpConn;
  401. } else {
  402. return $this->createConnect();
  403. }
  404. }
  405. private function formatSignString($host, $uri, $param, $requestMethod)
  406. {
  407. $tmpParam = [];
  408. ksort($param);
  409. foreach ($param as $key => $value) {
  410. array_push($tmpParam, $key . "=" . $value);
  411. }
  412. $strParam = join ("&", $tmpParam);
  413. $signStr = strtoupper($requestMethod) . $host . $uri ."?".$strParam;
  414. return $signStr;
  415. }
  416. private function getPrivateMethod($obj, $methodName) {
  417. $objReflectClass = new ReflectionClass(get_class($obj));
  418. $method = $objReflectClass->getMethod($methodName);
  419. $method->setAccessible(true);
  420. return $method;
  421. }
  422. /**
  423. * User might call httpProfile.SetEndpoint after client is initialized,
  424. * so everytime we get the enpoint we need to check it.
  425. * Or we must find a way to disable such usage.
  426. */
  427. private function getRefreshedEndpoint() {
  428. $this->endpoint = $this->profile->getHttpProfile()->getEndpoint();
  429. if ($this->endpoint === null) {
  430. $this->endpoint = $this->service.".".$this->profile->getHttpProfile()->getRootDomain();
  431. }
  432. return $this->endpoint;
  433. }
  434. }