1. 首先获得微信的tokenID
package com.txj.bwbd.common.wechat.task; import com.txj.bwbd.constraint.WeixinConstants; import com.txj.bwbd.utils.WeChatCommonUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class WeChatAccessTokenTask { Logger logger = LoggerFactory.getLogger(WeChatAccessTokenTask.class); @Autowired private WeChatCommonUtil weChatCommonUtil; public static String token; // 第一次延迟1秒执行,当执行完后7100秒再执行 @Scheduled(initialDelay = 1000, fixedDelay = 7100*1000 ) // @Scheduled(initialDelay = 1000, fixedDelay = 7100*1000 ) public void WeChatAccessToken(){ try { token = weChatCommonUtil.getToken(WeixinConstants.APPID, WeixinConstants.APPSECRET).getAccess_token(); logger.info("获取到的微信access_token为"+token); } catch (Exception e) { logger.error("获取微信access_toke出错,信息如下"); e.printStackTrace(); } } }
package com.txj.bwbd.utils; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSONObject; import com.txj.bwbd.common.wechat.entity.AccessToken; import com.txj.bwbd.constraint.WeixinConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class WeChatCommonUtil { Logger logger = LoggerFactory.getLogger(WeChatCommonUtil.class); // 获取access_token的接口地址(GET) 限2000(次/天) private static String url = WeixinConstants.ACCESS_TOKEN_URL; public AccessToken getToken(String appid, String appsecret){ AccessToken token; //访问微信服务器的地址 String requestUrl=url.replace("APPID", appid).replace("APPSECRET", appsecret); //HttpRequestUtil httpRequestUtil=new HttpRequestUtil(); //创建一个json对象 String responseStr = HttpUtil.get(requestUrl); System.out.println("获取到的String格式的Response为:"+responseStr); //判断返回字符串是否为空 if (responseStr != null) { token = JSONObject.parseObject(responseStr, AccessToken.class); } else { token = null; // 获取token失败 logger.error("获取token失败 errcode:{} errmsg:{}"); } return token; } }
2.组装微信模板消息访问参数 调用微信发送模板消息接口
/** * post请求,发送消息 */ @RequestMapping(value = "/sendTemplateMessage", method = RequestMethod.POST) public String sendTemplateMessage() { WeChatTemplate weChatTemplate = new WeChatTemplate(); weChatTemplate.setTouser("o_Fm8s4563xOZfB05FYpS2IJmRHI"); weChatTemplate.setTemplate_id("TVNSDJdRNWEHQLMdLWWUcw-6gadxI1tBNeNaK0x40RE"); Map<String, TemplateData> dataMap = new HashMap<>(); dataMap.put("first", new TemplateData("这是第一", "#173177")); dataMap.put("keynote1", new TemplateData("这是第一", "#173177")); dataMap.put("keynote2", new TemplateData("这是第一", "#173177")); dataMap.put("keynote3", new TemplateData("这是第一", "#173177")); dataMap.put("remark", new TemplateData("这是第一", "#173177")); weChatTemplate.setData(dataMap); WeixinResponse weixinResponse = templateMessageService .sendTemplateMessage(WeChatAccessTokenTask.token, weChatTemplate); return "success"; }
package com.txj.bwbd.common.wechat.service; import com.txj.bwbd.common.wechat.entity.WeChatTemplate; import com.txj.bwbd.common.wechat.entity.WeixinResponse; public interface TemplateMessageService { WeixinResponse sendTemplateMessage(String accessToken, WeChatTemplate wechatTemplate); }
package com.txj.bwbd.common.wechat.service.impl; import com.txj.bwbd.common.wechat.entity.WeChatTemplate; import com.txj.bwbd.common.wechat.entity.WeixinResponse; import com.txj.bwbd.common.wechat.service.TemplateMessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.HashMap; @Service public class TemplateMessageServiceImpl implements TemplateMessageService { private RestTemplate restTemplate = new RestTemplate(); private String serviceHost = "https://api.weixin.qq.com"; @Override public WeixinResponse sendTemplateMessage(String accessToken, WeChatTemplate weChatTemplate) { WeixinResponse weixinResponse = null; String url = new StringBuffer(serviceHost).append("/cgi-bin/message/template/send?access_token=") .append(accessToken).toString(); weixinResponse = restTemplate.postForObject(url, weChatTemplate, WeixinResponse.class, new HashMap<String, String>()); return weixinResponse; } }
使用到的实体对象:
package com.txj.bwbd.common.wechat.entity; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class TemplateData { private String value; private String color; public TemplateData(String value, String color) { this.value = value; this.color = color; } }
package com.txj.bwbd.common.wechat.entity; import lombok.Data; import java.util.Map; @Data public class WeChatTemplate { private String touser; private String template_id; private String url; private Map<String, TemplateData> data; }
package com.txj.bwbd.common.wechat.entity; import lombok.Data; @Data public class WeixinResponse { private String msgid; private int errcode; private String errmsg; @Override public String toString() { StringBuffer buf = new StringBuffer("WeixinResponse[msgid="); buf.append(msgid) .append(",errcode=").append(errcode) .append(",errmsg=").append(errmsg) .append("]"); return buf.toString(); } }
使用idea httpCilent调用接口