微信扫码登录网站

需求:网站登录提供微信扫码登录,关注公众号即可完成登录,关注之后直接登录。同时又提供了引流的方案。

一个是基于ajax轮询实现,一个的websocket实现 。本教程使用ajax轮询实现

 本教程基于easywechat制作 


配置config.php

<?php
define("MYSQL_HOST","127.0.0.1");	
define("MYSQL_USER","");	
define("MYSQL_DBNAME","");	
define("MYSQL_PASSWORD","");
define("TABLEPRE","");
$config = [
    'app_id' => 'wxebf56b31f350xxx',
    'secret' => '8f2667ad2e66b9b5xxxx',
    'token' => 'Token',
	// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
    'response_type' => 'array',	
    /**
     * 日志配置
     *
     * level: 日志级别, 可选为:
     *         debug/info/notice/warning/error/critical/alert/emergency
     * path:日志文件位置(绝对路径!!!),要求可写权限
     */
    'log' => [
        'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
        'channels' => [
            // 测试环境
            'dev' => [
                'driver' => 'single',
                'path' => '/data/easywechat.log',
                'level' => 'debug',
            ],
            // 生产环境
            'prod' => [
                'driver' => 'daily',
                'path' => '/data/easywechat.log',
                'level' => 'info',
            ],
        ],
    ],
	//回调路径
	'oauth' => [
      'scopes'   => ['snsapi_userinfo'],
      'callback' => '/oauth_callback.php',
	],
];


主文件index.p结合redis实现

<?php
session_start();
require_once './vendor/autoload.php';
require_once './config.php';
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
try {
	$db = new PDO("mysql:host=".MYSQL_HOST.";dbname=".MYSQL_DBNAME,MYSQL_USER,MYSQL_PASSWORD);
	$db->exec("SET NAMES 'utf8'");
	$redis = new Redis();
	$redis->connect('127.0.0.1', 6379);	
	$app = Factory::officialAccount($config);
	$app->server->push(function ($message) use ($app,$db,$redis) {
		// $message['FromUserName'] // 用户的 openid
		// $message['MsgType'] // 消息类型:event, text....
		$user = $app->user->get($message['FromUserName']);
		//前端生成一个随机的字符串,请求qrcode获取二维码的时候,为临时二维码的参数,然后把这个参数写到二维码里面,点击的时候请求后端	
		if($message['MsgType'] == 'event'){
			if($message['Event'] == 'subscribe' || $message['Event'] == 'SCAN'){			
				//return "第一次关注{$message['EventKey']}";
				$sql="SELECT * FROM ".TABLEPRE."member where openid = '".$message['FromUserName']."'";		
				$flag = false;
				foreach($db->query($sql) as $member){					
					$flag = true;
				}
				if(!$flag){
					$sql="INSERT INTO ".TABLEPRE."member (openid,nickname,sex,city,province,country,headimgurl,subscribe_time,subscribe,code) VALUES ('".$message['FromUserName']."','".$user['nickname']."','".$user['sex']."','".$user['city']."','".$user['province']."','".$user['country']."','".$user['headimgurl']."','".$user['subscribe_time']."','".$user['subscribe']."','".$message['EventKey']."')";
					$db->exec($sql);
				}else{
					$sql="UPDATE `hrt_member` SET `nickname`='".$user['nickname']."', `sex`='".$user['sex']."', `city`='".$user['city']."', `province`='".$user['province']."', `country`='".$user['country']."', `headimgurl`='".$user['headimgurl']."', `subscribe_time`='".$user['subscribe_time']."', `subscribe`='".$user['subscribe']."', `code`='".$message['EventKey']."' WHERE (`openid`='".$message['FromUserName']."')";
					$db->exec($sql);
				}
				$key = str_replace('qrscene_','',$message['EventKey']);
				//$_SESSION[$key] = $message['FromUserName'];
				$redis->set($key,$message['FromUserName']);
				//$redis->expireAt($key, 3600);
				return "{$user['nickname']} 扫码登录成功";
			}
			
		}
		
	   
	});


	$response = $app->server->serve();

	$response->send();
	
	
} catch (PDOException $ex) {
		echo "<script language=\"javascript\">alert(\"数据库连接失败\")</script>";exit();
}

?>

登录login.php

<!DOCTYPE html>
<html>
  <head>
    <title></title>
	<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<script src="./lib/jquery-2.1.4.js"></script>
	<style>
		.row{
			margin-top:200px;
		}
		.col-md-4{
			text-align:center;
		}
	</style>
</head>
  <body>
		 <div class="row">
		  <div class="col-md-4"></div>
		  <div class="col-md-4">
		  <button type="button" id="login" class="btn btn-success">微信登录</button>
			<div><img id='img'></div>
		  </div>
		  <div class="col-md-4"></div>
		</div>
		
		<script>
		
		function getData(key){
			$.post('./user.php',{key:key},function(data){
    			if(data.code == 0){
					window.location.href = './user1.php?uid='+data.key;					
				}
    		},'json');
		}
		
    	$("#login").click(function() {     		
			code  = new Date().getTime();
			console.log(code);
    		$.post('./code.php',{code:code},function(data){
    			console.log(data);
    			if(data.code == 0){
					$("#img").attr('src',data.url);
					 getData(data.key); // 第一次加载数据
					 // 开启定时任务,时间间隔为3000 ms。
					 setInterval(function(){
					  getData(data.key);
					 }, 3000);
    			}else{
					
				}
    		},'json');
			
			
			
		});
		
		
    </script>
  </body>
</html>

user.php判断用户是否扫码存入redis sessionkey

<?php
	
	//$_SESSION['1556202539627'] = 111;
	$redis = new Redis();
	$redis->connect('127.0.0.1', 6379);	
	$k = $_REQUEST["key"];
	$key = $redis->get($k);
	if($key){
		$data = [
			'key'=>$key,
			'code'=>0
		];

		echo json_encode($data);
	}else{
		$data = [
			'key'=>'',
			'code'=>1
		];

		echo json_encode($data);
	}


user1.php用户登录成功之后跳转的页面

<?php
require_once './config.php';
$db = new PDO("mysql:host=".MYSQL_HOST.";dbname=".MYSQL_DBNAME,MYSQL_USER,MYSQL_PASSWORD);
$db->exec("SET NAMES 'utf8'");

$uid = $_REQUEST["uid"];
$sql="SELECT * FROM ".TABLEPRE."member where openid = '".$uid."'";
//echo $sql;exit;
foreach($db->query($sql) as $member){					
	
}
//var_dump($member);exit;
?>
<?php echo $member['nickname']?>恭喜您登录成功
<img src="<?php echo $member['headimgurl']?>">


收工 体验地址 体验地址

eaa9W1weIf1M37IrFbFfSRZboIZ0ut.jpg

雷亮博客
请先登陆后发表评论
  • 最新评论
  • 总共0条评论
  • 本站使用thinkphp搭建 © 2014-2016 blog.wo97.com 版权所有 ICP证:蜀ICP备16024789号
  • 工信部
  • 联系邮箱:1031041088@qq.com