企业微信消息推送

zengfanpei 2019-12-17

@Slf4j
@Component
public class WxMessageTask {

    @Autowired
    private CorpWechatConfig corpWechatConfig;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RestTemplate restTemplate;

    /**
    * @Description: 企业微信消息推送 每天9点推送一次
    * @Param: []
    * @return: void
    * @Date: 2019-12-17
    */
//    @Scheduled(cron = "0 0 9 1/1 * ? *")
    public void pushMessage(){
        log.info("消息发送开始 时间:[{}]", LocalDateTime.now());
        //1.获取access_token 这里是讲access_token 放到缓存中了,也可以自己通过企业id 和 企业secret去获取
        String accessToken = (String) redisService.get(WxMsgConstant.TOKEN);
        if (StringUtils.isBlank(accessToken)){
            //添加重试
            throw new BusinessException("access_token无法获取");
        }
        //2.构造请求
        String url = String.format(corpWechatConfig.getSendMessageUrl(), accessToken);
        HttpHeaders headers=new HttpHeaders();
        MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
        //发送用户
        map.add(WxMsgConstant.TO_USER,"@all");
        //消息类型
        map.add(WxMsgConstant.MSG_TYPE,"text");
        // 企业应用id 整形
        map.add(WxMsgConstant.AGENT_ID, corpWechatConfig.getAgentId());
        //消息内容
        map.add(WxMsgConstant.CONTENT, "企业日报已生成,请及时查看");
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        //3.发送
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
        String body = responseEntity.getBody();
        Map resultMap = JSON.parseObject(body, Map.class);
        if ((Integer)resultMap.get("errcode")==0) {
            log.error("消息发送失败");
        }
        log.info("消息发送成功 时间:[{}]", LocalDateTime.now());
    }

}

相关参数配置

@Data
@Component
@ConfigurationProperties(prefix = "corpwechat")
public class CorpWechatConfig {

    /** 企业Id */
    private String corpid;

    /** 企业号密钥 */
    private String corpsecret;
    
    /** 企业应用的id */
    private Integer agentId;
    
    /** 消息推送url */
    private String sendMessageUrl;
}

微信消息推送相关常量

public class WxMsgConstant {
    
    /** 接收消息的成员 */
    public  static final String TO_USER="toUser";
    
    /** 消息类型 */
    public static final String  MSG_TYPE="msgtype";

    /** 企业应用的id */
    public  static final String AGENT_ID="agentid";

    /** 消息内容 */
    public  static final String CONTENT="content";

    /** 微信access_token */
    public static final String TOKEN="WX_ACCESS_TOKEN";
}

相关推荐