liang-chen-fly

依赖

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

配置

package com.ruoyi.community.common;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WxConfig {

   @Bean
   public WxMpConfigStorage wxMpConfigStorage() {
       WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
       // 公众号appId
       configStorage.setAppId("xx");
       // 公众号appSecret
       configStorage.setSecret("xx");
       // 公众号Token
       configStorage.setToken("123456456");
       // 公众号EncodingAESKey
//       configStorage.setAesKey("xx");
       return configStorage;
  }

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

工具类

package com.ruoyi.community.common;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WxMsgPush {

   /**
    * 微信公众号API的Service
    */
   private final WxMpService wxMpService;

   /**
    * 构造注入
    */
   WxMsgPush(WxMpService wxMpService) {
       this.wxMpService = wxMpService;
  }


   /**
    * 发送微信模板信息
    *
    * @param openId 接受者openId
    * @return 是否推送成功
    */
   public Boolean SendWxMsg(String openId) {
       // 发送模板消息接口
       WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
               // 接收者openid
              .toUser(openId)
               // 模板id
              .templateId("xx-xx")
               // 模板跳转链接
              .url("http://www.baidu.com")
              .build();
       // 添加模板数据
       templateMessage.addData(new WxMpTemplateData("msg", "您好", "#FF00FF"));
       String msgId = null;
       try {
           // 发送模板消息
           msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
      } catch (WxErrorException e) {
           e.printStackTrace();
      }
       log.warn("·==++--·推送微信模板信息:{}·--++==·", msgId != null ? "成功" : "失败");
       return msgId != null;
  }
}

接口

 @PostMapping("/sendWxInfo")
   public void sendWxInfo(String openId) {
       // 执行发送
       Boolean aBoolean = wxMsgPush.SendWxMsg(openId);
       System.out.println(aBoolean);
  }

 

分类:

技术点:

相关文章: