var $appid ='*********';
var $appsecret ='**********';
//构造函数,获取Access Token
public function __construct($appid = NULL, $appsecret = NULL){
parent::__construct();
//扫码登录不需要该Access Token, 语义理解需要
//1. 本地写入
$res = file_get_contents('access_token.json');
$result = json_decode($res, true);
$this->expires_time = $result["expires_time"];
$this->access_token = $result["access_token"];
if (time() > ($this->expires_time + 3600)) {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
$res = getHttpJson($url);
$result = json_decode($res, true);
$this->access_token = $result["access_token"];
$this->expires_time = time();
file_put_contents('access_token.json', '{"access_token": "' . $this->access_token . '", "expires_time": ' . $this->expires_time . '}');
}
}
/*
* PART1 网站应用
*/
//生成扫码登录的URL
public function qrconnect($redirect_url, $scope, $state = NULL)
{
$url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $this->appid . "&redirect_uri=" . urlencode($redirect_url) . "&response_type=code&scope=" . $scope . "&state=" . $state . "#wechat_redirect";
return $url;
}
//生成OAuth2的Access Token
public function oauth2_access_token($code)
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecret . "&code=" . $code . "&grant_type=authorization_code";
$res = getHttpJson($url);
return $res;
}
//获取用户基本信息(OAuth2 授权的 Access Token 获取 未关注用户,Access Token为临时获取)
public function oauth2_get_user_info($access_token, $openid)
{
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
$res = getHttpJson($url);
// return json_decode($res, true);
return $res;
}
public function wx_login(){
if (!isset($_GET["code"])){
$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
// $redirect_url = 'http://www.gizone.net'.$_SERVER['REQUEST_URI'];
$jumpurl = $this->qrconnect($redirect_url, "snsapi_login", "123");
Header("Location: $jumpurl");
}else{
$oauth2_info = $this->oauth2_access_token($_GET["code"]);
// $userinfo = $this->oauth2_get_user_info($oauth2_info['access_token'], $oauth2_info['openid']);
$user=M('wx_user')->where(array('unionid'=>$oauth2_info['unionid']))->find();
$username=M('person')->where(array('uid'=>$user['uid']))->find()['ps_name'];
$user_list=M('user')->where(array('uid'=>$user['uid']))->find();
if(!empty($user['uid'])){ //有unionid且是已绑定用户可以登录
session("username", $username);
session("uid", $user["uid"]);
session("user", $user_list);
$this->success('登录成功', U('Index/index'));
}else{ //没有unionid且不为已绑定用户不能登录
$this->error('您没有登录权限',U('Public/login'));
}
}
}