chengkun
2025-09-15 3c9050e82e582414dc7b208c8283fe47be37eeba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
<?php
/*
 * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
 
namespace TencentCloud\Common;
 
use \ReflectionClass;
 
use TencentCloud\Common\Http\HttpConnection;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Profile\RegionBreakerProfile;
use TencentCloud\Common\CircuitBreaker;
use TencentCloud\Common\Exception\TencentCloudSDKException;
 
 
/**
 * 抽象api类,禁止client引用
 * @package TencentCloud\Common
 */
abstract class AbstractClient
{
    /**
     * @var string SDK版本
     */
    public static $SDK_VERSION = "SDK_PHP_3.0.1339";
 
    /**
     * @var integer http响应码200
     */
    public static $HTTP_RSP_OK = 200;
 
    private $PHP_VERSION_MINIMUM = "5.6.0";
 
    /**
     * @var Credential 认证类实例,保存认证相关字段
     */
    private $credential;
    
    private $sseResponseCallbackFunc;
    
    /**
     * @var ClientProfile 会话配置信息类
     */
    private $profile;
 
    private $regionBreakerProfile;
    private $circuitBreaker;
    /**
     * @var string 产品地域
     */
    private $region;
 
    /**
     * @var string 请求路径
     */
    private $path;
 
    /**
     * @var string sdk版本号
     */
    private $sdkVersion;
 
    /**
     * @var string api版本号
     */
    private $apiVersion;
 
    /**
     * @var HttpConnection
     */
    private $httpConn;
 
    /**
     * 基础client类
     * @param string $endpoint Deprecated, we use service+rootdomain instead
     * @param string $version api版本
     * @param Credential $credential 认证信息实例
     * @param string $region 产品地域
     * @param ClientProfile $profile
     */
    function __construct($endpoint, $version, $credential, $region, $profile=null)
    {
        $this->path = "/";
        $this->credential = $credential;
        $this->region = $region;
        if ($profile) {
            $this->profile = $profile;
        } else {
            $this->profile = new ClientProfile();
        }
 
        $this->getRefreshedEndpoint();
 
        $this->sdkVersion = AbstractClient::$SDK_VERSION;
        $this->apiVersion = $version;
 
        if ($this->profile->enableRegionBreaker) {
            if (is_null($this->profile->getRegionBreakerProfile())) {
                throw new TencentCloudSDKException("ClientError", "RegionBreakerProfile have not been set yet.");
                }
            $this->circuitBreaker = new CircuitBreaker($this->profile->getRegionBreakerProfile());
        }
 
        if (version_compare(phpversion(), $this->PHP_VERSION_MINIMUM, '<') && $profile->getCheckPHPVersion()) {
            throw new TencentCloudSDKException("ClientError", "PHP version must >= ".$this->PHP_VERSION_MINIMUM.", your current is ".phpversion());
        }
 
        $this->httpConn = $this->createConnect();
    }
 
    /**
     * 设置产品地域
     * @param string $region 地域
     */
    public function setRegion($region)
    {
        $this->region = $region;
    }
 
    /**
     * 获取产品地域
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }
    
    /**
     * 设置sse
     * @param string $funcName sse响应回调函数名
     */
    public function setSseResponseCallbackFunc($funcName)
    {
        $this->sseResponseCallbackFunc = $funcName;
    }
    
    /**
     * 设置认证信息实例
     * @param Credential $credential 认证信息实例
     */
    public function setCredential($credential)
    {
        $this->credential = $credential;
    }
 
    /**
     * 返回认证信息实例
     * @return Credential
     */
    public function getCredential()
    {
        return $this->credential;
    }
 
    /**
     * 设置配置实例
     * @param ClientProfile $profile 配置实例
     */
    public function setClientProfile($profile)
    {
        $this->profile = $profile;
    }
 
    /**
     * 返回配置实例
     * @return ClientProfile
     */
    public function getClientProfile()
    {
        return $this->profile;
    }
 
    /**
     * @param string $action  方法名
     * @param array $request  参数列表
     * @return mixed
     * @throws TencentCloudSDKException
     */
    public function __call($action, $request)
    {
        if ($this->profile->enableRegionBreaker) {
            return $this->doRequestWithOptionsOnRegionBreaker($action, $request[0], array());
        }
        else {
            return $this->doRequestWithOptions($action, $request[0], array());
        }
    }
 
