微信公众号模板消息发送示例代码
微信公众号模板消息发送示例代码
本示例代码展示了如何使用微信公众号官方 SDK 发送模板消息,并提供了一个详细的发送模板消息的流程说明。
public class WeChatTemplateMessageSender {
private static final String APP_ID = 'your_app_id';
private static final String APP_SECRET = 'your_app_secret';
private static final String TEMPLATE_ID = 'your_template_id';
public static void main(String[] args) {
// 初始化微信公众号配置
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(new YourWxMpConfigStorage(APP_ID, APP_SECRET));
try {
// 获取用户的openId,这里使用一个假设的openId
String openId = 'your_open_id';
// 构建模板消息的数据
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(TEMPLATE_ID)
.url('https://example.com') // 模板消息点击跳转的URL
.build();
// 添加模板消息的参数
templateMessage.addWxMpTemplateData(new WxMpTemplateData('first', 'Hello, World!'));
templateMessage.addWxMpTemplateData(new WxMpTemplateData('keyword1', 'Value1'));
templateMessage.addWxMpTemplateData(new WxMpTemplateData('keyword2', 'Value2'));
// ...
// 发送模板消息
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (WxErrorException e) {
e.printStackTrace();
}
}
// 自定义WxMpConfigStorage,用于保存公众号的AppID和AppSecret
private static class YourWxMpConfigStorage extends WxMpDefaultConfigImpl {
public YourWxMpConfigStorage(String appId, String appSecret) {
setAppId(appId);
setSecret(appSecret);
}
}
}
说明:
- 在上面的示例代码中,accessToken并没有用到,因为在发送模板消息时,
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage)方法内部会自动获取最新的accessToken并发送消息。 - 在示例代码中,我们使用
WxMpTemplateMessage类来构建模板消息数据,并通过addWxMpTemplateData方法添加模板消息的参数。 url参数指定了模板消息点击跳转的URL,该URL必须是有效的URL。- 每个模板消息参数都有一个键和一个值,键必须与模板消息定义中指定的键一致,值可以是任何字符串。
其他说明:
- 在使用模板消息之前,需要先在微信公众平台上创建模板消息并获取模板消息ID。
- 模板消息只能发送给关注了公众号的用户。
- 模板消息每天发送次数有限制,具体限制请参考微信公众平台文档。
更多信息:
- 微信公众平台文档: https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message.html
- 微信公众号官方 SDK: https://github.com/Wechat-Group/weixin-java-mp
原文地址: http://www.cveoy.top/t/topic/pb5o 著作权归作者所有。请勿转载和采集!