首先開通微信開放平臺,申請網站應用,交錢經過後能夠使用appid和appsecret(和公衆平臺的不一樣)css
以後能夠生成掃碼登陸的二維碼了,主要根據開放平臺提供的api請求連接和appid,appsecrethtml
<%-- 測試首頁 --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>BBBGGG</title> </head> <body> BBBGGG index <a href="login">登陸集</a> ${snsUser.nickname} </body> </html>
下面頁面展現3種登陸示例:java
<%-- Created by IntelliJ IDEA. User: SeeClanUkyo Date: 2018/12/10 Time: 8:41 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>首頁</title> <!--BootStrap的樣式文件--> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- 可選的 Bootstrap 主題文件(通常不用引入) --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"> <!-- jQuery (Bootstrap 的 JavaScript 插件須要引入 jQuery) --> <script src="https://code.jquery.com/jquery.js"></script> <!-- Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="http://www.jq22.com/jquery/jquery-3.3.1.js"></script> <!--微信登陸二維碼插件js--> <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> 該頁面的目的不限於微信登陸,還應該包含其它方式登陸. snsUser 暱稱:${snsUser.nickname} <br> 三種登陸方式<br> <div class="center-block"> <button class="btn" id="btn1">用微信登陸 全屏二維碼</button> <button id="modal-742328" href="#modal-container-742328" role="button" class="btn" data-toggle="modal">微信登陸iframe</button> <a class="btn" href="/qrcode">登陸/qrcode</a> </div> <hr> 之下爲測試 <p>獲取code</p> <button id="btn2">獲取code</button> token:<p id="token"></p> openid:<p id="openid"></p> <p>獲取用戶信息</p> <button id="btn3">獲取用戶信息</button> <P>姓名:</P> <p id="name"></p> <p>頭像:</p><img src="" id="img"> <button id="btn4">直接從code獲取用戶信息</button> <p id="nickname"></p> <!--<div id="login_container"></div>--> <div class="modal fade" id="modal-container-742328" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="myModalLabel"> 微信掃碼登陸 </h4> </div> <div class="modal-body" style="width:500px;height:500px"> <!--<div id="login_container" style="width:400px;height:400px"></div>--> <iframe class="center" src="qrcode.jsp" style="width:400px;height:400px"></iframe> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button> </div> </div> </div> </div> </div> </div> </div> login.jsp <%--<% String code = request.getParameter("code");%>--%> <%--<%= code %>--%> <%--<% Weixin weixin = new Weixin();%>--%> <%--<% SnsUser snsUser = weixin.sns().getSnsUserByCode(code);%>--%> <%--<%=snsUser.getNickname()%>--%> <!-- <button id="btn">btn</button> --> <!-- 經過ajax獲取的用戶信息封裝在data中,能夠根據須要獲取不一樣的參數,如 --> <script> //not use // $("#btn").click(getSnsUser); function getSnsUser() { // alert("getSnsUser begin") $.ajax({ url: "/user/getSnsUserInfoByCode", data: "<%=request.getParameter("code")%>", contentType: "application/json", dataType: "json", method: "POST", success: function (data) { alert(JSON.stringify(data)); //將數據反填到html或jsp頁面上 } }); } //not use function getOpenSnsUser() { // alert("getSnsUser begin") $.ajax({ url: "/user/getOpenSnsUserInfoByCode", data: "<%=request.getParameter("code")%>", contentType: "application/json", dataType: "json", method: "POST", success: function (data) { window.location.href=window.location.host; alert(JSON.stringify(data)); //將數據反填到html或jsp頁面上 } }); } </script> <script> // var obj = new WxLogin({ // self_redirect: true, // id: "login_container", // appid: APPID, // scope: "", // redirect_uri: "", // state: "", // style: "", // href: "" // }); </script> <script> //開放平臺參數 //開放平臺appid var APPID = "wxxxxxxxxxxxxxxxxx"; //開放平臺請求做用域 var SCOPE = "snsapi_login"; //回調頁面 URL 進行utf cncode var REDIRECT_URI = encodeURIComponent("http://baige.free.idcfengye.com/callback"); //開放平臺appsecret // var STATE = "state"; // 快捷方式 // var obj = new WxLogin({ // self_redirect: true, // id: "login_container", // appid: APPID, // scope: SCOPE, // redirect_uri: REDIRECT_URI, // state: STATE, // style: "", // href: "" // }); //第一步,獲取code //用微信登陸按鈕 var btn1 = $("#btn1"); //微信登陸 btn1.click(getOpenCode); function getOpenCode() { alert("getOpenCode"); window.open("https://open.weixin.qq.com/connect/qrconnect?appid=" + APPID + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=" + SCOPE + "&state=STATE#wechat_redirect"); } //第二步,獲取access_token var btn2 = $("#btn2"); var btn4 = $("#btn4"); btn4.click(getUserInfoByCode); function getUserInfoByCode(){ alert("getUserInfoByCode begin"); $.ajax({ url: "/user/getOpenSnsUserInfoByCode", // url: "/callBackLogin", data: "<%=request.getParameter("code")%>", contentType: "application/json", dataType: "json", method: "POST", success: function (data) { alert(JSON.stringify(data)); var nickname = data.SnsUser.nickname; $("#nickname").html(nickname); alert(data.SnsUser.nickname); //將數據反填到html或jsp頁面上 } }); } btn2.click(getAccessToken); function getAccessToken() { var CODE = "<%=request.getParameter("code")%>"; var tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET + "&code=" + CODE + "&grant_type=authorization_code"; $.ajax({ url: tokenUrl, type: "POST", data:{"":1}, dataType: "json", success: function (data) { alert(JSON.stringify(data)); var token = data.access_token; var openid = data.openid; $("#token").html(token); $("#openid").html(openid); } }) } //第三步,獲取用戶信息 var btn3 = $("#btn3"); btn3.click(getUserInfo); function getUserInfo() { var token3 = $("#token").html(); var openid3 = $("#openid").html(); var ajaxUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token3 + "&openid=" + openid3; $.ajax({ url: ajaxUrl, type: "get", dataType: "JSONP", success: function (data) { alert(JSON.stringify(data)); var name = $("#name"); var img = $("#img"); $(name).html(data.nickname); $(img).attr("src", data.headimgurl); } }) } </script> </body> </html>
調用的callback頁面,同時也是回調頁面:jquery
<%-- 回調頁面 --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>callback</title> <script src="http://www.jq22.com/jquery/jquery-3.3.1.js"></script> </head> <body> 正在跳轉... <script> $.ajax({ // url: "/user/getOpenSnsUserInfoByCode", url: "/user/callBackLogin", data: "<%=request.getParameter("code")%>", contentType: "application/json", dataType: "json", method: "POST", success: function (data) { if(data===1){ window.location.href="http://baige.free.idcfengye.com"; }else{ window.location.href="http://baige.free.idcfengye.com/error"; } } }); </script> </body> </html>
之下的控制層方法:web
package com.baigehuidi.demo.controller; import com.baigehuidi.demo.loader.WeixinInsLoader; import com.baigehuidi.demo.weixin4j.WeixinException; import com.baigehuidi.demo.weixin4j.model.sns.SnsUser; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/user") public class WeixinUserInfoController { @RequestMapping("/getSnsUserInfoByCode") public Map getSnsUserInfoByCode(@RequestBody String code) throws WeixinException { if(code==null || code==""){ return null; } Map map = new HashMap(); System.out.println("code:"+code); SnsUser snsUser = WeixinInsLoader.getWeixinInstance().sns().getSnsUserByCode(code); map.put("SnsUser",snsUser); return map; } @RequestMapping("/getOpenSnsUserInfoByCode") public Map getOpenSnsUserInfoByCode(@RequestBody String code) throws WeixinException { if(code==null || code==""){ return null; } Map map = new HashMap(); System.out.println("code:"+code); SnsUser snsUser = WeixinInsLoader.getWeixinInstance().open().getOpenSnsUserByCode(code); map.put("SnsUser",snsUser); return map; } //微信掃碼登陸回調 @RequestMapping("/callBackLogin") public Integer callBackLogin(@RequestBody String code, HttpSession session) throws WeixinException, ServletException, IOException { System.out.println("callback method"); System.out.println("code:"+code); SnsUser snsUser = WeixinInsLoader.getWeixinInstance().open().getOpenSnsUserByCode(code); System.out.println("snsUser:"+snsUser); session.setAttribute("snsUser",snsUser); if(session!=null){ return 1; }else{ return 0; } } }
最終效果: (由於用的內網穿透不太穩定,響應稍慢)ajax