微信公众号模板消息发送示例代码 - 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);
    }
  }
}

代码解释:

  1. 获取AccessTokenwxMpService.getAccessToken()方法用于获取微信公众号的AccessToken,用于发送模板消息时进行身份验证。
  2. 构建模板消息数据WxMpTemplateMessage.builder()方法用于构建模板消息数据,包括接收者openId、模板ID、点击跳转链接等信息。
  3. 添加模板消息数据addData方法用于添加模板消息数据,每个数据包含三个字段:数据名称、数据值和数据颜色。
  4. 发送模板消息wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage)方法用于发送模板消息。
  5. 自定义WxMpConfigStorage:代码中定义了一个名为YourWxMpConfigStorage的类,继承自WxMpDefaultConfigImpl,用于保存公众号的AppID和AppSecret。

使用说明:

  1. 替换代码中的'your_app_id''your_app_secret''your_template_id'为你的实际值。
  2. 替换'your_open_id'为接收者的openId。
  3. 替换'your_template_url'为模板消息的点击跳转链接(可选)。
  4. 可以根据实际需求添加更多模板消息数据。

注意:

  1. 发送模板消息需要使用微信公众号提供的模板消息接口。
  2. 模板消息需要在微信公众号平台上进行配置和审核。
  3. 发送模板消息需要遵守微信公众号平台的相关规则。

更多信息:

希望本示例代码能够帮助你快速上手微信公众号模板消息开发。

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

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

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