StsTencent.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Created by KLXQ
  4. * user: youyi
  5. * Date:2024/6/28 下午2:12.
  6. * Tencent SDK.
  7. * 目前主要用于获取联合身份临时访问凭证.
  8. */
  9. namespace App\Http\Helpers\Tencent;
  10. use App\Services\TencentRequestService;
  11. use TencentCloud\Common\Credential;
  12. use TencentCloud\Common\Exception\TencentCloudSDKException;
  13. use TencentCloud\Common\Profile\ClientProfile;
  14. use TencentCloud\Common\Profile\HttpProfile;
  15. use TencentCloud\Sts\V20180813\StsClient;
  16. class StsTencent
  17. {
  18. public string $secretId;
  19. public string $secretKey;
  20. public string $region;
  21. public string $endpoint = 'sts.tencentcloudapi.com';
  22. public string $version = '2018-08-13';
  23. public object $client;
  24. public int $sdkAppId;
  25. public array $policy = [
  26. 'version' => '3.0',
  27. 'statement' => [
  28. [
  29. 'action' => 'sts:*',
  30. 'effect' => 'allow',
  31. 'resource' => '*',
  32. ],
  33. [
  34. 'action' => 'asr:*',
  35. 'effect' => 'allow',
  36. 'resource' => '*',
  37. ],
  38. ],
  39. ];
  40. public array $resultArr = ['code' => 200, 'msg' => 'success', 'data' => []];
  41. public function __construct($action, $params)
  42. {
  43. $this->secretId = config('tencent.tencent_cloud_secret_id');
  44. $this->secretKey = config('tencent.tencent_cloud_secret_key');
  45. $this->region = config('tencent.trtc.region');
  46. $this->sdkAppId = (int) config('tencent.trtc.app_id');
  47. try {
  48. $cred = new Credential($this->secretId, $this->secretKey);
  49. // 实例化一个http选项,可选的,没有特殊需求可以跳过
  50. $httpProfile = new HttpProfile();
  51. $httpProfile->setEndpoint($this->endpoint);
  52. // 实例化一个client选项,可选的,没有特殊需求可以跳过
  53. $clientProfile = new ClientProfile();
  54. $clientProfile->setHttpProfile($httpProfile);
  55. // 实例化要请求产品的client对象,clientProfile是可选的
  56. $this->client = new StsClient($cred, $this->region, $clientProfile);
  57. $params['Policy'] = urlencode(json_encode($this->policy, JSON_UNESCAPED_UNICODE));
  58. $params['DurationSeconds'] = 7200;
  59. // 实例化一个请求对象,每个接口都会对应一个request对象
  60. $respClass = 'TencentCloud\\'.ucfirst('sts').'\\V20180813\\Models\\'.ucfirst($action).'Request';
  61. $req = new $respClass();
  62. $req->fromJsonString(json_encode($params));
  63. // 返回的resp是一个RemoveUserResponse的实例,与请求对象对应
  64. $resp = $this->client->{$action}($req);
  65. $this->resultArr['data'] = json_decode($resp->toJsonString(), true);
  66. } catch (TencentCloudSDKException $e) {
  67. $this->resultArr['code'] = -1;
  68. $this->resultArr['msg'] = $e->getMessage();
  69. }
  70. // 记录日志
  71. TencentRequestService::create('sts', $action, $params, $this->resultArr);
  72. }
  73. }