Merge remote-tracking branch 'origin/develop' into develop

pull/12/MERGE
tanghc 4 years ago
commit 2150d499bb
  1. 3
      sop-sdk/sdk-nodejs/common/Class.js
  2. 119
      sop-sdk/sdk-nodejs/common/OpenClient.js
  3. 2
      sop-sdk/sdk-nodejs/common/RequestType.js
  4. 65
      sop-sdk/sdk-nodejs/common/SignUtil.js
  5. 48
      sop-sdk/sdk-nodejs/main.js
  6. 12
      sop-sdk/sdk-nodejs/request/BaseRequest.js
  7. 16
      sop-sdk/sdk-nodejs/request/StoryGetRequest.js
  8. 8
      sop-sdk/sdk-nodejs/testClass.js

@ -70,7 +70,7 @@ exports.Class = (function () {
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function (name, fn) {
prototype[name] = typeof prop[name] == 'function' && typeof _super[name] == 'function' && fnTest.test(prop[name]) ? (function (name, fn) {
return function () {
var tmp = this._super;
@ -107,7 +107,6 @@ exports.Class = (function () {
};// ------Class Creation end------
return {
/**
* 创建一个类

@ -1,22 +1,22 @@
const needle = require('needle')
const moment = require('moment')
const needle = require('needle');
const moment = require('moment');
const {Class} = require("./Class");
const {RequestType} = require('./RequestType')
const {SignUtil} = require('./SignUtil')
const {BaseRequest} = require('../request/BaseRequest')
const {Class} = require('./Class');
const {RequestType} = require('./RequestType');
const {SignUtil} = require('./SignUtil');
const {BaseRequest} = require('../request/BaseRequest');
const HEADERS = {'Accept-Encoding': 'identity'}
const HEADERS = {'Accept-Encoding': 'identity'};
const getHeaders = function (headers) {
if (!headers) {
return HEADERS
return HEADERS;
}
for (const key in HEADERS) {
headers[key] = HEADERS[key];
}
return headers
}
return headers;
};
const OpenClient = Class.create({
/**
@ -33,21 +33,37 @@ const OpenClient = Class.create({
/**
* 发送请求
* @param request 请求类
* @param callback 回调函数参数json
* @param callback 回调函数参数jsonundefined则使用executeSync
*/
execute: function (request, callback) {
this.executeToken(request, null, callback)
if (typeof callback == 'function') {
this.executeToken(request, null, callback);
} else {
return this.executeSync(request);
}
},
/**
* 发送同步请求
* @param request 请求类
* */
executeSync: function (request) {
return new Promise((resolve) => {
this.execute(request, res => {
resolve(res);
});
});
},
/**
* 发送请求
* @param request 请求类
* @param token token
* @param callback 回调函数参数json
* @param callback 回调函数参数jsonundefined则使用executeTokenSync
*/
executeToken: function (request, token, callback) {
if (!(request instanceof BaseRequest)) {
throw 'request类未继承BaseRequest'
throw 'request类未继承BaseRequest';
}
if (typeof callback == 'function') {
const requestType = request.getRequestType();
if (request.files) {
this._postFile(request, callback);
@ -55,72 +71,93 @@ const OpenClient = Class.create({
switch (requestType) {
case RequestType.GET:
this._get(request, callback);
break
break;
case RequestType.POST_FORM:
this._postForm(request, callback);
break
break;
case RequestType.POST_JSON:
this._postJson(request, callback);
break
break;
case RequestType.POST_FILE:
this._postFile(request, callback);
break
break;
default: {
throw 'request.getRequestType()类型不正确'
throw 'request.getRequestType()类型不正确';
}
}
}
} else {
return this.executeTokenSync(request, token);
}
},
/**
* 发送同步请求
* @param request 请求类
* @param token token
*/
executeTokenSync: function (request, token) {
return new Promise((resolve) => {
this.executeToken(request, token, res => {
resolve(res);
});
});
},
_get: function (request, callback) {
const allParams = this._buildParams(request)
const that = this
const allParams = this._buildParams(request);
const that = this;
// needle.request(method, url, data[, options][, callback])
needle.request('GET', this.url, allParams, {
headers: getHeaders()
}, function (error, response) {
callback(that._parseResponse(error, response, request))
callback(that._parseResponse(error, response, request));
});
},
_postForm: function (request, callback) {
const allParams = this._buildParams(request)
const that = this
const allParams = this._buildParams(request);
const that = this;
needle.request('POST', this.url, allParams, {
headers: getHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
}, function (error, response) {
callback(that._parseResponse(error, response, request))
callback(that._parseResponse(error, response, request));
});
},
_postJson: function (request, callback) {
const allParams = this._buildParams(request)
const that = this
const allParams = this._buildParams(request);
const that = this;
needle.request('POST', this.url, allParams, {
headers: getHeaders(), json: true
}, function (error, response) {
callback(that._parseResponse(error, response, request))
callback(that._parseResponse(error, response, request));
});
},
_postFile: function (request, callback) {
const allParams = this._buildParams(request)
const allParams = this._buildParams(request);
const files = request.files;
files.forEach(row => {
// 设置成{ file: row.path, content_type: 'application/octet-stream' }格式
// needle会认为是上传文件
allParams[row.name] = { file: row.path, content_type: 'application/octet-stream' }
})
const that = this
allParams[row.name] = {file: row.path, content_type: 'application/octet-stream'};
});
const that = this;
needle.request('POST', this.url, allParams, {
headers: getHeaders(), multipart: true
}, function (error, response) {
callback(that._parseResponse(error, response, request))
callback(that._parseResponse(error, response, request));
});
},
_parseResponse: function (error, response, request) {
if (!error && response.statusCode === 200) {
return request.parseResponse(response.body)
return request.parseResponse(response.body);
} else {
throw '请求异常:' + error
// throw '请求异常:' + error
return { // 重新封装请求异常回调,以防中断
msg: '请求异常',
code: '502',
sub_msg: `${error}`,
sub_code: 'isv.invalid-server'
};
}
},
_buildParams: function (request, token) {
@ -132,16 +169,16 @@ const OpenClient = Class.create({
'timestamp': moment().format('YYYY-MM-DD HH:mm:ss'),
'version': request.getVersion(),
'biz_content': JSON.stringify(request.bizModel)
}
};
if (token) {
allParams['app_auth_token'] = token
allParams['app_auth_token'] = token;
}
// 创建签名
const sign = SignUtil.createSign(allParams, this.privateKey, 'RSA2')
allParams.sign = sign
const sign = SignUtil.createSign(allParams, this.privateKey, 'RSA2');
allParams.sign = sign;
return allParams;
}
})
});
module.exports = OpenClient
module.exports = OpenClient;

@ -3,4 +3,4 @@ exports.RequestType = {
POST_FORM: 'POST_FORM',
POST_JSON: 'POST_JSON',
POST_FILE: 'POST_FILE'
}
};

@ -1,12 +1,12 @@
const {KJUR, hextob64} = require('jsrsasign')
const {KJUR, hextob64} = require('jsrsasign');
const HashMap = {
SHA256withRSA: 'SHA256withRSA',
SHA1withRSA: 'SHA1withRSA'
}
};
const PEM_BEGIN = '-----BEGIN PRIVATE KEY-----\n'
const PEM_END = '\n-----END PRIVATE KEY-----'
const PEM_BEGIN = '-----BEGIN PRIVATE KEY-----\n';
const PEM_END = '\n-----END PRIVATE KEY-----';
/**
* rsa签名参考https://www.jianshu.com/p/145eab95322c
@ -20,16 +20,16 @@ exports.SignUtil = {
* @returns 返回签名内容
*/
createSign(params, privateKey, signType) {
const content = this.getSignContent(params)
return this.sign(content, privateKey, signType)
const content = this.getSignContent(params);
return this.sign(content, privateKey, signType);
},
sign: function (content, privateKey, signType) {
if (signType.toUpperCase() === 'RSA') {
return this.rsaSign(content, privateKey, HashMap.SHA1withRSA)
return this.rsaSign(content, privateKey, HashMap.SHA1withRSA);
} else if (signType.toUpperCase() === 'RSA2') {
return this.rsaSign(content, privateKey, HashMap.SHA256withRSA)
return this.rsaSign(content, privateKey, HashMap.SHA256withRSA);
} else {
throw 'signType错误'
throw 'signType错误';
}
},
/**
@ -40,26 +40,26 @@ exports.SignUtil = {
* @returns 返回签名字符串base64
*/
rsaSign: function (content, privateKey, hash) {
privateKey = this._formatKey(privateKey)
privateKey = this._formatKey(privateKey);
// 创建 Signature 对象
const signature = new KJUR.crypto.Signature({
alg: hash,
//!这里指定 私钥 pem!
prvkeypem: privateKey
})
signature.updateString(content)
const signData = signature.sign()
});
signature.updateString(content);
const signData = signature.sign();
// 将内容转成base64
return hextob64(signData)
return hextob64(signData);
},
_formatKey: function (key) {
if (!key.startsWith(PEM_BEGIN)) {
key = PEM_BEGIN + key
key = PEM_BEGIN + key;
}
if (!key.endsWith(PEM_END)) {
key = key + PEM_END
key = key + PEM_END;
}
return key
return key;
},
/**
* 获取签名内容
@ -67,22 +67,23 @@ exports.SignUtil = {
* @returns {string}
*/
getSignContent: function (params) {
const paramNames = []
for(const key in params) {
paramNames.push(key)
}
const paramNames = [];
// 获取对象中的Key
paramNames.push(...Object.keys(params || {})
// 过滤无效的KeyValue
.filter(paramName => {
// 参数名不为undefined且参数值不为undefined
return !(typeof paramName === undefined || typeof params[paramName] === undefined);
}));
paramNames.sort()
paramNames.sort();
const paramNameValue = []
for (let i = 0, len = paramNames.length; i < len; i++) {
const paramName = paramNames[i];
// 合成签名字符串
const paramNameValue = paramNames.map(paramName => {
const val = params[paramName];
if (paramName && val) {
paramNameValue.push(`${paramName}=${val}`)
}
}
return paramNameValue.join('&')
}
return `${paramName}=${val}`;
});
return paramNameValue.join('&');
}
};

