官方文档
微信扫码登录目前有两种方式:
1:在微信作用域执行 ,就是条一个新页面
前端点击一个按钮,请求后端接口条微信作用域
后端php代码如下:
- $redirect_uri="http://你的微信开放平台绑定域名下处理扫码事件的方法";
- $redirect_uri=urlencode($redirect_uri);//该回调需要url编码
- $appID="你的appid";
- $scope="snsapi_login";//写死,微信暂时只支持这个值
- //准备向微信发请求
- $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri
- ."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
- //请求返回的结果(实际上是个html的字符串)
- $result = file_get_contents($url);
- //替换图片的src才能显示二维码
- $result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result);
- return $result; //返回页面
最终跳转页面如下:

2:内嵌js,在当前页面显示登录二维码
第一种操作实现起来比较简单,但是个人感觉用户体验稍微差一点。
最好还是在当前页面就是显示微信登录的二维码,直接扫描就好。
微信也为我们提供了这种方式。
(1):引入js
- <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/jquery.min.js"></script>
- <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
(2):html部分
- <div id="wx_login_container"></div>
(3):js示例
- <script>
-
- $(document).ready(function()
- {
- var obj = new WxLogin({
- self_redirect: true,
- id:"wx_login_container",
- appid: "appid",
- scope: "snsapi_login",
- redirect_uri: "回调地址",//这里的回调地址可以写后端的接口,也可以写前端的页面地址,我这里写的是前端的页面地址
- state: "",
- style: "black",
- href: "", //https://某个域名下的css文件
- });
- });
- // 将方法挂载到window主链上
- // 从iframe中获取到回调函数中获取的微信返回的code
- window.jumpTop = function(code){
- console.log(code);
- var data = {
- code: code
- };
- console.log(data);
- self.axios
- .post("/index.php/xxx/wxlogin_notice", data)
- .then(result => {
- if(result.data.code > 0)
- {
- Message.success(result.data.msg);
- if(result.data.type == 0)
- {// 跳学生首页
- self.$router.push("/manager/student/reportList");
- }
- else if(result.data.type == 1 || result.data.type == 9)
- {// 跳选择身份页
- self.$router.push("/manager/teacher/index");
- }
- }
- })
- .catch(err => {});//*/
- };
-
- </script>
注意其中href里指向的css文件必须放在https协议下才能引用的到,大体上不需改变默认样式,浪费脑细胞,可以针对div 来改变二维码的大小和位置,里边是内嵌一个iframe

整理的实现逻辑如下图所示:

微信的二维码嵌入在一个iframe中,微信扫码成功,手机点击确定后,回调地址接收到微信给我们的参数code,这里微信使用的是get传参,因此我们只需要在回调地址的页面中获取当前页面的URL中的code参数传给上一层(父级),上一层接收到code参数再请求后端接口执行登录逻辑即可。
回调地址:
- https://www.xxx.xxx/lims/web/wechat/login.html
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://res.wx.qq.com/connect/zh_CN/htmledition/style/impowerApp45a337.css" rel="external nofollow" >
- <link href="https://res.wx.qq.com/connect/zh_CN/htmledition/images/favicon3696b4.ico" rel="external nofollow" rel="Shortcut Icon">
- </head>
- <body style="color: rgb(55, 55, 55);">
- <div style="">
- <div class="main impowerBox">
- <div class="loginPanel normalPanel">
- <div>微信登录</div>
- <div class="waiting panelContent">
- <div>
- <img class="qrcode lightBorder" src="./img.jpg ">
- </div>
- <div>
- <div class="status status_succ js_status js_wx_after_scan" style="display: block;" id="wx_after_scan">
- <i class="status_icon icon38_msg succ"></i>
- <div>
- <h4>扫描成功</h4>
- <p>请在微信中点击确认即可登录</p>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <script src="https://www.mools.net/lims/web/common/common.js"></script>
- <script>
- if (parent) {
- // 将从url中解析出来的参数传到iframe的父级(调用父级方法)
- parent.jumpTop(ml.get("code"));
- }
- </script>
- </body>
- </html>
PHP回调代码:(上边的两种扫码方式都可用)
- /**
- * @name: 微信扫码登陆回调(不跳页二维码)
- * @author: camellia
- * @date: 2020-12-25 11:47:17
- */
- public function wxlogin_notice(Request $request)
- {
- $code = $request->input("code");
- if (!empty($code))
- {
- $jsonResult = '';
- if($jsonResult == '')
- {
- //通过code获得 access_token + openid
- $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecret . "&code=" . $code . "&grant_type=authorization_code";
- $jsonResult = file_get_contents($url);
- }
- // 对象转数组
- $resultArray = json_decode($jsonResult, true);
- $access_token = $resultArray["access_token"];
- $openid = $resultArray["openid"];
- //通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
- $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
- $infoResult = file_get_contents($infoUrl);
- $infoArray = json_decode($infoResult, true);
- // 没有unionid ,跳官网
- if (!isset($infoArray['unionid']))
- {
- // echo "<script >alert('登录失败,用户信息错误!')</script>";die;
- $result['code'] = -1;
- $result['msg'] = '登录失败,用户信息错误!';
- return $result;
- }
- // 获取unionid
- $unionid = $infoArray['unionid'];
- $userinfo = DB::table('user')->where('unionid', $unionid)->first();
- $userinfObj = json_decode(json_encode($userinfo), true);
- if ($userinfo)
- {
- // 存session
- $request->session()->put('userinfo', $userinfObj);
-
- // $session = $this->getSession($request);
- // var_dump($session);die;
-
- // 教师跳页
- if (($userinfo->type == 9) || ($userinfo->type == 1 && $userinfo->islogin == 9))
- {
- // echo "<script> top.location.href='https://www.xxxx.net/'; </script>";die;
- $result['code'] = 1;
- $result['msg'] = '登录成功';
- $result['type'] = $userinfo->type;
- return $result;
- }
- else if ($userinfo->type == 1 && $userinfo->islogin >= 3)
- { // 学生跳页
- // echo "<script> top.location.href='https://www.xxxx.net/'; </script>";die;
- $result['code'] = 2;
- $result['msg'] = '登录成功';
- $result['type'] = $userinfo->type;
- return $result;
- }
- else if($userinfo->type == 0)
- {
- // echo "<script> top.location.href='https://www.xxxx.net/'; </script>";die;
- $result['code'] = 3;
- $result['msg'] = '登录成功';
- $result['type'] = $userinfo->type;
- return $result;
- }
- else
- { // 无效用户跳至官网
- // echo "<script> top.location.href='https://www.xxxx.net'; </script>";die;
- $result['code'] =-2;
- $result['msg'] = '用户身份有误!';
- return $result;
- }
- }
- else
- {
- // echo "<script >alert('登录失败,用户信息错误~')</script>";die;
- $result['code'] = -3;
- $result['msg'] = '用户身份有误!';
- return $result;
- }
- }
- else
- {
- // echo "<script >alert('登录失败,请重试!')</script>";die;
- $result['code'] = -4;
- $result['msg'] = '登录失败,请重试!';
- return $result;
- }
- }
到此这篇关于PHP实现微信扫码登录功能的两种方式总结的文章就介绍到这了,更多相关PHP微信扫码登录内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!