<?php
define('IN_PHPMPS', true);
require dirname(__FILE__) . '/include/common.php';
	$code = $_GET['code'];
	$state = $_GET['state'];
	$appid = $CFG['wx_appid'];
	$appsecret = $CFG['wx_appsecret'];
	if (empty($code)) $this->error('授权失败');
	$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
	$token = json_decode(file_get_contents($token_url));
	if (isset($token->errcode)) {
		echo '<h1>错误：</h1>'.$token->errcode;
		echo '<br/><h2>错误信息：</h2>'.$token->errmsg;
		exit;
	}
	$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
	//转成对象
	$access_token = json_decode(file_get_contents($access_token_url));
	if (isset($access_token->errcode)) {
		echo '<h1>错误：</h1>'.$access_token->errcode;
		echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
		exit;
	}
	$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
	//转成对象
	$user_info = json_decode(file_get_contents($user_info_url));
	if (isset($user_info->errcode)) {
		echo '<h1>错误：</h1>'.$user_info->errcode;
		echo '<br/><h2>错误信息：</h2>'.$user_info->errmsg;
		exit;
	}
	$ret = objtoarr($user_info);
	setcookie('useropenid', $ret[openid], time()+86400*24);
	$open_id = $db->getRow("SELECT username,password,wx_openid FROM {$table}member where wx_openid='$ret[openid]'");
		if(empty($open_id)){
			if (check_user($ret[nickname]) > 0) {
				$maxid = $db->getOne("SELECT MAX(userid) FROM {$table}member");
			}
			if(register($ret['nickname'].$maxid,MD5('wx_'.time()),$ret['openid'],$ret['headimgurl'])) {
				header("Location:m/index.php");
			}
		}else{
			if(login($open_id['username'],$open_id['password'])) {
				header("Location:m/index.php");
			}
		}
?>