微信扫码登录demo

<?php


namespace app\index\controller;



use think\View;

class index
{

    private $OPEN_APPID = "";
    private $OPEN_APPSECRET = "";
    private $OPEN_CALLBACKURL = "";
    public function login(){


        return \think\facade\View::fetch('login');
    }

    public function index()
    {

        session_start();
//-------生成唯一随机串防CSRF攻击
        $state = md5(uniqid(rand(), TRUE));
        $_SESSION["wx_state"] = $state; //存到SESSION
        $callback = urlencode($this->OPEN_CALLBACKURL);
        $wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $this->OPEN_APPID . "&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
        header("Location: $wxurl");
    }

    public function wxBack()
    {
//        session_start();
//
//        if ($_GET['state'] != $_SESSION["wx_state"]) {
//            exit("5001");
//        }
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->OPEN_APPID . '&secret=' . $this->OPEN_APPSECRET . '&code=' . $_GET['code'] . '&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($json, 1);
//得到 access_token 与 openid
        dump($arr);
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $arr['access_token'] . '&openid=' . $arr['openid'] . '&lang=zh_CN';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($json, 1);
        halt($arr);
    }


}

//前端示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>11111111111111111
<div id="wx_login_container"></div>

</body>

<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/jquery.min.js"></script>
<script  src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<script>

    $(document).ready(function()
    {
        var obj = new WxLogin({
            self_redirect: true,
            id:"wx_login_container",
            appid: "wxd0182a04feb7dd4b",
            scope: "snsapi_login",
            redirect_uri: "http://xxxx/index/index/wxBack",
            state: "",
            style: "black",
            href: "", //https://某个域名下的css文件
        });
    });
</script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值