Java对接微信公众号模板消息推送

1,832 阅读3分钟

Java对接微信公众号模板消息推送

准备工作

​ 前段时间在公司做了一个微信公众号模板消息推送的Demo 感觉很有意思 做个记录分享一下

​ 微信公众号:mp.weixin.qq.com/

​ 接口文档:模板消息 | 微信开放文档 (qq.com)

​ 原文连接:www.cnblogs.com/chenghao24/…

首先我们需要准备一个公众号 然后在【功能】中添加新插件 因为默认新公众号是没有这个功能的 需要开发者申请 申请后需要 "鹅厂" 三到五天的审核

微信图片_20210427102703[1].png

在等待完成后我们就可以选择模板了

左侧菜单 【功能->模板消息->从模板库添加】

微信图片_20210427103255[1].png

可选择或修改所在行业 在该行业下搜寻模板

正式开发

新建maven项目 (我这里采用的是SpringBoot)

maven坐标:

<!-- WxJava公众号 -->
<dependency>
   <groupId>com.github.binarywang</groupId>
   <artifactId>weixin-java-mp</artifactId>
   <version>3.6.0</version>
</dependency>

然后就需要配置信息了 appId 和 secret 在公众号内就能看到了

weiChat:
  appId: xxxx
  secret: xxx

就这那么多就可以了

编写配置类

/**
 * @author: aodi
 * @create: 2021-04-15 09:37
 * 微信消息推送配置
 **/
@Configuration
public class WeChatConfig {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.sceret}")
    private String sceret;





    /**
     * 微信客户端配置存储
     *
     * @return
     */
    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        // 公众号appId
        configStorage.setAppId(appId);
        // 公众号appSecret
        configStorage.setSecret(sceret);
        return configStorage;
    }

    /**
     * 声明实例
     *
     * @return
     */
    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

接下来我们来看如何发送模板消息

我们先来分析一下你选择的模板

微信图片_20210427113758[1].png

拿到你的的模板ID 另外 微信已经说明的了 其中的 {{data}} 为你需要替换调的参数

好了知道这些后我们开始对代码,首先是这个

微信图片_20210427114021[1].png

WxMpTemplateMessage 微信对着类中进行了封装 点进去 瞅一眼 微信源码

/**
 * 模板消息.
 * 参考 http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN 发送模板消息接口部分
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class WxMpTemplateMessage implements Serializable {
  private static final long serialVersionUID = 5063374783759519418L;

  /**
   * 接收者openid.
   */
  private String toUser;

  /**
   * 模板ID.
   */
  private String templateId;

  /**
   * 模板跳转链接.
   * <pre>
   * url和miniprogram都是非必填字段,若都不传则模板无跳转;若都传,会优先跳转至小程序。
   * 开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时,将会跳转至url。
   * </pre>
   */
  private String url;

  /**
   * 跳小程序所需数据,不需跳小程序可不用传该数据.
   *
   * @see #url
   */
  private MiniProgram miniProgram;

  /**
   * 模板数据.
   */
  @Builder.Default
  private List<WxMpTemplateData> data = new ArrayList<>();

  public WxMpTemplateMessage addData(WxMpTemplateData datum) {
    if (this.data == null) {
      this.data = new ArrayList<>();
    }
    this.data.add(datum);
    return this;
  }

  public String toJson() {
    return WxMpGsonBuilder.create().toJson(this);
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  public static class MiniProgram implements Serializable {
    private static final long serialVersionUID = -7945254706501974849L;

    private String appid;
    private String pagePath;

    /**
     * 是否使用path,否则使用pagepath.
     * 加入此字段是基于微信官方接口变化多端的考虑
     */
    private boolean usePath = true;
  }

上面已经介绍的很清楚了 就不在一一赘述了 如果不知道怎么获取openId 直接去百度一下

下面我们开始往模板里面塞数据

微信图片_20210427114551[1].png

name: 对应的就是你的消息模板中的{{name}}

value:对应的描述中 你要添加的内容

color:字体颜色 (可不填)

    private final WxMpService wxMpService;

	// 需要提前注入
    public WeChatDialogueService(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    } 

// 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(userPersonMapper.select(Long.parseLong(weChatDialogue.getToUserId())).getSourceCode())
                // 模板id
                .templateId(feedbackMsg)
                // 模板跳转链接
                .build();

        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first","您好,您有一条新的反馈通知", "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", "反馈回复","#000000"))
                .addData(new WxMpTemplateData("keyword2", DateUtil.formatChineseDate(weChatDialogue.getCreateTime(),false)+" "+DateUtil.formatTime(weChatDialogue.getCreateTime()), "#000000"))
                .addData(new WxMpTemplateData("keyword3", "好的", "#000000"))
                .addData(new WxMpTemplateData("remark", "感谢您的反馈!", "#000000"));
        String msgId = null;
        try {
            // 发送模板消息
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        log.warn("·==++--·反馈通知微信模板信息:{}·--++==·", msgId != null ? "成功" : "失败");
        return msgId != null;

那就开始推吧

测试

前面的逻辑都完成了 那么直接写个Controller测试了

@GetMapping("/senFeedBackMsg/{msgId}")
public AjaxResult sendFeedbackMsg(@PathVariable("msgId") Long msgId){
     WeChatDialogue weChatDialogue = weChatDialogueService.select(msgId);
     weChatDialogueService.senFeedBackMsg(weChatDialogue);
     return AjaxResult.success();
}