微信授权登录(微信订阅号使用测试账号)

1.微信授权登录;
微信公众号测试登录:
准备:
1.1 花生壳! 下载地址:http://hsk.oray.com/download/

1.2 微信公众号:https://mp.weixin.qq.com/ 服务号申请起来太麻烦,我之前申请了一个订阅号,正好用来做测试

这个是测试账号的appid和appsecret

使用前提,设置【网页授权获取用户基本信息】中的【授权回调页面域名:】

所需的jar包:

开始步骤及准备:
1.AuthUtil.java

package com.wanglixia;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 功能描述:
 * <p>
 * Created by Mr.wang on 2017/9/17 11:57.
 */
public class AuthUtil {

    public static final String APPID = "这块填appid";
    public static final String APPSECRET = "这块是appsecret";

    public static JSONObject doGetJson(String url) throws IOException {
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = client.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }
}

2.CallBackServlet.java

package com.wanglixia;

import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述:
 * <p>
 * Created by Mr.wang on 2017/9/17 13:06.
 */
@WebServlet("/callBack")
public class CallBackServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + AuthUtil.APPID +
                "&secret=" + AuthUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        System.out.println(jsonObject.toString());
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");
//        String expires_in = jsonObject.getString("expires_in");
//        String refresh_token = jsonObject.getString("refresh_token");
//        String scope = jsonObject.getString("scope");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        System.out.println(userInfo);

        //1、使用微信用户信息直接登录,无需注册和绑定
//        req.setAttribute("info", userInfo);
//        req.getRequestDispatcher("/index1.jsp").forward(req, resp);


    }
}

3.WxLogin.java

package com.wanglixia;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 功能描述:
 * <p>
 * Created by Mr.wang on 2017/9/17 11:17.
 */
@WebServlet("/wxLogin")
public class WxLogin extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String backUrl = "http://这儿是你的回调地址,上图填的那个/callBack";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + AuthUtil.APPID +
                "&redirect_uri=" + URLEncoder.encode(backUrl) +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        resp.sendRedirect(url);
    }
}

4.index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Mr.wang
  Date: 2017/9/17
  Time: 11:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>$Title$</title>
</head>
<body style="font-size: 40px;text-align: center;">
<a href="/wxLogin">微信公众授权登录</a>
</body>
</html>

5.index1.jsp

<%--
  Created by IntelliJ IDEA.
  User: Mr.wang
  Date: 2017/9/17
  Time: 11:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>$Title$</title>
</head>
<body>
<div>登录成功!</div>
<div>${info}</div>
<div><img style="width: 100px;height: 100px;" src="${info.headimgurl}"></div>
</body>
</html>

中间遇到的问题:

  1. 接口回调地址设置错误,这个地址需要是公网中能够访问到的地址,因此需要用花生壳来进行内网映射;
  2. 因为没有微信公众服务号,因此,找了半天,突然想起有个测试账号,哈哈~~。
    参考自:慕课网教程:http://www.imooc.com/learn/713
posted @ 2017-09-17 15:44  ne_lucifer  阅读(2596)  评论(0编辑  收藏  举报