Fastadmin中使用百度翻译API

在Fastadmin中对接使用百度翻译API

目录

对接使用百度翻译API

使用前准备

项目集成

创建配置文件

封装API请求

调用

总结


对接使用百度翻译API

使用前准备

需要注册百度账号,也可以使用原有的百度账号登录。

在开发者中心找到APPid和密钥,以备开发使用。

项目集成

创建配置文件

在application/extra/中创建translate.php文件。

内容如下:

php 复制代码
<?php
/**
 * 百度翻译API配置文件
 * 文档标注:appid + apikey | 控制台实际:APPID + Secret Key(二者等价)
 * 复制位置:百度翻译开放平台 → 开发者中心 → 申请者信息
 */
return [
    // 你的控制台APPID
    'baidu_appid'    => '你的控制台APPID',
    // 百度翻译密钥
    'baidu_secret'   => '百度翻译密钥'
];
封装API请求

在application/common/service目录下创建Translate.php文件,内容如下:

php 复制代码
<?php
/**
 * FastAdmin 百度翻译通用文本API封装类
 * 支持:单文本翻译
 * 适配:百度翻译通用文本API(个人认证免费版)
 * 依赖:FastAdmin内置httpRequest函数(无需额外扩展curl)
 */
namespace app\common\service;

use think\Exception;

class Translate
{
    // 百度翻译通用文本API接口地址
    private const API_URL = 'http://api.fanyi.baidu.com/api/trans/vip/translate';
    // 百度翻译APPID
    private $appid;
    // 百度翻译秘钥
    private $secretKey;

    /**
     * 构造方法:初始化配置+校验密钥
     * 从extra/translate.php读取配置,避免硬编码
     * @throws Exception
     */
    public function __construct()
    {
        // 读取配置文件中的百度翻译密钥
        $this->appid = config('translate.baidu_appid');
        $this->secretKey = config('translate.baidu_secret');

        // 密钥校验,无配置直接抛异常
        if (empty($this->appid) || empty($this->secretKey)) {
            throw new Exception('请先在application/extra/translate.php配置百度翻译appid和secretKey');
        }
    }

    /**
     * 【基础方法】单文本翻译(百度通用API核心)
     * @param string $text 待翻译文本
     * @param string $from 源语言(auto=自动检测,百度官方默认)
     * @param string $to 目标语言(en=英文/ja=日语/ko=韩语/fr=法语,参考百度官方语言码)
     * @return string 翻译后的纯文本
     * @throws Exception
     */
    public function translateText(string $text, string $from = 'auto', string $to = 'en'): string
    {
        $text = trim($text);
        if (empty($text)) {
            return '';
        }

        // 必要参数
        $salt = rand(32768, 65536); // 随机盐值
        $signStr = $this->appid . $text . $salt . $this->secretKey; // 签名原串
        $sign = md5($signStr); // MD5签名

        $params = [
            'q'     => $text,
            'from'  => $from,
            'to'    => $to,
            'appid' => $this->appid,
            'salt'  => $salt,
            'sign'  => $sign
        ];

        $response = \fast\Http::get(self::API_URL, $params);
        if (empty($response)) {
            throw new Exception('百度翻译API请求失败,无返回数据');
        }

        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('百度翻译API返回格式错误,非有效JSON');
        }

        // 5. 捕获百度API官方错误(关键:方便排查配置/调用问题)
        if (isset($result['error_code'])) {
            $errorMsg = $result['error_msg'] ?? '未知错误';
            throw new Exception("百度翻译失败【错误码:{$result['error_code']}】:{$errorMsg}");
        }

        return $result['trans_result'][0]['dst'] ?? '';
    }
}
调用
php 复制代码
$text = (new Translate())->translateText('中文');
print_r($text);die;

总结

项目功能实现中需要使用翻译实现,整理了百度翻译API使用。

相关推荐
不正经的小寒3 小时前
PHP 8.4 核心特性
php
不正经的小寒5 小时前
PHP 8.3 核心特性
php
安妮的小熊呢8 小时前
CRMEB开源商城系统 & 标准版系统(PHP)开发规范
开发语言·javascript·php
在角落发呆9 小时前
跨越网络鸿沟:传统文件传输与现代内网穿透的奇妙交响
开发语言·php
minji...11 小时前
Linux 网络基础之网络IP层(十)IP 协议,网段划分,IP地址相关问题
linux·运维·服务器·网络·tcp/ip·智能路由器·php
枫叶林FYL12 小时前
【强化学习】2 大规模并行强化学习中的耦合策略优化:受控多样性驱动的样本高效探索
开发语言·php
zb2006412013 小时前
Laravel 8.x新特性全解析
php·laravel
code monkey.13 小时前
【Linux之旅】Linux 网络基础全解析:从协议分层到 Socket 编程,构建高性能网络服务的底层基石
linux·网络·php
我命由我1234513 小时前
PHP - PHP 基本随机数生成函数
开发语言·ide·后端·java-ee·php·intellij-idea·intellij idea
我命由我1234513 小时前
PHP - PHP 简易 Web 服务器、基础接口开发
服务器·开发语言·前端·php·intellij-idea·idea·intellij idea