对应腾讯翻译api v3签名
头文件tencentTranslator.h
#ifndef TENCENTTRANSLATOR_H
#define TENCENTTRANSLATOR_H
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
class TencentTranslator : public QObject {
Q_OBJECT
public:
TencentTranslator(const QString &secretId, const QString &secretKey, const QString ®ion, QObject *parent = nullptr);
/*
* @profile 构造函数,用于初始化翻译对象
*
* @parameter secretId 对应的是腾讯云 api密钥管理中的secretID
* @parameter secretKey 对应的是腾讯云 api密钥管理中的secretKey
* @parameter region 地区
* @parameter parent 父对象指针
*
*/
void translate(const QString &sourceText, const QString &sourceLang, const QString &targetLang, int projectId);
/*
* @profile 执行翻译操作
*
* @parameter sourceText 需要翻译的文本
* @parameter sourceLang 源语言
* @parameter targetLang 目标语言
* @parameter projectId 项目id
*
*/
signals:
void translationFinished(const QString &translatedText);
/*
* @profile 完成翻译后的信号
*
* @parameter translatedText 翻译后得到的目标文本
*
*/
private slots:
void onTranslationReply(QNetworkReply *reply);
/*
* @profile 收到回复请求的槽函数
*
* @parameter reply 响应对象
*
*/
private:
QString get_date(qint64 timestamp);
QString sha256Hex(const QString &str);
QByteArray hmacSha256(const QByteArray &key, const QByteArray &input);
QString SECRET_ID;
QString SECRET_KEY;
QString REGION;
QNetworkAccessManager *networkManager;
};
#endif // TENCENTTRANSLATOR_H
源文件tencentTranslator.cpp
#include "TencentTranslator.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>
#include <QCryptographicHash>
#include <QMessageAuthenticationCode>
#include <QNetworkRequest>
TencentTranslator::TencentTranslator(const QString &secretId, const QString &secretKey, const QString ®ion, QObject *parent)
: QObject(parent), SECRET_ID(secretId), SECRET_KEY(secretKey), REGION(region) {
networkManager = new QNetworkAccessManager(this);
connect(networkManager, &QNetworkAccessManager::finished, this, &TencentTranslator::onTranslationReply);
}
void TencentTranslator::translate(const QString &sourceText, const QString &sourceLang, const QString &targetLang, int projectId) {
QString endpoint = "tmt.tencentcloudapi.com";
QString service = "tmt";
QString version = "2018-03-21";
QString action = "TextTranslate";
QString timestamp = QString::number(QDateTime::currentSecsSinceEpoch());
QString date = get_date(QDateTime::currentSecsSinceEpoch());
QJsonObject params;
params["SourceText"] = sourceText;
params["Source"] = sourceLang;
params["Target"] = targetLang;
params["ProjectId"] = projectId;
QJsonDocument doc(params);
QString payload = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
QString canonicalRequest = "POST\n/\n\ncontent-type:application/json\nhost:" + endpoint + "\n\ncontent-type;host\n" + sha256Hex(payload);
QString stringToSign = "TC3-HMAC-SHA256\n" + timestamp + "\n" + date + "/" + service + "/tc3_request\n" + sha256Hex(canonicalRequest);
QByteArray secretDate = hmacSha256(("TC3" + SECRET_KEY).toUtf8(), date.toUtf8());
QByteArray secretService = hmacSha256(secretDate, service.toUtf8());
QByteArray secretSigning = hmacSha256(secretService, QString("tc3_request").toUtf8());
QString signature = hmacSha256(secretSigning, stringToSign.toUtf8()).toHex();
QString authorization = "TC3-HMAC-SHA256 Credential=" + SECRET_ID + "/" + date + "/" + service + "/tc3_request, SignedHeaders=content-type;host, Signature=" + signature;
QNetworkRequest request(QUrl("https://" + endpoint));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Authorization", authorization.toUtf8());
request.setRawHeader("X-TC-Action", action.toUtf8());
request.setRawHeader("X-TC-Timestamp", timestamp.toUtf8());
request.setRawHeader("X-TC-Version", version.toUtf8());
request.setRawHeader("X-TC-Region", REGION.toUtf8());
networkManager->post(request, payload.toUtf8());
}
void TencentTranslator::onTranslationReply(QNetworkReply *reply) {
if (reply->error() == QNetworkReply::NoError) {
QByteArray response = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(response);
QJsonObject jsonObject = jsonResponse.object();
QString translatedText = jsonObject["Response"].toObject()["TargetText"].toString();
emit translationFinished(translatedText);
} else {
emit translationFinished("Error: " + reply->errorString());
}
reply->deleteLater();
}
QString TencentTranslator::get_date(qint64 timestamp) {
QDateTime dateTime = QDateTime::fromSecsSinceEpoch(timestamp);
return dateTime.toUTC().toString("yyyy-MM-dd");
}
QString TencentTranslator::sha256Hex(const QString &str) {
QByteArray hash = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Sha256);
return QString(hash.toHex());
}
QByteArray TencentTranslator::hmacSha256(const QByteArray &key, const QByteArray &input) {
QMessageAuthenticationCode code(QCryptographicHash::Sha256);
code.setKey(key);
code.addData(input);
return code.result();
}