微信公众号模板消息发送示例:Java代码实现

本文提供一个使用Java代码发送微信公众号模板消息的示例,并解释了AccessToken的作用以及如何构建模板消息数据。

代码示例

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'));
      templateMessage.addData(new WxMpTemplateData('keyword1', 'World', '#000000'));
      templateMessage.addData(new WxMpTemplateData('keyword2', 'Example', '#000000'));
      templateMessage.addData(new WxMpTemplateData('remark', 'This is a template message', '#0000FF'));

      // 发送模板消息
      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:在上述代码中,accessToken是通过wxMpService.getAccessToken()方法获取的,但是在发送模板消息时并没有使用到。实际上,获取accessToken是为了确保发送模板消息的接口调用权限。
  • 模板消息数据构建:代码中通过addData()方法向模板消息中添加数据项。每个数据项都包含一个namevaluecolor字段。
    • name:模板中的关键字,如firstkeyword1等。
    • value:要替换的文本内容,如HelloWorld等。
    • color:文本颜色,如#FF0000表示红色。

注意

  • 请确保将TEMPLATE_ID替换为你自己的模板ID,并根据实际需求调整模板消息的内容。
  • url:可以通过url参数设置点击模板消息跳转的URL。
  • WxMpTemplateMessageWxMpTemplateData 等类来自微信公众平台的Java SDK,需要先引入相关依赖。

代码运行环境

  • 需要安装Java JDK。
  • 需要引入微信公众平台的Java SDK。

总结

本文提供了一个完整的微信公众号模板消息发送示例,并解释了相关的关键概念。希望对您使用微信公众号模板消息功能有所帮助。

微信公众号模板消息发送示例:Java代码实现

原文地址: http://www.cveoy.top/t/topic/pb5s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录