50 lines
2.8 KiB
JavaScript
50 lines
2.8 KiB
JavaScript
'use strict';
|
||
|
||
async function sendSmsAliyun (smsClient, phone, msgParam, templateCode, signName) { // msgParam 是消息模板参数对象,例如 { code: "890353" }
|
||
let matches = phone.match(/\d+/g);
|
||
let smsNumber = matches[0] === '86' ? matches[1] : '00' + matches[0] + matches[1];
|
||
const res = await smsClient.sendSMS({
|
||
PhoneNumbers: smsNumber,//必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
|
||
SignName: signName,//必填:短信签名-可在短信控制台中找到
|
||
TemplateCode: templateCode,//必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
|
||
TemplateParam: JSON.stringify(msgParam) //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时。
|
||
});
|
||
if (res && res.Code && res.Code === 'ok') {
|
||
return { state: 'DONE' };
|
||
} else {
|
||
return { state: 'FAILED', error: res };
|
||
}
|
||
}
|
||
|
||
module.exports = {
|
||
sendMail: function (SysConfig) {
|
||
const smtpTransporter = require('nodemailer').createTransport(SysConfig.SMTP);
|
||
return async function (option) { // 或者如果smtp参数已经确定,就可以直接定义 sendMail: Bluebird.promisify(Smtp.sendMail).bind(Smtp)
|
||
/*
|
||
{
|
||
from: '"Fred Foo 👻" <foo@example.com>', // sender address
|
||
to: "bar@example.com, baz@example.com", // list of receivers
|
||
subject: "Hello ✔", // Subject line
|
||
text: "Hello world?", // plain text body
|
||
html: "<b>Hello world?</b>" // html body
|
||
}
|
||
*/
|
||
return await smtpTransporter.sendMail(option);
|
||
};
|
||
}
|
||
,
|
||
sendSms: function (SysConfig) {
|
||
const smsClient = new (require('@alicloud/sms-sdk'))({ // 在调用时,才创建 smsClient,防止 SysConfig 还没有建立好。
|
||
accessKeyId: SysConfig.SMS.aliyun.accessKeyId,
|
||
secretAccessKey: SysConfig.SMS.aliyun.secretAccessKey
|
||
});
|
||
return async function (phone, option = {}) { // 通过option对象,对外提供统一的调用参数格式
|
||
if (/^\+\d+-\d+$/.test(phone)) {
|
||
if (option.msgParam && option.templateCode && option.signName) {
|
||
return await sendSmsAliyun(smsClient, phone, option.msgParam, option.templateCode, option.signName);
|
||
}
|
||
}
|
||
return null; // 手机号格式错误,或者 option.vendor 错误。
|
||
};
|
||
}
|
||
}; |