电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

springboot 微信授權網頁登錄操作流程

瀏覽:104日期:2022-06-16 16:00:22
操作流程

假設你已經有自己的域名,因為微信公眾號和微信回調都需要域名

先看看官方給的文檔

根據官方文檔,主要流程如下:

(1)引導用戶進入授權頁面同意授權,獲取code

(2)通過code換取網頁授權access_token(與基礎支持中的access_token不同)

(3)刷新access_token(如果有需要)

(3)通過網頁授權access_token和openid獲取用戶基本信息

提示:以下是本篇文章正文內容,下面案例可供參考

編寫微信授權方法和獲取用戶信息方法 二、使用步驟獲取微信二維碼信息

代碼如下(示例):

/** * 公眾號微信登錄授權 */ @RequestMapping('/wxLogin') public void wxLogin(HttpServletResponse response) throws IOException { //這個url的域名必須在公眾號中進行注冊驗證,這個地址是成功后的回調地址 String backUrl = 'http://7ca0c439f61c.ngrok.io/callback';//使用自己的域名 // 第一步:用戶同意授權,獲取code //請求地址 snsapi_base snsapi_userinfo String url = 'https://open.weixin.qq.com/connect/oauth2/authorize' + '?appid=' + HttpClientUtil.APPID + '&redirect_uri=' + URLEncoder.encode(backUrl,'utf-8') + '&response_type=code' + '&scope=snsapi_userinfo' + '&state=STATE#wechat_redirect'; logger.info('forward重定向地址{' + url + '}'); //必須重定向,否則不能成功 response.sendRedirect(url); }備注:在前端頁面直接加載url 就可以出現二維碼界面了。直接用的微信的頁面,也可以根據自己的愛好進行設計頁面 /** * 公眾號微信登錄授權回調函數 */ @RequestMapping('/callback') public UserLoginRes callback(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserLoginRes userLoginRes = new UserLoginRes(); try{ WXUserInfoReq weixinUserInfo = new WXUserInfoReq(); /*start 獲取微信用戶基本信息*/ String code = req.getParameter('code'); //第二步:通過code換取網頁授權access_token String url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' + 'appid=' + HttpClientUtil.APPID + '&secret=' + HttpClientUtil.APPSECRET + '&code=' + code + '&grant_type=authorization_code'; System.out.println(url); String result = HttpClientUtil.doGet(url); JSONObject jsonObject = JSON.parseObject(result); /* { 'access_token':'ACCESS_TOKEN', 'expires_in':7200, 'refresh_token':'REFRESH_TOKEN', 'openid':'OPENID', 'scope':'SCOPE' } */ String openid = jsonObject.getString('openid'); String access_token = jsonObject.getString('access_token'); //第三步驗證access_token是否失效; String chickUrl = 'https://api.weixin.qq.com/sns/auth?access_token=' + access_token + '&openid=' + openid; String resultInfo = HttpClientUtil.doGet(chickUrl); JSONObject chickuserInfo = JSON.parseObject(resultInfo); System.out.println(chickuserInfo.toString()); if (!'0'.equals(chickuserInfo.getString('errcode'))) { String refreshInfo1 = HttpClientUtil.doGet(chickUrl); JSONObject refreshInfo = JSON.parseObject(refreshInfo1); /* { 'access_token':'ACCESS_TOKEN', 'expires_in':7200, 'refresh_token':'REFRESH_TOKEN', 'openid':'OPENID', 'scope':'SCOPE' } */ access_token = refreshInfo.getString('access_token'); } // 第四步:拉取用戶信息 String infoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN'; JSONObject userInfo = JSON.parseObject(HttpClientUtil.doGet(infoUrl)); /* { 'openid':' OPENID', 'nickname': NICKNAME, 'sex':'1', 'province':'PROVINCE' 'city':'CITY', 'country':'COUNTRY', 'headimgurl': 'http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46', 'privilege':[ 'PRIVILEGE1' 'PRIVILEGE2' ], 'unionid': 'o6_bmasdasdsad6_2sgVt7hMZOPfL' } */ System.out.println(userInfo.getString('openid') + ':' + userInfo.getString('nickname') +':' + userInfo.getString('sex')); }catch (Exception e){ e.printStackTrace(); userLoginRes.setResult('NO'); userLoginRes.setRtnErrId('ERROR'); userLoginRes.setRtnErrMsg(e.getMessage()); } return userLoginRes; }使用到的HttpClientUtil工具類

代碼如下(示例):

public class HttpClientUtil { //appid、secret為自己公眾號平臺的appid和secret public static final String APPID='xxxxxxx'; public static final String APPSECRET ='xxxxxxx'; public static String doGet(String url, Map<String, String> param) { // 創建Httpclient對象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ''; CloseableHttpResponse response = null; HttpGet httpGet = null; try { // 創建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 創建http GET請求 httpGet = new HttpGet(uri); httpGet.setHeader('Host', 'api.weixin.qq.com'); httpGet.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'); httpGet.setHeader('Accept', 'text/html, application/xhtml+xml, */*'); httpGet.setHeader('Accept-Encoding', 'gzip, deflate, br'); httpGet.setHeader('Connection', 'keep-alive'); httpGet.setHeader('Accept-Language', 'zh-CN'); httpGet.setHeader('Cache-Control', 'no-cache'); // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), 'UTF-8'); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpGet.releaseConnection(); httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 創建Httpclient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ''; try { // 創建Http Post請求 HttpPost httpPost = new HttpPost(url); // 創建參數列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), 'utf-8'); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 創建Httpclient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ''; try { // 創建Http Post請求 HttpPost httpPost = new HttpPost(url); // 創建請求內容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), 'utf-8'); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGetStr(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回結果字符串 try { // 創建遠程url連接對象 URL url = new URL(httpurl); // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設置連接方式:get connection.setRequestMethod('GET'); // 設置連接主機服務器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取遠程返回的數據時間:60000毫秒 connection.setReadTimeout(60000); //設置請求頭 connection.setRequestProperty('Host', 'api.weixin.qq.com'); connection.setRequestProperty('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'); connection.setRequestProperty('Accept', 'text/html, application/xhtml+xml, */*'); connection.setRequestProperty('Accept-Encoding', 'gzip, deflate, br'); connection.setRequestProperty('Connection', 'keep-alive'); connection.setRequestProperty('Accept-Language', 'zh-CN'); connection.setRequestProperty('Cache-Control', 'no-cache'); // 發送請求 connection.connect(); // 通過connection連接,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, 'UTF-8')); // 存放數據 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append('rn'); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 關閉遠程連接 } return result; } }最后根據實際業務處理用戶登錄

//3.根據uuid查詢用戶是否存在,如果存在直接登錄。如果不存在則自動注冊,在登錄 UserInfoModel userInfoByWechat = iUserDao.getUserInfoByWechat(userInfoStr.get('unionid').toString()); if (userInfoByWechat != null) { return ReturnMessage.success(0,'獲取成功',userInfoByWechat); } //4.數據庫添加用戶信息 String username = userInfoStr.get('nickname').toString(); String unionid = userInfoStr.get('unionid').toString(); UserInfoBean userInfoBean = new UserInfoBean(); userInfoBean.setUuid(unionid); userInfoBean.setUsername(username); // 微信登錄 userInfoBean.setStatus(2); iUserDao.insertUser(userInfoBean); //5.根據uuid查詢新注冊的用戶信息 UserInfoModel userInfoModel= iUserDao.getUserInfoByWechat(unionid); if (userInfoModel == null) { return ReturnMessage.fail(400,'用戶添加失敗,請重新操作'); }

到此這篇關于springboot 微信授權網頁登錄操作流程的文章就介紹到這了,更多相關springboot 微信授權登錄內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: 微信
相關文章:
主站蜘蛛池模板: 火锅底料批发-串串香技术培训[川禾川调官网] | 广西绿桂涂料--承接隔热涂料、隔音涂料、真石漆、多彩仿石漆等涂料工程双包施工 | SDG吸附剂,SDG酸气吸附剂,干式酸性气体吸收剂生产厂家,超过20年生产使用经验。 - 富莱尔环保设备公司(原名天津市武清县环保设备厂) | 数显恒温培养摇床-卧式/台式恒温培养摇床|朗越仪器 | 重庆中专|职高|技校招生-重庆中专招生网| 台湾阳明固态继电器-奥托尼克斯光电传感器-接近开关-温控器-光纤传感器-编码器一级代理商江苏用之宜电气 | 聚氨酯催化剂K15,延迟催化剂SA-1,叔胺延迟催化剂,DBU,二甲基哌嗪,催化剂TMR-2,-聚氨酯催化剂生产厂家 | 5L旋转蒸发器-20L-50L旋转蒸发器-上海越众仪器设备有限公司 | 啤酒设备-小型啤酒设备-啤酒厂设备-济南中酿机械设备有限公司 | 次氯酸钠厂家,涉水级次氯酸钠,三氯化铁生产厂家-淄博吉灿化工 | 金属抛光机-磁悬浮抛光机-磁力研磨机-磁力清洗机 - 苏州冠古科技 | 楼梯定制_楼梯设计施工厂家_楼梯扶手安装制作-北京凌步楼梯 | 数年网路-免费在线工具您的在线工具箱-shuyear.com | 捷码低代码平台 - 3D数字孪生_大数据可视化开发平台「免费体验」 | 真空上料机(一种真空输送机)-百科 | 除湿机|工业除湿机|抽湿器|大型地下室车间仓库吊顶防爆除湿机|抽湿烘干房|新风除湿机|调温/降温除湿机|恒温恒湿机|加湿机-杭州川田电器有限公司 | 福州仿石漆加盟_福建仿石漆厂家-外墙仿石漆加盟推荐铁壁金钢(福建)新材料科技有限公司有保障 | 仓储笼_仓储货架_南京货架_仓储货架厂家_南京货架价格低-南京一品仓储设备制造公司 | 广州食堂承包_广州团餐配送_广州堂食餐饮服务公司 - 旺记餐饮 | 贴板式电磁阀-不锈钢-气动上展式放料阀-上海弗雷西阀门有限公司 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 | 电镀电源整流器_高频电解电源_单脉双脉冲电源 - 东阳市旭东电子科技 | 有机肥设备生产制造厂家,BB掺混肥搅拌机、复合肥设备生产线,有机肥料全部加工设备多少钱,对辊挤压造粒机,有机肥造粒设备 -- 郑州程翔重工机械有限公司 | 智能风向风速仪,风速告警仪,数字温湿仪,综合气象仪(气象五要素)-上海风云气象仪器有限公司 | 北京包装设计_标志设计公司_包装设计公司-北京思逸品牌设计 | 在线浊度仪_悬浮物污泥浓度计_超声波泥位计_污泥界面仪_泥水界面仪-无锡蓝拓仪表科技有限公司 | 背压阀|减压器|不锈钢减压器|减压阀|卫生级背压阀|单向阀|背压阀厂家-上海沃原自控阀门有限公司 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 仿古建筑设计-仿古建筑施工-仿古建筑公司-汉匠古建筑设计院 | 宝鸡市人民医院| 注塑模具_塑料模具_塑胶模具_范仕达【官网】_东莞模具设计与制造加工厂家 | 罐体电伴热工程-消防管道电伴热带厂家-山东沃安电气 | 冷藏车厂家|冷藏车价格|小型冷藏车|散装饲料车厂家|程力专用汽车股份有限公司销售十二分公司 | 紧急切断阀_气动切断阀_不锈钢阀门_截止阀_球阀_蝶阀_闸阀-上海上兆阀门制造有限公司 | 行业分析:提及郑州火车站附近真有 特殊按摩 ?2025实地踩坑指南 新手如何避坑不踩雷 | 不锈钢水箱生产厂家_消防水箱生产厂家-河南联固供水设备有限公司 | 英超直播_英超免费在线高清直播_英超视频在线观看无插件-24直播网 | 桁架楼承板-钢筋桁架楼承板-江苏众力达钢筋楼承板厂 | 香港新时代国际美容美发化妆美甲培训学校-26年培训经验,值得信赖! | 恒温恒湿试验箱_高低温试验箱_恒温恒湿箱-东莞市高天试验设备有限公司 | 屏蔽泵厂家,化工屏蔽泵_维修-淄博泵业 | 闸阀_截止阀_止回阀「生产厂家」-上海卡比阀门有限公司 | 匀胶机旋涂仪-声扫显微镜-工业水浸超声-安赛斯(北京)科技有限公司 |