签名生成的url有问题(用移动云官网示例java代码运行的url正确)
#代码
// 导入 express 模块
const express = require('express');
// 创建 express 的服务器实例
const app = express()
const { v4: uuidv4 } = require('uuid');
const crypto = require('crypto');
const axios = require('axios');
const moment = require('moment');
app.use('/qm', (req, res) => {
// 填写您的accesskey 和secretKey
access_key = "d70fe22b1e334177a065de*"
secret_key = "5f63f84bb7634ead8fa482e*"
function doSignature(http_method, playlocd, servlet_path) {
const servletPath = decodeURI(servlet_path) //请求URL解码为原始URL
let canonicalized_query_string = sort_params(playlocd).slice(1)
let string_to_sign = http_method + '\n'
+ percent_encode(servletPath) + '\n'
+ sha256(Buffer.from(canonicalized_query_string, 'utf-8'))
let key = Buffer.from("BC_SIGNATURE&" + secret_key)
string_to_sign = Buffer.from(string_to_sign, 'utf-8')
let signature = sha1(key, string_to_sign).toString()
return servletPath + '?' + canonicalized_query_string + '&' + 'Signature=' + signature
}
// 参数编码
function percent_encode(encode_str) {
let res = encode_str.toString()
res = encodeURIComponent(Buffer.from(encode_str, 'utf-8'))
res = res.replace(/\+/g, '%20')
res = res.replace(/\*/g, '%2A')
res = res.replace(/%7E/g, '~')
return res
}
function sort_params(params) {
let strParam = "";
let keys = Object.keys(params);
keys.sort();
for (let k in keys) {
strParam += '&' + percent_encode(keys[k]) + '=' + percent_encode(params[keys[k]])
}
return strParam
}
function sha256(strsign) {
let hmac = crypto.createHmac('sha256', "");
return hmac.update(Buffer.from(strsign, 'utf-8')).digest('hex')
}
function sha1(secretKey, strsign) {
let signMethodMap = { 'HmacSHA1': "sha1" };
let hmac = crypto.createHmac(signMethodMap['HmacSHA1'], secretKey || "");
return hmac.update(Buffer.from(strsign, 'utf-8')).digest('hex')
}
// http method
const method = 'POST'
// 目标域名 端口
const url = "https://api-wuxi-1.cmecloud.cn:8443"
// 请求url
const path = '/api/lingxiyun/cloud/translate/v1'
// 请求头
const headers = { "userId": "123", 'Content-Type': 'application/json' }
// 签名公参
let querystring = {
"AccessKey": access_key,
"Timestamp": moment(new Date()).format("YYYY-MM-DDTHH:mm:ss") + 'Z',
"SignatureMethod": "HmacSHA1",
"SignatureVersion": "V2.0",
"SignatureNonce": uuidv4().toString().replace(/-/g, '')
}
//接口自定义参数
let data = {
"text": "我们都是地球人",
"type": "cnen",
"format": "json"
}
// 执行签名
let Burl = doSignature(method, querystring, path)
// 生成最终url
let Zurl = url + Burl
console.log(Zurl) --- 生成的这个url有问题
//发送请求
axios({
url: Zurl,
method,
headers,
data,
}).then((res) => {
res.send('ok')
}).catch((error) => {
res.send(error)
})
})
app.listen(5000, function () {
console.log('api server running at http://127.0.0.1:5000/qm')
})
#
签名机制网址
https://ecloud.10086.cn/op-help-center/doc/article/24283
#按步骤来的,不知道错到哪了