经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
PHP实现微信扫码登录功能的两种方式总结
来源:jb51  时间:2022/8/23 11:27:11  对本文有异议

官方文档

微信扫码登录目前有两种方式:

1:在微信作用域执行 ,就是条一个新页面

前端点击一个按钮,请求后端接口条微信作用域

后端php代码如下:

  1. $redirect_uri="http://你的微信开放平台绑定域名下处理扫码事件的方法";
  2. $redirect_uri=urlencode($redirect_uri);//该回调需要url编码
  3. $appID="你的appid";
  4. $scope="snsapi_login";//写死,微信暂时只支持这个值
  5. //准备向微信发请求
  6. $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri
  7. ."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
  8. //请求返回的结果(实际上是个html的字符串)
  9. $result = file_get_contents($url);
  10. //替换图片的src才能显示二维码
  11. $result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result);
  12. return $result; //返回页面

最终跳转页面如下:

2:内嵌js,在当前页面显示登录二维码

第一种操作实现起来比较简单,但是个人感觉用户体验稍微差一点。

最好还是在当前页面就是显示微信登录的二维码,直接扫描就好。

微信也为我们提供了这种方式。

(1):引入js

  1. <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/jquery.min.js"></script>
  2. <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>

(2):html部分

  1. <div id="wx_login_container"></div>

(3):js示例

  1. <script>
  2. $(document).ready(function()
  3. {
  4. var obj = new WxLogin({
  5. self_redirect: true,
  6. id:"wx_login_container",
  7. appid: "appid",
  8. scope: "snsapi_login",
  9. redirect_uri: "回调地址",//这里的回调地址可以写后端的接口,也可以写前端的页面地址,我这里写的是前端的页面地址
  10. state: "",
  11. style: "black",
  12. href: "", //https://某个域名下的css文件
  13. });
  14. });
  15. // 将方法挂载到window主链上
  16. // 从iframe中获取到回调函数中获取的微信返回的code
  17. window.jumpTop = function(code){
  18. console.log(code);
  19. var data = {
  20. code: code
  21. };
  22. console.log(data);
  23. self.axios
  24. .post("/index.php/xxx/wxlogin_notice", data)
  25. .then(result => {
  26. if(result.data.code > 0)
  27. {
  28. Message.success(result.data.msg);
  29. if(result.data.type == 0)
  30. {// 跳学生首页
  31. self.$router.push("/manager/student/reportList");
  32. }
  33. else if(result.data.type == 1 || result.data.type == 9)
  34. {// 跳选择身份页
  35. self.$router.push("/manager/teacher/index");
  36. }
  37. }
  38. })
  39. .catch(err => {});//*/
  40. };
  41. </script>

注意其中href里指向的css文件必须放在https协议下才能引用的到,大体上不需改变默认样式,浪费脑细胞,可以针对div 来改变二维码的大小和位置,里边是内嵌一个iframe

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

微信的二维码嵌入在一个iframe中,微信扫码成功,手机点击确定后,回调地址接收到微信给我们的参数code,这里微信使用的是get传参,因此我们只需要在回调地址的页面中获取当前页面的URL中的code参数传给上一层(父级),上一层接收到code参数再请求后端接口执行登录逻辑即可。

回调地址:

  1. https://www.xxx.xxx/lims/web/wechat/login.html
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <link rel="stylesheet" href="https://res.wx.qq.com/connect/zh_CN/htmledition/style/impowerApp45a337.css" rel="external nofollow" >
  8. <link href="https://res.wx.qq.com/connect/zh_CN/htmledition/images/favicon3696b4.ico" rel="external nofollow" rel="Shortcut Icon">
  9. </head>
  10. <body style="color: rgb(55, 55, 55);">
  11. <div style="">
  12. <div class="main impowerBox">
  13. <div class="loginPanel normalPanel">
  14. <div>微信登录</div>
  15. <div class="waiting panelContent">
  16. <div>
  17. <img class="qrcode lightBorder" src="./img.jpg ">
  18. </div>
  19. <div>
  20. <div class="status status_succ js_status js_wx_after_scan" style="display: block;" id="wx_after_scan">
  21. <i class="status_icon icon38_msg succ"></i>
  22. <div>
  23. <h4>扫描成功</h4>
  24. <p>请在微信中点击确认即可登录</p>
  25. </div>
  26. </div>
  27. </div>
  28. </div>
  29. </div>
  30. </div>
  31. </div>
  32. <script src="https://www.mools.net/lims/web/common/common.js"></script>
  33. <script>
  34. if (parent) {
  35. // 将从url中解析出来的参数传到iframe的父级(调用父级方法)
  36. parent.jumpTop(ml.get("code"));
  37. }
  38. </script>
  39. </body>
  40. </html>

