/** * @author songxiwen * @date 2020/08/04 10:58 */ import tencentCloud from 'tencentcloud-sdk-nodejs'; import { RequestType, SMSPromiseResponse, SMSResponse } from './type/sms.type'; import { ServerError } from '../common'; const { Credential, ClientProfile, HttpProfile } = tencentCloud.common; const models = tencentCloud.sms.v20190711.Models; const SmsClient = tencentCloud.sms.v20190711.Client; export class Util { static async sendSMS(param: { phone: string; secretId: string; secretKey: string; smsSign: string; smsTemplateId: string; smsSdkAppId: string; }): Promise { const credit = new Credential(param.secretId, param.secretKey); const httpProfile = new HttpProfile(); httpProfile.endpoint = 'sms.tencentcloudapi.com'; const clientProfile = new ClientProfile(); clientProfile.httpProfile = httpProfile; const client = new SmsClient(credit, '', clientProfile); const request: RequestType = new models.AddSmsTemplateRequest(); const smsCode = Util.generateRandomNumber(4); request.PhoneNumberSet = [`+86${param.phone}`]; request.TemplateID = param.smsTemplateId; request.Sign = param.smsSign; request.SmsSdkAppid = param.smsSdkAppId; request.Action = 'SendSms'; request.Version = '2019-07-11'; request.TemplateParamSet = [smsCode]; return new Promise(resolve => { client.SendSms(request, (error: Error, response: SMSResponse) => { if (error) { throw ServerError.code.SMSCodeRemoteWrong; } if ( response.SendStatusSet && response.SendStatusSet[0] && response.SendStatusSet[0].Code === 'Ok' ) { resolve({ message: response.SendStatusSet[0].Message, data: { smsCode } }); } else { throw ServerError.code.SMSCodeRemoteWrong; } }); }); } static generateRandomNumber(count: number): string { const max = count > 10 ? 10 : count; return Math.random() .toString() .substring(2, 2 + max); } }