AbstractClient.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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.108";
  34. /**
  35. * @var integer http响应码200
  36. */
  37. public static $HTTP_RSP_OK = 200;
  38. /**
  39. * @var Credential 认证类实例,保存认证相关字段
  40. */
  41. private $credential;
  42. /**
  43. * @var ClientProfile 会话配置信息类
  44. */
  45. private $profile;
  46. /**
  47. * @var string 产品地域
  48. */
  49. private $region;
  50. /**
  51. * @var string 请求路径
  52. */
  53. private $path;
  54. /**
  55. * @var string sdk版本号
  56. */
  57. private $sdkVersion;
  58. /**
  59. * @var string api版本号
  60. */
  61. private $apiVersion;
  62. /**
  63. * 基础client类
  64. * @param string $endpoint 请求域名
  65. * @param string $version api版本
  66. * @param Credential $credential 认证信息实例
  67. * @param string $region 产品地域
  68. * @param ClientProfile $profile
  69. */
  70. function __construct($endpoint, $version, $credential, $region, $profile=null)
  71. {
  72. $this->path = "/";
  73. $this->credential = $credential;
  74. $this->region = $region;
  75. if ($profile) {
  76. $this->profile = $profile;
  77. } else {
  78. $this->profile = new ClientProfile();
  79. }
  80. if ($this->profile->getHttpProfile()->getEndpoint() === null) {
  81. $this->profile->getHttpProfile()->setEndpoint($endpoint);
  82. }
  83. $this->sdkVersion = AbstractClient::$SDK_VERSION;
  84. $this->apiVersion = $version;
  85. }
  86. /**
  87. * 设置产品地域
  88. * @param string $region 地域
  89. */
  90. public function setRegion($region)
  91. {
  92. $this->region = $region;
  93. }
  94. /**
  95. * 获取产品地域
  96. * @return string
  97. */
  98. public function getRegion()
  99. {
  100. return $this->region;
  101. }
  102. /**
  103. * 设置认证信息实例
  104. * @param Credential $credential 认证信息实例
  105. */
  106. public function setCredential($credential)
  107. {
  108. $this->credential = $credential;
  109. }
  110. /**
  111. * 返回认证信息实例
  112. * @return Credential
  113. */
  114. public function getCredential()
  115. {
  116. return $this->credential;
  117. }
  118. /**
  119. * 设置配置实例
  120. * @param ClientProfile $profile 配置实例
  121. */
  122. public function setClientProfile($profile)
  123. {
  124. $this->profile = $profile;
  125. }
  126. /**
  127. * 返回配置实例
  128. * @return ClientProfile
  129. */
  130. public function getClientProfile()
  131. {
  132. return $this->profile;
  133. }
  134. /**
  135. * @param string $action 方法名
  136. * @param array $request 参数列表
  137. * @return mixed
  138. * @throws TencentCloudSDKException
  139. */
  140. public function __call($action, $request)
  141. {
  142. return $this->doRequestWithOptions($action, $request[0], array());
  143. }
  144. protected function doRequestWithOptions($action, $request, $options)
  145. {
  146. try {
  147. $responseData = null;
  148. $serializeRequest = $request->serialize();
  149. $method = $this->getPrivateMethod($request, "arrayMerge");
  150. $serializeRequest = $method->invoke($request, $serializeRequest);
  151. switch ($this->profile->getSignMethod()) {
  152. case ClientProfile::$SIGN_HMAC_SHA1:
  153. case ClientProfile::$SIGN_HMAC_SHA256:
  154. $responseData = $this->doRequest($action, $serializeRequest);
  155. break;
  156. case ClientProfile::$SIGN_TC3_SHA256:
  157. $responseData = $this->doRequestWithTC3($action, $request, $options);
  158. break;
  159. default:
  160. throw new TencentCloudSDKException("ClientError", "Invalid sign method");
  161. break;
  162. }
  163. if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
  164. throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
  165. }
  166. $tmpResp = json_decode($responseData->getBody(), true)["Response"];
  167. if (array_key_exists("Error", $tmpResp)) {
  168. throw new TencentCloudSDKException($tmpResp["Error"]["Code"], $tmpResp["Error"]["Message"], $tmpResp["RequestId"]);
  169. }
  170. return $this->returnResponse($action, $tmpResp);
  171. } catch (\Exception $e) {
  172. if (!($e instanceof TencentCloudSDKException)) {
  173. throw new TencentCloudSDKException("", $e->getMessage());
  174. } else {
  175. throw $e;
  176. }
  177. }
  178. }
  179. private function doRequest($action, $request)
  180. {
  181. switch ($this->profile->getHttpProfile()->getReqMethod()) {
  182. case HttpProfile::$REQ_GET:
  183. return $this->getRequest($action, $request);
  184. break;
  185. case HttpProfile::$REQ_POST:
  186. return $this->postRequest($action, $request);
  187. break;
  188. default:
  189. throw new TencentCloudSDKException("", "Method only support (GET, POST)");
  190. break;
  191. }
  192. }
  193. private function doRequestWithTC3($action, $request, $options)
  194. {
  195. $headers = array();
  196. $endpoint = $this->profile->getHttpProfile()->getEndpoint();
  197. $headers["Host"] = $endpoint;
  198. $headers["X-TC-Action"] = ucfirst($action);
  199. $headers["X-TC-RequestClient"] = $this->sdkVersion;
  200. $headers["X-TC-Timestamp"] = time();
  201. $headers["X-TC-Version"] = $this->apiVersion;
  202. if ($this->region) {
  203. $headers["X-TC-Region"] = $this->region;
  204. }
  205. if ($this->credential->getToken()) {
  206. $headers["X-TC-Token"] = $this->credential->getToken();
  207. }
  208. $canonicalUri = $this->path;
  209. $reqmethod = $this->profile->getHttpProfile()->getReqMethod();
  210. if (HttpProfile::$REQ_GET == $reqmethod) {
  211. $headers["Content-Type"] = "application/x-www-form-urlencoded";
  212. $rs = $request->serialize();
  213. $am = $this->getPrivateMethod($request, "arrayMerge");
  214. $rsam = $am->invoke($request, $rs);
  215. $canonicalQueryString = http_build_query($rsam);
  216. $payload = "";
  217. } else if (isset($options["IsMultipart"]) && $options["IsMultipart"] === true) {
  218. $boundary = uniqid();
  219. $headers["Content-Type"] = "multipart/form-data; boundary=".$boundary;
  220. $canonicalQueryString = "";
  221. $payload = $this->getMultipartPayload($request, $boundary, $options);
  222. } else {
  223. $headers["Content-Type"] = "application/json";
  224. $canonicalQueryString = "";
  225. $payload = $request->toJsonString();
  226. }
  227. if ($this->profile->getUnsignedPayload() == true) {
  228. $headers["X-TC-Content-SHA256"] = "UNSIGNED-PAYLOAD";
  229. $payloadHash = hash("SHA256", "UNSIGNED-PAYLOAD");
  230. } else {
  231. $payloadHash = hash("SHA256", $payload);
  232. }
  233. $canonicalHeaders = "content-type:".$headers["Content-Type"]."\n".
  234. "host:".$headers["Host"]."\n";
  235. $signedHeaders = "content-type;host";
  236. $canonicalRequest = $reqmethod."\n".
  237. $canonicalUri."\n".
  238. $canonicalQueryString."\n".
  239. $canonicalHeaders."\n".
  240. $signedHeaders."\n".
  241. $payloadHash;
  242. $algo = "TC3-HMAC-SHA256";
  243. // date_default_timezone_set('UTC');
  244. // $date = date("Y-m-d", $headers["X-TC-Timestamp"]);
  245. $date = gmdate("Y-m-d", $headers["X-TC-Timestamp"]);
  246. $service = explode(".", $endpoint)[0];
  247. $credentialScope = $date."/".$service."/tc3_request";
  248. $hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
  249. $str2sign = $algo."\n".
  250. $headers["X-TC-Timestamp"]."\n".
  251. $credentialScope."\n".
  252. $hashedCanonicalRequest;
  253. $skey = $this->credential->getSecretKey();
  254. $signature = Sign::signTC3($skey, $date, $service, $str2sign);
  255. $sid = $this->credential->getSecretId();
  256. $auth = $algo.
  257. " Credential=".$sid."/".$credentialScope.
  258. ", SignedHeaders=content-type;host, Signature=".$signature;
  259. $headers["Authorization"] = $auth;
  260. if (HttpProfile::$REQ_GET == $reqmethod) {
  261. $connect = $this->createConnect();
  262. return $connect->getRequest($this->path, $canonicalQueryString, $headers);
  263. } else {
  264. $connect = $this->createConnect();
  265. return $connect->postRequestRaw($this->path, $headers, $payload);
  266. }
  267. }
  268. private function getMultipartPayload($request, $boundary, $options)
  269. {
  270. $body = "";
  271. $params = $request->serialize();
  272. foreach ($params as $key => $value) {
  273. $body .= "--".$boundary."\r\n";
  274. $body .= "Content-Disposition: form-data; name=\"".$key;
  275. if (in_array($key, $options["BinaryParams"])) {
  276. $body .= "\"; filename=\"".$key;
  277. }
  278. $body .= "\"\r\n";
  279. if (is_array($value)) {
  280. $value = json_encode($value);
  281. $body .= "Content-Type: application/json\r\n";
  282. }
  283. $body .= "\r\n".$value."\r\n";
  284. }
  285. if ($body != "") {
  286. $body .= "--".$boundary."--\r\n";
  287. }
  288. return $body;
  289. }
  290. /**
  291. * @throws TencentCloudSDKException
  292. */
  293. private function getRequest($action, $request)
  294. {
  295. $query = $this->formatRequestData($action, $request, httpProfile::$REQ_GET);
  296. $connect = $this->createConnect();
  297. return $connect->getRequest($this->path, $query, []);
  298. }
  299. /**
  300. * @throws TencentCloudSDKException
  301. */
  302. private function postRequest($action, $request)
  303. {
  304. $body = $this->formatRequestData($action, $request, httpProfile::$REQ_POST);
  305. $connect = $this->createConnect();
  306. return $connect->postRequest($this->path, [], $body);
  307. }
  308. /**
  309. * @throws TencentCloudSDKException
  310. */
  311. private function formatRequestData($action, $request, $reqMethod)
  312. {
  313. $param = $request;
  314. $param["Action"] = ucfirst($action);
  315. $param["RequestClient"] = $this->sdkVersion;
  316. $param["Nonce"] = rand();
  317. $param["Timestamp"] = time();
  318. $param["Version"] = $this->apiVersion;
  319. if ($this->credential->getSecretId()) {
  320. $param["SecretId"] = $this->credential->getSecretId();
  321. }
  322. if ($this->region) {
  323. $param["Region"] = $this->region;
  324. }
  325. if ($this->credential->getToken()) {
  326. $param["Token"] = $this->credential->getToken();
  327. }
  328. if ($this->profile->getSignMethod()) {
  329. $param["SignatureMethod"] = $this->profile->getSignMethod();
  330. }
  331. $signStr = $this->formatSignString($this->profile->getHttpProfile()->getEndpoint(),
  332. $this->path, $param, $reqMethod);
  333. $param["Signature"] = Sign::sign($this->credential->getSecretKey(), $signStr, $this->profile->getSignMethod());
  334. return $param;
  335. }
  336. private function createConnect()
  337. {
  338. return new HttpConnection($this->profile->getHttpProfile()->getProtocol().
  339. $this->profile->getHttpProfile()->getEndpoint(), $this->profile);
  340. }
  341. private function formatSignString($host, $uri, $param, $requestMethod)
  342. {
  343. $tmpParam = [];
  344. ksort($param);
  345. foreach ($param as $key => $value) {
  346. array_push($tmpParam, $key . "=" . $value);
  347. }
  348. $strParam = join ("&", $tmpParam);
  349. $signStr = strtoupper($requestMethod) . $host . $uri ."?".$strParam;
  350. return $signStr;
  351. }
  352. private function getPrivateMethod($obj, $methodName) {
  353. $objReflectClass = new ReflectionClass(get_class($obj));
  354. $method = $objReflectClass->getMethod($methodName);
  355. $method->setAccessible(true);
  356. return $method;
  357. }
  358. }