Java 微信公众号模板消息发送示例代码
Java 微信公众号模板消息发送示例代码
本示例代码演示如何使用 Java 代码发送微信公众号模板消息。
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';
// 获取微信公众号的AccessToken
String accessToken = wxMpService.getAccessToken();
// 构建模板消息的数据
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(TEMPLATE_ID)
.build();
// 添加模板消息的参数
templateMessage.addData(new WxMpTemplateData('first', 'Hello', '#FF0000')); // 参数1
templateMessage.addData(new WxMpTemplateData('keyword1', 'World', '#000000')); // 参数2
templateMessage.addData(new WxMpTemplateData('keyword2', 'Example', '#000000')); // 参数3
templateMessage.addData(new WxMpTemplateData('remark', 'Goodbye', '#0000FF')); // 参数4
// 发送模板消息
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);
}
}
}
发送模板消息的示例代码如下:
// 构建模板消息的数据
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId) // 用户的openId
.templateId(TEMPLATE_ID) // 模板消息的ID
.url('https://example.com') // 模板消息跳转链接(可选)
.build();
// 添加模板消息的参数
templateMessage.addData(new WxMpTemplateData('first', 'Hello', '#FF0000')); // 参数1
templateMessage.addData(new WxMpTemplateData('keyword1', 'World', '#000000')); // 参数2
templateMessage.addData(new WxMpTemplateData('keyword2', 'Example', '#000000')); // 参数3
templateMessage.addData(new WxMpTemplateData('remark', 'Goodbye', '#0000FF')); // 参数4
// 发送模板消息
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
在这个示例中,我们构建了一个模板消息对象templateMessage,并为其添加了四个参数。这些参数将在模板消息中被替换为实际的值。参数的格式为new WxMpTemplateData(key, value, color),其中key是参数的名称,value是参数的值,color是参数的字体颜色。你可以根据自己的实际需求添加更多的参数。
请注意,这只是一个示例,你需要根据你自己的模板消息的具体格式来构建模板消息对象并添加参数。
原文地址: http://www.cveoy.top/t/topic/pb5r 著作权归作者所有。请勿转载和采集!