第三方登录之微信扫码登录

article/2025/9/18 8:48:31

文章目录

    • 1. 申请微信接入:
    • 2. 项目环境搭建:
    • 3.后端Controller接口:
    • 4.HTML页面代码:
    • 5.测试结果:
    • 6.补充说明:

小伙伴们有各种疑问可以去参考官方文档进行详细的学习下 微信开发文档 ,此次介绍的将是前后端不分离的微信扫码登录

微信登录开发流程:

  1. 申请微信接入
  2. 生成登录二维码
  3. 用户扫码并授权
  4. 调用回调方法
  5. 通过code去获取用户信息带到页面展示

官方流程图:
在这里插入图片描述

1. 申请微信接入:

先提醒下各位:申请微信接入很麻烦,本人因为公司业务需要,用的是公司申请好的。还没自己去申请过。

先去到 微信开放平台 https://open.weixin.qq.com

在这里插入图片描述
申请一个网站应用 (要审核通过之后才能用)

在这里插入图片描述
注:

  1. appid和appSecret就是调用微信接口的凭证
  2. 授权回调域:调用微信接口生成的二维码地址,用户扫码并授权后,会重定向到回调地址
  3. 因为在本地localhost进行测试,如果回调地址为localhost第三方微信将无法进行跳转。原因是外网访问不到本地,怎么办?解决办法:那就使用 ngrok 内网穿透把本地项目服务映射到公网,所以在测试时填写的回调地址是内网穿透时的访问域名
  4. 如果不知道内网穿透的小伙伴,建议先看看 Sunny-Ngrok 内网穿透的使用

在这里插入图片描述

如果不知道内网穿透的小伙伴,建议先看看 Sunny-Ngrok 内网穿透的使用

启动 Sunny-Ngrok 内网穿透的客户端,先将本地服务映射到公网。

在这里插入图片描述

2. 项目环境搭建:

下面正式开始代码部分,创建SpringBoot项目并导入所需Jar包:
环境:JDK1.8,SpringBoot2.3.5.RELEASE

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20200518</version></dependency>
</dependencies>

yaml文件:
因为所需要这4个参数,所以直接配置在yaml文件中,使用时直接在类中直接通过@Value注解引入即可

  1. appid:
  2. appsecret:
  3. scope: snsapi_login
  4. callBack:
server:port: 80spring:thymeleaf:prefix: classpath:/templates/suffix: .htmlmvc:static-path-pattern: classpath:/static/wechat:#微信接口的AppID:appid: #微信接口的AppSecret:appsecret: #应用授权作用域(网站应用目前的固定写法就是snsapi_login)scope: snsapi_login#扫码之后的回调地址:callBack: http://wechatlogin.free.idcfengye.com/callBack

这里需要一个工具类HttpRequestUtils ,用于发起http请求。可以将代码直接复制过去用

package com.login.utils;import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;/*** @author: libo* @date: 2020/11/21  20:49* @motto: 即使再小的帆也能远航*/
public class HttpRequestUtils {private static CloseableHttpClient httpClient;static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(100);cm.setDefaultMaxPerRoute(20);cm.setDefaultMaxPerRoute(50);httpClient = HttpClients.custom().setConnectionManager(cm).build();}public static String httpGet(String url) {CloseableHttpResponse response = null;BufferedReader in = null;String result = "";try {HttpGet httpGet = new HttpGet(url);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();httpGet.setConfig(requestConfig);httpGet.setConfig(requestConfig);httpGet.addHeader("Content-type", "application/json; charset=utf-8");httpGet.setHeader("Accept", "application/json");response = httpClient.execute(httpGet);in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = in.readLine()) != null) {sb.append(line + NL);}in.close();result = sb.toString();} catch (IOException e) {e.printStackTrace();} finally {try {if (null != response) {response.close();}} catch (IOException e) {e.printStackTrace();}}return result;}
}

3.后端Controller接口:

