您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用Java怎么實現微信網頁授權,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
授權步驟:
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/oauth3/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/oauth3/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 > <a href="/WxAuth/wxLogin" rel="external nofollow" >微信公眾授權登錄</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 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包
上述內容就是使用Java怎么實現微信網頁授權,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。