    /**
     * @param string $action
     * @param array  $headers
     * @param string $body json content
     * @return mixed
     * @throws TencentCloudSDKException
     */
    public function callJson($action, $body, $headers=null) {
        try {
            $responseData = null;
            $options = array(
                "IsCommonJson" => true,
            );
            if ($this->profile->getHttpProfile()->getReqMethod() == HttpProfile::$REQ_GET) {
                throw new TencentCloudSDKException("ClientError", "Common client call doesn't support GET method");
            }
            if ($this->profile->getSignMethod() != ClientProfile::$SIGN_TC3_SHA256) {
                throw new TencentCloudSDKException("ClientError", "Common client call must use TC3-HMAC-SHA256");
            }
            $responseData = $this->doRequestWithTC3($action, $body, $options, $headers, null);
            if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
                throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
            }
            $resp = json_decode($responseData->getBody(), true)["Response"];
            if (array_key_exists("Error", $resp)) {
                throw new TencentCloudSDKException($resp["Error"]["Code"], $resp["Error"]["Message"], $resp["RequestId"]);
            }
            return $resp;
        } catch (\Exception $e) {
            if (!($e instanceof TencentCloudSDKException)) {
                throw new TencentCloudSDKException("", $e->getMessage());
            } else {
                throw $e;
            }
        }
    }
    
    /**
     * @param string $action
     * @param array  $headers
     * @param string $body json content
     * @return mixed
     * @throws TencentCloudSDKException
     */
    public function callJsonWithSSEResponse($callback, $action, $body, $headers = null)
    {
        try {
            $responseData = null;
            $options = array(
                "IsCommonJson" => true,
            );
            if ($this->profile->getHttpProfile()->getReqMethod() == HttpProfile::$REQ_GET) {
                throw new TencentCloudSDKException("ClientError", "Common client call doesn't support GET method");
            }
            if ($this->profile->getSignMethod() != ClientProfile::$SIGN_TC3_SHA256) {
                throw new TencentCloudSDKException("ClientError", "Common client call must use TC3-HMAC-SHA256");
            }
            $responseData = $this->doRequestWithTC3($action, $body, $options, $headers, null);
            if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
                throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
            }
            $contentType = $responseData->getHeaderLine('Content-Type');
            if ($contentType === 'text/event-stream') {
                $body = $responseData->getBody();
                $buffer = '';                
                if (isset($callback) && is_callable($callback)) {
                    while (!$body->eof()) {
                        $buffer .= $body->read(1024);
                        $delimiterPosition = strpos($buffer, "\n\n");
                        while ($delimiterPosition !== false) {
                            $chunk = substr($buffer, 0, $delimiterPosition + 2);
                            $buffer = substr($buffer, $delimiterPosition + 2);
                            
                            $callback($chunk);
                            $delimiterPosition = strpos($buffer, "\n\n");
                        }
                    }
                    if (!empty($buffer)) {
                        $callback($buffer);
                    }
                } else {
                    while (!$body->eof()) {
                        $buffer .= $body->read(1024);
                    }
                    return $buffer;
                }
            } else {
                $resp = json_decode($responseData->getBody(), true)["Response"];
                if (array_key_exists("Error", $resp)) {
                    throw new TencentCloudSDKException($resp["Error"]["Code"], $resp["Error"]["Message"], $resp["RequestId"]);
                }                
                return $resp;
            }            
 
        } catch (\Exception $e) {
            if (!($e instanceof TencentCloudSDKException)) {
                throw new TencentCloudSDKException("", $e->getMessage());
            } else {
                throw $e;
            }
        }
    }
    
    /**
     * @param string $action  方法名
     * @param array  $headers  自定义headers
     * @param string $body     content
     * @return mixed
     * @throws TencentCloudSDKException
     */
    public function call_octet_stream($action, $headers, $body) {
        try {
            $responseData = null;
            $options = array(
                "IsOctetStream" => true,
            );
            switch ($this->profile->getSignMethod()) {
                case ClientProfile::$SIGN_TC3_SHA256:
                    $responseData = $this->doRequestWithTC3($action, Null, $options, $headers, $body);
                    break;
                default:
                    throw new TencentCloudSDKException("ClientError", "Invalid sign method");
                    break;
            }
            if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
                throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
            }
            $tmpResp = json_decode($responseData->getBody(), true)["Response"];
            if (array_key_exists("Error", $tmpResp)) {
                throw new TencentCloudSDKException($tmpResp["Error"]["Code"], $tmpResp["Error"]["Message"], $tmpResp["RequestId"]);
            }
 
            return $this->returnResponse($action, $tmpResp);
        } catch (\Exception $e) {
            if (!($e instanceof TencentCloudSDKException)) {
                throw new TencentCloudSDKException("", $e->getMessage());
            } else {
                throw $e;
            }
        }
    }
 
    protected function doRequestWithOptions($action, $request, $options)
    {
        try {
            $serializeRequest = $request->serialize();
            $method = $this->getPrivateMethod($request, "arrayMerge");
            $serializeRequest = $method->invoke($request, $serializeRequest);
            $responseData = $this->getResponseData($action, $request, $options);
            
            if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
                throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
            }
            
            $contentType = $responseData->getHeaderLine('Content-Type');
            if ($contentType === 'text/event-stream') {
                return $this->handleEventStreamResponse($responseData);
            } else {
                return $this->handleJsonResponse($action, $responseData);
            }
        } catch (\Exception $e) {
            if (!($e instanceof TencentCloudSDKException)) {
                throw new TencentCloudSDKException("", $e->getMessage());
            } else {
                throw $e;
            }
        }
    }
 
    protected function doRequestWithOptionsOnRegionBreaker($action, $request, $options)
    {
        try {
            $endpoint = $this->profile->getRegionBreakerProfile()->masterEndpoint;
            list($generation, $need_break) = $this->circuitBreaker->beforeRequests();
            if ($need_break) {
                $endpoint = $this->profile->getRegionBreakerProfile()->slaveEndpoint;
            }
            $this->profile->getHttpProfile()->setEndpoint($endpoint);
            $responseData = null;
            $serializeRequest = $request->serialize();
            $method = $this->getPrivateMethod($request, "arrayMerge");
            $serializeRequest = $method->invoke($request, $serializeRequest);
            switch ($this->profile->getSignMethod()) {
                case ClientProfile::$SIGN_HMAC_SHA1:
                case ClientProfile::$SIGN_HMAC_SHA256:
                    $responseData = $this->doRequest($action, $serializeRequest);
                    break;
                case ClientProfile::$SIGN_TC3_SHA256:
                    $responseData = $this->doRequestWithTC3($action, $request, $options, array(), "");
                    break;
                default:
                    throw new TencentCloudSDKException("ClientError", "Invalid sign method");
                    break;
            }
            if ($responseData->getStatusCode() !== AbstractClient::$HTTP_RSP_OK) {
                throw new TencentCloudSDKException($responseData->getReasonPhrase(), $responseData->getBody());
            }
            
            $contentType = $responseData->getHeaderLine('Content-Type');
            if ($contentType === 'text/event-stream') {
                return $this->handleEventStreamResponse($responseData);
            } else {
                $tmpResp = json_decode($responseData->getBody(), true)["Response"];
                if (array_key_exists("Error", $tmpResp)) {
                    $this->circuitBreaker->afterRequests($generation, True);
                    throw new TencentCloudSDKException($tmpResp["Error"]["Code"], $tmpResp["Error"]["Message"], $tmpResp["RequestId"]);
                }
                $this->circuitBreaker->afterRequests($generation, True);
                return $this->returnResponse($action, $tmpResp);
            }
            
            
        } catch (\Exception $e) {
            $this->circuitBreaker->afterRequests($generation, False);
            if (!($e instanceof TencentCloudSDKException)) {
                throw new TencentCloudSDKException("", $e->getMessage());
            } else {
                throw $e;
            }
        }
    }
    
    private function getResponseData($action, $request, $options)
    {
        switch ($this->profile->getSignMethod()) {
            case ClientProfile::$SIGN_HMAC_SHA1:
            case ClientProfile::$SIGN_HMAC_SHA256:
                return $this->doRequest($action, $request->serialize());
            case ClientProfile::$SIGN_TC3_SHA256:
                return $this->doRequestWithTC3($action, $request, $options, array(), "");
            default:
                throw new TencentCloudSDKException("ClientError", "Invalid sign method");
        }
    }
    
    private function handleEventStreamResponse($responseData)
    {
        $body = $responseData->getBody();
        $buffer = '';
        $temp_func = $this->sseResponseCallbackFunc;
        
        if (isset($temp_func) && is_callable($temp_func)) {
            while (!$body->eof()) {
                $buffer .= $body->read(1024);
                $delimiterPosition = strpos($buffer, "\n\n");
                while ($delimiterPosition !== false) {
                    $chunk = substr($buffer, 0, $delimiterPosition + 2);
                    $buffer = substr($buffer, $delimiterPosition + 2);
                    
                    $temp_func($chunk);
                    $delimiterPosition = strpos($buffer, "\n\n");
                }
            }
            if (!empty($buffer)) {
                $temp_func($buffer);
            }
        } else {
            while (!$body->eof()) {
                $buffer .= $body->read(1024);
            }
            return $buffer;
        }
    }
    
    private function handleJsonResponse($action, $responseData)
    {
        $tmpResp = json_decode($responseData->getBody(), true)["Response"];
        if (array_key_exists("Error", $tmpResp)) {
            throw new TencentCloudSDKException($tmpResp["Error"]["Code"], $tmpResp["Error"]["Message"], $tmpResp["RequestId"]);
        }
        
        return $this->returnResponse($action, $tmpResp);
    }
    
    
    
    private function doRequest($action, $request)
    {
        switch ($this->profile->getHttpProfile()->getReqMethod()) {
            case HttpProfile::$REQ_GET:
                return $this->getRequest($action, $request);
                break;
            case HttpProfile::$REQ_POST:
                return $this->postRequest($action, $request);
                break;
            default:
                throw new TencentCloudSDKException("", "Method only support (GET, POST)");
                break;
        }
    }
 
    private function doRequestWithTC3($action, $request, $options, $headers, $payload)
    {
        $endpoint = $this->getRefreshedEndpoint();
        $headers["Host"] = $endpoint;
        $headers["X-TC-Action"] = ucfirst($action);
        $headers["X-TC-RequestClient"] = $this->sdkVersion;
        $headers["X-TC-Timestamp"] = time();
        $headers["X-TC-Version"] = $this->apiVersion;
 
        if ($this->region) {
            $headers["X-TC-Region"] = $this->region;
        }
 
        if ($this->credential->getToken()) {
            $headers["X-TC-Token"] = $this->credential->getToken();
        }
 
        $language = $this->profile->getLanguage();
        if ($language) {
            $headers["X-TC-Language"] = $language;
        }
 
        $canonicalUri = $this->path;
 
        $reqmethod = $this->profile->getHttpProfile()->getReqMethod();
        if (HttpProfile::$REQ_GET == $reqmethod) {
            $headers["Content-Type"] = "application/x-www-form-urlencoded";
            $rs = $request->serialize();
            $am = $this->getPrivateMethod($request, "arrayMerge");
            $rsam = $am->invoke($request, $rs);
            $canonicalQueryString = http_build_query($rsam);
            $payload = "";
        }
        if (HttpProfile::$REQ_POST == $reqmethod)  {
            if (isset($options["IsMultipart"]) && $options["IsMultipart"] === true) {
                $boundary = uniqid();
                $headers["Content-Type"] = "multipart/form-data; boundary=" . $boundary;
                $canonicalQueryString = "";
                $payload = $this->getMultipartPayload($request, $boundary, $options);
            } else if (isset($options["IsOctetStream"]) && $options["IsOctetStream"] === true) {
                $headers["Content-Type"] = "application/octet-stream";
                $canonicalQueryString = "";
            } else if (isset($options["IsCommonJson"]) && $options["IsCommonJson"] === true) {
                $headers["Content-Type"] = "application/json";
                $canonicalQueryString = "";
                $payload = json_encode($request);
            } else {
                $headers["Content-Type"] = "application/json";
                $canonicalQueryString = "";
                $payload = $request->toJsonString();
            }
        }
 
        if ($this->profile->getUnsignedPayload() == true) {
            $headers["X-TC-Content-SHA256"] = "UNSIGNED-PAYLOAD";
            $payloadHash = hash("SHA256", "UNSIGNED-PAYLOAD");
        } else {
            $payloadHash = hash("SHA256", $payload);
        }
 
 
        $canonicalHeaders = "content-type:".$headers["Content-Type"]."\n".
                            "host:".$headers["Host"]."\n";
        $signedHeaders = "content-type;host";
        $canonicalRequest = $reqmethod."\n".
                            $canonicalUri."\n".
                            $canonicalQueryString."\n".
                            $canonicalHeaders."\n".
                            $signedHeaders."\n".
                            $payloadHash;
        $algo = "TC3-HMAC-SHA256";
        // date_default_timezone_set('UTC');
        // $date = date("Y-m-d", $headers["X-TC-Timestamp"]);
        $date = gmdate("Y-m-d", $headers["X-TC-Timestamp"]);
        $service = explode(".", $endpoint)[0];
        $credentialScope = $date."/".$service."/tc3_request";
        $hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
        $str2sign = $algo."\n".
                    $headers["X-TC-Timestamp"]."\n".
                    $credentialScope."\n".
                    $hashedCanonicalRequest;
        $skey = $this->credential->getSecretKey();
        $signature = Sign::signTC3($skey, $date, $service, $str2sign);
 
        $sid = $this->credential->getSecretId();
        $auth = $algo.
                " Credential=".$sid."/".$credentialScope.
                ", SignedHeaders=content-type;host, Signature=".$signature;
        $headers["Authorization"] = $auth;
 
        if (HttpProfile::$REQ_GET == $reqmethod) {
            $connect = $this->getConnect();
            return $connect->getRequest($this->path, $canonicalQueryString, $headers);
        } else {
            $connect = $this->getConnect();
            return $connect->postRequestRaw($this->path, $headers, $payload);
        }
    }
 
    private function getMultipartPayload($request, $boundary, $options)
    {
        $body = "";
        $params = $request->serialize();
        foreach ($params as $key => $value) {
            $body .= "--".$boundary."\r\n";
            $body .= "Content-Disposition: form-data; name=\"".$key;
            if (in_array($key, $options["BinaryParams"])) {
                $body .= "\"; filename=\"".$key;
            }
            $body .= "\"\r\n";
            if (is_array($value)) {
                $value = json_encode($value);
                $body .= "Content-Type: application/json\r\n";
            }
            $body .= "\r\n".$value."\r\n";
        }
        if ($body != "") {
            $body .= "--".$boundary."--\r\n";
        }
        return $body;
    }
 
    /**
     * @throws TencentCloudSDKException
     */
    private function getRequest($action, $request)
    {
        $query = $this->formatRequestData($action, $request, httpProfile::$REQ_GET);
        $connect = $this->getConnect();
        return $connect->getRequest($this->path, $query, []);
    }
 
    /**
     * @throws TencentCloudSDKException
     */
    private function postRequest($action, $request)
    {
        $body = $this->formatRequestData($action, $request, httpProfile::$REQ_POST);
        $connect = $this->getConnect();
        return $connect->postRequest($this->path, [], $body);
    }
 
    /**
     * @throws TencentCloudSDKException
     */
    private function formatRequestData($action, $request, $reqMethod)
    {
        $param = $request;
        $param["Action"] = ucfirst($action);
        $param["RequestClient"] = $this->sdkVersion;
        $param["Nonce"] = rand();
        $param["Timestamp"] = time();
        $param["Version"] = $this->apiVersion;
 
        if ($this->credential->getSecretId()) {
            $param["SecretId"] = $this->credential->getSecretId();
        }
 
        if ($this->region) {
            $param["Region"] = $this->region;
        }
 
        if ($this->credential->getToken()) {
            $param["Token"] = $this->credential->getToken();
        }
 
        if ($this->profile->getSignMethod()) {
            $param["SignatureMethod"] = $this->profile->getSignMethod();
        }
 
        $language = $this->profile->getLanguage();
        if ($language) {
            $param["Language"] = $language;
        }
 
        $signStr = $this->formatSignString($this->getRefreshedEndpoint(), $this->path, $param, $reqMethod);
        $param["Signature"] = Sign::sign($this->credential->getSecretKey(), $signStr, $this->profile->getSignMethod());
        return $param;
    }
 
    private function createConnect()
    {
        $prot = $this->profile->getHttpProfile()->getProtocol();
        return new HttpConnection($prot.$this->getRefreshedEndpoint(), $this->profile);
    }
 
    private function getConnect() {
        $keepAlive = $this->profile->getHttpProfile()->getKeepAlive();
        if (true === $keepAlive) {
            return $this->httpConn;
        } else {
            return $this->createConnect();
        }
    }
 
    private function formatSignString($host, $uri, $param, $requestMethod)
    {
        $tmpParam = [];
        ksort($param);
        foreach ($param as $key => $value) {
            array_push($tmpParam, $key . "=" . $value);
        }
        $strParam = join ("&", $tmpParam);
        $signStr = strtoupper($requestMethod) . $host . $uri ."?".$strParam;
        return $signStr;
    }
 
    private function getPrivateMethod($obj, $methodName) {
        $objReflectClass = new ReflectionClass(get_class($obj));
        $method = $objReflectClass->getMethod($methodName);
        $method->setAccessible(true);
        return $method;
    }
 
    /**
     * User might call httpProfile.SetEndpoint after client is initialized,
     * so everytime we get the enpoint we need to check it.
     * Or we must find a way to disable such usage.
     */
    private function getRefreshedEndpoint() {
        $this->endpoint = $this->profile->getHttpProfile()->getEndpoint();
        if ($this->endpoint === null) {
            $this->endpoint = $this->service.".".$this->profile->getHttpProfile()->getRootDomain();
        }
        return $this->endpoint;
    }
}