H5页面获取openid,完成支付公众号(未关注公众号)支付
一、页面授权
// 进入页面获取权限code function initAuthorizeCode() { var appid = $("#appid").val();//公众号appid var openid = $("#openId").val();//openid var userId = $("#userId").val(); var code = getUrlParam('code'); var local = window.location.href; var hrefurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+encodeURIComponent(local)+"&response_type=code&scope=snsapi_base&state=dcabe11a-751f-490f-9dcc-606881c6fcdb#wechat_redirect"; var localopenid = localStorage.getItem("loginStorageKey"+userId); if((code==null || code == "")&&(openid==null||openid==""||openid=="null")){ window.location.href = hrefurl; // window.location.replace(hrefurl); }else{ // var localopenid = localStorage.getItem("loginStorageKey"+userId); if(openid==undefined || openid=="" || openid==null|| openid=="null"||openid=="undefined"){ console.info(code); $.ajax({ url: basePath+'loginController/getOpenId', type:'post', dataType:'json', data:{code:code}, async:false, success:function(result){ console.info(result); localStorage.setItem("loginStorageKey"+userId,result.openid); result = true; }, error:function(msg){ console.info(msg); }, }); } } }
二、通过code获取openid
@RequestMapping(value = "/getOpenId") public @ResponseBody String getOpenId(HttpServletRequest request) { Map<String, Object> maps = new HashMap<String, Object>(); maps.put("succ", true); maps.put("msg", "success"); String code = request.getParameter("code"); String openId = (String) request.getSession().getAttribute("wx_user_openid"); try { // 调用查询接口 如果还是失败返回失败页面 WxOauthLogin wxAuth = new WxOauthLogin(); String url = wxAuth.getAccessTokenUrl(code); log.info("获取用户openid请求参数 result param:{}", url); URL urlObject = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) urlObject.openConnection(); // 将返回的输入流转换成字符串 InputStream inputStream = urlConnection.getInputStream(); // 指定编码格式 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader in = new BufferedReader(inputStreamReader); String jsonUserStr = in.readLine().toString(); // 释放资源 inputStream.close(); inputStream = null; urlConnection.disconnect(); log.info("通过code换取网页授权access_token result:{}", jsonUserStr); if (jsonUserStr != null) { Map<String, String> resultmap = Json.toObject(jsonUserStr, Map.class); if (StringUtil.empty(resultmap.get("openid"))) { log.error("获取openid失败"); maps.put("succ", false); maps.put("msg", "获取openid失败"); } else { maps.put("openid", resultmap.get("openid")); maps.put("unionid", resultmap.get("unionid")); // 将openId放到缓存 if(ObjectUtils.isEmpty(openId)){ openId = resultmap.get("openid"); request.getSession().setAttribute("wx_user_openid", openId); maps.put("openid", openId); } } } } catch (Exception e) { log.error("获取openid失败"); maps.put("succ", false); maps.put("msg", "获取openid失败"); } log.info("获取用户openid执行结果:{}",Json.toJson(maps)); return Json.toJson(maps); // return openId; }
三、根据code获取openid
public String getAccessTokenUrl(String code) { // ?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token"); url.append("?appid=" + wxResourceProp.getAppid()); url.append("&secret=" + wxResourceProp.getAppsecret()); url.append("&code=" + code); url.append("&grant_type=authorization_code"); return url.toString(); }
至此未关注公众号的微信用,可以用jsapi支付方式支付公众号里的订单。