<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 前台公共库文件
 * 主要定义前台公共函数库
 */

/**
 * 微信网页授权
 */

function getOpenID()
{
	if ($_SESSION['openid']) {
		return $_SESSION['openid'];
	} else {
		$baseUrl = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']);

		if (!isset($_GET['code'])) {
			if ($_POST) {
				$_SESSION['post'] = $_POST;
			}

			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . C('Weixin.appid') . '&redirect_uri=' . $baseUrl . '&response_type=code&scope=snsapi_base#wechat_redirect';
			header("location:$url");
			exit();
		}

		if (isset($_GET['code'])) {
			if ($_SESSION['post']) {
				$_POST = $_SESSION['post'];
				extract($_POST, EXTR_SKIP);
			}

			$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . C('Weixin.appid') . '&secret=' . C('Weixin.appsecret') . '&code=' . $_GET['code'] . '&grant_type=authorization_code';

			$output = (array)json_decode(http_request($url));
			$_SESSION['openid'] = $output['openid'];

// 				echo '<pre>';
// 				print_r($output);

			return $output['openid'];
		}
	}
}


function http_request($url, $data = null)
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

	if (!empty($data)) {
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data))
		);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}


//设置微信卡券
function setWxcard()
{
	$card_id = I('card_id', '');
	if ($card_id) {
		$wxcard['card_id'] = $card_id;
		$wxcard['encrypt_code'] = I('encrypt_code', '');
		session('wxcard', $wxcard);
	} else {
		session('wxcard', null);
	}
}

//是否使用了微信卡券
function hasWxcard()
{
	$card = session('wxcard');
	if ($card)
		return true;
	else
		return false;
}


//获取微信卡券
function getWxcard()
{
	$card = session('wxcard');
	return $card;
}


/**
 * 支付宝网页授权
 */

function getAlipayID()
{
	if ($_SESSION['alipayid']) {
		return $_SESSION['alipayid'];
	} else {
		require_once VENDOR_PATH . 'Alipay/config.php';

		$baseUrl = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']);

		if (!isset($_GET['auth_code'])) {
			$url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $config['app_id'] . '&scope=auth_base&redirect_uri=' . $baseUrl;

			header("location:$url");
			exit();
		}

		if (isset($_GET['auth_code'])) {
			require_once VENDOR_PATH . 'Alipay/AopSdk.php';

			$aop = new \AopClient();

			$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
			$aop->appId = $config['app_id'];
			$aop->rsaPrivateKey = $config['merchant_private_key'];
			$aop->alipayrsaPublicKey = $config['alipay_public_key'];
			$aop->signType = 'RSA2';
			$request = new \AlipaySystemOauthTokenRequest();
			$request->setGrantType("authorization_code");
			$request->setCode($_GET['auth_code']);
			$request->setRefreshToken("");
			$result = $aop->execute($request);

//     		    print_pre($result);

			$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//     		    echo $responseNode;
			$resultCode = $result->$responseNode->code;
			if (!empty($result->$responseNode->user_id)) {
				$_SESSION['alipayid'] = $result->$responseNode->user_id;
				return $_SESSION['alipayid'];
			} else {
				die($result->$responseNode->sub_code);
			}

		}
	}
}


/**
 * Line网页授权
 */

function getLineID($redir = null)
{
	$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
	$baseUrl = ($redir ? $redir : $url);
	$_SESSION['orginUrl'] = $baseUrl;


	if ($_SESSION['lineid']) {
		return $_SESSION['lineid'];
	} else {
		$url = 'https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=' . C('Line.channel_id') . '&redirect_uri=' . C('Line.redirect_uri') . '&state=12345abcde&scope=openid%20profile&nonce=09876xyz';
		header("location:$url");
		exit();
	}
}
