WeChat authorization login process record

The overall process:

WeChat authorized login can be divided into four types:
1. Authorized login on the mobile terminal;
2. Authorized login on the website application side (only scan code login is supported. If it is a mobile phone access, then two mobile phones are required to complete the operation. It is not possible to take a screenshot and scan again. Yes, I tried to activate WeChat in the mobile browser for authorization, and found that there is no universal application. Only JD.com and Xiaomi web pages have integrated WeChat authorization login, which may have a separate interface or other interactive processes and methods);
3. Official account , Mini program authorized to log in;

4. Third-party platform (unused)

1. Official account authorization process and source code; (These tools can be found in SDK)

1. The client server gives an authorization interface (this place gives the callback address for WeChat to access the client server. Note that this address needs to be configured in the "Web Authorization" on the public platform):

	@RequestMapping(value = "/")
	public String login(){
    
    
//		String backUrl = "http://surenguangbo.com/suren/callBack";
		String backUrl = "http://xxx.com/sur-api/web";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
				+ "appid="+ WXLogin.APPID
				+ "&redirect_uri="+URLEncoder.encode(backUrl)
				+ "&response_type=code"
				+ "&scope=snsapi_userinfo"
				+ "&state=STATE#wechat_redirect";
		return "redirect:"+url;
	}

2. Get the code directly here and request WeChat to get the customer's information and openid and give it to the H5 page. The disadvantage of this method can only be the openid in the form of a get request, splicing it behind;

@RequestMapping(value="web")
	public String callBack(HttpServletRequest request) throws ClientProtocolException, IOException{
    
    
		String code = request.getParameter("code");
		// 获取openid
		String url  = "https://api.weixin.qq.com/sns/oauth2/access_token"
				+ "?appid="+WXLogin.APPID
				+ "&secret="+WXLogin.APPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject wxuser = WXLogin.doGetjson(url); 	 
		
		  String openid = wxuser.getString("openid");
		  System.out.println(openid);
		  String token = wxuser.getString("access_token");
		  System.out.println(token);
		  // 获取微信昵称、头像等用户信息
		  String infoUrl = "https://api.weixin.qq.com/sns/userinfo" 
		  		+ "?access_token="+token
		  		+ "&openid="+openid
		  		+ "&lang=zh_CN";
		  JSONObject userinfo = WXLogin.doGetjson(infoUrl); 
		  /*
		   * {"city":"新乡","country":"中国",
		   * "headimgurl":"http://wx.qlogo.cn/mmopen/j2wX8eqnnnhd0Ie6WeosMYuWibO0zoKPsmPbtJzqB6UCiaN3bic8zkkcGqyZWoiamzWqTDVM8OV58JB30ibv1NPboAiaj6g3eTwYnr/0",
		   * "language":"zh_CN",
		   * "nickname":"sup",
		   * "openid":"oUWMrwX2009ZBdhqlKi-rD0OeMSI",
		   * "privilege":[],
		   * "province":"河南",
		   * "sex":1}
		   */
//		  	获取用户的信息后,创建用户, 先判断用户是否存在,   不存在的话  创建,  存在的话省略 :
		  
		  String name = userinfo.getString("nickname");
		  String photo = userinfo.getString("headimgurl");
		  String openidUser = userinfo.getString("openid");
		  String id = null;
		  String userName = "";
		  List<TSurenUser> userList = tSurenUserService.selectOneUser(openid);
		  if(userList != null && userList.size() > 0){
    
    
			   userName = WXLogin.filterEmoji(name, "1");
			  // 该用户存在的话, 更新下头像和名称;
			  userList.get(0).setPhoto(photo);
			  userList.get(0).setUsername(userName);
			  boolean b = tSurenUserService.updateUserNameAndPhoto(userList.get(0));

		  }else{
    
    
			  if(StringUtils.isNotBlank(openidUser) && StringUtils.isNotBlank(name) && StringUtils.isNotBlank(photo) ){
    
    
				   userName = WXLogin.filterEmoji(name, "1");
				  TSurenUser user = new TSurenUser();
				  user.setOpenid(openidUser);
				  user.setPhoto(photo);
				  user.setUsername(userName);
				 boolean b = tSurenUserService.saveUser(user);
			  }
		  }

		  return "redirect:http://xxx.com/sur/index.html?openid="+openidUser;

	}

PS: This interface can be split into two interfaces, one returns the code to H5, and the other queries the current user openid and user information based on the code;

