<?php
/* 返回数据 md5(uniqid(rand(), TRUE))
openid 用户的唯一标识
nickname 用户昵称
sex 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
province 用户个人资料填写的省份
city 普通用户个人资料填写的城市
country 国家,如中国为CN
headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
privilege 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
unionid 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)
*/
class controller_chat {
protected $access_token = ""; // 初始化为空
protected $appid = ""; // 申请是微信官方给的appid
protected $appsecret = ""; // 申请时微信官方给的secrect
protected $callback = ''; // 回调地址(域名即可)
// 登录接口
public function ChatLogin() {
session_start();
$state = md5(uniqid(rand(), TRUE));
$_SESSION["wx_state"] = $state; //存到SESSION
$callback = urlencode($this->callback);
//var_dump($callback,$_SESSION);exit();
// 获取code
$wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $this->appid
. "&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
header("Location: $wxurl");
}
// 具体回调地址
public function oauth2() {
if ($_GET['state'] != $_SESSION["wx_state"]) {
echo '5001:非法登录<br/>';
exit();
}
// 获取Access Token
$clienturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid
. "&secret=" . $this->appsecret;
$client = $this->https_request($clienturl);
$result = json_decode($client, true);
$this->access_token = $result["access_token"];
if (isset($_GET['code'])) {
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid
. "&secret=" . $this->appsecret . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
$res = $this->https_request($url);
$res = (json_decode($res, true));
$row = $this->get_user_info($res['openid']);
if ($row['openid']) {
cookie('weixin', $row, 86400);
$this->display('main/index.html');
} else {
$this->error($row['errmsg']);
}
} else {
$this->error('授权出错,请重新授权!');
}
}
//获取用户基本信息
public function get_user_info($openid) {
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->access_token . "&openid=" . $openid . "&lang=zh_CN";
$res = $this->https_request($url);
return json_decode($res, true);
}
//https请求
public function https_request($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
$chat = new controller_chat();
$chat->ChatLogin();