Java实现微信网页授权-程序员宅基地

 

微信测试平台

https://open.weixin.qq.com/connect/qrconnect?appid=wx39c379788eb1286a&scope=snsapi_login&redirect_uri=http%3A%2F%2Fmp.weixin.qq.com%2Fdebug%2Fcgi-bin%2Fsandbox%3Ft%3Dsandbox%2Flogin

开发前的准备:

1、需要有一个公众号(我这里用的测试号),拿到AppID和AppSecret;

2、进入公众号开发者中心页配置授权回调域名。具体位置:接口权限-网页服务-网页账号-网页授权获取用户基本信息-修改

    注意,这里仅需填写全域名(如www.qq.com、www.baidu.com),勿加 http:// 等协议头及具体的地址字段;

  我们可以通过使用Ngrok来虚拟一个域名映射到本地开发环境,网址https://www.ngrok.cc/,大家自己去下载学习怎么使用

 

同时还需要扫一下这个二维码

 

授权步骤:

1、引导用户进入授权页面同意授权,获取code 

2、通过code换取网页授权access_token(与基础支持中的access_token不同) 

3、通过网页授权access_token和openid获取用户基本信息

 

先看一下我的项目结构:

web.xml相关代码:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>WxAuth</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>wxCallBack</servlet-name> <servlet-class>com.xingshang.servlet.CallBackSerclet</servlet-class> <init-param> <param-name>dbUrl</param-name> <param-value>jdbc:mysql://127.0.0.1:3306/wxauth</param-value> </init-param> <init-param> <param-name>driverClassName</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </init-param> <init-param> <param-name>userName</param-name> <param-value>root</param-value> </init-param> <init-param> <param-name>passWord</param-name> <param-value>123456</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>wxCallBack</servlet-name> <url-pattern>/wxCallBack</url-pattern> </servlet-mapping> </web-app>
复制代码

AuthUtil工具类:

复制代码
package com.xingshang.util;

import java.io.IOException;

