import * as uuid from 'uuid';
import * as crypto from 'crypto';
import { SfExpressUtils } from '../utils/sf-express.utils';
export class SfApiRequestDto {
private static readonly reg0 = new RegExp("%20","gm")
private static readonly reg1 = new RegExp("!","gm")
private static readonly reg2 = new RegExp("~","gm")
private static readonly reg3 = new RegExp("'","gm")
private static readonly reg4 = new RegExp("[(]","gm")
private static readonly reg5 = new RegExp("[)]","gm")
/** 合作伙伴编码(即顾客编码) */
partnerID: string;
/** 请求唯一号UUID */
requestID: string;
/** 接口服务代码(到API接口详情查看具体服务代码) */
serviceCode: string;
/** 调用接口时间戳 */
timestamp: string;
/** 数字签名 */
msgDigest: string;
/** 业务数据报文 */
msgData: string;
/**
* 构建顺丰请求报文
* @param serviceCode 接口服务代码(到API接口详情查看具体服务代码)
* @param data 业务数据报文
*/
constructor(serviceCode: string, data: any, utils: SfExpressUtils) {
this.partnerID = utils.sfConfig.PARTNER_ID;
this.requestID = uuid.v1().replace(/-/g, '');
this.serviceCode = serviceCode;
this.timestamp = (new Date()).valueOf() + '';
this.msgData = JSON.stringify(data);
this.msgDigest = this.getDigist(utils.sfConfig.CHECK_WORD);
}
/**
* 计算数字签名
*/
getDigist(checkWord: string): string {
//将业务报文+时间戳+校验码组合成需加密的字符串(注意顺序)
let toVerifyText = this.msgData + this.timestamp + checkWord;
toVerifyText = encodeURIComponent(toVerifyText);
toVerifyText = crypto.createHash('md5').update(this.nodeEncode2JavaEncode(toVerifyText)).digest("hex")
return Buffer.from(toVerifyText, 'hex').toString('base64');
}
nodeEncode2JavaEncode(encodeString: string): string {
return encodeString
.replace(SfApiRequestDto.reg0, '+')
.replace(SfApiRequestDto.reg1, '%21')
.replace(SfApiRequestDto.reg2, '%7E')
.replace(SfApiRequestDto.reg3, '%27')
.replace(SfApiRequestDto.reg4, '%28')
.replace(SfApiRequestDto.reg5, '%29');
}
}