当前位置: 首页 > 工具软件 > java-openid > 使用案例 >

java 微信开放平台、公众平台获取 openid以及unionid

浦墨竹
2023-12-01

    

  • 测试框架springboot。
  • 开发平台只是PC扫码登录,获取的openid跟公众平台获取的openid不同,所以要获取唯一的unionid。
  • 需要微信公众号,以及开放平台账号。本demo用的正式公众号,开放平台需绑定开发所需公众号。无需关注可获取用户信息
  • 需要内网穿透的请下载natapp 官网地址 https://natapp.cn/,使用教程:NATAPP1分钟快速新手图文教程
  • 公众号配置在这不说了。就是一系列申请。
  • 不跳转显示二维码,页面自定义位置扫码。
  • <!-- 微信开放平台二维码js-->
    	<script th:src="@{http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js}">
    
    
    
    <!-- js 请求二维码  建议ajax获取公众平台的各种参数-->
    
      var obj = new WxLogin({
    			        id:"login_container",
    			        appid: "appid",//开放平台appid
    			        scope: "snsapi_login",
    			        redirect_uri: "redirect_uri",//请求回调的url 这需要全路径带域名的 例 
                                                       如: https://xxx.net/getWeChatCallback 
    			        state: "请求校验值",//自定的的值,后台存缓存或者存redis中 防止csrf攻击
    			        style: "black",//这个是二维码样式
    			        href: ""//二维码样式引用链接 也需要带域名
    			    }); 
    
    <!-- 显示二维码的div-->
     <div  id="login_container">
                  
     </div>
    

    后台代码 

  • openWeChatLogin 是直接请求跳转扫码的方法 

  • getWeChatCallback  请求成功回调方法 用于上面JS内容部分 的redirect_uri   例如: https://xxx.net/getWeChatCallback 


   //微信开放平台请求二维码方法
    @RequestMapping("/openWeChatLogin")
    public String openWeChatLogin(HttpServletRequest request,HttpServletRequest 
    httpServletRequest) {
    	 // 防止csrf攻击(跨站请求伪造攻击)
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        CacheUtils.put("state", state);
      //  https://open.weixin.qq.com/connect/oauth2/authorize?
        String url = "https://open.weixin.qq.com/connect/qrconnect?" +
        		     "appid=" +
        		     env.getProperty("wechat.open.appid").trim() +
        		     "&redirect_uri=" +
        		     env.getProperty("application.url") +
        		     env.getProperty("wechat.open.redirect_uri").trim() +
        		     "&response_type=code" +
        		     "&scope=snsapi_login" +
        		     "&state=" +
        		      state + // 由后台自动生成
        		     "#wechat_redirect";
        return "redirect:" + url;	
      }

 //微信开发平台回调方法
    @RequestMapping("/getWeChatCallback")
    public String getWeChatCallback(HttpServletRequest request,HttpServletRequest httpServletRequest) {
    	 String code = httpServletRequest.getParameter("code");
    	 String state = httpServletRequest.getParameter("state");
    	// 判断state是否合法
    	 String stateStr = (String) CacheUtils.get("state");//缓存取值
    	 if (StringUtils.isEmpty(code) || StringUtils.isEmpty(stateStr) || !state.equals(stateStr)) {
    		 return "illegalityRequest"; //不合法跳转提示页面
    	  }
    	 String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
    			 "appid=" +
    			env.getProperty("wechat.open.appid").trim() +
    			"&secret=" +
    			env.getProperty("wechat.open.appsecret").trim() +
    			"&code=" +
    			 code +
    			"&grant_type=authorization_code";
    	  try {
    		// 调用请求方法
  			    String json = urlToJson(url);
  			    JSONObject json1 = JSONObject.parseObject(json.toString());
	            String unionid = json1.get("unionid").toString();
	            if(StringUtils.isNotEmpty(unionid) ) {
	            	TSBaseUser baseUser = tSBaseUserService.selectTSBaseUserByOpenId(unionid);
	            	if(baseUser != null) {
	            		CustomizedToken token = new CustomizedToken(baseUser.getUsername(), baseUser.getPassword() ,LoginType.APP.toString());
	            		Subject subject = SecurityUtils.getSubject();
	            		 try
	            	        {
	            	            subject.login(token);
	            	            return "index";	 
	            	        }  
	            		 catch (AuthenticationException e){
	            	            String msg = "登录失败";
	            	        }
	            	}else {
	            		 //跳转绑定页面  用户再次登录绑定微信openid
	            		 request.setAttribute("openid",unionid);
	            		 return "weChatBinding";
	            	}
	            }else {
	            	//获取openid 失败 
	            }
	        } catch (JsonParseException e) {
	        	 System.out.println("json解析失败:");
	        } catch (Exception e) {
	        	 System.out.println("http获取openId请求失败:");
	        }
    	  return "login";
    }

 /**
	* 对url发送请求并获取返回的数据
	 * 
	 * @param url
	 * @return
	 */
	public String urlToJson(String url) {
		StringBuffer json1 = new StringBuffer();
		try {
			URL oracle = new URL(url);
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "utf-8"));
			String inputLine = null;
			// StringBuffer json1 = new StringBuffer();
			while ((inputLine = in.readLine()) != null) {
				json1.append(inputLine);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return json1.toString();
	}
