微信公众号授权获取用户OpenID和UnionId然后发生消息通知
1.获取微信公众号code1.微信公众拿取公众号appid和appSecret2.网页域名授权,这里的域名拼接上html所在位置即可访问html3.设置公众号开发者4.java代码获取code(这里可以获取code但是前端截取不太方便)5.html中获取code 2.获取openIDjava代码获取公众号openID 3.获取UnionId1.获取unionId需要access_token2.获取unionId 4.发送消息通知1.建立消息模板2.java实现发送消息通知1.获取微信公众号code
1.微信公众拿取公众号appid和appSecret
图片里的ip白名单是html所在的服务器ip
2.网页域名授权,这里的域名拼接上html所在位置即可访问html
3.设置公众号开发者
公众号与小程序不同,所以公众号授权需要通过h5页面进行授权
4.java代码获取code(这里可以获取code但是前端截取不太方便)
@RequestMapping("/getCode")public String getCode() {// 官方地址String urlFir = "redirect:https://open./connect/oauth2/authorize?appid=";// 微信申请的域名(提前准备)String domain = "";// 自定义跳转方法 这个路径是html放在服务器上的位置String redirectMethod = "/wx/index.html";// 地址进行encode转译 (未转译的地址是:/wx/index.html)////复制此地址到浏览器上可以直接访问// 转译后的地址是: http%3A%2F%%2Fwxpay%2FweixinoauthString encoderUrl = getURLEncoderString(domain + redirectMethod);String url = urlFir +appId + "&redirect_uri=" +encoderUrl+"&response_type=code&scope=snsapi_base"+ "&state=STATE" + "#wechat_redirect";log.info(url);return url;}/*** 编码* @param str* @return*/public static String getURLEncoderString(String str) {String result = "";if (null == str) {return "";}try {result = .URLEncoder.encode(str, "GBK");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}
5.html中获取code
const { origin } = window.location //获取域名//const currentUrl = encodeURIComponent(`${origin}/wx/index.html`)这个方式我没法使用const currentUrl = decodeURIComponent(`${origin}/wx/index.html`)//对域名进行转码//获取微信公众号codeconst redirectUrl = `https://open./connect/oauth2/authorize?appid=微信公众号id&&redirect_uri=${currentUrl}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;const code = this.getQueryString('code')
2.获取openID
java代码获取公众号openID
@ResponseBody@GetMapping("/getOpenId")public Map<String, String> getOpenId(@RequestParam("code") String code ) throws Exception {Map<String, String> map = new HashMap<String, String>();String url = "https://api./sns/oauth2/access_token?" +"appid="+appId+"&secret="+appIdSecret+"&code="+code+"&grant_type=authorization_code";RestTemplate restTemplate = new RestTemplate();String wxResult = restTemplate.getForObject(url, String.class);JSONObject jsonObject = JSON.parseObject(wxResult);log.info(jsonObject.toString());String access_token = jsonObject.getObject("access_token", String.class);String openid = jsonObject.getObject("openid", String.class);String unionid = jsonObject.getObject("unionid", String.class);map.put("url", url);map.put("access_token", access_token);map.put("unionid", unionid);map.put("openid", openid);log.info(url);return map;}
3.获取UnionId
1.获取unionId需要access_token
@GetMapping("/getToken")@ResponseBodypublic String getAccessToken() throws Exception{String url = "https://api./cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret=" + appIdSecret;String res = HttpUtil.get(url);JSONObject jsonObject = JSONObject.parseObject(res);String accessToken = jsonObject.getString("access_token");return accessToken;}
2.获取unionId
@ResponseBody@GetMapping("/getUnionid")public Map<String, String> getUnionid(@RequestParam("token") String token) throws Exception {//获取unionidString unionIdUrl = "https://api./cgi-bin/user/info?access_token=" + token+ "&openid="+openid+"&lang=zh_CN";RestTemplate unionIdTemplate = new RestTemplate();String unionIdResult = unionIdTemplate.getForObject(unionIdUrl, String.class);JSONObject unionIdJson = JSON.parseObject(unionIdResult);log.info(unionIdJson.toString());String unionid = unionIdJson.getObject("unionid", String.class);map.put("unionid", unionid);log.info(unionIdUrl );return map;}
4.发送消息通知
1.建立消息模板
2.java实现发送消息通知
java代码实现公众号发送消息通知
@GetMapping("/sendMessage")@ResponseBodypublic String sendMessage(@RequestParam("openId") String openId, @RequestParam("accessToken")String accessToken) {// 模板参数Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();// openId代表一个唯一微信用户,即微信消息的接收人String openId1 = "XXX";// 公众号的模板id(也有相应的接口可以查询到)String templateId = "XXXXX";// 微信的基础accessTokenString accessToken1 = "XXXX";String url = "https://api./cgi-bin/message/template/send?access_token=" + accessToken;/*** 其他模板可以从模板库中自己添加*/sendMag.put("first", new WeChatTemplateMsg("您有一天新的设备通知"));sendMag.put("keyword1", new WeChatTemplateMsg("生产进度异常请及时查看!"));sendMag.put("keyword2", new WeChatTemplateMsg("-01-05"));// sendMag.put("keyword3", new WeChatTemplateMsg("333"));// sendMag.put("keyword4", new WeChatTemplateMsg("444"));sendMag.put("remark", new WeChatTemplateMsg("请及时查看。"));RestTemplate restTemplate = new RestTemplate();//拼接base参数Map<String, Object> sendBody = new HashMap<>();sendBody.put("touser", openId);// openIdsendBody.put("url", ""); // 点击模板信息跳转地址sendBody.put("topcolor", "#FF0000");// 顶色sendBody.put("data", sendMag); // 模板参数sendBody.put("template_id", templateId);// 模板IdResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);log.info("结果是: {}",forEntity.getBody());JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody());String messageCode = jsonObject.getString("errcode");String msgId = jsonObject.getString("msgid");System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);return forEntity.getBody();}
下面附上详细代码,有需要的的可以下载一波
微信公众发送消息通知,java代码
/download/qq_39095085/87448456
公众号消息通知授权html
/download/qq_39095085/87448461