微信授权登录开发步骤说明
最开始,要先修改授权回调域名
在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
第一步:用户同意授权,获取code
第二步:通过code换取网页授权access_token
第三步:刷新access_token(如果需要)
第四步:拉取用户信息(需scope为 snsapi_userinfo)
1.用户同意授权,获取code
思路流程图
修改菜单并创建菜单
ViewButton firstButton31 = new ViewButton();
firstButton31.setName("微信授权登录");
firstButton31.setType(messageUtil.userResp_message_type_VIEW);
firstButton31.setUrl("http://sn4mtp.natappfree.cc/WinXin/wxSource/auth.jsp");
@Test
public void testCreateMenu() throws Exception{
Menu initMenu = weiXinUtil.initMenu();
String menu = JSONObject.fromObject(initMenu).toString();
int result = weiXinUtil.createMenu(weiXinUtil.getAccessToken().getAccess_token(),menu);
if (result==0) {
System.out.println("创建菜单成功");
}else {
System.out.println(result);
}
}
- auth.jsp页面
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<div style="margin:0 auto;">
<h1><a href="/WinXin/wxLogin">微信授权登录</a></h1>
</div>
</body>
</html>
- 拦截/WinXin/wxLogin请求,拼接url
@WebServlet("/wxLogin")
public class loginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(1);
String backUrl = "http://sn4mtp.natappfree.cc/WinXin/callback";
String scope = "snsapi_userinfo";
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weiXinUtil.APPID
+ "&redirect_uri="+URLEncoder.encode(backUrl)
+ "&response_type=code&scope="+scope
+ "&state=STATE#wechat_redirect";
response.sendRedirect(url);
System.out.println(url);
System.out.println("url重定向成功");
}
}
- 拦截callback请求,获取code
@WebServlet("/callback")
public class callbackServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
System.out.println(code);
}
}
最后,得到code=071DaqhV1GqHkT0h5RhV1Q2ohV1Daqhn