package com.login.controller;import com.login.utils.HttpRequestUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;/*** @author: libo* @date: 2020/11/21  21:32* @motto: 即使再小的帆也能远航*/
@Controller
@CrossOrigin
@SuppressWarnings("unchecked")
public class weChatController {@Value(value = "${wechat.appid}")private String appid;@Value(value = "${wechat.appsecret}")private String appsecret;@Value(value = "${wechat.scope}")private String scope;@Value(value = "${wechat.callback}")private String callBack;/*生产二维码链接进行扫码登录*/@RequestMapping("/login")public String index(Model model) throws Exception {String oauthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";String redirect_uri = URLEncoder.encode(callBack, "utf-8");oauthUrl = oauthUrl.replace("APPID", appid).replace("REDIRECT_URI", redirect_uri).replace("SCOPE", scope);model.addAttribute("oauthUrl", oauthUrl);return "login";}/*生成自定义二维码*/@RequestMapping("/custom")public String custom(Model model) throws UnsupportedEncodingException {String redirect_uri = URLEncoder.encode(callBack, "utf-8");model.addAttribute("appid", appid);model.addAttribute("scope", scope);model.addAttribute("redirect_uri", redirect_uri);return "custom";}/*回调方法*/@RequestMapping("/callBack")public String callBack(String code,Map<String,Object> map) {//1.通过code获取access_tokenString url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";url = url.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);String tokenInfoStr = HttpRequestUtils.httpGet(url);JSONObject tokenInfoObject = new JSONObject(tokenInfoStr);//2.通过access_token和openid获取用户信息String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN", tokenInfoObject.getString("access_token")).replace("OPENID", tokenInfoObject.getString("openid"));String userInfoStr = HttpRequestUtils.httpGet(userInfoUrl);map.put("token", tokenInfoStr);/*转为JSON*/JSONObject user = new JSONObject(userInfoStr);/*只获取openid并返回,openid是微信用户的唯一标识,userInfoStr里面有用户的全部信息*/String openid = user.getString("openid");map.put("openid", openid);/*获取用户头像url*/String headimgurl = user.getString("headimgurl");map.put("headimgurl", headimgurl);/*获取用户昵称*/String nickname = user.getString("nickname");map.put("nickname", nickname);/*获取用户性别*/int sex = user.getInt("sex");map.put("sex", sex);/*获取用户国家*/String country = user.getString("country");map.put("country", country);/*获取用户省份*/String province = user.getString("province");map.put("province", province);/*获取用户城市*/String city = user.getString("city");map.put("city", city);return "callBack";}}

4.HTML页面代码:

1.点击生成二维码页面:我这里是嵌入了一张微信的Logo图片,点击a标签跳转 weChatLogin.html在这里插入图片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>wechat登录</title>
</head>
<body><a th:href="${oauthUrl}"><img src="../static/wechat_logo.png" alt="微信登录"></a>
</body>
</html>

2.回调方法后返回用户信息页面 callBack.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>授权结果页</title>
</head>
<body><h2>用戶,授权成功!</h2><br><h3>通过code获取access_token 结果:</h3><p th:text="${token}"></p><h3>通过access_token获取用户信息 结果:</h3>头像:<img th:src="${headimgurl}" alt="用户头像"><br/>openid:<span th:text="${openid}"></span><br/>昵称:<span th:text="${nickname}"></span><br/>性别:<span th:text="${sex}"></span><br/>国家:<span th:text="${country}"></span><br/>省份:<span th:text="${province}"></span><br/>城市:<span th:text="${city}"></span></body>
</html>

3.内嵌(自定义二维码) custom.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>内嵌(自定义二维码)</title>
</head>
<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<body><center><div id="login_container"></div></center>
<script th:inline="javascript">var obj = new WxLogin({self_redirect:true,id:"login_container",appid: [[${appid}]],scope: [[${scope}]],redirect_uri: [[${redirect_uri}]],state: "",style: "",href: ""});
</script>
</body>
</html>

5.测试结果:

使用内网穿透的域名来访问接口哦,因为已经在公网映射到本地项目了

  1. 访问login接口,点击logo图标
    在这里插入图片描述

  2. 扫码测试

在这里插入图片描述

