微信扫码登录详细操作流程(微信公众平台开发)

您所在的位置:网站首页 微信公众平台登录页面在哪里 微信扫码登录详细操作流程(微信公众平台开发)

微信扫码登录详细操作流程(微信公众平台开发)

2024-06-09 20:08:10| 来源: 网络整理| 查看: 265

在平常的业务开发中,经常会涉及到扫码登录的案例。下面我将对扫码登录流程做简要概述。

1、概念

首先需要清楚的是扫码登录大体上有两种实现方式。(重点)

一种是基于微信公众平台的扫码登录,另一种是基于微信开放平台的扫码登录。注意这两个平台一定要区分开。在这里做简要解释:

微信开放平台就是为了让第三方应用投入微信的怀抱而设计的,这第三方应用指的是比如android、ios、网站、系统等;微信公众平台就是为了让程序员小伙伴利用微信自家技术(公众号、小程序)开发公众号、小程序而准备的。

微信开放平台入口:https://open.weixin.qq.com/ 

微信公众平台入口:https://mp.weixin.qq.com/ 

 微信开放平台也有公众号开发,不过点进去会发现它让你跳转到微信公众平台。

注意两者使用微信扫码登录的区别:

微信开放平台需要开企业认证才能注册。

 微信公众平台需要认证微信服务号,才能进行扫码登录的开发。

下面我们使用第二种方式(微信公众号开发)

2、开发

首先我们介绍微信开发的主要流程:开发文档地址

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

我们携同微信开发,所需的接口和微信用户的信息需要请求微信服务器。

微信服务器提供很多接口便于与开发者进行交互,所以首先需要接入微信服务器。

主要步骤:

1、填写服务器配置

2、验证服务器地址的有效性

3、依据接口文档实现业务逻辑

第一步:

        简单来说,URL为开发者服务器的接口地址,微信服务器通过该接口与开发者服务器建立连接。Token可由开发者可以任意填写,用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)

第二步:

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:

参数描述signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。timestamp时间戳nonce随机数echostr随机字符串

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。 

第三步:

验证URL有效性成功后即接入生效,成为开发者。进入成功后微信服务器与开发者的服务器建立了连接,便可进一步进行业务开发和接口调用。

验证签名的主要代码:

