<?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>