微信小程序与微信是深度融合的,很少需要发送短信验证码的,对于企业用户,可以在微信开发者工具中直接购买和使用,相对比较简单。个人开发的小程序就比较麻烦了,但最近也有此需求了,我验证了使用腾讯云短信包,实现发送短信验证码的功能。
第一步,腾讯云短信包开通和环境准备工作
1、进入官网,并自行购买。登录 - 腾讯云
2、创建签名,根据真实情况填写。
3、创建正文模板,选择刚刚创建的签名,填写正文模板。
我创建的正文模板为:验证码为:{1},您正在登录,若非本人操作,请勿泄露。
4、创建secreKey,切记保存后再关闭。
第二步,在微信小程序中新建云函数sendcode
第三步,安装sdk库,npm install tencentcloud-sdk-nodejs-sms --save
第四步,写云函数代码
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
exports.main = async (event, context) => {
console.log('event1',event)
const tencentcloud = require("tencentcloud-sdk-nodejs-sms")
const smsClient = tencentcloud.sms.v20210111.Client
const client = new smsClient({
credential: {
secretId: '你的secretId',
secretKey: '你的secretKey',
},
region: "ap-guangzhou",
})
const params = {
SmsSdkAppId: "你的SmsSdkAppId",
SignName: "你的SignName",
TemplateId: "你的TemplateId",
TemplateParamSet: [event.code],
PhoneNumberSet: [event.PhoneNumber],
SessionContext: "",
ExtendCode: "",
SenderId: "",
}
await client.SendSms(params, function (err, response) {
// 请求异常返回,打印异常信息
if (err) {
return {'err':err}
}
// 请求正常返回,打印response对象
return {'response':response}
})
}
第五步,小程序中,写调用云函数的代码
wx.cloud.callFunction({
name: 'sendsms',
data: {
code: '9999',
PhoneNumber:'+8612345678888',
}
}).then((resp) => {
console.log('then',resp)
}).catch((e) => {
console.log('catch',e);
});
通过以上几步就是先了,向手机12345678888的用户,发送9999的验证码