admin管理员组

文章数量:1534194

JAVA实现微信授权登录(详解)

第一步:(前期设置)登录微信公众号接口测试平台设置信息

链接:http://mp.weixin.qq/debug/cgi-bin/sandbox?t=sandbox/login

登录成功后可以看到测试用的appidappsecret,稍后再后台我们要用到这两个ID,如下图

紧接着需要设置网页授权(体验接口权限表 —》 网页服务 —》网页帐号 —》 网页授权获取用户基本信息)

没有域名的话可以用内网穿透动态解析一个域名。

NATAPP链接:点击注册
注册登录成功后可以看到下图,选择免费隧道

购买免费的隧道之后,可以直接按照官方的一分钟教程完成内网穿透,这样我们就拿到了我们的域名

第二步:代码实现微信授权。

简单来说,微信授权分为四步:

  1. 授权登录接口。
  2. 用户点击授权。
  3. 微信授权回调接口。
  4. 在回调接口中获取openid、access_token、获取用户信息。
第一步:先上工具类AuthUtil
public class AuthUtil {
	public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
		JSONObject jsonObject = null;
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = client.execute(httpGet);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");
			jsonObject = JSONObject.fromObject(result);
		}
		httpGet.releaseConnection();
		return jsonObject;
	}
}
第二步:WxAuthorizeController的微信授权接口
   /**
    * Tea微信登录接口
    * @throws IOException 
    */
   @ApiOperation(value = "微信登录接口")
   @IgnoreAuth
   @RequestMapping("wx_login")
   public void wxLogin(HttpServletResponse response) throws IOException{
   	//域名(暂时写死的)
   	String sym = "http://c8d3v2.natappfree";
       //这里是回调的url
       String redirect_uri = URLEncoder.encode(sym+"/front/auth/callBack", "UTF-8");
       String url = "https://open.weixin.qq/connect/oauth2/authorize?" +
               "appid=APPID" +
               "&redirect_uri=REDIRECT_URI"+
               "&response_type=code" +
               "&scope=SCOPE" +
               "&state=123#wechat_redirect";
       response.sendRedirect(url.replace("APPID",WxConstant.APPID).replace("REDIRECT_URI",redirect_uri).replace("SCOPE","snsapi_userinfo"));
   }
参数说明如下:
参数必须说明
appid公众号的唯一标识
redirect_uri授权后重定向的回调链接地址,请使用urlencode对链接进行处理
response_type返回类型,请填写code
scope应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
state重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect无论直接打开还是做页面302重定向时候,必须带此参数
第三步:WxAuthorizeController微信授权登录回调接口
	/**
	 * Tea微信授权成功的回调函数
	 * 
	 * @param request
	 * @param response
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ServletException
	 */
    @ApiOperation(value = "微信授权回调接口")
    @IgnoreAuth
	@RequestMapping("/callBack")
	protected void deGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	//获取回调地址中的code
		String code = request.getParameter("code");
		//拼接url
		String url = "https://api.weixin.qq/sns/oauth2/access_token?appid=" + WxConstant.APPID + "&secret="
				+ WxConstant.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
		JSONObject jsonObject = AuthUtil.doGetJson(url);
		//1.获取微信用户的openid
		String openid = jsonObject.getString("openid");
		//2.获取获取access_token
		String access_token = jsonObject.getString("access_token");
		String infoUrl = "https://api.weixin.qq/sns/userinfo?access_token=" + access_token + "&openid=" + openid
				+ "&lang=zh_CN";
		//3.获取微信用户信息
		JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
		//至此拿到了微信用户的所有信息,剩下的就是业务逻辑处理部分了
		//保存openid和access_token到session
		request.getSession().setAttribute("openid", openid);
		request.getSession().setAttribute("access_token", access_token);
		//去数据库查询此微信是否绑定过手机
		UserVo user = userService.queryByOpenId(openid);
		String mobile=user==null?"":user.getMobile();
		
		if(null == mobile || "".equals(mobile)){
			//如果无手机信息,则跳转手机绑定页面
			response.sendRedirect("/front/register.html");
		}else{
			//否则直接跳转首页
			response.sendRedirect("/front/index.html");
		}
	}

至此,后台的代码暂时就这么多,剩下的需要前台页面了。

前端页面JS:index.js
var vm = new Vue({
    el: '#rrapp',
    data: {
    },
    methods: {
    //方法说明:首页加载时去查询Session中有没有存储openid,如果没有存储说明未经过授权,需要去授权页面
        getOpenId: function () {
            ApiAjax.request({
            	//此接口部分代码过于简单就不展示了
                url: '/front/auth/getOpenId',
                params: "",
                type: "POST",
                async: true,
                successCallback: function (r) {
                	if(r.data.openid == null){
                		//返回的openid如果为空就进入微信授权接口
                		window.location.href = "/front/auth/wx_login";
                	}
                }
            });
        }
    },
    mounted: function() {
		//页面渲染完成后执行该方法
    	this.getOpenId();
    }
});

本文标签: 详解Java