/** * 验证签名,扫码后回调验证签名 * @param request * @return * @throws Exception */ @RequestMapping("checkSign") public String checkSign ( HttpServletRequest request) throws Exception { log.info("===========>checkSign"); //获取微信请求参数 String signature = request.getParameter ("signature"); String timestamp = request.getParameter ("timestamp"); String nonce = request.getParameter ("nonce"); String echostr = request.getParameter ("echostr"); //参数排序。 token 就要换成自己实际写的 token String [] params = new String [] {timestamp,nonce,wxConfig.getToken()} ; Arrays.sort (params) ; //拼接 String paramstr = params[0] + params[1] + params[2] ; //加密 //获取 shal 算法封装类 MessageDigest Sha1Dtgest = MessageDigest.getInstance("SHA-1") ; //进行加密 byte [] digestResult = Sha1Dtgest.digest(paramstr.getBytes ("UTF-8")); //拿到加密结果 String mysignature = CodeLoginUtil.bytes2HexString(digestResult); mysignature=mysignature.toLowerCase(Locale.ROOT); //是否正确 boolean signsuccess = mysignature.equals(signature); //逻辑处理 if (signsuccess && echostr!=null) { //验证签名,接入服务器 return echostr ; }else{ //接入失败或已经接入成功后 JSONObject jsonObject = callback(request); return jsonObject.toJSONString(); } }

微信扫码登录的主要流程:

需要在微信公众平台的配置:

配置服务器接口地址,微信服务器会将信息传给开发者服务器的该接口地址。

 在这里用微信公众号的测试号演示,和真实的公众号配置一样。

 填写服务器的域名:

 以上两个配置完毕即可进行扫码登录的开发。服务器域名可以通过内网穿透工具获得,请移步百度。

开发的主要流程:

1、服务器向微信服务器发送请求,获取唯一接口调用凭据access_token。

url请求(1):

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

通过appid和secret获取access_token,access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。appid是公众号的标识,每个公众号都会有一个appid,相当于公众号的账号,secret为公众号密码。

2、通过access_token来换取调用二维码的凭借ticket。

url请求(2):

https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN

凭借ticket到指定URL换取二维码。每次创建二维码ticket需要提供一个开发者自行设定的参数(scene_id)。

目前有2种类型的二维码:

        临时二维码,是有过期时间的,最长可以设置为在二维码生成后的30天(即2592000秒)后过期,但能够生成较多数量。临时二维码主要用于帐号绑定等不要求二维码永久保存的业务场景

        永久二维码,是无过期时间的,但数量较少(目前为最多10万个)。永久二维码主要用于适用于帐号绑定、用户来源统计等场景。

3、通过ticket到指定URL获取带参二维码。

url请求(3):

https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET

4、获取二维码后用户进行扫描。微信服务器会收到用户扫描成功的信息,并通过开始配置的URL回调地址将扫描事件推送给服务器。服务器会收到微信用户的openid和带参二维码的参数等信息,并进行业务的处理。可以通过openid和access_token获取用户的基本信息。openi在同一个公众号内用来唯一的标识一个微信用户。

url请求(4):

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN 

 由上图可分析:可以在浏览器端在用户获取二维码并扫码后,启动定时任务。间断的向服务器发送请求,当服务器收到微信服务器的通知并确定用户已经扫码后,将信息返回给浏览器,浏览器

取消定时任务,并跳转扫码成功页面。这一步骤亦可在服务器端进行监听,若收到微信服务器的通知,进行处理后将信息返回给浏览器。

注开发时的域名可以使用内网穿透工具。。。。

以上便是简要流程。主要代码如下:

后台controller层

/** * @Author lx * @Description 微信扫码登录 * @Description 回调地址 http://域名/wx/qrCodeFirstLogin/checkSign * @Date 15:21 2021/7/20 **/ @Slf4j @RestController @RequestMapping(GlobalConstant.WX_URL_PREFIX+"/qrCodeFirstLogin") // /wx/qrCodeFirstLogin public class QrCodeLoginFirstController { @Autowired private WxUserInfoService wxUserInfoService; @Autowired private RedisUtil redisUtil; @Autowired private WxConfig wxConfig; // 模拟数据库存储或者缓存存储 Map loginMap = new ConcurrentHashMap(64); /** * 获取登录二维码 * @return */ @GetMapping("getQrCode") private ResultJson getQrCode(){ try { log.info("getQ"); // 获取token开发者 String accessToken =getAccessToken(); String getQrCodeUrl = wxConfig.getQrCodeUrl().replace("TOKEN", accessToken); // 这里生成一个带参数的二维码,参数是scene_str String sceneStr = CodeLoginUtil.getRandomString(8); String json="{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\"" +", \"action_info\": {\"scene\": {\"scene_str\": \""+sceneStr+"\"}}}"; String result = HttpClientUtil.doPostJson(getQrCodeUrl,json); JSONObject jsonObject = JSONObject.parseObject(result); jsonObject.put("sceneStr",sceneStr); /* ticket expire_seconds url sceneStr*/ return ResultJson.ok(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResultJson.error(e.getMessage()); } } /** * 获取accessToken * @return */ public String getAccessToken(){ String accessToken = null; //根据appid和appsecret获取access_token String getTokenUrl = wxConfig.getTokenUrl().replace("APPID", wxConfig.getAppId()).replace("APPSECRET", wxConfig.getAppSecret()); String result = HttpClientUtil.doGet(getTokenUrl); JSONObject jsonObject = JSONObject.parseObject(result); accessToken = jsonObject.getString("access_token"); return accessToken ; } /** * 验证签名,扫码后回调验证签名 * @param request * @return * @throws Exception */ @RequestMapping("checkSign") public String checkSign ( HttpServletRequest request) throws Exception { log.info("===========>checkSign"); //获取微信请求参数 String signature = request.getParameter ("signature"); String timestamp = request.getParameter ("timestamp"); String nonce = request.getParameter ("nonce"); String echostr = request.getParameter ("echostr"); //参数排序。 token 就要换成自己实际写的 token String [] params = new String [] {timestamp,nonce,wxConfig.getToken()} ; Arrays.sort (params) ; //拼接 String paramstr = params[0] + params[1] + params[2] ; //加密 //获取 shal 算法封装类 MessageDigest Sha1Dtgest = MessageDigest.getInstance("SHA-1") ; //进行加密 byte [] digestResult = Sha1Dtgest.digest(paramstr.getBytes ("UTF-8")); //拿到加密结果 String mysignature = CodeLoginUtil.bytes2HexString(digestResult); mysignature=mysignature.toLowerCase(Locale.ROOT); //是否正确 boolean signsuccess = mysignature.equals(signature); //逻辑处理 if (signsuccess && echostr!=null) { //验证签名,接入服务器 return echostr ; }else{ //接入失败或已经接入成功后 JSONObject jsonObject = callback(request); return jsonObject.toJSONString(); } } /** * 回调方法 * @param request * @return * @throws Exception */ public JSONObject callback(HttpServletRequest request) throws Exception{ log.info("===========>callback"); //request中有相应的信息,进行解析 WxMpXmlMessage message= WxMpXmlMessage.fromXml(request.getInputStream());//获取消息流,并解析xml String messageType=message.getMsgType(); //消息类型 String messageEvent=message.getEvent(); //消息事件 // openid String fromUser=message.getFromUser(); //发送者帐号 String touser=message.getToUser(); //开发者微信号 String text=message.getContent(); //文本消息 文本内容 // 生成二维码时穿过的特殊参数 String eventKey=message.getEventKey(); //二维码参数 String uuid=""; //从二维码参数中获取uuid通过该uuid可通过websocket前端传数据 String userid=""; //if判断,判断查询 JSONObject jsonObject = new JSONObject(); jsonObject.put("code","200"); if(messageType.equals("event")){ jsonObject = null; //先根据openid从数据库查询 => 从自己数据库中查取用户信息 => jsonObject WxUser wxUser = wxUserInfoService.getByOpenId(fromUser); if(wxUser!=null){ String jsonString = JSON.toJSONString(wxUser); jsonObject = JSONObject.parseObject(jsonString); } if(messageEvent.equals("SCAN")){ log.info("欢迎回来"); //扫描二维码 //return "欢迎回来"; } if(messageEvent.equals("subscribe")){ //关注 //return "谢谢您的关注"; log.info("感谢您的关注"); eventKey = eventKey.substring(8); System.out.println(eventKey); } if(messageEvent.equals("unsubscribe")){ //取消关注,从数据库中删除用户信息 wxUserInfoService.removeByOpenId(fromUser); } //没有该用户 if(jsonObject==null){ //从微信上中拉取用户信息 String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" +getAccessToken() + "&openid=" + fromUser + "&lang=zh_CN"; String result = HttpClientUtil.doGet(url); jsonObject = JSONObject.parseObject(result); //获取用户信息字段 String nickname = jsonObject.getString("nickname"); String sex = jsonObject.getString("sex"); String province = jsonObject.getString("province"); String city = jsonObject.getString("city"); String country = jsonObject.getString("country"); String headimgurl = jsonObject.getString("headimgurl"); WxUser wxUser1 = new WxUser(fromUser, nickname, Integer.parseInt(sex), province, city, country, headimgurl); //判断数据库中是否有重复数据,没有重复数据插入数据库 wxUserInfoService.save(wxUser1); } // 扫码成功,存入缓存 loginMap.put(eventKey,new CodeLoginKey(eventKey,fromUser)); return jsonObject; } return jsonObject; //log.info("消息类型:{},消息事件:{},发送者账号:{},接收者微信:{},文本消息:{},二维码参数:{}",messageType,messageEvent,fromUser,touser,text,eventKey); } /** * 根据二维码标识获取用户openId=>获取用户信息 * @param eventKey * @return */ @RequestMapping("getOpenId") public ResultJson getOpenId(String eventKey){ if(loginMap.get(eventKey) == null){ return ResultJson.error("未扫码成功!") ; } CodeLoginKey codeLoginKey = loginMap.get(eventKey); String openId = codeLoginKey.getOpenId(); loginMap.remove(eventKey); return ResultJson.ok(codeLoginKey); } }

前端页面:

微信扫码登录 *{ padding: 0; margin: 0; } body{ background: aqua url("/images/bodybg.png"); } #container{ margin: 0px auto; display: flex; justify-content: center; margin-top: 100px; color: rgb(140,0,0); font-size: 20px; } #container span{ font-family: "楷体"; } #bottom{ display: flex; margin: 0 auto; justify-content: space-around; } #bottom button{ padding: 5px 20px; background-color: rgb(140,0,0); color:#ffffff; font-size: 18px; border: none; border-radius: 5px; } #bottom button:hover{ padding: 5px 20px; background-color: #ffffff; color:rgb(140,0,0); font-size: 18px; border: 2px solid rgb(140,0,0); border-radius: 5px; } #emPower{ margin-right: 20px; } #right, #left{ width: 300px; height: 300px; padding: 50px; background: url("/images/wxCode.png"); } .qrCodeImgId{ display: none; } 温馨提示: 微信登录后,您可以在微信公众号查看自己的捐赠信息,您的捐赠信息还有可能被展示在平台主页 扫码授权 跳过授权 $("#emPower").on("click",function(){ if($("#right").hasClass("qrCodeImgId")){ $("#right").removeClass("qrCodeImgId"); }else{ $("#right").addClass("qrCodeImgId"); } }) // 存储二维码标识,用于验证是否扫码成功 var sceneStr; var t; // 获取登录二维码 function getQrCode(){ $.ajax({ url:'/wx/qrCodeFirstLogin/getQrCode', success: function (data) { console.log("=============getQrCode======================="); console.log(data); if (data.code == 200) { sceneStr = data.data.sceneStr; $('#qrCodeImgId').attr('src', "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + data.data.ticket); $('#qrCodeImgId').show(); t = window.setInterval(getOpenId, 3000); } else { alert(data.msg); } } }); } // 扫码成功,获取用户openId=>为获取用户信息做准备 function getOpenId() { $.ajax({ url:'/wx/qrCodeFirstLogin/getOpenId', data:{ "eventKey":sceneStr}, success:function (data) { if (data.code == 200) { console.log("========getOpenId=========="); console.log(data.data); window.clearInterval(t); window.location.href = "/wx/toDonate?openId="+data.data.openId alert("登录成功"); /** * 1、第一次扫码登录进行账号绑定 * 2、以后根据openId获取用户信息 */ } } }); } $("#cancelEmPower").on("click",function () { var data={ payMoney:$("#payMoney").val(), projectName:$("#projectName").val(), projectId:$("#projectId").val(), projectPicture:$("#projectPicture").val() } window.location.href = "/wx/jumpWxCode?"+$.param(data) })

application.yml配置文件 

#微信扫码配置 wx: appId: wx1cf8b00a31a96cc1 appSecret: XXXXXXXXXXXXXXXXXXX server: http://rgu7d8.natappfree.cc qrCodeUrl: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN #获取二维码 tokenUrl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET #基础接口的token openIdUrl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET #获取openId userInfoUrl: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN #获取用户 token: weixin #验证签名

wxConfig用于获取配置文件的信息。

@Data @Component @ConfigurationProperties(prefix = "wx") //配置yml文件的前置名 public class WxConfig { private String appId; //公众号标识 private String appSecret; //公众号密码 private String server; //服务器域名地址,用于微信服务器回调。 private String qrCodeUrl; //获取code接口 private String tokenUrl; //获取token接口 private String openIdUrl; //获取openid接口 private String userInfoUrl; //获取用户信息接口 private String token; //验证接口的标识 }



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