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

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

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

需求:后台需要添加微信扫码登录。
首先需要阅读官方文档,了解大致过程。介绍有两种微信扫码,一是跳转到微信网页生成的二维码进行扫码,二是把二维码内嵌到自己的网站页面。下面微信文档。
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年8月21日
    2
  • 面试知识点总结之操作系统

    面试知识点总结之操作系统

    2021年9月17日
    46
  • Java8:LocalDate LocalDateTime Date相互转化

    Java8:LocalDate LocalDateTime Date相互转化概述时间日期处理是平时工作中使用非常频繁的逻辑,Java8中提供的新的时间类LocalDateTime和LocalDate,使日期处理可以更简单。友情提醒下,业务开发中最好默认使用LocalDateTime,因为LocalDateTime可以很方便的转换为LocalDate,但是LocalDate是不可以转为LocalDateTime的,会没有时分秒的数据!!!实例publicstaticvoidmain(String[]args){StringcurrentDate

    2022年9月28日
    0
  • 浅谈md5加密[通俗易懂]

    浅谈md5加密[通俗易懂]md5加密是我们生活中十分常见的加密算法。我是最近在写一个H5的项目时接触到的这个算法,这个算法极大的引起了我的好奇心,是登陆界面,要求是将用户输入的密码使用md5加密之后,再传回服务器,当时我十分不理解原因是什么.废话少说原因密码在前端进行加密,然后服务器使用摘要进行比对,这样在整个密码的校验过程中是在服务器端不知道明码的情况下进行的,极大的保证了密码的安全在避免文件内容被篡改

    2022年7月11日
    11
  • html格式转换word_html嵌入word

    html格式转换word_html嵌入word1基于wps直接将页面信息下载成word文档1publicvoidtest()2{34WPS.Applicationwps=null;5try6{7…

    2022年8月6日
    1
  • 在Debian上安装SVN。

    在Debian上安装SVN。

    2021年8月12日
    40

发表回复

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

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