doomi-helper
Version:
Doomisoft NodeJs Common Utilities
97 lines (80 loc) • 2.61 kB
JavaScript
/* eslint-disable global-require */
/* eslint-disable no-sync */
/**
* 腾讯云的验证码相关的API算法封装
*/
/**
* 封装腾讯云的验证码服务
*/
const tencentcloud = require('tencentcloud-sdk-nodejs');
const CaptchaClient = tencentcloud.captcha.v20190722.Client;
var path = require('path');
var fs = require('fs');
class CaptchaService {
constructor(config) {
this.secretId = config.SecretId;
this.secretKey = config.SecretKey;
this.region = config.region || 'ap-guangzhou';
this.CaptchaAppId = config.CaptchaAppId;
this.AppSecretKey = config.AppSecretKey;
this.init();
}
/**
* 初始化情感分析的参数
*/
init() {
const clientConfig = {
credential: {
secretId: this.secretId,
secretKey: this.secretKey,
},
region: this.region,
signMethod: 'HmacSHA256', // 签名方法
profile: {
httpProfile: {
endpoint: 'captcha.tencentcloudapi.com',
reqMethod: 'POST', // 请求方法
},
},
};
this.client = new CaptchaClient(clientConfig);
}
/**
* 当前配置中的腾讯云短信实例配置
*/
static getInstance() {
if (!CaptchaService.instance) {
let configfilename = process.env.CONFIGFILE || 'configuration.json';
let configfile = path.join(process.cwd(), configfilename);
if (!fs.existsSync(configfile)) {
throw new Error('Missing app configuration file');
}
let config = require(configfile);
CaptchaService.instance = new CaptchaService(config.tencentApi);
}
return CaptchaService.instance;
}
/***
* 验证码
*/
Captcha(ticket, randstr) {
return new Promise(reslove => {
const params = {
CaptchaType: 9,
Ticket: ticket,
UserIp: '127.0.0.1',
Randstr: randstr,
CaptchaAppId: parseInt(this.CaptchaAppId),
AppSecretKey: this.AppSecretKey,
};
this.client.DescribeCaptchaResult(params, (error) => {
if (error) {
console.error('error', error);
return reslove({ successed: false, error: error });
}
return reslove({ successed: true });
});
});
}
}
exports = module.exports = CaptchaService;