在微信小程序中发送模板消息需要通过微信公众平台配置模板,并结合后端接口实现。以下是实现步骤和关键代码:
### 实现步骤
1. 在微信公众平台配置模板
- 登录[微信公众平台](https://mp.weixin.qq.com/)
- 进入"模板消息"栏目,添加所需模板
- 获取模板ID
2. 前端获取用户授权和formId
- 需要用户触发表单提交获取formId(用于发送模板消息的凭证)
- formId有效期为7天,且只能使用一次
3. 后端调用微信接口发送消息
- 后端需要获取access_token
- 使用获取到的formId和模板ID调用微信发送模板消息接口
### 前端关键代码
< form bindsubmit="formSubmit" report-submit="true">
< button form-type="submit">提交表单获取formId< /button>
< /form>
```
```javascript
// 小程序.js文件
Page({
formSubmit: function(e) {
// 获取formId
const formId = e.detail.formId;
// 获取用户openId(通常从登录信息中获取)
const openId = wx.getStorageSync('openId');
// 调用后端接口发送模板消息
wx.request({
url: 'https://你的后端域名/sendTemplateMessage',
method: 'POST',
data: {
openId: openId,
formId: formId,
// 其他需要传递的参数
},
success: function(res) {
console.log('模板消息发送成功', res);
},
fail: function(err) {
console.error('模板消息发送失败', err);
}
});
}
});
```
### 后端关键代码(Node.js示例)
### sendTemplate.js
const request = require('request-promise');
// 配置信息
const config = {
appId: '你的小程序appId',
appSecret: '你的小程序appSecret',
templateId: '你的模板ID'
};
// 获取access_token
async function getAccessToken() {
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appId}&secret=${config.appSecret}`;
try {
const response = await request(url);
const result = JSON.parse(response);
return result.access_token;
} catch (error) {
console.error('获取access_token失败', error);
throw error;
}
}
// 发送模板消息
async function sendTemplateMessage(openId, formId, data) {
try {
const accessToken = await getAccessToken();
const url = `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${accessToken}`;
const message = {
touser: openId,
template_id: config.templateId,
page: 'pages/index/index', // 点击模板消息跳转的页面
form_id: formId,
data: data, // 模板数据
emphasis_keyword: 'keyword1.DATA' // 需要加粗显示的关键词
};
const response = await request({
url: url,
method: 'POST',
body: message,
json: true
});
return response;
} catch (error) {
console.error('发送模板消息失败', error);
throw error;
}
}
// 接口调用示例
// sendTemplateMessage(
// '用户openId',
// '获取到的formId',
// {
// keyword1: { value: '订单编号' },
// keyword2: { value: '订单金额' },
// keyword3: { value: '下单时间' }
// }
// );
module.exports = {
sendTemplateMessage
};
### 注意事项
1. formId只能通过用户主动提交表单获取,且每个formId只能使用一次
2. 模板消息的字段需要与公众平台配置的模板字段一一对应
3. access_token有有效期(2小时),建议后端缓存处理
4. 小程序账号需要有发送模板消息的权限
5. 自2020年1月10日起,微信对模板消息进行了调整,建议同时了解订阅消息的使用方法作为补充
如果需要更详细的实现或有特定场景需求,可以进一步说明具体业务场景。