使用业务类型关联模板id, 不同的业务类型关联不同的模板,如果需要区分不同的公众号,可以在配置文件里加入 appId 字段
// 定义配置文件,也可以从数据库里获取, 根据不同的业务,配置模板id和发送内容格式
const templateConfig = [
{ bz_type: 1, appId: '111', template_id: '模板id1', msgData: '{"first":{"value":"$1","color":""},"keyword1":{"value":"$2","color":""},"keyword2":{"value":"$3","color":""},"keyword3":{"value":"$4","color":""},"remark":{"value":"$5","color":""}}', pagePath: '/page/index' } ,
{ bz_type: 2, appId: '222', template_id: '模板id2' ,msgData: '{"first":{"value":"$1","color":""},"keyword1":{"value":"$2","color":""},"keyword2":{"value":"$3","color":""},"keyword3":{"value":"$4","color":""},"remark":{"value":"$5","color":""}}', pagePath: '/page/index2' }
]
// 自行获取 access_token
let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${ access_token}`;
// 根据appId, 业务类型, 取配置信息
const appId = '111'
const bz_type = 1;
const templateInfo = templateConfig.find(s => s.appId == appId && s.bz_type == bztype);
let message = {
touser: openid,
template_id: templateInfo.template_id,
url: templateInfo.pagePath,
}
// 参数拼装
const params = {
'$1': '111',
'$2': '111',
'$3': '111',
}
let dataStr = templateInfo.msgData;
// 使用参数替换模板里的配置
Object.keys(params).forEach(key => {
dataStr = dataStr.replace(key, params[key]);
})
message.data = JSON.parse(dataStr);
// 发送模板消息
axios.post(url, message).then(response => {
console.log(response.data)
})