Last active
October 28, 2019 02:21
-
-
Save fbukevin/2cd650a9bf599cf5be239f9e8c1f7e99 to your computer and use it in GitHub Desktop.
訊飛科技機器翻譯 WebAPI Node.js Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
const rq = require('request-promise'); | |
class Translate { | |
constructor(host) { | |
// 应用 ID(到控制台获取) | |
this.APPID = '*******'; | |
// 接口 APIKey(到控制台机器翻译服务页面获取) | |
this.APIKey = '**************'; | |
// 接口 APISercet(到控制台机器翻译服务页面获取) | |
this.Secret = '**************'; | |
// 以下为 POST 请求 | |
this.Host = host; | |
this.RequestUri = '/v2/ots'; | |
// 设置url | |
// console.log(host) | |
this.url = `https://${host}${this.RequestUri}`; | |
this.HttpMethod = 'POST'; | |
this.Algorithm = 'hmac-sha256'; | |
this.HttpProto = 'HTTP/1.1'; | |
// 设置当前时间 (format: Wed, 23 Oct 2019 12:36:57 GMT) | |
const currentTimeUTC = new Date().toUTCString(); | |
this.Date = currentTimeUTC; | |
// 设置业务参数 | |
// 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/niutrans/API.html | |
this.Text = '你'; | |
this.BusinessArgs = { | |
from: 'ch', | |
to: 'en' | |
}; | |
this.Header = {}; | |
} | |
sha256SignBody(res) { | |
const m = crypto | |
.createHash('sha256') | |
.update(res) | |
.digest('base64'); | |
const result = `SHA-256=${m}`; | |
// console.log(result); | |
return result; | |
} | |
generateSignature(digest) { | |
let signatureStr = `host: ${this.Host}\n`; | |
signatureStr += `date: ${this.Date}\n`; | |
signatureStr += `${this.HttpMethod} ${this.RequestUri} ${this.HttpProto}\n`; | |
signatureStr += `digest: ${digest}`; | |
const signature = crypto | |
.createHmac('sha256', this.Secret) | |
.update(signatureStr) | |
.digest('base64'); | |
return signature; | |
} | |
initHeader(data) { | |
const digest = this.sha256SignBody(data); | |
// console.log(digest); | |
const sign = this.generateSignature(digest); | |
const authHeader = `api_key="${this.APIKey}", algorithm="${ | |
this.Algorithm | |
}", headers="host date request-line digest", signature="${sign}"`; | |
const headers = { | |
'Content-Type': 'application/json', | |
Accept: 'application/json', | |
Method: 'POST', | |
Host: this.Host, | |
Date: this.Date, | |
Digest: digest, | |
Authorization: authHeader | |
}; | |
return headers; | |
} | |
getBody() { | |
const content = Buffer.from(this.Text).toString('base64'); | |
// console.log(content); | |
const postdata = { | |
common: { app_id: this.APPID }, | |
business: this.BusinessArgs, | |
data: { | |
text: content | |
} | |
}; | |
const body = JSON.stringify(postdata); | |
// console.log(body); | |
return body; | |
} | |
async callUrl() { | |
if (this.APPID === '' || this.APIKey === '' || this.Secret === '') { | |
console.log('Appid 或 APIKey 或 APISecret 为空!'); | |
} else { | |
const body = this.getBody(); | |
const headers = this.initHeader(body); | |
const options = { | |
method: 'POST', | |
uri: this.url, | |
body: JSON.parse(body), | |
headers, | |
timeout: 600000, // 8 or 10000 will cause timeout | |
json: true | |
}; | |
try { | |
const response = await rq(options); | |
/** | |
* { code: 0, | |
* data: { result: { from: 'ch', to: 'en', trans_result: { dst: 'You ', src: '你' } } }, | |
* message: 'success', | |
* sid: '*****' } | |
*/ | |
console.log(response); | |
// 以下仅用于调试 | |
// const code = response.code; | |
// if(code !== '0'){ | |
// console.log(`请前往 https://www.xfyun.cn/document/error-code?code=${code} 查询解决办法`) | |
// } | |
return response.data.result; | |
} catch (err) { | |
console.log(err.message); | |
return {}; | |
} | |
} | |
} | |
} | |
(async () => { | |
const host = 'ntrans.xfyun.cn'; | |
// 初始化类 | |
const gClass = new Translate(host); | |
const result = await gClass.callUrl(); | |
console.log(result); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment