小程序云开发环境共享给公众号,发送不了公众号模板消息
[图片] //前端代码
sendTemplateMsg() {
// 替换为实际参数:
const params = {
touser: 'ochWuvg4vb5bGkvaXxfUaOHtLBqc', // 公众号用户的 openid(需提前获取)
templateId: 'VjMWY17E3ONXsOKk4y5pO226nG7DU5n3w2jRDCiY3Qg', // 公众号模板 ID
data: { // 模板数据(与公众号模板字段一一对应)
thing7: { value: '杨朝宇' },
thing5: { value: '你有新消息请及时查看' },
time3: { value: '2025-08-28 09:25:26' },
},
url: 'https://your-domain.com/detail' // 点击跳转链接(可选)
}
wx.cloud.callFunction({
name: 'sendTemplateMessage', // 云函数名
data: params,
}).then(res => {
if (res.result.code === 0) {
wx.showToast({ title: '发送成功' })
} else {
wx.showToast({ title: '发送失败', icon: 'none' })
console.error(res.result.err)
}
}).catch(err => {
wx.showToast({ title: '调用失败', icon: 'none' })
console.error(err)
})
},
//云函数
const cloud = require('wx-server-sdk');
exports.main = async (event, context) => {
const { touser, templateId, data, url } = event;
const wxContext = cloud.getWXContext();
// 参数校验
if (!touser || !templateId || !data) {
return { code: 1, err: '参数缺失:touser、templateId、data为必填项' };
}
try {
// 初始化资源方(小程序)的云环境实例
const targetCloud = new cloud.Cloud({
resourceAppid: "wx923c5dfc65663940",
resourceEnv: "cloud1-1g6kzn9v7f2e4279" // 共享的云环境ID
});
await targetCloud.init();
// 调用发送模板消息接口,appid是公众号appid
const result = await targetCloud.openapi({ appid: 'wxee9bdeae6d16b96a' }).officialAccount.messageTemplate.send({
touser,
templateId,
data,
url: url || ''
});
return { code: 0, success: true, result };
} catch (err) {
console.error('调用失败:', err);
return { code: 2, success: false, err: err.toString() };
}
};
[图片]