| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Servers\Tenxunyun;
- use TencentCloud\Common\Credential;
- use TencentCloud\Common\Profile\ClientProfile;
- use TencentCloud\Common\Profile\HttpProfile;
- use TencentCloud\Tmt\V20180321\TmtClient;
- use TencentCloud\Tmt\V20180321\Models\TextTranslateRequest;
- use Exception;
- use Illuminate\Support\Facades\Log;
- /**
- * 腾讯云文本翻译服务
- * @author 唐远望
- * @date 2026-04-08
- */
- class TextTranslate
- {
- protected $client;
- public function __construct()
- {
- // 从 .env 文件中获取密钥
- $secretId = config('tenxunyun.tencentcloud.secret_id', '');
- $secretKey = config('tenxunyun.tencentcloud.secret_key', '');
- // 1. 实例化一个认证对象
- $credential = new Credential($secretId, $secretKey);
- // 2. 配置HTTP访问属性
- $httpProfile = new HttpProfile();
- $httpProfile->setEndpoint("tmt.tencentcloudapi.com");
- // 3. 配置客户端参数
- $clientProfile = new ClientProfile();
- $clientProfile->setHttpProfile($httpProfile);
- // 4. 实例化要请求的client对象,这里选择上海区,你也可选其他地域如ap-beijing
- $this->client = new TmtClient($credential, "ap-shanghai", $clientProfile);
- }
- /**
- * 执行文本翻译
- *
- * @param string $sourceText 待翻译的文本
- * @param string $source 源语言,如 'auto'(自动检测), 'zh'(中文), 'en'(英文)
- * @param string $target 目标语言,如 'en'(英文), 'zh'(中文)
- * @param int $projectId 项目ID,没有特殊要求传0即可
- * @return array 包含翻译结果和请求ID的数组
- */
- public function translateText($sourceText, $source, $target, $projectId = 0)
- {
- try {
- // 实例化请求对象
- $req = new TextTranslateRequest();
-
- // 设置请求参数
- $req->setSourceText($sourceText);
- $req->setSource($source);
- $req->setTarget($target);
- $req->setProjectId($projectId);
- // 调用API,获取响应
- $resp = $this->client->TextTranslate($req);
-
- // 返回结果
- return [
- 'success' => true,
- 'target_text' => $resp->getTargetText(),
- 'source' => $resp->getSource(),
- 'target' => $resp->getTarget(),
- 'used_amount' => $resp->getUsedAmount(),
- 'request_id' => $resp->getRequestId()
- ];
- } catch (Exception $e) {
- // 记录错误日志
- Log::error('腾讯云翻译失败: ' . $e->getMessage());
-
- return [
- 'success' => false,
- 'error' => $e->getMessage()
- ];
- }
- }
- }
|