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>

 

### Java 实现微信授权登录 #### 关键概念与准备事项 为了成功实现Java整合拉起微信授权登录,开发者需先完成一些准备工作。这包括但不限于注册微信小程序并获得必要的API密钥信息,如`appid`和`appsecret`[^3]。 #### 后端服务搭建 后端服务建议采用Spring Boot框架构建,该框架提供了简洁的方式处理HTTP请求以及与其他组件集成的能力。对于微信授权登录而言,主要关注点在于如何通过OAuth2.0协议获取用户的访问令牌(access_token),进而利用此令牌查询用户基本信息或执行其他操作。 #### 获取Access Token 当从小程序接收到code参数时,在服务器端发起HTTPS POST请求至指定URL以换取access_token: ```java public String getAccessToken(String appId, String secret, String jsCode){ StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("https://api.weixin.qq.com/sns/jscode2session?"); urlBuilder.append("appid=").append(appId); urlBuilder.append("&secret=").append(secret); urlBuilder.append("&js_code=").append(jsCode); urlBuilder.append("&grant_type=authorization_code"); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlBuilder.toString(), String.class); JSONObject jsonObject = JSON.parseObject(responseEntity.getBody()); return (String)jsonObject.get("access_token"); // 或者返回整个JSON对象供后续解析使用 } ``` 上述方法接收三个参数:`appId`, `secret`(即`appsecret`) 和由前端传递过来的临时登陆凭证`jsCode`。它构造了一个指向微信官方接口的GET请求链接,并调用了RestTemplate工具发送网络请求;最后对响应体进行了简单的JSON解析,提取出了所需的`access_token`字段值[^2]。 #### 用户信息解码 一旦获得了有效的`access_token`,就可以进一步向微信开放平台申请更多关于当前已认证用户的个人信息了。不过需要注意的是,某些敏感数据可能不会直接暴露给第三方应用,而是经过加密传输后再交予开发者自行解密处理。 #### 安全性和隐私保护 在整个过程中务必重视安全性考量,比如妥善保管好各密钥材料、遵循最小权限原则仅索取必需的信息项等措施都是不可或缺的一部分。此外还要注意遵守当地法律法规有关个人隐私方面的规定[^1]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值