Java实现微信公众号模板消息推送给用户

  1. 创建消息模板实体对象
package com.htdz.ydkx.wxModelMsg.entity;

public class Content {

   private String value;//消息内容
   private String color;//内容颜色

   public String getValue() {
       return value;
   }

   public void setValue(String value) {
       this.value = value;
   }

   public String getColor() {
       return color;
   }

   public void setColor(String color) {
       this.color = color;
   }
}
package com.htdz.ydkx.wxModelMsg.entity;

public class MsgData {

  private  Content first;
  private  Content keyword1;
  private  Content keyword2;
  private  Content keyword3;
  private  Content keyword4;
  private  Content keyword5;
  private  Content remark;

  public Content getFirst() {
      return first;
  }

  public void setFirst(Content first) {
      this.first = first;
  }

  public Content getKeyword1() {
      return keyword1;
  }

  public void setKeyword1(Content keyword1) {
      this.keyword1 = keyword1;
  }

  public Content getKeyword2() {
      return keyword2;
  }

  public void setKeyword2(Content keyword2) {
      this.keyword2 = keyword2;
  }

  public Content getKeyword3() {
      return keyword3;
  }

  public void setKeyword3(Content keyword3) {
      this.keyword3 = keyword3;
  }

  public Content getKeyword4() {
      return keyword4;
  }

  public void setKeyword4(Content keyword4) {
      this.keyword4 = keyword4;
  }

  public Content getKeyword5() {
      return keyword5;
  }

  public void setKeyword5(Content keyword5) {
      this.keyword5 = keyword5;
  }

  public Content getRemark() {
      return remark;
  }

  public void setRemark(Content remark) {
      this.remark = remark;
  }
}

package com.htdz.ydkx.wxModelMsg.entity;

public class TemplateMsg {

  //用户openid
  private String touser;

  //模板消息ID
  private String template_id;

  //详情跳转页面
  private String url;

  //模板数据封装实体
  private MsgData data;

  public String getTouser() {
      return touser;
  }

  public void setTouser(String touser) {
      this.touser = touser;
  }

  public String getTemplate_id() {
      return template_id;
  }

  public void setTemplate_id(String template_id) {
      this.template_id = template_id;
  }

  public String getUrl() {
      return url;
  }

  public void setUrl(String url) {
      this.url = url;
  }

  public MsgData getData() {
      return data;
  }

  public void setData(MsgData data) {
      this.data = data;
  }
}

消息模板
在这里插入图片描述

  1. 先获取用于发送消息模板的access_token,创建HttpClientService.java
//因为微信的access_token的有效期是2小时,所以用一个全局变量保存
//可以设置一个定时job,每隔1个半小时更新一次access_token
private static String ACCESS_TOKEN = "";

/**
通过https get请求获取access_token
*/
public void sendHttpGetRequest(){
       String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
       try{
      	   //替换url中的参数
           url = url.replace("APPID","公众号的appid");
           url = url.replace("APPSECRET","公众号的appsecret");
           //创建默认的httpclient客户端
           CloseableHttpClient client = HttpClients.createDefault();
           //通过请求的url初始化一个HttpGet请求
           HttpGet httpGet = new HttpGet(url);
           //通过客户端来执行请求
           CloseableHttpResponse response = client.execute(httpGet);
           //处理返回的结果
           //获得响应行 200:响应成功
           if(response.getStatusLine().getStatusCode() == 200){
               //获得响应体
               HttpEntity httpEntity = response.getEntity();
               String content = EntityUtils.toString(httpEntity,"utf-8");
               JSONObject jsonObject = JSONObject.parseObject(content);
               ACCESS_TOKEN = jsonObject.getString("access_token");
           }
       }catch (Exception e){
           e.printStackTrace();
       }
   }
  1. 发送模板消息方法(HttpClientService.java)
/**
    * 微信模板消息推送请求 http post 请求
    * @return
    */
   public static JSONObject sendWXMsgRequest(String url,String data){
       JSONObject jsonObject = null;
       try {
           //创建默认的httpClient客户端
           CloseableHttpClient client = HttpClients.createDefault();
           //通过请求的url初始化一个httpPost
           HttpPost httpPost = new HttpPost(url);
           //参数设置
           httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
           httpPost.addHeader("Accept","application/json");
           // 参数设置
           JSONObject obj = JSONObject.parseObject(data);
           // 解决中文乱码问题
           StringEntity stringEntity = new StringEntity(obj.toString(), "UTF-8");
           stringEntity.setContentEncoding("UTF-8");
           httpPost.setEntity(stringEntity);
           CloseableHttpResponse response = client.execute(httpPost);
           //获得响应行 200:响应成功
           if(response.getStatusLine().getStatusCode() == 200){
               //获得响应体
               HttpEntity httpEntity = response.getEntity();
               String content = EntityUtils.toString(httpEntity,"utf-8");
               logger.info("content:"+content);
               jsonObject = JSONObject.parseObject(content);
           }
       }catch (Exception e){
           e.printStackTrace();
       }
       return jsonObject;
   }
 /**
   * 获取微信token
   * @return
   */
  public static String getToken(){
      return ACCESS_TOKEN;
  }
  1. 创建TemplateSendImpl.java类,调用sendWXMsgRequest()方法
package com.htdz.ydkx.wxModelMsg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.htdz.ydkx.wxModelMsg.entity.Content;
import com.htdz.ydkx.wxModelMsg.entity.MsgData;
import com.htdz.ydkx.wxModelMsg.entity.TemplateMsg;
import com.htdz.ydkx.wxModelMsg.service.TemplateSendI;
import com.htdz.ydkx.wxModelMsg.util.HttpClientService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service("templateSend")
public class TemplateSendImpl implements TemplateSendI {

   private static final Logger logger = Logger.getLogger(TemplateSendImpl.class);

   @Override
   public String sendTemplateMsg(String content) {
       String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
       String access_token = HttpClientService.getToken();
       String returnMsg = "";
       try{
           url = url.replace("ACCESS_TOKEN",access_token);
           //调用微信微信模板推送接口
           JSONObject jsonObject = HttpClientService.sendWXMsgRequest(url,content);
           Integer errorCode = jsonObject.getInteger("errcode");
           if(null != jsonObject){
               if(errorCode == 0){
                   returnMsg = "模板推送成功!";
               }else{
                   returnMsg = "模板推送失败!";
               }
           }else{
               returnMsg = "模板推送失败!";
           }
       }catch (Exception e){
           e.printStackTrace();
       }
       return returnMsg;
   }
}
  1. 设置定时任务,生成access_token
package com.htdz.ydkx.job;

import com.htdz.ydkx.wxModelMsg.util.HttpClientService;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TemplateMsgSendJob {

  private static final Logger logger = Logger.getLogger(TemplateMsgSendJob.class);

  @Scheduled(cron="0 30 */1 * * ?")
  public void test(){
      logger.info("开始调用获取微信token方法TemplateMsgSendJob");
      try{
          HttpClientService httpClientService = new HttpClientService();
          httpClientService.sendHttpGetRequest();
      }catch (Exception e){
          e.printStackTrace();
      }
      logger.info("结束调用获取微信token方法");
  }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值