微信开放平台 微信登录-扫码登录[通俗易懂]

微信开放平台 微信登录-扫码登录[通俗易懂]需求:后台需要添加微信扫码登录,要求能跟小程序用户绑定,同步用户信息。

大家好,又见面了,我是你们的朋友全栈君。

需求:后台需要添加微信扫码登录。
首先需要阅读官方文档,了解大致过程。介绍有两种微信扫码,一是跳转到微信网页生成的二维码进行扫码,二是把二维码内嵌到自己的网站页面。下面微信文档。
https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
准备:
1.appid 开放平台查找
2.redirect_uri 回调链接 跟开放平台配置一致,使用时需要urlEncode处理。用php 处理直接用urlEncode,用JavaScript处理用urlEncode没反应的话就用,encodeURIComponent。
微信文档截图
例一,跳转扫码


<?php
$appid = "填写你的APPID";
$redirect_uri = UrlEncode("http://www.baidu.com/login.php");
$data = time();
$state = MD5($data);
//跳转页面
echo "<script>location.href=\"https://open.weixin.qq.com/connect/qrconnect?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_login&state=$state#wechat_redirect\";</script>";
?>

效果
在这里插入图片描述
情形二:把二维码内嵌到网页

<!-- 引入微信扫码登录js文件 -->
<script type="text/javascript" src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
</head>
<body>
  <!-- 放置二维码的div -->
  <div id="login_container"></div>
</body>
<script type="text/javascript">
var obj = new WxLogin({ 
   
  self_redirect:true,
  id:"login_container", //二维码容器id
  appid: "wxbdc5610cc59c1631", 
  scope: "snsapi_login", 
  redirect_uri: encodeURIComponent("http://"+window.location.host+"/..."), 
  state: Math.ceil(Math.random()*1000), 
 // style: "black",//黑底或者白底 可不填
  href: ""//样式,公网链接样式,可不填
});
</script>

效果:
内嵌二维码效果图
回调处理:

public function callback(){ 
   
        $code = input('code');
        if($code){ 
   
            $WxLogin = new \WxLogin\WxLogin();//这个是我封装的获取用户信息的类
            $re = $WxLogin->getOpenid($code);
            /*
			//我回调处理主要是用unionid判断
			1.是否跟之前的用户表已经有了unionid,匹配进入后台
			2.是否已经绑定过其他账户 ,如果有重新进入扫码页面,提示换号绑定
			3.如果用户账号登录后 ,微信未绑定过,则绑定后进入页面
			……
			*/
            $UserModel = new \app\common\model\common\User();
            $MprUser = new \app\common\model\common\MprUser();
            $user_id = is_login();
            if($user_id>0){ 
   
                //账号登录后扫码
                //微信是否已经绑定过其他账号
                $isexit = $UserModel->where('type',0)->where('unionid',$re['unionid'])->where('status',1)->find();
                if($isexit){ 
   
                    $this->error('此微信已经绑定过,请用另外的微信扫码绑定!','/wxLogin?time='.time());
                }else{ 
   
                    //绑定微信
                    session(md5('wxLogin_session'),1);
               
                    $exit = $MprUser->where('openid',$re['unionid'])->find();
                    if($exit){ 
   
                        $UserModel->save(['mpr_user_id'=>$exit['mpr_user_id'],'unionid'=>$re['unionid']],['id'=>$user_id]);
                    }else{ 
   
                        $UserModel->save(['unionid'=>$re['unionid']],['id'=>$user_id]);
                    }
                    $this->success('绑定成功!',url('admin/index/index'));exit;
                }
            }else{ 
   
                //扫码登录
                //是否有用户信息
                $isexit = $UserModel->where('type',0)->where('unionid',$re['unionid'])->where('status',1)->find();
                if($isexit){ 
   
                    $exit = $MprUser->where('openid',$re['unionid'])->find();
                    if($exit){ 
   
                        $UserModel->save(['mpr_user_id'=>$exit['mpr_user_id']],['unionid'=>$re['unionid']]);
                    }
                    $user = new \app\admin\logic\Session();
                    $res = $user->wxLogin($isexit['id']);
                    if($res['code']==1){ 
   
                        session(md5('wxLogin_session'),1);
                        $this->success($res['msg'],$res['url']);exit;
                    }
                }else{ 
   
                    //未有绑定微信的账号或者账号不可用,
                    $this->error('未查询到此微信的账号或者账号不可用!','/wxLogin?time='.time());
                }
            }
        }else{ 
   
            return '欢迎光临!这是微信扫码进入的回调方法,亲是不是走错了~~哈哈哈!';
        }
	}

