SSM 实现微信授权登录(Java)

1.先写一个工具类 AuthUtil.java 来存放APPID等信息

public class AuthUtil {
	public static final String APPID = "换成自己的APPID ";
	public static final String APPSECRET = "换成自己的APPSECRET ";

	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;
	}
}

2.新建一个 LoginController.java 类来实现授权登录

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import net.sf.json.JSONObject;

@Controller
public class LoginController extends HttpServlet {

	/**
	 * 微信授权登录
	 */
	@RequestMapping("/wxLogin")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// backUrl 需要遵循微信官方的定义,微信的接口只能用 https 来访问
		// 所以我这里是直接把整个项目打包成 jar 包,然后扔到自己的服务器上
		String backUrl = "https://www.yyzheng.cn/o2o/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";
		response.sendRedirect(url);
	}

	/**
	 * 登录成功的回调函数
	 * 
	 * @param request
	 * @param response
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/callBack")
	protected void deGet(HttpServletRequest request, HttpServletResponse response)
			throws ClientProtocolException, IOException, ServletException {
		String code = request.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);
		String openid = jsonObject.getString("openid");
		String token = jsonObject.getString("access_token");
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid
				+ "&lang=zh_CN";
		JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
		
		if( userInfo != null ){
			// 这里是把授权成功后,获取到的东西放到 info 里面,前端可以通过 EL 表达式直接获取相关信息
			request.setAttribute("info", userInfo);
			// 这里是授权成功返回的页面
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/fail.jsp").forward(request, response);
		}
		
	}
}

3.写一个页面来访问授权功能

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<title>Insert title here</title>
</head>
<body>
	<a href="/o2o/wxLogin">微信公众授权登录</a>
</body>
</html>

4.微信授权成功访问的页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<title>Insert title here</title>
</head>
<body>
授权成功!!!
${info }
</body>
</html>

5.微信授权失败访问的页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<title>Insert title here</title>
</head>
<body>
授权失败!!!
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weidong_y/article/details/81433054