<?php
define('IN_ECTOUCH', true);
if(!empty($_SESSION['wxch_oid'])) {
	$oid = $_SESSION['wxch_oid'];
} else {
	if(isset($_GET['oid'])) {
		$oid = $_GET['oid'];
	} else {
		$oid = '';
	}
}
require ('config.php');
require ('cls_mysql.php');
$db = new cls_mysql($db_host, $db_user, $db_pass, $db_name);
$tag=$_GET['tag'];
$wxch_config = $db->getRow("SELECT * FROM `wxch_config` WHERE `id` = 1");
$appid = $wxch_config['appid'];
$appsecret = $wxch_config['appsecret'];
$code = !empty($_GET['code']) ? $_GET['code'] : '';
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
//echo $url;

$ret_json = curl_get_contents($url);
//print_r($ret_json);
//exit;
$ret = json_decode($ret_json);
$openid = $ret->openid;
$openid = !empty($ret->openid) ? $ret->openid : '';
//$access_token = $ret->access_token;
$access_token_url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
$ret_json2 = curl_get_contents($access_token_url);
$ret2 = json_decode($ret_json2);
$access_token=$ret2->access_token;
$cfg_baseurl = $db->getOne("SELECT cfg_value FROM wxch_cfg WHERE cfg_name = 'baseurl'");
$cfg_murl = $db->getOne("SELECT cfg_value FROM wxch_cfg WHERE cfg_name = 'murl'");
$userinfo_url = $cfg_baseurl . 'wechat/oauth/wxch_userinfo.php?code=' . $code.'&openid='.$openid.'&oid='.$oid.'&access_token='.$access_token.'&tag='.$tag;



header("Location: $userinfo_url");
function curl_get_contents($url) 
{
	if(isset($_SERVER['HTTP_USER_AGENT'])) {
		$agent = $_SERVER['HTTP_USER_AGENT'];
	} else {
		$agent = '';
	}
	
	if(isset($_SERVER['HTTP_REFERER'])) {
		$referer = $_SERVER['HTTP_REFERER'];
	} else {
		$referer = '';
	}

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);
	curl_setopt($ch, CURLOPT_USERAGENT, $agent);
	curl_setopt($ch, CURLOPT_REFERER,$referer);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$r = curl_exec($ch);
	curl_close($ch);
	return $r;
}
?>