@ -1,26 +1,26 @@
const OpenClient = require('./common/OpenClient')
const OpenClient = require('./common/OpenClient');
const {StoryGetRequest} = require('./request/StoryGetRequest')
const {StoryGetRequest} = require('./request/StoryGetRequest');
// 应用ID
const appId = '2019032617262200001'
const appId = '2019032617262200001';
// 应用私钥,2048位,PKCS8
const privateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXJv1pQFqWNA/++OYEV7WYXwexZK/J8LY1OWlP9X0T6wHFOvxNKRvMkJ5544SbgsJpVcvRDPrcxmhPbi/sAhdO4x2PiPKIz9Yni2OtYCCeaiE056B+e1O2jXoLeXbfi9fPivJZkxH/tb4xfLkH3bA8ZAQnQsoXA0SguykMRZntF0TndUfvDrLqwhlR8r5iRdZLB6F8o8qXH6UPDfNEnf/K8wX5T4EB1b8x8QJ7Ua4GcIUqeUxGHdQpzNbJdaQvoi06lgccmL+PHzminkFYON7alj1CjDN833j7QMHdPtS9l7B67fOU/p2LAAkPMtoVBfxQt9aFj7B8rEhGCz02iJIBAgMBAAECggEARqOuIpY0v6WtJBfmR3lGIOOokLrhfJrGTLF8CiZMQha+SRJ7/wOLPlsH9SbjPlopyViTXCuYwbzn2tdABigkBHYXxpDV6CJZjzmRZ+FY3S/0POlTFElGojYUJ3CooWiVfyUMhdg5vSuOq0oCny53woFrf32zPHYGiKdvU5Djku1onbDU0Lw8w+5tguuEZ76kZ/lUcccGy5978FFmYpzY/65RHCpvLiLqYyWTtaNT1aQ/9pw4jX9HO9NfdJ9gYFK8r/2f36ZE4hxluAfeOXQfRC/WhPmiw/ReUhxPznG/WgKaa/OaRtAx3inbQ+JuCND7uuKeRe4osP2jLPHPP6AUwQK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iNGQKBgGxU6P2aDAt6VNwWosHSe+d2WWXt8IZBhO9d6dn0f7ORvcjmCqNKTNGgrkewMZEuVcliueJquR47IROdY8qmwqcBAN7Vg2K7r7CPlTKAWTRYMJxCT1Hi5gwJb+CZF3+IeYqsJk2NF2s0w5WJTE70k1BSvQsfIzAIDz2yE1oPHvwVAoGAA6e+xQkVH4fMEph55RJIZ5goI4Y76BSvt2N5OKZKd4HtaV+eIhM3SDsVYRLIm9ZquJHMiZQGyUGnsvrKL6AAVNK7eQZCRDk9KQz+0GKOGqku0nOZjUbAu6A2/vtXAaAuFSFx1rUQVVjFulLexkXR3KcztL1Qu2k5pB6Si0K/uwQ=';
// 接口url
const url = 'http://localhost:8081'
const url = 'http://localhost:8081';
// 创建客户端
const openClient = new OpenClient(appId, privateKey, url)
const openClient = new OpenClient(appId, privateKey, url);
function test() {
// 创建请求
const request = new StoryGetRequest()
const request = new StoryGetRequest();
// 设置业务参数
request.bizModel = {
id: 111,
name: 'jim'
}
};
// 添加上传文件
// request.files = [
@ -30,15 +30,41 @@ function test() {
// ]
openClient.execute(request, data => {
console.log('异步请求');
// 成功
if (!data.sub_code) {
console.log('成功', data);
} else {
console.error('失败', data);
}
});
// 使用Promise进行封装
openClient.executeSync(request).then(data => {
console.log('同步请求-Promise');
// 成功
if (!data.sub_code) {
console.log('成功', data);
} else {
console.error('失败', data)
console.error('失败', data);
}
})
});
// 使用Async/Await进行封装
async function syncRequest() {
const data = await openClient.execute(request);
console.log('同步请求-Async/Await');
// 成功
if (!data.sub_code) {
console.log('成功', data);
} else {
console.error('失败', data);
}
}
syncRequest();
}
test()
test();