下面类似通过code 获取用户信息

<?php
namespace WxLogin;

use think\Db;

/**
 * 微信登录类
 */

class WxLogin{ 
   
	private $appid = 'wxAPPID';//小程序appid,主要用appid
    private $secret = 'SECRET';//开放平台秘钥,用不到 
	
	public function getOpenid($code){ 
   
		//获取access_token和openid
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->secret&code=$code&grant_type=authorization_code";
		//发送请求
		$result = $this->post($url);
		//返回接口的数据
		$arr = json_decode($result,true);
		$data = $this->getUser($arr['access_token'],$arr['openid']);
		return $data;
	}
	
	function getUser($token,$openid){ 
   
		//获取用户信息需要openid 和 access_token
		//获取用户信息
		$getinfourl = "https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid";
		//发送请求获取用户信息
		$info_result = $this->post($getinfourl);
		//返回接口的数据
		// echo $info_result;
		$info_arr = json_decode($info_result,true);
		return $info_arr;
	}

	function post($url) { 
   
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		$rst = curl_exec($ch);
		curl_close($ch);
		return $rst;
	}
	
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/146074.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月15日 下午9:40
下一篇 2022年5月15日 下午10:00


相关推荐

  • SE是什么意思_pe是什么的英文简称

    SE是什么意思_pe是什么的英文简称AEApplicationEngineer应用工程师。定位:IC流片后,需要在通用应用系统(比如Intel/AMD主板)或者关键刻画的系统平台上进行功能验证,发现问题反馈给IC设计工程师。与FAE相比,AE偏向IC设计,FAE偏向市场对一点。FAEFieldAppilcationEngineer现场应用工程师,又称现场应用技术支持工程师。定位:IC产品在客户端送样时,可能出现技术问题,协助客户的工程技术人员解决技术问题;协助市场人员,从技术角度推广产品,开拓新客户,收集客户的技术问题与

    2025年8月1日
    3
  • webform激活成功教程及汉化

    webform激活成功教程及汉化首先现在官网上下载最新版本 webstorm 需要的可以私信我 自己最好下最新的 安装直接下一步就可以了 安装完成后会弹出一个注册框 先不要管也不要关闭 打开下载的激活成功教程包 根据你的电脑系统运行相应的服务器模拟程序 32 位系统的 xp win7 win10 运行 dvt jb licsrv 386 exe64 位系统的 win10 amd 运行 dvt jb licsrv amd64 exe

    2026年3月18日
    2
  • GPU利用率低的解决办法

    GPU利用率低的解决办法watch-n0.1-dnvidia-smi#检查GPU利用率参数解决办法:1.dataloader设置参数2.增大batchsize3.减少IO操作,比如tensorboard的写入和打印。4.换显卡

    2022年6月30日
    78
  • idea 2021.12激活-激活码分享

    (idea 2021.12激活)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月30日
    105
  • 16012014_李鑫第三次过程性考核

    16012014_李鑫第三次过程性考核码云地址 https gitee com lixin 123 课堂练习 https gitee com lixin 123 a7 1 输出数组元素本题要求编写程序 对顺序读入的 n 个整数 顺次计算后项减前项之差 并按每行三个元素的格式输出结果 设计思路 首先定义一个数组 定义两个变量 然后使用 FOR 循环运用到的知识点 数组 FOr 循环代码

    2026年3月18日
    2
  • sscanf用法

    sscanf用法SSCANF 用法 继 qsort bsearch strchr 后发现的又一好使的函数 sscanf 与 scanf 类似 都是用于输入的 只是后者以键盘 stdin 为输入源 前者以固定字符串为输入源 例子 nbsp 1 常见用法 charbuf 512 sscanf s buf 此处 buf 是数组名 它的意思是将 123

    2026年3月16日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号