2. Website application authorization login:
1. The same as the official account authorization process, the code is directly uploaded here; but there are several issues that need to be paid attention to:
(1) Website application authorization login is performed on the "WeChat Open Platform" for parameter configuration;
(2) ) Need to apply for applications, some corporate information and website application information;
(3) You need to apply for developer qualifications to have interface permissions. It should be certified once a year. The certification fee in mainland China is 300 yuan. Application for certification on the public platform also costs , May not need to repeatedly charge;
(4) If the open platform is not bound to the official account, then the openid obtained by the same user is different, and there is a unionid that seems to be the same, and there is no specific research in the future. Interested Can be tested; (The
WeChat official account must be bound to the open platform to ensure that the openid of the same user is the same;) (5) The appId and AppSecret of the open platform are different, there are two sets;
(6) The address of the first step to get the code is different, mainly scope=snsapi_login

 unionid	用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。
//---------------- web 微信授权登陆
	@RequestMapping(value = "/webLogin")
	public String webLogin(){
    
    
		String backUrl = "http://xxx.com/sur/callBackWeb";
		String url = "https://open.weixin.qq.com/connect/qrconnect?"
				+ "appid="+ WXLogin.WEBAPPID
				+ "&redirect_uri="+URLEncoder.encode(backUrl)
				+ "&response_type=code"
				+ "&scope=snsapi_login";
		return "redirect:"+url;
	}

	/**
	 *  web端的回调地址
	 * @param request
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@RequestMapping(value="callBackWeb")
	public String callBackWeb(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException, ServletException {
    
    
		String code = request.getParameter("code");
		  return "redirect:http://xxx.com/index.html?code="+code+"#/buy";
	}

	/**
	 * 获取openid
	 * @param request
	 * @param vo
	 * @param response
	 * @return
	 * @throws IOException
	 */
    @RequestMapping(value="getOpenId")
    @ResponseBody
    public Result getOpenId(HttpServletRequest request, @RequestBody IndexVO vo,  HttpServletResponse response) throws IOException {
    
    
//        String code = request.getParameter("code");
        String code = request.getParameter("code");
        if(StringUtils.isBlank(code) || "null".equals(code)){
    
    
			code = vo.getCode();
				if(StringUtils.isBlank(code) || "null".equals(code)){
    
    
					return Result.error("未接收到code");
				}
        }

		String url  = "https://api.weixin.qq.com/sns/oauth2/access_token"
				+ "?appid="+WXLogin.WEBAPPID
				+ "&secret="+WXLogin.WEBAPPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject wxuser = WXLogin.doGetjson(url);

		String openid = wxuser.getString("openid");
		System.out.println(openid);
		String token = wxuser.getString("access_token");
		System.out.println(token);
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo"
				+ "?access_token="+token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		JSONObject userinfo = WXLogin.doGetjson(infoUrl);
		/*
		 * {"city":"新乡","country":"中国",
		 * "headimgurl":"http://wx.qlogo.cn/mmopen/j2wX8eqnnnhd0Ie6WeosMYuWibO0zoKPsmPbtJzqB6UCiaN3bic8zkkcGqyZWoiamzWqTDVM8OV58JB30ibv1NPboAiaj6g3eTwYnr/0",
		 * "language":"zh_CN",
		 * "nickname":"supe",
		 * "openid":"oUWMrwX2009ZBdhqlKi-rD0OeMSI",
		 * "privilege":[],
		 * "province":"河南",
		 * "sex":1}
		 */
//		  	获取用户的信息后,创建用户, 先判断用户是否存在,   不存在的话  创建,  存在的话省略 :

		String name = userinfo.getString("nickname");
		String photo = userinfo.getString("headimgurl");
		String openidUser = userinfo.getString("openid");
		String id = null;
		String userName = "";
		List<TSurenUser> userList = tSurenUserService.selectOneUser(openid);
		if(userList != null && userList.size() > 0){
    
    
			userName = WXLogin.filterEmoji(name, "1");
			// 该用户存在的话, 更新下头像和名称;
			userList.get(0).setPhoto(photo);
			userList.get(0).setUsername(userName);
			boolean b = tSurenUserService.updateUserNameAndPhoto(userList.get(0));
		}else{
    
    
			if(StringUtils.isNotBlank(openidUser) && StringUtils.isNotBlank(name) && StringUtils.isNotBlank(photo) ){
    
    
				userName = WXLogin.filterEmoji(name, "1");
				TSurenUser user = new TSurenUser();
				user.setOpenid(openidUser);
				user.setPhoto(photo);
				user.setUsername(userName);
				boolean b = tSurenUserService.saveUser(user);
			}
		}
		response.addHeader("openidWeb",openidUser);
		return Result.resData();
    }
//---------------- web 微信授权登陆

So far, the authorization process of the two methods is actually similar, but the details need attention;

Guess you like

Origin blog.csdn.net/qq_37521174/article/details/106335095