PHP回调代码:(上边的两种扫码方式都可用)

  1. /**
  2. * @name: 微信扫码登陆回调(不跳页二维码)
  3. * @author: camellia
  4. * @date: 2020-12-25 11:47:17
  5. */
  6. public function wxlogin_notice(Request $request)
  7. {
  8. $code = $request->input("code");
  9. if (!empty($code))
  10. {
  11. $jsonResult = '';
  12. if($jsonResult == '')
  13. {
  14. //通过code获得 access_token + openid
  15. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecret . "&code=" . $code . "&grant_type=authorization_code";
  16. $jsonResult = file_get_contents($url);
  17. }
  18. // 对象转数组
  19. $resultArray = json_decode($jsonResult, true);
  20. $access_token = $resultArray["access_token"];
  21. $openid = $resultArray["openid"];
  22. //通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
  23. $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
  24. $infoResult = file_get_contents($infoUrl);
  25. $infoArray = json_decode($infoResult, true);
  26. // 没有unionid ,跳官网
  27. if (!isset($infoArray['unionid']))
  28. {
  29. // echo "<script >alert('登录失败,用户信息错误!')</script>";die;
  30. $result['code'] = -1;
  31. $result['msg'] = '登录失败,用户信息错误!';
  32. return $result;
  33. }
  34. // 获取unionid
  35. $unionid = $infoArray['unionid'];
  36. $userinfo = DB::table('user')->where('unionid', $unionid)->first();
  37. $userinfObj = json_decode(json_encode($userinfo), true);
  38. if ($userinfo)
  39. {
  40. // 存session
  41. $request->session()->put('userinfo', $userinfObj);
  42. // $session = $this->getSession($request);
  43. // var_dump($session);die;
  44. // 教师跳页
  45. if (($userinfo->type == 9) || ($userinfo->type == 1 && $userinfo->islogin == 9))
  46. {
  47. // echo "<script> top.location.href='https://www.xxxx.net/'; </script>";die;
  48. $result['code'] = 1;
  49. $result['msg'] = '登录成功';
  50. $result['type'] = $userinfo->type;
  51. return $result;
  52. }
  53. else if ($userinfo->type == 1 && $userinfo->islogin >= 3)
  54. { // 学生跳页
  55. // echo "<script> top.location.href='https://www.xxxx.net/'; </script>";die;
  56. $result['code'] = 2;
  57. $result['msg'] = '登录成功';
  58. $result['type'] = $userinfo->type;
  59. return $result;
  60. }
  61. else if($userinfo->type == 0)
  62. {
  63. // echo "<script> top.location.href='https://www.xxxx.net/'; </script>";die;
  64. $result['code'] = 3;
  65. $result['msg'] = '登录成功';
  66. $result['type'] = $userinfo->type;
  67. return $result;
  68. }
  69. else
  70. { // 无效用户跳至官网
  71. // echo "<script> top.location.href='https://www.xxxx.net'; </script>";die;
  72. $result['code'] =-2;
  73. $result['msg'] = '用户身份有误!';
  74. return $result;
  75. }
  76. }
  77. else
  78. {
  79. // echo "<script >alert('登录失败,用户信息错误~')</script>";die;
  80. $result['code'] = -3;
  81. $result['msg'] = '用户身份有误!';
  82. return $result;
  83. }
  84. }
  85. else
  86. {
  87. // echo "<script >alert('登录失败,请重试!')</script>";die;
  88. $result['code'] = -4;
  89. $result['msg'] = '登录失败,请重试!';
  90. return $result;
  91. }
  92. }

到此这篇关于PHP实现微信扫码登录功能的两种方式总结的文章就介绍到这了,更多相关PHP微信扫码登录内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号