使用 NodeJS 调用金蝶管易云 C-ERP 的 openAPI
金蝶管易云ERP提供完善的数据接口,可供用于外部系统做数据对接。
获取密钥
调用C-ERP
接口之前先要获取接口密钥:
- 登录金蝶管易云
- 点击左上角
菜单
- 搜索:
云ERP授权
密钥包含:
- appkey
- sessionkey
- secret
接口认证
参考金碟管易ERP openAPI 文档编写通用客户端。
import sa from 'superagent';
import cryptoJS from 'crypto-js';
/**
* 密钥配置结构
*/
export interface GuanyiCerpConfig {
apiUrl: string;
appkey: string;
sessionkey: string;
secret: string;
}
/**
* 金蝶管易云C-ERP API 客户端
* @param config 密钥配置
* @param method 接口方法
* @param params 业务参数
* @throws {Error} 接口调用时发生传输层异常
*/
export async function cerpRequest({config, method, params}: {
config: GuanyiCerpConfig,
method: string, params: any
}): Promise<any> {
const {appkey, sessionkey, secret, apiUrl} = config;
// 构造签名前的请求参数
const data = {
appkey, sessionkey, method,
...params,
};
// 签名并将签名结果放入请求参数
data.sign = sign(JSON.stringify(data), secret);
// 发送请求,请求时发生的传输层异常会被抛出
const {text} = await sa.post(apiUrl).send(data);
// 解析并返回响应结果,可能包含业务功能错误信息
return Promise.resolve(JSON.parse(text));
}
/**
* 签名
* 拼接密钥和请求参数,然后进行MD5加密
* @param str
* @param secret
*/
export function sign(str: string, secret: string): string {
return encryptByMD5(`${secret}${str}${secret}`);
}
export function encryptByMD5(data: any): string {
return cryptoJS.MD5(data).toString().toUpperCase();
}
如果发生sessionkey对应的授权不存在
的错误,请先检查sessionkey和secret有没有填错,有没有填反
。
{
"success": false,
"errorCode": "Base Param error",
"subErrorCode": "ErrorSessionKey",
"errorDesc": "基本参数错误",
"subErrorDesc": "sessionkey对应的授权不存在",
"requestMethod": null,
"flag": null
}
调用业务接口
编写好通用认证接口后,就可以调用业务接口了。
/**
* 封装业务接口:调用店铺接口
* @param config
* @param params
* @throws {Error} 接口调用时发生传输层异常,需要从调用栈中捕获
*/
export async function gyErpShopGet(config: GuanyiCerpConfig, params: GyErpShopGetParam): Promise<GyErpShopGetResponse> {
return cerpRequest({config, method: 'gy.erp.shop.get', params});
}