天天看点

微信账号和系统账号绑定

微信开发接口文档:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Authorized_Interface_Calling_UnionID.html

获取用户个人信息(UnionID机制)

接口说明

此接口用于获取用户个人信息。开发者可通过OpenID来获取用户基本信息。特别需要注意的是,如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号,用户的unionid是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。请注意,在用户修改微信头像后,旧的微信头像URL将会失效,因此开发者应该自己在获取用户信息后,将头像图片保存下来,避免微信头像URL失效后的异常情况。

请求说明

http请求方式: GET
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
           
微信账号和系统账号绑定
返回说明
正确的Json返回结果:

{
"openid":"OPENID",
"nickname":"NICKNAME",
"sex":1,
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
"privilege":[
"PRIVILEGE1",
"PRIVILEGE2"
],
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

}
           
微信账号和系统账号绑定
微信账号和系统账号绑定
<div class="layadmin-user-login-box layadmin-user-login-body layui-form" id="bind-account">
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-username"></label>
          <input type="text" name="username" id="username" lay-verify="required" placeholder="用户名" class="layui-input">
        </div>
        <div class="layui-form-item">
          <label class="layadmin-user-login-icon layui-icon layui-icon-password"></label>
          <input type="password" name="password" id="password" lay-verify="required" placeholder="密码" class="layui-input">
        </div>
        <div class="layui-form-item">
          <button class="layui-btn layui-btn-fluid" id="bind-login" onClick="bindLogin()">确 定</button>
        </div>
</div>
           
//确认绑定微信且登录
function bindLogin(){
	var account = $('#username').val().trim();
    var password = $('#password').val().trim();
	if(account == ""){
		layer.msg('请输入账号!', {icon: 5});
		return;
	}
	if(password == ""){
		layer.msg('请输入密码!', {icon: 5});
		return;
	}
	
	//获取url中的key参数   //跳转微信绑定页面时候带来的参数
	var paramKey = window.location.search.substring(1).substring(4);
	if(paramKey == ""){
		layer.alert('请求错误,点击确定跳转至登录页重新登录!', {icon: 2,end :function(){
			location.href = 'login.html';
		}});
		return;
	}
	
	var param ={"account":account,"password":password,"key":paramKey};
	$.post("login/wxBindLogin.do",param,function(data){
		if(data.code== "failed"){
			layer.msg('绑定失败,请重试!',{icon: 5});
		}else if(data.code== "success"){
    		location.href = 'index.jsp';
		}else{
			layer.msg('参数错误!',{icon: 2});
		}
		
		$("#bind-login").text("确定");
    	$("#bind-login").css("color","#fff");
    	
	});
}
           
//绑定微信且执行登录
@ResponseBody
@RequestMapping("/wxBindLogin")
public Object wxBindLogin(HttpServletRequest request,HttpServletResponse response){
	JSONObject jsonObj = new JSONObject();
	try {
		String account = WebUtil.decode(request.getParameter("account"));
		String password = WebUtil.decode(request.getParameter("password"));
		redisUtil.setDb(6);
		//在上一个扫码登入的时候,存入redis缓存中
		String code = (String)redisUtil.get("code");
		//非法请求直接返回
		if(StringUtils.isBlank(account) || StringUtils.isBlank(password)){
		    jsonObj.put("code", "failed");
			return jsonObj;
		}

		//请求微信通过code获取access_token
		String accessToken = getUrlInfo("https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code="+code+"&grant_type=authorization_code");
		
		//将请求结果字符串转json
		JSONObject accessTokenJson = JSONObject.fromObject(accessToken);
		
		String access_token = (String)accessTokenJson.get("access_token");//接口调用凭证,登录后右上角展示数据需要该值去获取
		String openid = (String)accessTokenJson.get("openid");//授权用户唯一标识
		String unionid = (String)accessTokenJson.get("unionid");//用户统一标识(微信登录不需要该字段,但后面如果拓展其他功能可能需要)
					
		//验证成功,开始执行登陆方法
		User newUser = new User();
		newUser.setAccount(account);
		newUser.setOpenid(openid);//更新授权用户唯一标识
		newUser.setUnionid(unionid);//更新用户统一标识
		//把openid和unionid存到数据库中
		loginService.updatePWD(newUser);
		
		//根据access_token和openid获取用户昵称和头像用作右上角显示
		String wxInfo = getInfo("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid);
		//将请求结果字符串转json
		JSONObject wxInfoJson = JSONObject.fromObject(wxInfo);
		String nickname = (String)wxInfoJson.get("nickname");//普通用户昵称
		String headimgurl = (String)wxInfoJson.get("headimgurl");//用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
		HttpSession session = request.getSession();
		session.setAttribute("wxusername", nickname);
		session.setAttribute("wxuserimg", headimgurl);
		jsonObj.put("code", "success");
		
		//删除redis中的key信息
		redisUtil.setDb(6);
		redisUtil.del("code");				
	} catch (Exception e) {
		jsonObj.put("code", "failed");
		e.printStackTrace();
	}
	return jsonObj;
}
           
//调用接口
private String getInfo(String URL) {
	// 创建Httpclient对象
	CloseableHttpClient httpclient = HttpClients.createDefault();
	CloseableHttpResponse response = null;
	String resultString = null;
	try {
		// 创建uri
		URIBuilder builder = new URIBuilder(URL);
		URI uri = builder.build();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(uri);
		// 执行请求
		response = httpclient.execute(httpGet);
		// 判断返回状态是否为200
		if (response.getStatusLine().getStatusCode() == 200) {
			resultString = EntityUtils.toString(response.getEntity(),"UTF-8");
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		} catch (IOException e) {
		e.printStackTrace();
		}
	}
	return resultString;
}