<?php

// 检查用户是否已经是注册用户
require_once ("../user_include.inc");

ErrorLogger::doOutput("Compass...ajax_check_user_registed.php....Start.", 0);

//根据常量获取定义的值
$jsCode = ParamUtil::getRequestString("code", "");
$openId = ParamUtil::getRequestString("openId", "");

ErrorLogger::doOutput("Compass...ajax_check_user_registed.php....code=" . $jsCode, 0);
ErrorLogger::doOutput("Compass...ajax_check_user_registed.php....openId=" . $openId, 0);

$result = array();
//如果都为空说明调用错误
if(empty($code) && empty($openId)) {
	$result["message"] = "参数错误！";
	responseNG($result);
}

//有openId的情况下
if(!empty($openId)) {
	//检索数据库
	$param['openid'] = $openId;
	$param['delete_flg'] = false;
	$tmpUserMst = UserMst::getList($param,'id','desc', 0, 1);
	if(empty($tmpUserMst)) {
		$result["message"] = "未注册！";
		responseOK($result);
	} else {
		$result["message"] = "已注册！";
		responseNG($result);
	}
}

//有code的情况下
if(!empty($js_code)) {
	$appId = WECHAT_APP_ID;
	$appSecret = WECHAT_APP_SECRET;
	//调用微信接口获取用户的openId和unionId
	//调用服务器查询并插入数据
	$ch = curl_init();
	$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appId . "&secret=" . $appSecret . "&js_code=" . $jsCode . "&grant_type=authorization_code";
	//通过code换取网页授权access_token
	$weixin =  file_get_contents($url);
	$weixinJson = json_decode($weixin); //对JSON格式的字符串进行编码
	$weixinArray = get_object_vars($weixinJson);//转换成数组
	$openId = $weixinArray["openid"];
	if(!empty($openId)) {
		//检索数据库
		$param['openid'] = $openId;
		$param['delete_flg'] = false;
		$tmpUserMst = UserMst::getList($param,'id','desc', 0, 1);
		if(empty($tmpUserMst)) {
			$result["openId"] = $openId;
			$result["message"] = "未注册！";
			responseOK($result);
		} else {
			$result["openId"] = $openId;
			$result["message"] = "已注册！";
			responseNG($result);
		}
	} else {
			$result["message"] = "参数错误！";
			responseNG($result);
	}
}

function responseNG($result) {
	$result = array("status"=>"NG", "result"=>$result);
	print json_encode($result);
	exit;
}
function responseOK($result) {
	$result = array("status"=>"OK", "result"=>$result);
	print json_encode($result);
	exit;
}
?>