import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import net.sf.json.JSONObject; public class AuthUtil { public static final String APPID = "wx45c1428e5584fcdb"; public static final String APPSECRET = "98174450eb706ada330f37e646be85d5"; public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException{ JSONObject jsonObject = null; //首先初始化HttpClient对象 DefaultHttpClient client = new DefaultHttpClient(); //通过get方式进行提交 HttpGet httpGet = new HttpGet(url); //通过HTTPclient的execute方法进行发送请求 HttpResponse response = client.execute(httpGet); //从response里面拿自己想要的结果 HttpEntity entity = response.getEntity(); if(entity != null){ String result = EntityUtils.toString(entity,"UTF-8"); jsonObject = jsonObject.fromObject(result); } //把链接释放掉  httpGet.releaseConnection(); return jsonObject; } }
复制代码

 

Java实现:

1、引导用户进入授权页面同意授权,获取code 

    这一步其实就是将需要授权的页面url拼接到微信的认证请求接口里面,比如需要用户在访问页面  时进行授权认证

    其中的scope参数有两个值:

    snsapi_base:只能获取到用户openid。好处是静默认证,无需用户手动点击认证按钮,感觉上像是直接进入网站一样。

    snsapi_userinfo:可以获取到openid、昵称、头像、所在地等信息。需要用户手动点击认证按钮。

相关代码

复制代码
package com.xingshang.servlet;

import java.io.IOException;
import java.net.URLEncoder; 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 com.xingshang.util.AuthUtil; /** * 入口地址 * @author Administrator * */ @WebServlet("/wxLogin") public class LoginServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //第一步:引导用户进入授权页面同意授权,获取code //回调地址 // String backUrl = "http://suliu.free.ngrok.cc/WxAuth/callBack"; //第1种情况使用 String backUrl = "http://suliu.free.ngrok.cc/WxAuth/wxCallBack";//第2种情况使用,这里是web.xml中的路径 //授权页面地址 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); } }
复制代码

 

2、通过第一步获取的code换取网页授权access_token(与基础支持中的access_token不同) 

    这一步需要在控制器中获取微信回传给我们的code,通过这个code来请求access_token,通过access_token和openid获取用户基本信息:

相关代码:

复制代码
package com.xingshang.servlet;

import java.io.IOException;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletConfig; 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 com.xingshang.util.AuthUtil; import net.sf.json.JSONObject; /** * 回调地址 * @author Administrator * */ //@WebServlet("/callBack") public class CallBackSerclet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private String dbUrl; private String driverClassName; private String userName; private String passWord; private Connection conn =null; private PreparedStatement ps =null; private ResultSet rs = null; //初始化数据库  @Override public void init(ServletConfig config) throws ServletException { //加载驱动 try { this.dbUrl = config.getInitParameter("dbUrl"); this.driverClassName = config.getInitParameter("driverClassName"); this.userName = config.getInitParameter("userName"); this.passWord = config.getInitParameter("passWord"); Class.forName(driverClassName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block  e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //第二步:通过code换取网页授权access_token //从request里面获取code参数(当微信服务器访问回调地址的时候,会把code参数传递过来) String code = request.getParameter("code"); System.out.println("code:"+code); //获取code后,请求以下链接获取access_token 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"+jsonObject); //从返回的JSON数据中取出access_token和openid,拉取用户信息时用 String token = jsonObject.getString("access_token"); String openid = jsonObject.getString("openid"); // 第三步:刷新access_token(如果需要) // 第四步:拉取用户信息(需scope为 snsapi_userinfo) 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种情况:使用微信用户信息直接登录,无需注册和绑定 // request.setAttribute("info", userInfo); //直接跳转 // request.getRequestDispatcher("/index1.jsp").forward(request, response); //第2种情况: 将微信与当前系统的账号进行绑定(需将第1种情况和@WebServlet("/callBack")注释掉) //第一步,根据当前openid查询数据库,看是否该账号已经进行绑定 try { String nickname = getNickName(openid); if(!"".equals(nickname)){ //已绑定 request.setAttribute("nickname", nickname); request.getRequestDispatcher("/index2.jsp").forward(request, response); }else{ //未绑定 request.setAttribute("openid", openid); request.getRequestDispatcher("/login.jsp").forward(request, response); } } catch (SQLException e) { // TODO Auto-generated catch block  e.printStackTrace(); } } //数据库的查询 public String getNickName(String openid) throws SQLException{ String nickName = ""; //创建数据库链接 conn = DriverManager.getConnection(dbUrl, userName, passWord); String sql = "select nickname from user where openid = ?"; ps = conn.prepareStatement(sql); ps.setString(1, openid); rs = ps.executeQuery(); while (rs.next()) { nickName = rs.getString("nickname"); } //关闭链接  rs.close(); ps.close(); conn.close(); return nickName; } //数据库的修改(openid的綁定) public int updateUser(String account,String password,String openid) throws SQLException{ //创建数据库链接 conn = DriverManager.getConnection(dbUrl, userName, passWord); String sql = "update user set openid = ? where account = ? and password = ?"; ps = conn.prepareStatement(sql); ps.setString(1, openid); ps.setString(2, account); ps.setString(3, password); int temp = ps.executeUpdate(); //关闭链接  rs.close(); ps.close(); conn.close(); return temp; } //post方法,用来接受登录请求 @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String account = request.getParameter("account"); String password = request.getParameter("password"); String openid = request.getParameter("openid"); try { int temp = updateUser(account, password, openid); if(temp > 0){ String nickname = getNickName(openid); request.setAttribute("nickname", nickname); request.getRequestDispatcher("/index2.jsp").forward(request, response); System.out.println("账号绑定成功"); }else{ System.out.println("账号绑定失败"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
复制代码

login.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"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Insert title here</title> </head> <body> <form action="/WxAuth/wxCallBack" method="post"> <input type="text" name="account" /> <input type="password" name="password" /> <input type="hidden" name="openid" value="${openid }" /> <input type="submit" value="提交并绑定" /> </form> </body> </html>
复制代码

index.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"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Insert title here</title> </head> <body style="font-size: 40px; text-align: center;"> <a href="/WxAuth/wxLogin">微信公众授权登录</a> </body> </html>
复制代码

index1.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"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Insert title here</title> </head> <body> <div>登陆成功!</div> <div>用户昵称:${info.nickname}</div> <div>用户头像:<img style="text-align: top;" width="100" src="${info.headimgurl }"></div> </body> </html>
复制代码

index2.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"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Insert title here</title> </head> <body> <div>登陆成功!</div> <div>用户昵称:${nickname}</div> </body> </html>
复制代码

最后附上需要的jar包

 

jar包下载链接:

链接:https://pan.baidu.com/s/1tLJ8Z-ZFrDOv9-YduUj9Nw 密码:rmr6

 

 到此,微信授权登录成功,如果有运行问题请自行调试,我这边能正常运行的

转载于:https://www.cnblogs.com/chenlove/p/9342588.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/aici0819/article/details/101961741

智能推荐

Android Studio 安卓手机上实现火柴人动画(Java源代码—Python)-程序员宅基地

文章浏览阅读621次,点赞24次,收藏23次。ImageView

R语言可视化——熵曲线_熵函数曲线-程序员宅基地

文章浏览阅读2.6k次。引言熵的定义是:f(x)=−xln(x)f(x) = -xln(x)f(x)=−xln(x),其中xxx是一个事件发生的频率。今天就R语言curve函数来画一下从0到1的熵曲线。代码fun <- function(x){ -log(x)*x}curve(fun, 0, 1)曲线总结我们可以看到比较有意思的现象,熵最大的时候不是在0.5而是在0.4左右。最后希望可以帮助大家学习使用R语言。水平有限发现错误还望及时评论区指正,您的意见和批评是我不断前进的动力。..._熵函数曲线

c语言二叉树最小值,C语言递归之二叉树的最小深度-程序员宅基地

文章浏览阅读289次。题目描述给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。说明:叶子节点是指没有子节点的节点。示例输入:[3,9,20,null,null,15,7]输出:2题目要求/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *le..._二叉树 最小值 递归

VS调用大漠插件-程序员宅基地

文章浏览阅读331次。地方撒旦_vs调用大漠插件

python3.6 FileNotFoundError: [Errno 2] No such file or directory-程序员宅基地

文章浏览阅读1.0k次。问题描述:在windows下批量下载mp3文件时,存储的是中文名,有几个特殊的文件下载报错了,提示“FileNotFoundError: [Errno 2] No such file or directory: 'E:\\门丽 - 死心塌地去爱你(DJ宇轩\xa0Remix)(DJ宇轩 /门丽 remix).mp3”,检查存储路径都OK的解决方案:经过多番测试验证,发现原来是文件里多了特殊字符“/”,所以最终解决方案是通过str.replace(' ', '').replace('/', '') _filenotfounderror: [errno 2] no such file or directory: '/usr/bin/python3.6

pandas API Reference_pandas reference-程序员宅基地

文章浏览阅读753次。http://pandas.pydata.org/pandas-docs/stable/api.html#api-reference API ReferenceThis page gives an overview of all public pandas objects, functions and methods. All classes and functions exposed..._pandas reference

随便推点

分享phpyun 7.0vip开源版新消息模板设置及零工插件的安装小程序配置_phpyun 模板怎么改-程序员宅基地

文章浏览阅读340次,点赞6次,收藏4次。大家都知道,最近微信官方公众号又改版了,这次改版的是消息模板,因为以前的消息机制造成很多客户投诉被骚扰,这样在体验上非常差,于是官方更新了消息模板机制,这个苦了一批CMS系统开发者,因为针对公众号消息推送模板的改版他们又要批量修改,有需要代码可以Q我昵称注明CSDN网友,针对于此我分享下新版本phpyun,V7.0人才系统针对新消息模板怎么匹配和设置。对应编号:OPENTM418069699 (行业 商业服务 - 中介服务)对应编号:OPENTM202361543 (行业 商业服务 - 中介服务)_phpyun 模板怎么改

SpringBoot项目部署到Tomcat-程序员宅基地

文章浏览阅读7.2k次,点赞9次,收藏59次。一般情况下,我们开发 SpringBoot 项目,由于内置了Tomcat,所以项目可以直接启动 (使用内置 Tomcat 的话,可以在 application.yml 中进行相关配置)_springboot项目部署到tomcat

electron-egg: 新一代桌面应用开发框架_electron框架-程序员宅基地

文章浏览阅读3.4k次。EE框架已经应用于医疗、学校、政务、股票交易、ERP、娱乐、视频、企业等领域客户端。_electron框架

Python串口助手简介及pySerial模块使用指南-程序员宅基地

文章浏览阅读624次。pySerial 模块封装了对串行端口(serial port)的访问。它提供了在 Windows,OSX,Linux,BSD(可能是任何 POSIX 兼容系统)和 IronPython 上运行的 Python 的后端。模块名为“serial”会自动选择适当的后端。在所有支持的平台上基于相同类的接口。通过 Python 属性访问端口设置。通过 RTS/CTS 和/或 Xon/Xoff 支持不同的字..._python 串口助手

如何用c语言写驱动程序,c – 如何启动自编写的驱动程序-程序员宅基地

文章浏览阅读1.4k次。我在Visual Studio 2013中编写了一个驱动程序.该构建过程是成功的.然后我准备了一个traget-computer并将驱动程序文件复制到它.然后我安装了驱动程序:C:\Windows\system32>pnputil -a "E:\driverZeug\KmdfHelloWorldPackage\KmdfHelloWorld.inf"Microsoft-PnP-Dienstpr..._用c语言编写dos设备驱动程序

常用的会话跟踪技术有哪些?_web开发中会话跟踪的方法有哪些-程序员宅基地

文章浏览阅读567次。常用的会话跟踪技术有哪些?_web开发中会话跟踪的方法有哪些