//微信公众平台请求二维码方法
    @RequestMapping("/openWeChatLogin")
    public String openWeChatLogin(HttpServletRequest request,HttpServletRequest 
    httpServletRequest) {
    	 // 防止csrf攻击(跨站请求伪造攻击)
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        CacheUtils.put("state", state);
      //  https://open.weixin.qq.com/connect/oauth2/authorize?
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
        		     "appid=" +
        		     env.getProperty("wechat.open.appid").trim() +
        		     "&redirect_uri=" +
        		     env.getProperty("application.url") +
        		     env.getProperty("wechat.open.redirect_uri").trim() +
        		     "&response_type=code" +
        		     "&scope=snsapi_userinfo" +
        		     "&state=" +
        		      state + // 由后台自动生成
        		     "#wechat_redirect";
        return "redirect:" + url;	
      }
    //微信公众平台回调方法
    @RequestMapping("/getWeChatCallback")
    public String getWeChatCallback(HttpServletRequest request,HttpServletRequest httpServletRequest) {
    	 String code = httpServletRequest.getParameter("code");
    	 String state = httpServletRequest.getParameter("state");
    	 String url = null;
    	 // 判断state是否合法
    	 String stateStr = (String) CacheUtils.get("state");//缓存取值
    	 if (StringUtils.isEmpty(code) || StringUtils.isEmpty(stateStr) || !state.equals(stateStr)) {
    		 return "illegalityRequest";
    	  }
    	 url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
    			 "appid=" +
    			env.getProperty("wechat.open.appid").trim() +
    			"&secret=" +
    			env.getProperty("wechat.open.appsecret").trim() +
    			"&code=" +
    			 code +
    			"&grant_type=authorization_code";
    	  try {
    		// 调用请求方法
  			    String json = urlToJson(url);
  			    JSONObject json1 = JSONObject.parseObject(json.toString());
	            String unionid = json1.get("unionid").toString();
	            if(StringUtils.isNotEmpty(unionid) ) {
	            	TSBaseUser baseUser = tSBaseUserService.selectTSBaseUserByOpenId(unionid);
	            	if(baseUser != null) {
	            		CustomizedToken token = new CustomizedToken(baseUser.getUsername(), baseUser.getPassword() ,LoginType.APP.toString());
	            		Subject subject = SecurityUtils.getSubject();
	            		 try
	            	        {
	            	            subject.login(token);
	            	            return "index";	 
	            	        }  
	            		 catch (AuthenticationException e){
	            	            String msg = "登录失败";
	            	        }
	            	}else {
	            		 //跳转绑定页面  用户再次登录绑定微信openid
	            		 request.setAttribute("openid",unionid);
	            		 return "weChatBinding";
	            	}
	            }else {
	            	//获取openid 失败 
	            }
	        } catch (JsonParseException e) {
	        	 System.out.println("json解析失败:");
	        } catch (Exception e) {
	        	 System.out.println("http获取openId请求失败:");
	        }
    	  return "login";
    }
 /**
	* 对url发送请求并获取返回的数据
	 * 
	 * @param url
	 * @return
	 */
	public String urlToJson(String url) {
		StringBuffer json1 = new StringBuffer();
		try {
			URL oracle = new URL(url);
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "utf-8"));
			String inputLine = null;
			// StringBuffer json1 = new StringBuffer();
			while ((inputLine = in.readLine()) != null) {
				json1.append(inputLine);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return json1.toString();
	}

 

 类似资料: