广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >PHP实现微信扫码登录功能的两种方式总结
  • 488
分享到

PHP实现微信扫码登录功能的两种方式总结

2024-04-02 19:04:59 488人浏览 泡泡鱼
摘要

官方文档 微信扫码登录目前有两种方式: 1:在微信作用域执行 ,就是条一个新页面 前端点击一个按钮,请求后端接口条微信作用域 后端PHP代码如下: $redirect_ur

官方文档

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

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 => {});/
    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微信扫码登录内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: PHP实现微信扫码登录功能的两种方式总结

本文链接: https://www.lsjlt.com/news/165729.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作