微信公众号的推送
3个基本参数,公众号id , 秘钥,模板id
一,引入maven
<!--公众号的--> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>3.6.0</version> </dependency>
二。 公众号id , 秘钥,模板id的配置
配置了这个就需要对应这个配置的Component了(实体类)
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class WxConfig { //消息模板id public static String approvalTemplateId; //跳转路径 public static String toUrl; //公众号id public static String appid; public static String messageTemplateId; //秘钥 public static String appSecret; @Value("${messageTemplateId}") public void setMessageTemplateId(String messageTemplateId) { WxConfig.messageTemplateId = messageTemplateId; } @Value("${approvalTemplateId}") public void setTemplateId(String approvalTemplateId){ WxConfig.approvalTemplateId = approvalTemplateId; } @Value("${toUrl}") public void setToUrl(String toUrl) { WxConfig.toUrl = toUrl; } @Value("${appId}") public void setAppid(String appid) { WxConfig.appid = appid; } @Value("${appSecret}") public void setAppSecret(String appSecret) { WxConfig.appSecret = appSecret; } }
模板不展示
三。获取openId
@PostMapping("/getOpen") @ApiOperation("获取用户openId") public Result<Map<String, String>> getOpen(@RequestBody BaseRequest baseRequest, HttpServletRequest request) throws Exception { return Result.OK(messageTableService.getOpen(baseRequest,request)); }
public Map<String, String> getOpen(BaseRequest baseRequest, HttpServletRequest request) throws Exception { String WXPUBLIC_ID = WxConfig.appid; String APPSECRET = WxConfig.appSecret; String GETOPENID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?"; log.info("code---->>>>{}", baseRequest.getCode()); String getOpenIdUrl = GETOPENID_URL + "appid=" + WXPUBLIC_ID + "&secret=" + APPSECRET + "&code=" + baseRequest.getCode() + "&grant_type=authorization_code"; RestTemplate rest = new RestTemplate(); rest.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String resString = null; try { resString = rest.getForObject(new URI(getOpenIdUrl), String.class); } catch (URISyntaxException e) { e.printStackTrace(); } JSONObject opidJsonObject = JSONObject.parseObject(resString); if (ObjectUtils.isEmpty(opidJsonObject)) { throw new WokeException(202090, "获取openId失败"); } log.info("获取openId{}" + opidJsonObject); String openid = opidJsonObject.get("openid").toString(); // ------------------------- Map<String, String> map = new HashMap<>(); String timeStap = String.valueOf(System.currentTimeMillis() / 1000); String nonceStr = UUIDUtils.getRandomString(24); map.put("appId", WXPUBLIC_ID); map.put("timeStamp", timeStap); map.put("nonceStr", nonceStr); map.put("signType", "SHA-1"); String paySign = getSignature(baseRequest.getUrl(), timeStap, nonceStr); map.put("paySign", paySign); map.put("openId", openid); return map; }
public String getSignature(String url, String timeStap, String nonceStr) { String signature = ""; String WXPUBLIC_ID = WxConfig.appid; String APPSECRET = WxConfig.appSecret; String appid = WXPUBLIC_ID;//微信公众号的appid String appsecret = APPSECRET;//微信公众号的appsecret //获取access_token String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret; RestTemplate rest = new RestTemplate(); rest.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String resString = ""; try { resString = rest.getForObject(new URI(GetPageAccessTokenUrl), String.class); System.out.println("resString1111{}" + resString); } catch (URISyntaxException e) { e.printStackTrace(); } JSONObject opidJsonObject = JSONObject.parseObject(resString); String access_token = String.valueOf(opidJsonObject.get("access_token")); //获取jspai_ticket String jsapi_ticket = getTicket(access_token); //将四个数据进行组合,传给SHA1进行加密 String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "×tamp=" + timeStap + "&url=" + url; //sha1加密 signature = SHA1(str); return signature; } public String SHA1(String str) { try { MessageDigest digest = java.security.MessageDigest .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可 digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexStr = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexStr.append(0); } hexStr.append(shaHex); } return hexStr.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public String getTicket(String accessToken) { // 网页授权接口 String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"; HttpUtil client = null; String ticket = ""; int expires_in = 0; try { RestTemplate rest = new RestTemplate(); rest.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String resString = null; try { resString = rest.getForObject(new URI(GetPageAccessTokenUrl), String.class); } catch (URISyntaxException e) { e.printStackTrace(); } JSONObject opidJsonObject = JSONObject.parseObject(resString); System.out.println("获取Ticket{}" + opidJsonObject); ticket = String.valueOf(opidJsonObject.get("ticket"));//获取ticket expires_in = Integer.parseInt(String.valueOf(opidJsonObject.get("expires_in")));//获取时间 } catch (Exception e) { throw new WokeException(10023, "获取Ticket出错!"); } return ticket; }
四,发送消息(参数自定义)直接调接口
/*** * 发送消息 * @param */ public boolean sendWeChatMsg(Long messionId, Integer type, ApproveInfoVo approveInfoVo) throws FinanceException, ParseException { log.info("推送消息开始<<<"); String token = getToken(); //接口地址 String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token; //审批消息模板ID String approvalTemplateId = WxConfig.approvalTemplateId; String toUrl = WxConfig.toUrl; String msgId=""; // 后台推送 if (type==0){ String messageTemplateId= WxConfig.messageTemplateId; // 查询消息是否存在 MessageTable messageTable=messageTableMapper.queryById(messionId); if (ObjectUtils.isEmpty(messageTable)){ throw new FinanceException(111,"该条消息记录不存在"); } // 拿到推送范围(具体到人) String[] pushRange = messageTable.getPushRange().split(","); for (String a:pushRange) { //拿到每个人的openId UserManagement userManagement=userManagementMapper.queryById(Long.valueOf(a)); String toUser = userManagement.getOpenId(); log.info("接受者的openId: {}", toUser); //整体参数map Map<String, Object> paramMap = new HashMap<>(); //消息主题显示相关map Map<String, Object> dataMap = new HashMap<>(); dataMap.put("first",new DataEntity("有新通知,等待您确认","#173177")); dataMap.put("keyword1",new DataEntity(messageTable.getId(),"#173177")); dataMap.put("keyword2",new DataEntity(messageTable.getTitle(),"#173177")); dataMap.put("keyword3",new DataEntity(messageTable.getUserName(),"#173177")); dataMap.put("keyword4",new DataEntity(messageTable.getText(),"#173177")); dataMap.put("keyword5",new DataEntity(messageTable.getText(),"#173177")); dataMap.put("remark",new DataEntity("请及时确认是否接待","#173177")); paramMap.put("touser", toUser); paramMap.put("template_id", messageTemplateId); paramMap.put("url", toUrl); paramMap.put("data", dataMap); RestTemplate template = new RestTemplate(); String resultMsg = template.postForObject(sendMsgApi, paramMap, String.class); log.info("推送消息返回的报文: {}", resultMsg); msgId = JSONObject.parseObject(resultMsg).getString("msgid"); } }else if ( type==1){ //审批处理 if (ObjectUtils.isEmpty(approveInfoVo.getOpenId())){ throw new FinanceException(111,"openId未找到"); } String toUser = approveInfoVo.getOpenId(); log.info("接受者的openId: {}", toUser); //整体参数map Map<String, Object> paramMap = new HashMap<>(); //消息主题显示相关map Map<String, Object> dataMap = new HashMap<>(); dataMap.put("first",new DataEntity("财务系统通知","#173177")); dataMap.put("keyword1",new DataEntity(approveInfoVo.getApproveNum(),"#173177")); dataMap.put("keyword2",new DataEntity(approveInfoVo.getApproveType(),"#173177")); dataMap.put("keyword3",new DataEntity(approveInfoVo.getApplyUser(),"#173177")); dataMap.put("keyword4",new DataEntity(approveInfoVo.getApplyTime(),"#173177")); dataMap.put("keyword5",new DataEntity(approveInfoVo.getApplyDetail(),"#173177")); dataMap.put("remark",new DataEntity("感谢您的使用,请尽快做出审批处理","#173177")); paramMap.put("touser", toUser); paramMap.put("template_id", approvalTemplateId); paramMap.put("url", toUrl); paramMap.put("data", dataMap); RestTemplate template = new RestTemplate(); String resultMsg = template.postForObject(sendMsgApi, paramMap, String.class); log.info("推送消息返回的报文: {}", resultMsg); msgId = JSONObject.parseObject(resultMsg).getString("msgid"); MessageTable messageTable=new MessageTable(); messageTable.setId(String.valueOf(snowFlake.nextId())); messageTable.setApproveNum(approveInfoVo.getApproveNum()); messageTable.setApproveType(approveInfoVo.getApproveType()); messageTable.setMessageType(1); messageTable.setDeleteFlag(0); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); messageTable.setCreateTime(sdf.parse(approveInfoVo.getApplyTime())); messageTable.setText(JSONObject.toJSONString(approveInfoVo.getApplyDetail())); messageTable.setApplyUser(approveInfoVo.getApplyUser()); messageTableMapper.insert(messageTable); } return null != msgId; }
/** * 获取token * @return token */ public String getToken(){ //授予形式 String grant_type = "client_credential"; String appid = WxConfig.appid; String secret = WxConfig.appSecret; //接口地址拼接参数 String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+appid+"&secret="+secret; RestTemplate template = new RestTemplate(); String tokenJsonStr = template.getForObject(getTokenApi, String.class); JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr); log.info("获取tokenJson: {}", JSONObject.toJSONString(tokenJson)); String token = tokenJson.get("access_token").toString(); log.info("获取到的TOKEN: " + token); return token; }
五,结果