微信公众号模板消息发送示例代码 - 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)
.url('your_template_url') // 替换为模板消息的点击跳转链接(可选)
.build();
// 添加模板消息的数据
templateMessage.addData(new WxMpTemplateData('first', 'Hello', '#FF0000'));
templateMessage.addData(new WxMpTemplateData('keyword1', 'World', '#00FF00'));
templateMessage.addData(new WxMpTemplateData('keyword2', 'Test', '#0000FF'));
templateMessage.addData(new WxMpTemplateData('remark', 'This is a test message', '#000000'));
// 发送模板消息
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.getAccessToken()方法用于获取微信公众号的AccessToken,用于发送模板消息时进行身份验证。 - 构建模板消息数据:
WxMpTemplateMessage.builder()方法用于构建模板消息数据,包括接收者openId、模板ID、点击跳转链接等信息。 - 添加模板消息数据:
addData方法用于添加模板消息数据,每个数据包含三个字段:数据名称、数据值和数据颜色。 - 发送模板消息:
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage)方法用于发送模板消息。 - 自定义WxMpConfigStorage:代码中定义了一个名为
YourWxMpConfigStorage的类,继承自WxMpDefaultConfigImpl,用于保存公众号的AppID和AppSecret。
使用说明:
- 替换代码中的
'your_app_id'、'your_app_secret'和'your_template_id'为你的实际值。 - 替换
'your_open_id'为接收者的openId。 - 替换
'your_template_url'为模板消息的点击跳转链接(可选)。 - 可以根据实际需求添加更多模板消息数据。
注意:
- 发送模板消息需要使用微信公众号提供的模板消息接口。
- 模板消息需要在微信公众号平台上进行配置和审核。
- 发送模板消息需要遵守微信公众号平台的相关规则。
更多信息:
希望本示例代码能够帮助你快速上手微信公众号模板消息开发。
原文地址: http://www.cveoy.top/t/topic/pb5i 著作权归作者所有。请勿转载和采集!