<?php
namespace Biz\Pay;
/**
 * 基础支付类
 */
class BasePayment {
	/**
	 * 网关地址
	 * @var [type]
	 */
	protected $getWay;
	/**
	 * 支付名称或代三
	 * @var [type]
	 */
	protected $paymentName;
	/**
	 * 支付配置文件
	 * @var [type]
	 */
	protected $paymentConfig;
	/**
	 * 通知地址
	 * @var [type]
	 */
	protected $notifyUrl;
	/**
	 * 跳转地址
	 * @var [type]
	 */
	protected $redirectUrl;

	/**
	 * 编码
	 * @var string
	 */
	protected $charset = 'utf-8';

	/**
	 * 驱动数据对像
	 * @var [type]
	 */
	protected $dataAccess;
	/**
	 * 私有证书路径
	 * @var [type]
	 */
	protected $privateCertPath;
	/**
	 * 公有证书路径
	 * @var [type]
	 */
	protected $publicCertPath;
	/**
	 * 后台配置的商户信息将在初始化时自动解析完成
	 * @var [type]
	 */
	protected $sellerInfo;

	/**
	 * 设定支付接口允许的域名
	 * @var [type]
	 */
	protected $domain;

	/**
	 * 返回类型
	 * @var [type]
	 */
	protected $returnType;

	/**
	 * 是否手机版
	 *
	 * @var [type]
	 */
	public $isMobile;

	/**
	 * 开启调试模式
	 * @var integer
	 */
	public $debug = 0;

	/**
	 * 初始化
	 */
	public function __construct(PaymentDataAccess $dataAccess) {
		// $this->getConfig();
		$this->domain = PAY_URI;
		$this->notifyUrl = "http://{$this->domain}/pay-{$this->paymentName}Notify";
		$this->redirectUrl = "http://{$this->domain}/pay-{$this->paymentName}Redirect";
		$this->dataAccess = $dataAccess;
		$this->isMobile = is_mobile();
		$this->init();
	}
	/**
	 * 设置返回类型
	 * @param [type] $type [description]
	 */
	public function setReturnType($type) {
		$this->returnType = $type;
	}
	/**
	 * 发起配置
	 * @param  array  $orderInfo 订单信息
	 * @return [type]            发起支付流程
	 */
	public function toPay() {

	}
	/**
	 * 接收通知
	 * @param  array  $orderInfo 订单信息
	 * @return [type] [description] 返回为1或success视接口而定
	 */
	public function notify() {

	}
	/**
	 * 返回跳转
	 * @param  array  $orderInfo 订单信息
	 * @return [type] [description]
	 */
	public function redirect() {

	}

	/**
	 * 检查支付信息
	 * @param  array  $orderInfo 订单信息
	 * @return [type]            0=失败，1=成功
	 */
	public function check() {
		# code...
	}

	/**
	 * 返回DATAACCESS
	 */
	public function DataAccess() {
		return $this->dataAccess;
	}

