百度翻译API代码实现的PHP之Laravel版

PHP类
645
0
0
2022-06-04

现在的翻译API,五花八门的,非常之多,百度翻译API算是所有中非常不错的一个,门槛很低,只要去百度翻译平台注册一个账号,唯一就是要验证手机号就行,不需要真人实名验证,如果做了真人实名验证,那有更多实用的东西,不像某腾讯,用个翻译API,还有真人实名验证,恶心至极。

百度翻译API每秒一次请求,完全免费,无限使用,可以看DEMO

不过自2022年8月1日起也开始收费了,标准版免费调用量由不限额度改为5万字符/月,高级版免费调用量由200万字符/月改为100万字符/月,详情可查看百度翻译文档。

把下面的类放入app/Service目录,填入申请的APP_ID和APP_KEY就可以使用了,非常方便。

百度翻译平台入口

<?php
namespace App\Service;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class BaiduTranslator
{
    const APP_ID          = ''; //换成你申请的APP_ID 
    const APP_KEY         = ''; //换成你申请的APP_KEY 
    const API_TIMEOUT     = 1;

    const API_URL = 'https://fanyi-api.baidu.com/api/trans/vip/translate';

    const KEY_QUERY  = 'q';
    const KEY_FROM   = 'from';
    const KEY_TO     = 'to';
    const KEY_APPID  = 'appid';
    const KEY_SALT   = 'salt';
    const KEY_SIGN   = 'sign';
    const KEY_DOMAIN = 'domain';

    const KEY_RESULT     = 'trans_result';
    const KEY_RESULT_DST = 'dst';

    const KEY_ERROR_CODE = 'error_code';
    const KEY_ERROR_MSG  = 'error_msg';

    const DEFAULT_FROM_LANG = 'auto';
    const DEFAULT_TO_LANG   = 'en';
    const DEFAULT_DOMAIN    = 'electronics'; #common

    const LANG_CN = 'zh';
    const LANG_EN = 'en';

    public function getTranslation($string, $toLang = '', &$fromLang = '')
    {
        $params = $this->getQueryParams($string, $toLang, $fromLang);
        $response = $this->curlApi($params);
        if ($response->failed()) {
            return $string;
        } else {
            $result = $response->json();
            if (isset($result[self::KEY_ERROR_CODE]) && $result[self::KEY_ERROR_CODE]) {
                $errCode = $result[self::KEY_ERROR_CODE] ?? '';
                $errMsg = $result[self::KEY_ERROR_MSG] ?? 'translate api return error';
                $this->writeErrorLog(sprintf('translate api error, code: %d, msg: %s', $errCode, $errMsg));
                return $string;
            }
            $fromLang = $result[self::KEY_FROM] ?? $fromLang;
            if (isset($result[self::KEY_RESULT])) {
                if (is_array($result[self::KEY_RESULT])) {
                    $trans = array_pop($result[self::KEY_RESULT]);
                    return $trans[self::KEY_RESULT_DST] ?? $string;
                } else {
                    return $result[self::KEY_RESULT][self::KEY_RESULT_DST] ?? $string;
                }
            }
        }
        return $string;
    }

    /**
     * if not using laravel framework, please change this
     */ 
    protected function curlApi($params)
    {
        $params = is_array($params) ? http_build_query($params) : $params;
        return Http::timeout(self::API_TIMEOUT)
            ->get(self::API_URL, $params);
    }

    /**
     * if not using laravel framework, please change this
     */ 
    protected function writeErrorLog($msg)
    {
        Log::error($msg);
    }

    protected function getQueryParams($string, $toLang = '', $fromLang = '')
    {
        $salt = $this->getSalt();
        $sign = md5(self::APP_ID . $string . $salt . self::APP_KEY);
        return [
            self::KEY_QUERY  => $string,
            self::KEY_FROM   => $fromLang ?: self::DEFAULT_FROM_LANG,
            self::KEY_TO     => $toLang ?: self::DEFAULT_TO_LANG,
            self::KEY_APPID  => self::APP_ID,
            self::KEY_SALT   => $salt,
            self::KEY_SIGN   => $sign,
            self::KEY_DOMAIN => self::DEFAULT_DOMAIN,
        ];
    }

    protected function getSalt()
    {
        return time();
    }
}