  1. 授权后调用回调方法,拿到用户信息放到页面展示
    注:openid是微信用户的唯一id

在这里插入图片描述

6.补充说明:

到这里呢微信登录SpringBoot前后端不分离就差不多了,在这里想给大家提一下如果是前后端分离怎么做?

1.回调地址一般是网站的主页对吧,例如:www.abc.com
2.前端按钮通过appid和回调地址生成二维码
3.用户扫码授权之后,微信接口会再通过回调地址重定向回主页 www.abc.com。在这是会有一个名为code的参数
4.此时前端拥有code之后,传到后端接口方法中去,后端通过code获取用户信息。再返回前端

总结为一句话:1.www.adc.com主页生成二维码,2.扫码授权登录,3.拿code参数去获取用户信息

如果我们有再三思考的机会,几乎没有一件事情是不能被简化的。

http://chatgpt.dhexx.cn/article/iWxllj8H.shtml

相关文章

扫码登录操作过程

转载自http://justcoding.iteye.com/blog/2213661浏览器输入&#xff1a;https://wx.qq.com/?langzh_CN手机登录微信&#xff0c;利用“扫一扫”功能扫描网页上的二维码手机扫描成功后&#xff0c;提示“登录网页版微信”&#xff1b;网页上显示“成功扫描 请在手机点击确认以…

实现手机扫描二维码进行登录

项目结构&#xff1a; 实现流程&#xff1a; pc端&#xff1a; 1:打开二维码登录网页index.html 2:index.html调用GetQrCodeServlet 3:GetQrCodeServlet干2件事 a:生成随机的uuid,是一个唯一标识&#xff0c;该标识贯穿整个流程 b:生成二维码图片&#xff0c;二维码信息&#x…

扫码登录,背后是如何实现的?

引言 近年来&#xff0c;随着智能手机和移动支付的普及以及互联网应用的不断更新迭代&#xff0c;扫码登录已经成为了我们日常生活中非常普遍的登录方式。扫码登录能够迅速的成为我们各大网站常用的登录方式一定存在它的原因。 首先一个非常重要的原因&#xff0c;扫码登录还可…

网站实现微信扫码登录

网站实现微信扫码登录 1 准备工作1.1 申请网站应用 2 快速开始2.1 微信扫码登录流程说明2.2 生成微信二维码的两种方式2.2.1 微信提供的二维码生成URL2.2.2 将微信登录二维码内嵌到自己页面 2.3 系统微信扫码登录示例2.3.1 流程说明2.3.2 核心代码2.3.2.1 前端代码2.3.2.2 后端…

【一】微信公众号之扫码登录

微信公众号之扫码登录 ​ 原来公司的官网就支持账号密码、手机验证码、QQ扫码授权、微信扫码授权等多种登录方式。今天要分享的就是关于微信扫码授权登录的原理。 一、准备工作 使用的是微信登录功能实现的&#xff0c;需要先在微信开放平台注册开发者帐号&#xff0c;并拥有一…

公众号扫码登录

1.流程概述 1.1 申请公众号 1.2 创建带参数的公众号二维码&#xff0c;参数值为scen_id的值 1.3 微信基础配置接口编写&#xff0c;get方式的接口为微信测试接口&#xff0c;必须能正常访问&#xff0c;post方式的接口为扫码回调接口&#xff0c;从请求中获取微信返回的xml包…

二维码扫描登录,你必须知道的 3 件事!

作者 | 互联网平头哥 本文经授权转载自互联网平头哥&#xff08;ID&#xff1a;it_pingtouge&#xff09; 扫二维码登录现在比较常见&#xff0c;比如微信、支付宝等 PC 端登录&#xff0c;并且好像每款 APP 都支持扫码登录&#xff0c;不搞个扫码登录都不好意思。作为技术人员…

微信扫码登录实现

需求 使用微信扫码登录的授权方式登录系统 实现 此扫码登陆过程中使用了&#xff0c;微信开放平台&#xff08;需支付300开通开发者认证&#xff09;的网站应用实现的。 官方文档&#xff1a;https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wec…

web扫码登录

文章目录 需求流程交互流程服务交互流程 关键思路代码生成二维码&#xff0c;返回给PC展示轮询查询二维码状态APP扫码请求登录 总结 需求 pc端实现app扫码登录 流程 交互流程 服务交互流程 关键思路 主要问题在于如何识别APP端用户&#xff0c;然后传递给PC端已经登录成功 …

开放平台–扫描微信二维码登录

准备 如不了解第三方登录流程&#xff0c;建议先大概了解一下&#xff0c;在来看看代码。 说明&#xff1a; 由于开放平台无测试号测试&#xff0c;所以只能上开放平台进行配置信息。公众平台的测试号并不能给开放平台使用。 微信开放平台地址&#xff1a;https://open.weixi…

二维码登陆

上一段时间研究微信公共账号,发现微信提供了一个扫码登陆验证的功能。近期头痛于经常忘记用户名密码,因此考虑是否可以结合这个功能,完成免密码登陆。百度后发现&#xff0c;有很多仁兄已经做过类似的功能了。 如这篇文章: 实现网站二维码扫描登录 仔细研究后&#xff0c;发现很…

二维码登录(三)扫码登录

承接上篇博客&#xff0c;在进行二维码生成之后&#xff0c;app进行扫码&#xff0c;扫码成功之后&#xff0c;手机点击登录&#xff0c;进行绑定登录关系&#xff0c;后台做自动关联与自动登录。 本文git地址&#xff1a;https://github.com/xvshu/qrlogin 1&#xff0c;扫码…

微信扫码登陆(1)---扫码登录流程讲解、获取授权登陆二维码

扫码登录流程讲解、获取授权登陆二维码 具体流程可以看微信官网的扫码登录文档 地址&#xff1a;准备工作 | 微信开放文档 其实官方文档已经讲的非常清楚而且讲的也很明白。 一、扫码登录流程讲解 1、首先准备工作 网站应用微信登录是基于OAuth2.0协议标准构建的微信OAut…

二维码扫码登录

项目结构 模块介绍 流程1 pc端&#xff1a;1:打开二维码登录网页index.html2:index.html调用GetQrCodeServlet3:GetQrCodeServlet干2件事 a:生成随机的uuid,是一个唯一标识&#xff0c;该标识贯穿整个流程 b:生成二维码图片&#xff0c;二维码信息&#xff1a;http://60.2…

扫码登录详解

目录 扫码流程分析 流程详解 步骤一&#xff1a;PC端准备二维码 步骤三&#xff1a;状态确认 token认证机制 扫码流程分析 1.扫码前&#xff0c;手机端已经是登陆状态&#xff0c;PC端显示一个二维码&#xff0c;等待扫描。 2.手机端打开应用&#xff0c;扫描PC端的二维码…

新增商品

1、在http代理设置&#xff0c;添加过滤参数&#xff1a; .*pusher\.*\/websocket.* .*/venilog/log/one .*\.(bmp|css|js|gif|ico|jpe?g|png|swf|woff) .*pusher\/info.* 2、启动http代理设置&#xff0c;录制脚本&#xff0c;将登陆和发布商品的脚本修改成’登陆‘&#x…

自定义商品分类,选择分类之后,添加商品附属性;仿淘宝后台添加商品附属性的价格和数量

效果图&#xff08;图片较大&#xff0c;加载较慢&#xff09; 页面部分&#xff1a; <div class"layui-form-item" id"add_attribute"><label class"layui-form-label">商品分类</label><div class"layui-input-i…

javaScript原生版购物车:全选、单选、全删、商品数量增减、计算总价、添加商品(代码)

题目&#xff1a; CSS代码如下&#xff1a; <style> *{ margin: 0px; padding: 0px; } .header,.content,.floot{ width: 800px; margin:0px auto; } .header ul li,.content ul li{ float: left; list-style: none; width: 100px; line-height: 100px; text-align: cen…

商品管理的新增

实现的功能如下&#xff1a; 点击新增弹出新增模态框通过下拉框绑定商品类别和商品单位保存新增 主要代码&#xff1a; 以上就是我的分享&#xff0c;如果有更好的方法或不懂得地方欢迎在评论区教导和提问喔&#xff01;

案例:实现在购物车中添加商品和删除购物车中指定商品的功能

一、向购物车中添加商品 1.1.创建AddCartServlet public class AddCartServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}SuppressWarnings(&q…