@ -1,18 +1,18 @@
const {Class} = require("../common/Class");
const {Class} = require('../common/Class');
/**
* 请求类父类
*/
exports.BaseRequest = Class.create({
init: function () {
this.bizModel = {}
this.bizModel = {};
/*
[
{name: 'file1', path: 'd:/dd/1.txt'},
{name: 'file2', path: 'd:/dd/2.txt'}
]
*/
this.files = []
this.files = [];
},
/**
* 返回接口名称
@ -40,9 +40,9 @@ exports.BaseRequest = Class.create({
parseResponse: function (responseData) {
let data = responseData['error_response'];
if (!data) {
const dataNodeName = this.getMethod().replace(/\./g, '_') + '_response'
data = responseData[dataNodeName]
const dataNodeName = this.getMethod().replace(/\./g, '_') + '_response';
data = responseData[dataNodeName];
}
return data;
}
})
});

@ -1,6 +1,6 @@
const {Class} = require("../common/Class");
const {RequestType} = require("../common/RequestType");
const {BaseRequest} = require('./BaseRequest')
const {Class} = require('../common/Class');
const {RequestType} = require('../common/RequestType');
const {BaseRequest} = require('./BaseRequest');
/**
* 创建一个请求类继承BaseRequest重写三个函数
@ -8,15 +8,15 @@ const {BaseRequest} = require('./BaseRequest')
const StoryGetRequest = Class.create({
getMethod: function () {
return "story.get"
return 'story.get';
},
getVersion: function () {
return "1.0"
return '1.0';
},
getRequestType: function () {
return RequestType.GET
return RequestType.GET;
}
}, BaseRequest) // 继承BaseRequest
}, BaseRequest); // 继承BaseRequest
module.exports.StoryGetRequest = StoryGetRequest
module.exports.StoryGetRequest = StoryGetRequest;

@ -3,7 +3,7 @@
* 运行node testClass.js
*/
const {Class} = require('./common/Class')
const {Class} = require('./common/Class');
function testClass() {
//-------------------------
@ -24,7 +24,7 @@ function testClass() {
// 声明类实例
var Jim = new Person({name: 'Jim'});
console.log('Jim name:' + Jim.getName())
console.log('Jim name:' + Jim.getName());
//例子2:-------------------------
@ -43,10 +43,10 @@ function testClass() {
}, Person);
var man = new Man({name: 'Tom', age: 22});
console.log('man name:' + man.getName())
console.log('man name:' + man.getName());
console.log('Jim instanceof Person: ' + (Jim instanceof Person));
console.log('man instanceof Person: ' + (man instanceof Person));
}
testClass()
testClass();

Loading…
Cancel
Save