MobileClient.php 4.67 KB
<?php
class YHMAuth_Package_Alimobile_Sdk_MobileClient {
	//应用ID
	public $partner = '2088701661478015';
    //网关
	public $gatewayUrl = "https://mapi.alipay.com/gateway.do";
    //返回数据格式
	public $format = "xml";
    //签名类型
	protected $signType = "MD5";
	//编码
	public $_input_charset = 'UTF-8';
	//私钥文件路径
	public $rsaPrivateKeyFilePath;

	protected function generateSign($params) {
		ksort($params);

		$stringToBeSigned = "";
		$i = 0;
		foreach ($params as $k => $v) {
			if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1) && $k != 'sign_type') {
				if ($i == 0) {
					$stringToBeSigned .= "$k" . "=" . "$v";
				} else {
					$stringToBeSigned .= "&" . "$k" . "=" . "$v";
				}
				$i++;
			}
		}
		unset ($k, $v);

		return $this->sign($stringToBeSigned);
	}

	protected function sign($data) {
		if($this->signType == "RSA") { 
			$this->rsaPrivateKeyFilePath = dirname(__FILE__). '/key/mobile_rsa_private_key.pem';
			$priKey = file_get_contents($this->rsaPrivateKeyFilePath);
			$res = openssl_get_privatekey($priKey);
			openssl_sign($data, $sign, $res);
			openssl_free_key($res);
			$sign = base64_encode($sign);
		} else {
			$priKey = 'kcxawi9bb07mzh0aq2wcirsf9znusobw';
			$sign = md5($data . $priKey);
		}
		return $sign;
	}

	protected function curl($url, $postFields = null) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$postBodyString = "";
		if (is_array($postFields) && 0 < count($postFields)) {
			
			$postMultipart = false;
			foreach ($postFields as $k => $v) {
				if ("@" != substr($v, 0, 1)) //判断是不是文件上传
					{
					$postBodyString .= "$k=" . urlencode($v) . "&";
				} else //文件上传用multipart/form-data,否则用www-form-urlencoded
					{
					$postMultipart = true;
				}
			}
			unset ($k, $v);
			curl_setopt($ch, CURLOPT_POST, true);
			if ($postMultipart) {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
			} else {
				curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
			}
		}
		$headers = array('content-type: application/x-www-form-urlencoded;charset=UTF-8');	
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		$reponse = curl_exec($ch);

		if (curl_errno($ch)) {
			throw new Exception(curl_error($ch), 0);
		} else {
			$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if (200 !== $httpStatusCode) {
				throw new Exception($reponse, $httpStatusCode);
			}
		}
		curl_close($ch);
		return $reponse;
	}

	protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt) {

	}

	public function execute($request) {
		//组装系统参数
		$sysParams["service"] = $request->getApiMethodName();
		$sysParams["partner"] = $this->partner;
		$sysParams["_input_charset"] = $this->_input_charset;
	//	$sysParams["format"] = $this->format;
		$sysParams["sign_type"] = $this->signType;
		$sysParams["timestamp"] = date("Y-m-d H:i:s");

		//获取业务参数
		$apiParams = $request->getApiParas();
		//签名
		$sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams));

		//系统参数放入GET请求串
		$requestUrl = $this->gatewayUrl . "?";
		foreach ($sysParams as $sysParamKey => $sysParamValue) {
			$requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
		}
		$requestUrl = substr($requestUrl, 0, -1);

		//发起HTTP请求
		try {
			$resp = $this->curl($requestUrl, $apiParams);
		} catch (Exception $e) {
			$this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
			return false;
		}

		//解析AOP返回结果
		$respWellFormed = false;

		if ("json" == $this->format) {
			$respObject = json_decode($resp);
			if (null !== $respObject) {
				$respWellFormed = true;								
			}
		} else
			if ("xml" == $this->format) {
			//	$respObject = @ simplexml_load_string($resp);
				$xmlObj = new Zend_Config_Xml($resp);
				$respObject = $xmlObj->toArray();
				if (false !== $respObject) {
					$respWellFormed = true;
				}
			}

		//返回的HTTP文本不是标准JSON或者XML,记下错误日志
		if (false === $respWellFormed) {
			$this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
			return false;
		}

		//如果AOP返回了错误码,记录到业务错误日志中
		if (isset ($respObject->code)) {
			
		}
		return $respObject;
	}
	
	/**
	 * 校验$value是否非空
	 *  if not set ,return true;
	 *	if is null , return true;
	 **/
	protected function checkEmpty($value) {
		if(!isset($value))
			return true ;
		if($value === null )
			return true;
		if(trim($value) === "")
			return true;
		
		return false;
	}
}