	/**
	 * 获取配置信息
	 * @return [type] [description]
	 */
	public function getConfig() {
		if (empty($this->paymentName)) {
			throw new \Exception("支付名不能为空", 1);
		}
		$this->paymentConfig = $M('payment')->where('payment_name', $this->paymentName)->find();
		if (!$this->paymentConfig) {
			throw new \Exception("支付不存在", 1);
		}
		$this->privateCertPath = $this->paymentConfig['cert_priv_path'];
		$this->publicCertPath = $this->paymentConfig['cert_pub_path'];
		$this->sellerInfo = empty($this->paymentConfig['seller_info']) ? '' : json_decode($this->paymentConfig['seller_info'], 1);
		if (!(is_array($this->sellerInfo) && count($this->sellerInfo) > 0)) {
			throw new \Exception("商户信息不存在", 1);
		}
	}
	/**
	 * 系统初始化
	 * @return [type] [description]
	 */
	public function init() {

	}
	/**
	 * 跳转到支付接口
	 * @param  [type] $orderInfo 订单信息
	 * @param  string $action    提交方式
	 * @return [type]            void
	 */
	public function goPay($orderInfo = array(), $action = "POST", $url = '') {
		if ($this->debug) {
			$inputType = "text";
			$script = '';
		} else {
			$inputType = "hidden";
			$script = 'document.getElementById("submitForm").submit();';
		}

		if (is_array($orderInfo) && count($orderInfo) > 0) {
			foreach ($orderInfo as $k => $v) {
				$forms .= "<input type={$inputType} name='{$k}' value='{$v}' />";
			}
		}
		if (empty($url)) {
			$url = $this->getWay;
		}

		$str = "<html>
			<head>
			<title>Payment By CreditCard online</title>
			<meta http-equiv='Content-Type' content='text/html; charset={$this->charset}'>
			</head>
			<body>
			<form action='{$url}' method='{$action}' id='submitForm' name='E_FORM'>
			 {$forms}
			</form>
			</body>
			</html>
			<script type='text/javascript'>
			{$script}
			</script>
		";

		//toLog($str);
		echo $str;
	}
	/**
	 * 返回支付类型的数组
	 * @return [type] [description]
	 */
	public function getPaymentType() {
		# code...
	}
	/**
	 * 提取证书中的公钥和私钥KEy，以数据形式返回
	 * @return [type] [description]
	 */
	public function certPatchKey() {
		$priContent = file_get_contents($this->privateCertPath);
		$pubContent = file_get_contents($this->publicCertPath);
		$priKey = openssl_get_privatekey($priContent);
		$pubKey = openssl_pkey_get_public($pubContent);
		if (empty($priKey) || empty($pubKey)) {
			throw new \Exception("支付的私钥和公钥不能为空", 1);
		}
		return array('private' => $priKey, 'public' => $pubKey);
	}
	/**
	 * 处理CURL提交
	 * @param  [type] $url    [description]
	 * @param  string $action [description]
	 * @param  array  $data   [description]
	 * @return [type]         [description]
	 */
	function goPayCurl($url, $action = "POST", $data = array(), $header = array()) {
		//toLog($url);
		//toLog($data);
		if (is_array($data)) {
			$data = http_build_query($data);
		}
		$ch = curl_init();
		$res = curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		if (is_array($header) && count($header) > 0) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch, CURLOPT_HEADER, 0);
		}
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		// curl_setopt($ch, CURLOPT_HTTPHEADER, 1);
		$result = curl_exec($ch);
		$errno = curl_errno($ch);
		curl_close($ch);
		if ($result == NULL) {
			return 0;
		}
		return $result;
	}
	/**
	 * 发送信息到远程
	 * @param  string  $action [description]
	 * @param  integer $status [description]
	 * @return [type]          [description]
	 */
	function toRemoteUri($action = 'notify', $status = 0) {
		$data = array(
			'orderSn' => $this->dataAccess->orderSn,
			'money' => $this->dataAccess->money,
			'goodsName' => ($this->dataAccess->goodsName == null ? '' : $this->dataAccess->goodsName),
			'status' => $status,
		);
		$sign = http_build_query($data);
		$sign = urldecode($sign);
		$key = md5($sign);
		$sign = md5($sign . '&' . $key);
		$data['sign'] = $sign;
		if ($action == 'notify') {
			if ($remote_type == 0) {
				$url = "http://" . WEB_URI . "/Home/ReceiveNotify/Notify";
				return $this->goPayCurl($url, 'POST', $data);
			}
		} else {
			$url = "http://" . WEB_URI . "/Home/ReceiveNotify/Redirect";
			$this->goPay($data, 'POST', $url);
		}

	}
	/**
	 * 发送信息到远程
	 * @param  string  $action [description]
	 * @param  integer $status [description]
	 * @return [type]          [description]
	 */
	function reciveRemoteDetails() {
		$data = array(
			'orderSn' => trim($_POST['orderSn']),
			'money' => trim($_POST['money']),
			'goodsName' => trim($_POST['goodsName']),
			'status' => trim($_POST['status']),
		);
		$sourceSign = trim($_POST['sign']);
		$sign = http_build_query($data);
		$sign = urldecode($sign);
		$key = md5($sign);
		$sign = md5($sign . '&' . $key);
		if ($sign == $sourceSign) {
			return 1;
		}
		return 0;
	}
	/**
	 * 提示信息
	 * @param  [type] $key [description]
	 * @return [type]      [description]
	 */
	function notifyMsg($key) {

	}
	/**
	 * 提示信息
	 * @param  [type]  $msg  [description]
	 * @param  integer $code [description]
	 * @return [type]        [description]
	 */
	function showNotice($msg, $code = -1) {
		if ($this->returnType == 'json') {
			JsonReturn('', $code, $msg);
		} else {
			exit($msg);
		}
	}
	/**
	 * 成功信息
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	function jsonSuccess($data) {
		if ($this->returnType == 'json') {
			JsonReturn($data, 1, 'success');
		}
	}
	/**
	 * 检查金额
	 * @param  [type] $money [description]
	 * @return [type]        [description]
	 */
	function checkMoney($money) {

	}

}
?>