PC端微信登录之公众号二维码登录
2018-12-22 本文已影响0人
骚伦
- front
<script type="text/javascript">
var t2 ='';
$(function() {
var rand = parseInt(Math.random() * (999999999 - 10000000 + 1) + 10000000); //生成随机数做为二维码的参数 (用来判断扫码的用户)
//生成二维码
$.post("https://xxxxx/index.php/mobile/KF/buildQrcode",{str:rand},function(result){
console.log(result);
var obj = JSON.parse(result);
var sign = obj.scene_str;
var src = "https://mp.weixin.qq.com/cgi-bin/showqrcode"+obj.src;
$('#wxewm').attr('src',src);
$('input[name=sign]').val(sign);
});
//轮询扫码后的登录
t2 = window.setInterval("login()",1000);//使用字符串执行方法
//window.clearTimeout(t1);//去掉定时器
setTimeout("end()",30000);
})
function end(){ //如果超过一定时间不扫码,停止轮询,提示过期
$('#wxewm').hide(); //隐藏二维码
window.clearTimeout(t2); //停止轮询
$('#notice').show(); //提示二维码过期
}
function login(){ //不停发送请求,获取扫码人的信息,如果扫码了获取信息停止轮询,
var code =$('input[name=sign]').val();
$.post("https://xxxxxxx/mobile/KF/pass",{str:code},function(result){
console.log(result);
var obj = JSON.parse(result);
var user_name = obj.user_name;
var pass = obj.pass;
if(pass){
window.clearTimeout(t2);
window.location.href="https://www.baidu.com"; //跳转到登录后的页面
}
});
}
</script>
- backend
php用file_get_contents(“php://input”)或者$HTTP_RAW_POST_DATA可以接收xml数据
public function get_ACCESS_TOKEN() //获取token
{
$appid= ‘wx8feca7bba41accc4’;
$secret='beca81f0da48dc92f9610dc21648fec6';
$data = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret")) ;
return $data->access_token;
}
public function buildQrcode() //生成带参数二维码
{
$str = $_POST['str'];
$access_token=$this->get_ACCESS_TOKEN();
// scene_id 参数
$data = '{
"expire_seconds": 604800,
"action_name": "QR_SCENE",
"action_info": {
"scene": {
"scene_id":'.$str.'
}
}
}';
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
$obj = json_decode(httpRequest($url, 'POST', $data));
$ticket=$obj->ticket;
return json_encode(['src'=>"?ticket=$ticket",'scene_str'=>$str]);
}
public function kf_login() //扫码客服
{
//$GLOBALS["HTTP_RAW_POST_DATA"]; //这个用不了了;换成下面那个
$postStr = file_get_contents("php://input");
$postObj = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
$openid = $postObj['FromUserName'];
$EventKey = $postObj['EventKey'];
$user=M('sms_log')->field('id')->where(['openid'=>$openid])->find();
if(!$user['id']){
$id = M('sms_log')->add(['openid'=>$openid]);
$Login=new Login();
$pass=$Login->get_sign('kf'.$id);
M('sms_log')->where(['id'=>$id])->save(['pass'=>$pass,'code'=>$EventKey]);
}else{
M('sms_log')->where(['id'=>$user['id']])->save(['code'=>$EventKey]);
}
}
public function pass(){ //登录
$str = $_POST['str'];
$user=M('sms_log')->field('id,pass')->where(['code'=>$str])->find();
M('sms_log')->where(['code'=>$str])->save(['code'=>'']); //每次登录后清空参数,避免出现重复
return json_encode(['user_name'=>'kf'.$user['id'],'pass'=>$user['pass']]);
}