zoukankan      html  css  js  c++  java
  • 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支付方式支付公众号里的订单。

  • 相关阅读:
    如何解决python连接数据库编码问题(python传数据到mysql乱码)'ascii' codec can't encode _mysql_exceptions.OperationalError: (1366, "Incorrect string value:?
    git 和 github 链接
    python 链接 redis 失败 由于目标计算机积极拒绝,无法连接
    假设检验,alpha,p值 通俗易懂的的理解。
    python 爬虫学习之路
    SQL邮件服务(解决各种疑难杂症)+案例 + 使用SQLserver 邮件系统发送SQL代理作业执行警告
    使用tomcat,不能连接localhost/8080的解决办法
    制作R中分词的字典的办法
    Windos 下python2.7安装 pymssql 解决方案
    R语言做相关性分析
  • 原文地址:https://www.cnblogs.com/sunshine052697/p/9708215.html
Copyright © 2011-2022 走看看