TextTranslate.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Servers\Tenxunyun;
  3. use TencentCloud\Common\Credential;
  4. use TencentCloud\Common\Profile\ClientProfile;
  5. use TencentCloud\Common\Profile\HttpProfile;
  6. use TencentCloud\Tmt\V20180321\TmtClient;
  7. use TencentCloud\Tmt\V20180321\Models\TextTranslateRequest;
  8. use Exception;
  9. use Illuminate\Support\Facades\Log;
  10. /**
  11. * 腾讯云文本翻译服务
  12. * @author 唐远望
  13. * @date 2026-04-08
  14. */
  15. class TextTranslate
  16. {
  17. protected $client;
  18. public function __construct()
  19. {
  20. // 从 .env 文件中获取密钥
  21. $secretId = config('tenxunyun.tencentcloud.secret_id', '');
  22. $secretKey = config('tenxunyun.tencentcloud.secret_key', '');
  23. // 1. 实例化一个认证对象
  24. $credential = new Credential($secretId, $secretKey);
  25. // 2. 配置HTTP访问属性
  26. $httpProfile = new HttpProfile();
  27. $httpProfile->setEndpoint("tmt.tencentcloudapi.com");
  28. // 3. 配置客户端参数
  29. $clientProfile = new ClientProfile();
  30. $clientProfile->setHttpProfile($httpProfile);
  31. // 4. 实例化要请求的client对象,这里选择上海区,你也可选其他地域如ap-beijing
  32. $this->client = new TmtClient($credential, "ap-shanghai", $clientProfile);
  33. }
  34. /**
  35. * 执行文本翻译
  36. *
  37. * @param string $sourceText 待翻译的文本
  38. * @param string $source 源语言,如 'auto'(自动检测), 'zh'(中文), 'en'(英文)
  39. * @param string $target 目标语言,如 'en'(英文), 'zh'(中文)
  40. * @param int $projectId 项目ID,没有特殊要求传0即可
  41. * @return array 包含翻译结果和请求ID的数组
  42. */
  43. public function translateText($sourceText, $source, $target, $projectId = 0)
  44. {
  45. try {
  46. // 实例化请求对象
  47. $req = new TextTranslateRequest();
  48. // 设置请求参数
  49. $req->setSourceText($sourceText);
  50. $req->setSource($source);
  51. $req->setTarget($target);
  52. $req->setProjectId($projectId);
  53. // 调用API,获取响应
  54. $resp = $this->client->TextTranslate($req);
  55. // 返回结果
  56. return [
  57. 'success' => true,
  58. 'target_text' => $resp->getTargetText(),
  59. 'source' => $resp->getSource(),
  60. 'target' => $resp->getTarget(),
  61. 'used_amount' => $resp->getUsedAmount(),
  62. 'request_id' => $resp->getRequestId()
  63. ];
  64. } catch (Exception $e) {
  65. // 记录错误日志
  66. Log::error('腾讯云翻译失败: ' . $e->getMessage());
  67. return [
  68. 'success' => false,
  69. 'error' => $e->getMessage()
  70. ];
  71. }
  72. }
  73. }