要求必须公众号曾经认证
原理通过生成带参数二维码 +随机字符串
存入库中
而后用户扫描关注后,微信推送音讯中带 随机字符串
,与库中相比实现登录
只贴外围代码
生成二维码推送
<?php
include('./curl.php');
include('./file.php');
$appid = "APPID";
$secret = "SECRET";
$get_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";// 获取 access_token 的 url
// 获取 token 过程开始
$token = curl_get($get_token_url);
$token = json_decode($token,true);
$token = $token['access_token'];
// 获取 token 过程完结
$get_code_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$token}";// 获取 ticket 的 url
$string = createToken(24);// 随机字符串
$get_code_url_parmeter = array(
'expire_seconds'=>2592000,// 二维码有效期 2592000 是 30 天
'action_name'=>'QR_STR_SCENE',// 微信推送音讯时的参数类型,QR_STR_SCENE 为字符串
'action_info'=>array(
'scene'=>array('scene_str'=>$string,// 微信随送音讯时的参数。)
)
);
// 模拟器数据库存入开始
$logininfo_array = array('string'=>$string,'islogin'=>0);
writeArrayToFile($logininfo_array,"logininfo.txt");
// 模拟器数据库存入完结
// 获取 ticket 开始
$get_code_url_parmeter = json_encode($get_code_url_parmeter);
$qrcode = curl_post($get_code_url,$get_code_url_parmeter);
$ticket = json_decode($qrcode,true);
$ticket = $ticket['ticket'];
// 获取 ticket 完结
$qrcodeimg = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}";
echo $qrcodeimg;
// 向前端返回二维码链接
function createToken($long){// 创立随机字符串 long 参数为字符串长度
$char = '1234567890ABCDEFGHIGHLMNOPQRSTUVWXYZ';
$token = '';
for ($i = 0; $i <= $long; $i++) {$token.= $char[rand(0, strlen($char) - 1) ];
}
return $token;
}
?>
// 接管微信推送音讯
<?php
include('./file.php');
if($_SERVER['REQUEST_METHOD'] == 'GET'){// 配置服务器时的验证
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$echostr = $_GET["echostr"];
$token = "abcd";
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if($tmpStr == $signature){echo $echostr;}else{return false;}
}else{$xml = $GLOBALS['HTTP_RAW_POST_DATA']; // 接管微信推送,xml 格局
$logininfo = readFileToArray("logininfo.txt"); // 读取之前存入的随机字符串。$objectxml = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA); //xml 转 objcet
$userinfo = json_decode(json_encode($objectxml),true); //objcet 转 php array
if($userinfo['EventKey']==$logininfo['string'] || $userinfo['EventKey']=='qrscene_'.$logininfo['string']){
// 首次关注的推送后面多了一个 qrscene_ 所以做或判断
// 随机字符串和推送的字符串相匹配,证实已进入公众号
$logininfo['islogin']=1; // 模仿数据库操作,登陆状态变 1
$logininfo['openid']=$userinfo['FromUserName']; // 模仿数据库操作,保留用户 openid
if($userinfo['Event']==="subscribe"){// 首次关注事件类型:subscribe
//first
$logininfo['text']="该用户首次关注";
}else if($userinfo['Event']==="SCAN"){// 间接进入事件类型:SCAN
$logininfo['text']="该用户已关注";
}
writeArrayToFile($logininfo,"logininfo.txt");// 模仿数据库操作。}
}
?>