<?php
/**
 * 
 * ============================================================================
 * api˵
 * init(),ʼĬϸһЩֵcmdno,dateȡ
 * getGateURL()/setGateURL(),ȡ/ڵַ,ֵ
 * getKey()/setKey(),ȡ/Կ
 * getParameter()/setParameter(),ȡ/òֵ
 * getAllParameters(),ȡв
 * getRequestURL(),ȡURL
 * doSend(),ض򵽲Ƹ֧ͨ
 * getDebugInfo(),ȡdebugϢ
 * 
 * ============================================================================
 *
 */
class RequestHandler {
	
	/** urlַ */
	var $gateUrl;
	
	/** Կ */
	var $key;
	
	/** Ĳ */
	var $parameters;
	
	/** debugϢ */
	var $debugInfo;
	
	function __construct() {
		$this->RequestHandler();
	}
	
	function RequestHandler() {
		$this->gateUrl = "https://www.tenpay.com/cgi-bin/v1.0/service_gate.cgi";
		$this->key = "";
		$this->parameters = array();
		$this->debugInfo = "";
	}
	
	/**
	*ʼ
	*/
	function init() {
		//nothing to do
	}
	
	/**
	*ȡڵַ,ֵ
	*/
	function getGateURL() {
		return $this->gateUrl;
	}
	
	/**
	*ڵַ,ֵ
	*/
	function setGateURL($gateUrl) {
		$this->gateUrl = $gateUrl;
	}
	
	/**
	*ȡԿ
	*/
	function getKey() {
		return $this->key;
	}
	
	/**
	*Կ
	*/
	function setKey($key) {
		$this->key = $key;
	}
	
	/**
	*ȡֵ
	*/
	function getParameter($parameter) {
		return $this->parameters[$parameter];
	}
	
	/**
	*òֵ
	*/
	function setParameter($parameter, $parameterValue) {
		$this->parameters[$parameter] = $parameterValue;
	}
	
	/**
	*ȡĲ
	*@return array
	*/
	function getAllParameters() {
		return $this->parameters;
	}
	
	/**
	*ȡURL
	*/
	function getRequestURL() {
	
		$this->createSign();
		
		$reqPar = "";
		ksort($this->parameters);
		foreach($this->parameters as $k => $v) {
			$reqPar .= $k . "=" . urlencode($v) . "&";
		}
		
		//ȥһ&
		$reqPar = substr($reqPar, 0, strlen($reqPar)-1);
		
		$requestURL = $this->getGateURL() . "?" . $reqPar;
		
		return $requestURL;
		
	}
		
	/**
	*ȡdebugϢ
	*/
	function getDebugInfo() {
		return $this->debugInfo;
	}
	
	/**
	*ض򵽲Ƹ֧ͨ
	*/
	function doSend() {
		header("Location:" . $this->getRequestURL());
		exit;
	}
	
	/**
	*md5ժҪ,:a-z,ֵĲμǩ
	*/
	function createSign() {
		$signPars = "";
		ksort($this->parameters);
		foreach($this->parameters as $k => $v) {
			if("" != $v && "sign" != $k) {
				$signPars .= $k . "=" . $v . "&";
			}
		}
		$signPars .= "key=" . $this->getKey();
		$sign = strtolower(md5($signPars));
		$this->setParameter("sign", $sign);
		
		//debugϢ
		$this->_setDebugInfo($signPars . " => sign:" . $sign);
		
	}	
	
	/**
	*debugϢ
	*/
	function _setDebugInfo($debugInfo) {
		$this->debugInfo = $debugInfo;
	}

}

?>