微信官方开放了获得用户微信绑定手机号的API,但是数据是以加密的形式提供的,使用时需要解密,官方给的示例代码用的原生node代码,现在改造成typescript的方式提供给大家
import * as crypto from 'crypto';
/**
* 微信敏感数据解密处理类
*
*/
module.exports = class WXBizDataCrypt {
appId: string;
sessionKey: string;
constructor(appId: string, sessionKey: string) {
this.appId = appId;
this.sessionKey = sessionKey;
}
/**
* 解密敏感数据
* @param encryptedData
* @param iv
*/
async decryptData(encryptedData: any, iv: any) {
// base64 decode
console.log('sessionkey='+this.sessionKey+',appId='+this.appId);
let sessionKey = new Buffer(this.sessionKey, 'base64');
encryptedData = new Buffer(encryptedData, 'base64');
iv = new Buffer(iv, 'base64');
let decoded = '';
try {
// 解密
const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(true);
decoded = decipher.update(encryptedData, 'binary', 'utf8');
decoded += decipher.final('utf8');
decoded = JSON.parse(decoded);
} catch (err) {
console.log('解密微信敏感数据时出错!错误信息:' + err.toString());
return '';
}
//验证来源合法性
if (decoded['watermark'].appid !== this.appId) {
console.log('解密微信敏感数据时出错,非法的appId!');
return '';
}
return decoded;
}
};