AopClient.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. <?php
  2. require_once 'AopEncrypt.php';
  3. require_once 'EncryptParseItem.php';
  4. require_once 'EncryptResponseData.php';
  5. require_once 'SignData.php';
  6. class AopClient
  7. {
  8. //应用ID
  9. public $appId;
  10. //私钥文件路径
  11. public $rsaPrivateKeyFilePath;
  12. //私钥值
  13. public $rsaPrivateKey;
  14. //网关
  15. public $gatewayUrl = "https://openapi.alipay.com/gateway.do";
  16. //返回数据格式
  17. public $format = "json";
  18. //api版本
  19. public $apiVersion = "1.0";
  20. // 表单提交字符集编码
  21. public $postCharset = "UTF-8";
  22. //使用文件读取文件格式,请只传递该值
  23. public $alipayPublicKey = null;
  24. //使用读取字符串格式,请只传递该值
  25. public $alipayrsaPublicKey;
  26. public $debugInfo = false;
  27. private $fileCharset = "UTF-8";
  28. private $RESPONSE_SUFFIX = "_response";
  29. private $ERROR_RESPONSE = "error_response";
  30. private $SIGN_NODE_NAME = "sign";
  31. //加密XML节点名称
  32. private $ENCRYPT_XML_NODE_NAME = "response_encrypted";
  33. private $needEncrypt = false;
  34. //签名类型
  35. public $signType = "RSA";
  36. //加密密钥和类型
  37. public $encryptKey;
  38. public $encryptType = "AES";
  39. private $targetServiceUrl = "";
  40. protected $alipaySdkVersion = "alipay-sdk-php-easyalipay-20191227";
  41. public function generateSign($params, $signType = "RSA")
  42. {
  43. return $this->sign($this->getSignContent($params), $signType);
  44. }
  45. public function rsaSign($params, $signType = "RSA")
  46. {
  47. return $this->sign($this->getSignContent($params), $signType);
  48. }
  49. public function getSignContent($params)
  50. {
  51. ksort($params);
  52. $stringToBeSigned = "";
  53. $i = 0;
  54. foreach ($params as $k => $v) {
  55. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  56. // 转换成目标字符集
  57. $v = $this->characet($v, $this->postCharset);
  58. if ($i == 0) {
  59. $stringToBeSigned .= "$k" . "=" . "$v";
  60. } else {
  61. $stringToBeSigned .= "&" . "$k" . "=" . "$v";
  62. }
  63. $i++;
  64. }
  65. }
  66. unset ($k, $v);
  67. return $stringToBeSigned;
  68. }
  69. //此方法对value做urlencode
  70. public function getSignContentUrlencode($params)
  71. {
  72. ksort($params);
  73. $stringToBeSigned = "";
  74. $i = 0;
  75. foreach ($params as $k => $v) {
  76. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  77. // 转换成目标字符集
  78. $v = $this->characet($v, $this->postCharset);
  79. if ($i == 0) {
  80. $stringToBeSigned .= "$k" . "=" . urlencode($v);
  81. } else {
  82. $stringToBeSigned .= "&" . "$k" . "=" . urlencode($v);
  83. }
  84. $i++;
  85. }
  86. }
  87. unset ($k, $v);
  88. return $stringToBeSigned;
  89. }
  90. protected function sign($data, $signType = "RSA")
  91. {
  92. if ($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
  93. $priKey = $this->rsaPrivateKey;
  94. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  95. wordwrap($priKey, 64, "\n", true) .
  96. "\n-----END RSA PRIVATE KEY-----";
  97. } else {
  98. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  99. $res = openssl_get_privatekey($priKey);
  100. }
  101. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  102. if ("RSA2" == $signType) {
  103. openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
  104. } else {
  105. openssl_sign($data, $sign, $res);
  106. }
  107. if (!$this->checkEmpty($this->rsaPrivateKeyFilePath)) {
  108. openssl_free_key($res);
  109. }
  110. $sign = base64_encode($sign);
  111. return $sign;
  112. }
  113. /**
  114. * RSA单独签名方法,未做字符串处理,字符串处理见getSignContent()
  115. * @param $data 待签名字符串
  116. * @param $privatekey 商户私钥,根据keyfromfile来判断是读取字符串还是读取文件,false:填写私钥字符串去回车和空格 true:填写私钥文件路径
  117. * @param $signType 签名方式,RSA:SHA1 RSA2:SHA256
  118. * @param $keyfromfile 私钥获取方式,读取字符串还是读文件
  119. * @return string
  120. */
  121. public function alonersaSign($data, $privatekey, $signType = "RSA", $keyfromfile = false)
  122. {
  123. if (!$keyfromfile) {
  124. $priKey = $privatekey;
  125. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  126. wordwrap($priKey, 64, "\n", true) .
  127. "\n-----END RSA PRIVATE KEY-----";
  128. } else {
  129. $priKey = file_get_contents($privatekey);
  130. $res = openssl_get_privatekey($priKey);
  131. }
  132. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  133. if ("RSA2" == $signType) {
  134. openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
  135. } else {
  136. openssl_sign($data, $sign, $res);
  137. }
  138. if ($keyfromfile) {
  139. openssl_free_key($res);
  140. }
  141. $sign = base64_encode($sign);
  142. return $sign;
  143. }
  144. protected function curl($url, $postFields = null)
  145. {
  146. $ch = curl_init();
  147. curl_setopt($ch, CURLOPT_URL, $url);
  148. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  149. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  150. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  151. $postBodyString = "";
  152. $encodeArray = Array();
  153. $postMultipart = false;
  154. if (is_array($postFields) && 0 < count($postFields)) {
  155. foreach ($postFields as $k => $v) {
  156. if ("@" != substr($v, 0, 1)) //判断是不是文件上传
  157. {
  158. $postBodyString .= "$k=" . urlencode($this->characet($v, $this->postCharset)) . "&";
  159. $encodeArray[$k] = $this->characet($v, $this->postCharset);
  160. } else //文件上传用multipart/form-data,否则用www-form-urlencoded
  161. {
  162. $postMultipart = true;
  163. $encodeArray[$k] = new \CURLFile(substr($v, 1));
  164. }
  165. }
  166. unset ($k, $v);
  167. curl_setopt($ch, CURLOPT_POST, true);
  168. if ($postMultipart) {
  169. curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray);
  170. } else {
  171. curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
  172. }
  173. }
  174. if (!$postMultipart) {
  175. $headers = array('content-type: application/x-www-form-urlencoded;charset=' . $this->postCharset);
  176. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  177. }
  178. $reponse = curl_exec($ch);
  179. if (curl_errno($ch)) {
  180. throw new Exception(curl_error($ch), 0);
  181. } else {
  182. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  183. if (200 !== $httpStatusCode) {
  184. throw new Exception($reponse, $httpStatusCode);
  185. }
  186. }
  187. curl_close($ch);
  188. return $reponse;
  189. }
  190. protected function getMillisecond()
  191. {
  192. list($s1, $s2) = explode(' ', microtime());
  193. return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
  194. }
  195. protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt)
  196. {
  197. $logData = array(
  198. date("Y-m-d H:i:s"),
  199. $apiName,
  200. $this->appId,
  201. PHP_OS,
  202. $this->alipaySdkVersion,
  203. $requestUrl,
  204. $errorCode,
  205. str_replace("\n", "", $responseTxt)
  206. );
  207. echo json_encode($logData);
  208. }
  209. /**
  210. * 生成用于调用收银台SDK的字符串
  211. * @param $request SDK接口的请求参数对象
  212. * @param $appAuthToken 三方应用授权token
  213. * @return string
  214. */
  215. public function sdkExecute($request, $appAuthToken = null)
  216. {
  217. $this->setupCharsets($request);
  218. $params['app_id'] = $this->appId;
  219. $params['method'] = $request->getApiMethodName();
  220. $params['format'] = $this->format;
  221. $params['sign_type'] = $this->signType;
  222. $params['timestamp'] = date("Y-m-d H:i:s");
  223. $params['alipay_sdk'] = $this->alipaySdkVersion;
  224. $params['charset'] = $this->postCharset;
  225. $version = $request->getApiVersion();
  226. $params['version'] = $this->checkEmpty($version) ? $this->apiVersion : $version;
  227. if ($notify_url = $request->getNotifyUrl()) {
  228. $params['notify_url'] = $notify_url;
  229. }
  230. $params['app_auth_token'] = $appAuthToken;
  231. $dict = $request->getApiParas();
  232. $params['biz_content'] = $dict['biz_content'];
  233. ksort($params);
  234. $params['sign'] = $this->generateSign($params, $this->signType);
  235. foreach ($params as &$value) {
  236. $value = $this->characet($value, $params['charset']);
  237. }
  238. return http_build_query($params);
  239. }
  240. /**
  241. * 页面提交执行方法
  242. * @param $request 跳转类接口的request
  243. * @param string $httpmethod 提交方式,两个值可选:post、get;
  244. * @param null $appAuthToken 三方应用授权token
  245. * @return 构建好的、签名后的最终跳转URL(GET)或String形式的form(POST)
  246. * @throws Exception
  247. */
  248. public function pageExecute($request, $httpmethod = "POST", $appAuthToken = null)
  249. {
  250. $this->setupCharsets($request);
  251. if (strcasecmp($this->fileCharset, $this->postCharset)) {
  252. // writeLog("本地文件字符集编码与表单提交编码不一致,请务必设置成一样,属性名分别为postCharset!");
  253. throw new Exception("文件编码:[" . $this->fileCharset . "] 与表单提交编码:[" . $this->postCharset . "]两者不一致!");
  254. }
  255. $iv = null;
  256. if (!$this->checkEmpty($request->getApiVersion())) {
  257. $iv = $request->getApiVersion();
  258. } else {
  259. $iv = $this->apiVersion;
  260. }
  261. //组装系统参数
  262. $sysParams["app_id"] = $this->appId;
  263. $sysParams["version"] = $iv;
  264. $sysParams["format"] = $this->format;
  265. $sysParams["sign_type"] = $this->signType;
  266. $sysParams["method"] = $request->getApiMethodName();
  267. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  268. $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
  269. $sysParams["terminal_type"] = $request->getTerminalType();
  270. $sysParams["terminal_info"] = $request->getTerminalInfo();
  271. $sysParams["prod_code"] = $request->getProdCode();
  272. $sysParams["notify_url"] = $request->getNotifyUrl();
  273. $sysParams["return_url"] = $request->getReturnUrl();
  274. $sysParams["charset"] = $this->postCharset;
  275. $sysParams["app_auth_token"] = $appAuthToken;
  276. //获取业务参数
  277. $apiParams = $request->getApiParas();
  278. if (method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
  279. $sysParams["encrypt_type"] = $this->encryptType;
  280. if ($this->checkEmpty($apiParams['biz_content'])) {
  281. throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
  282. }
  283. if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
  284. throw new Exception(" encryptType and encryptKey must not null! ");
  285. }
  286. if ("AES" != $this->encryptType) {
  287. throw new Exception("加密类型只支持AES");
  288. }
  289. // 执行加密
  290. $enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
  291. $apiParams['biz_content'] = $enCryptContent;
  292. }
  293. //print_r($apiParams);
  294. $totalParams = array_merge($apiParams, $sysParams);
  295. //待签名字符串
  296. $preSignStr = $this->getSignContent($totalParams);
  297. //签名
  298. $totalParams["sign"] = $this->generateSign($totalParams, $this->signType);
  299. if ("GET" == strtoupper($httpmethod)) {
  300. //value做urlencode
  301. $preString = $this->getSignContentUrlencode($totalParams);
  302. //拼接GET请求串
  303. $requestUrl = $this->gatewayUrl . "?" . $preString;
  304. return $requestUrl;
  305. } else {
  306. //拼接表单字符串
  307. return $this->buildRequestForm($totalParams);
  308. }
  309. }
  310. /**
  311. * 建立请求,以表单HTML形式构造(默认)
  312. * @param $para_temp 请求参数数组
  313. * @return 提交表单HTML文本
  314. */
  315. protected function buildRequestForm($para_temp)
  316. {
  317. $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='" . $this->gatewayUrl . "?charset=" . trim($this->postCharset) . "' method='POST'>";
  318. while (list ($key, $val) = $this->fun_adm_each($para_temp)) {
  319. if (false === $this->checkEmpty($val)) {
  320. //$val = $this->characet($val, $this->postCharset);
  321. $val = str_replace("'", "&apos;", $val);
  322. //$val = str_replace("\"","&quot;",$val);
  323. $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
  324. }
  325. }
  326. //submit按钮控件请不要含有name属性
  327. $sHtml = $sHtml . "<input type='submit' value='ok' style='display:none;''></form>";
  328. $sHtml = $sHtml . "<script>document.forms['alipaysubmit'].submit();</script>";
  329. return $sHtml;
  330. }
  331. protected function fun_adm_each(&$array)
  332. {
  333. $res = array();
  334. $key = key($array);
  335. if ($key !== null) {
  336. next($array);
  337. $res[1] = $res['value'] = $array[$key];
  338. $res[0] = $res['key'] = $key;
  339. } else {
  340. $res = false;
  341. }
  342. return $res;
  343. }
  344. public function execute($request, $authToken = null, $appInfoAuthtoken = null, $targetAppId = null)
  345. {
  346. $this->setupCharsets($request);
  347. //如果两者编码不一致,会出现签名验签或者乱码
  348. if (strcasecmp($this->fileCharset, $this->postCharset)) {
  349. // writeLog("本地文件字符集编码与表单提交编码不一致,请务必设置成一样,属性名分别为postCharset!");
  350. throw new Exception("文件编码:[" . $this->fileCharset . "] 与表单提交编码:[" . $this->postCharset . "]两者不一致!");
  351. }
  352. $iv = null;
  353. if (!$this->checkEmpty($request->getApiVersion())) {
  354. $iv = $request->getApiVersion();
  355. } else {
  356. $iv = $this->apiVersion;
  357. }
  358. //组装系统参数
  359. $sysParams["app_id"] = $this->appId;
  360. $sysParams["version"] = $iv;
  361. $sysParams["format"] = $this->format;
  362. $sysParams["sign_type"] = $this->signType;
  363. $sysParams["method"] = $request->getApiMethodName();
  364. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  365. $sysParams["auth_token"] = $authToken;
  366. $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
  367. $sysParams["terminal_type"] = $request->getTerminalType();
  368. $sysParams["terminal_info"] = $request->getTerminalInfo();
  369. $sysParams["prod_code"] = $request->getProdCode();
  370. $sysParams["notify_url"] = $request->getNotifyUrl();
  371. $sysParams["charset"] = $this->postCharset;
  372. $sysParams["app_auth_token"] = $appInfoAuthtoken;
  373. $sysParams["target_app_id"] = $targetAppId;
  374. if (!$this->checkEmpty($this->targetServiceUrl)) {
  375. $sysParams["ws_service_url"] = $this->targetServiceUrl;
  376. }
  377. //获取业务参数
  378. $apiParams = $request->getApiParas();
  379. if (method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
  380. $sysParams["encrypt_type"] = $this->encryptType;
  381. if ($this->checkEmpty($apiParams['biz_content'])) {
  382. throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
  383. }
  384. if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
  385. throw new Exception(" encryptType and encryptKey must not null! ");
  386. }
  387. if ("AES" != $this->encryptType) {
  388. throw new Exception("加密类型只支持AES");
  389. }
  390. // 执行加密
  391. $enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
  392. $apiParams['biz_content'] = $enCryptContent;
  393. }
  394. //签名
  395. $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
  396. //系统参数放入GET请求串
  397. $requestUrl = $this->gatewayUrl . "?";
  398. foreach ($sysParams as $sysParamKey => $sysParamValue) {
  399. $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
  400. }
  401. $requestUrl = substr($requestUrl, 0, -1);
  402. //发起HTTP请求
  403. try {
  404. $resp = $this->curl($requestUrl, $apiParams);
  405. } catch (Exception $e) {
  406. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
  407. return false;
  408. }
  409. //解析AOP返回结果
  410. $respWellFormed = false;
  411. // 将返回结果转换本地文件编码
  412. $r = @iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  413. $signData = null;
  414. if ("json" == $this->format) {
  415. $respObject = json_decode($r);
  416. if (null !== $respObject) {
  417. $respWellFormed = true;
  418. $signData = $this->parserJSONSignData($request, $resp, $respObject);
  419. }
  420. } else if ("xml" == $this->format) {
  421. $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
  422. $respObject = @ simplexml_load_string($resp);
  423. if (false !== $respObject) {
  424. $respWellFormed = true;
  425. $signData = $this->parserXMLSignData($request, $resp);
  426. }
  427. libxml_disable_entity_loader($disableLibxmlEntityLoader);
  428. }
  429. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  430. if (false === $respWellFormed) {
  431. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
  432. return false;
  433. }
  434. // 验签
  435. $this->checkResponseSign($request, $signData, $resp, $respObject);
  436. // 解密
  437. if (method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
  438. if ("json" == $this->format) {
  439. $resp = $this->encryptJSONSignSource($request, $resp);
  440. // 将返回结果转换本地文件编码
  441. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  442. $respObject = json_decode($r);
  443. } else {
  444. $resp = $this->encryptXMLSignSource($request, $resp);
  445. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  446. $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
  447. $respObject = @ simplexml_load_string($r);
  448. libxml_disable_entity_loader($disableLibxmlEntityLoader);
  449. }
  450. }
  451. return $respObject;
  452. }
  453. /**
  454. * 转换字符集编码
  455. * @param $data
  456. * @param $targetCharset
  457. * @return string
  458. */
  459. function characet($data, $targetCharset)
  460. {
  461. if (!empty($data)) {
  462. $fileType = $this->fileCharset;
  463. if (strcasecmp($fileType, $targetCharset) != 0) {
  464. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  465. // $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
  466. }
  467. }
  468. return $data;
  469. }
  470. public function exec($paramsArray)
  471. {
  472. if (!isset ($paramsArray["method"])) {
  473. trigger_error("No api name passed");
  474. }
  475. $inflector = new LtInflector;
  476. $inflector->conf["separator"] = ".";
  477. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  478. if (!class_exists($requestClassName)) {
  479. trigger_error("No such api: " . $paramsArray["method"]);
  480. }
  481. $session = isset ($paramsArray["session"]) ? $paramsArray["session"] : null;
  482. $req = new $requestClassName;
  483. foreach ($paramsArray as $paraKey => $paraValue) {
  484. $inflector->conf["separator"] = "_";
  485. $setterMethodName = $inflector->camelize($paraKey);
  486. $inflector->conf["separator"] = ".";
  487. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  488. if (method_exists($req, $setterMethodName)) {
  489. $req->$setterMethodName ($paraValue);
  490. }
  491. }
  492. return $this->execute($req, $session);
  493. }
  494. /**
  495. * 校验$value是否非空
  496. * if not set ,return true;
  497. * if is null , return true;
  498. **/
  499. protected function checkEmpty($value)
  500. {
  501. if (!isset($value))
  502. return true;
  503. if ($value === null)
  504. return true;
  505. if (trim($value) === "")
  506. return true;
  507. return false;
  508. }
  509. /** rsaCheckV1 & rsaCheckV2
  510. * 验证签名
  511. * 在使用本方法前,必须初始化AopClient且传入公钥参数。
  512. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  513. **/
  514. public function rsaCheckV1($params, $rsaPublicKeyFilePath, $signType = 'RSA')
  515. {
  516. $sign = $params['sign'];
  517. $params['sign_type'] = null;
  518. $params['sign'] = null;
  519. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
  520. }
  521. public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType = 'RSA')
  522. {
  523. $sign = $params['sign'];
  524. $params['sign'] = null;
  525. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
  526. }
  527. function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA')
  528. {
  529. if ($this->checkEmpty($this->alipayPublicKey)) {
  530. $pubKey = $this->alipayrsaPublicKey;
  531. $res = "-----BEGIN PUBLIC KEY-----\n" .
  532. wordwrap($pubKey, 64, "\n", true) .
  533. "\n-----END PUBLIC KEY-----";
  534. } else {
  535. //读取公钥文件
  536. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  537. //转换为openssl格式密钥
  538. $res = openssl_get_publickey($pubKey);
  539. }
  540. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  541. //调用openssl内置方法验签,返回bool值
  542. $result = FALSE;
  543. if ("RSA2" == $signType) {
  544. $result = (openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256) === 1);
  545. } else {
  546. $result = (openssl_verify($data, base64_decode($sign), $res) === 1);
  547. }
  548. if (!$this->checkEmpty($this->alipayPublicKey)) {
  549. //释放资源
  550. openssl_free_key($res);
  551. }
  552. return $result;
  553. }
  554. /**
  555. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  556. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  557. **/
  558. public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt, $signType = 'RSA')
  559. {
  560. $charset = $params['charset'];
  561. $bizContent = $params['biz_content'];
  562. if ($isCheckSign) {
  563. if (!$this->rsaCheckV2($params, $rsaPublicKeyPem, $signType)) {
  564. echo "<br/>checkSign failure<br/>";
  565. exit;
  566. }
  567. }
  568. if ($isDecrypt) {
  569. return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
  570. }
  571. return $bizContent;
  572. }
  573. /**
  574. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  575. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  576. **/
  577. public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign, $signType = 'RSA')
  578. {
  579. // 加密,并签名
  580. if ($isEncrypt && $isSign) {
  581. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  582. $sign = $this->sign($encrypted, $signType);
  583. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$encrypted</response><encryption_type>RSA</encryption_type><sign>$sign</sign><sign_type>$signType</sign_type></alipay>";
  584. return $response;
  585. }
  586. // 加密,不签名
  587. if ($isEncrypt && (!$isSign)) {
  588. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  589. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$encrypted</response><encryption_type>$signType</encryption_type></alipay>";
  590. return $response;
  591. }
  592. // 不加密,但签名
  593. if ((!$isEncrypt) && $isSign) {
  594. $sign = $this->sign($bizContent, $signType);
  595. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$bizContent</response><sign>$sign</sign><sign_type>$signType</sign_type></alipay>";
  596. return $response;
  597. }
  598. // 不加密,不签名
  599. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?>$bizContent";
  600. return $response;
  601. }
  602. /**
  603. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  604. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  605. **/
  606. public function rsaEncrypt($data, $rsaPublicKeyFilePath, $charset)
  607. {
  608. if ($this->checkEmpty($this->alipayPublicKey)) {
  609. //读取字符串
  610. $pubKey = $this->alipayrsaPublicKey;
  611. $res = "-----BEGIN PUBLIC KEY-----\n" .
  612. wordwrap($pubKey, 64, "\n", true) .
  613. "\n-----END PUBLIC KEY-----";
  614. } else {
  615. //读取公钥文件
  616. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  617. //转换为openssl格式密钥
  618. $res = openssl_get_publickey($pubKey);
  619. }
  620. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  621. $blocks = $this->splitCN($data, 0, 30, $charset);
  622. $chrtext  = null;
  623. $encodes  = array();
  624. foreach ($blocks as $n => $block) {
  625. if (!openssl_public_encrypt($block, $chrtext , $res)) {
  626. echo "<br/>" . openssl_error_string() . "<br/>";
  627. }
  628. $encodes[] = $chrtext ;
  629. }
  630. $chrtext = implode(",", $encodes);
  631. return base64_encode($chrtext);
  632. }
  633. /**
  634. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  635. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  636. **/
  637. public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset)
  638. {
  639. if ($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
  640. //读字符串
  641. $priKey = $this->rsaPrivateKey;
  642. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  643. wordwrap($priKey, 64, "\n", true) .
  644. "\n-----END RSA PRIVATE KEY-----";
  645. } else {
  646. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  647. $res = openssl_get_privatekey($priKey);
  648. }
  649. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  650. //转换为openssl格式密钥
  651. $decodes = explode(',', $data);
  652. $strnull = "";
  653. $dcyCont = "";
  654. foreach ($decodes as $n => $decode) {
  655. if (!openssl_private_decrypt($decode, $dcyCont, $res)) {
  656. echo "<br/>" . openssl_error_string() . "<br/>";
  657. }
  658. $strnull .= $dcyCont;
  659. }
  660. return $strnull;
  661. }
  662. function splitCN($cont, $n = 0, $subnum, $charset)
  663. {
  664. //$len = strlen($cont) / 3;
  665. $arrr = array();
  666. for ($i = $n; $i < strlen($cont); $i += $subnum) {
  667. $res = $this->subCNchar($cont, $i, $subnum, $charset);
  668. if (!empty ($res)) {
  669. $arrr[] = $res;
  670. }
  671. }
  672. return $arrr;
  673. }
  674. function subCNchar($str, $start = 0, $length, $charset = "gbk")
  675. {
  676. if (strlen($str) <= $length) {
  677. return $str;
  678. }
  679. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  680. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  681. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  682. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  683. preg_match_all($re[$charset], $str, $match);
  684. $slice = join("", array_slice($match[0], $start, $length));
  685. return $slice;
  686. }
  687. function parserResponseSubCode($request, $responseContent, $respObject, $format)
  688. {
  689. if ("json" == $format) {
  690. $apiName = $request->getApiMethodName();
  691. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  692. $errorNodeName = $this->ERROR_RESPONSE;
  693. $rootIndex = strpos($responseContent, $rootNodeName);
  694. $errorIndex = strpos($responseContent, $errorNodeName);
  695. if ($rootIndex > 0) {
  696. // 内部节点对象
  697. $rInnerObject = $respObject->$rootNodeName;
  698. } elseif ($errorIndex > 0) {
  699. $rInnerObject = $respObject->$errorNodeName;
  700. } else {
  701. return null;
  702. }
  703. // 存在属性则返回对应值
  704. if (isset($rInnerObject->sub_code)) {
  705. return $rInnerObject->sub_code;
  706. } else {
  707. return null;
  708. }
  709. } elseif ("xml" == $format) {
  710. // xml格式sub_code在同一层级
  711. return $respObject->sub_code;
  712. }
  713. }
  714. function parserJSONSignData($request, $responseContent, $responseJSON)
  715. {
  716. $signData = new SignData();
  717. $signData->sign = $this->parserJSONSign($responseJSON);
  718. $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
  719. return $signData;
  720. }
  721. function parserJSONSignSource($request, $responseContent)
  722. {
  723. $apiName = $request->getApiMethodName();
  724. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  725. $rootIndex = strpos($responseContent, $rootNodeName);
  726. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  727. if ($rootIndex > 0) {
  728. return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
  729. } else if ($errorIndex > 0) {
  730. return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  731. } else {
  732. return null;
  733. }
  734. }
  735. function parserJSONSource($responseContent, $nodeName, $nodeIndex)
  736. {
  737. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  738. $signIndex = strrpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  739. // 签名前-逗号
  740. $signDataEndIndex = $signIndex - 1;
  741. $indexLen = $signDataEndIndex - $signDataStartIndex;
  742. if ($indexLen < 0) {
  743. return null;
  744. }
  745. return substr($responseContent, $signDataStartIndex, $indexLen);
  746. }
  747. function parserJSONSign($responseJSon)
  748. {
  749. return $responseJSon->sign;
  750. }
  751. function parserXMLSignData($request, $responseContent)
  752. {
  753. $signData = new SignData();
  754. $signData->sign = $this->parserXMLSign($responseContent);
  755. $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
  756. return $signData;
  757. }
  758. function parserXMLSignSource($request, $responseContent)
  759. {
  760. $apiName = $request->getApiMethodName();
  761. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  762. $rootIndex = strpos($responseContent, $rootNodeName);
  763. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  764. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  765. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  766. if ($rootIndex > 0) {
  767. return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
  768. } else if ($errorIndex > 0) {
  769. return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  770. } else {
  771. return null;
  772. }
  773. }
  774. function parserXMLSource($responseContent, $nodeName, $nodeIndex)
  775. {
  776. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  777. $signIndex = strrpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
  778. // 签名前-逗号
  779. $signDataEndIndex = $signIndex - 1;
  780. $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
  781. if ($indexLen < 0) {
  782. return null;
  783. }
  784. return substr($responseContent, $signDataStartIndex, $indexLen);
  785. }
  786. function parserXMLSign($responseContent)
  787. {
  788. $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
  789. $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
  790. $indexOfSignNode = strpos($responseContent, $signNodeName);
  791. $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
  792. if ($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
  793. return null;
  794. }
  795. $nodeIndex = ($indexOfSignNode + strlen($signNodeName));
  796. $indexLen = $indexOfSignEndNode - $nodeIndex;
  797. if ($indexLen < 0) {
  798. return null;
  799. }
  800. // 签名
  801. return substr($responseContent, $nodeIndex, $indexLen);
  802. }
  803. /**
  804. * 验签
  805. * @param $request
  806. * @param $signData
  807. * @param $resp
  808. * @param $respObject
  809. * @throws Exception
  810. */
  811. public function checkResponseSign($request, $signData, $resp, $respObject)
  812. {
  813. if (!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
  814. if ($signData == null || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
  815. throw new Exception(" check sign Fail! The reason : signData is Empty");
  816. }
  817. // 获取结果sub_code
  818. $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
  819. if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign))) {
  820. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  821. if (!$checkResult) {
  822. if (strpos($signData->signSourceData, "\\/") > 0) {
  823. $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
  824. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  825. if (!$checkResult) {
  826. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  827. }
  828. } else {
  829. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  830. }
  831. }
  832. }
  833. }
  834. }
  835. private function setupCharsets($request)
  836. {
  837. if ($this->checkEmpty($this->postCharset)) {
  838. $this->postCharset = 'UTF-8';
  839. }
  840. $str = preg_match('/[\x80-\xff]/', $this->appId) ? $this->appId : print_r($request, true);
  841. $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == 'UTF-8' ? 'UTF-8' : 'GBK';
  842. }
  843. // 获取加密内容
  844. private function encryptJSONSignSource($request, $responseContent)
  845. {
  846. $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
  847. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  848. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  849. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  850. return $bodyIndexContent . $bizContent . $bodyEndContent;
  851. }
  852. private function parserEncryptJSONSignSource($request, $responseContent)
  853. {
  854. $apiName = $request->getApiMethodName();
  855. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  856. $rootIndex = strpos($responseContent, $rootNodeName);
  857. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  858. if ($rootIndex > 0) {
  859. return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
  860. } else if ($errorIndex > 0) {
  861. return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  862. } else {
  863. return null;
  864. }
  865. }
  866. private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex)
  867. {
  868. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  869. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  870. // 签名前-逗号
  871. $signDataEndIndex = $signIndex - 1;
  872. if ($signDataEndIndex < 0) {
  873. $signDataEndIndex = strlen($responseContent) - 1;
  874. }
  875. $indexLen = $signDataEndIndex - $signDataStartIndex;
  876. $encContent = substr($responseContent, $signDataStartIndex + 1, $indexLen - 2);
  877. $encryptParseItem = new EncryptParseItem();
  878. $encryptParseItem->encryptContent = $encContent;
  879. $encryptParseItem->startIndex = $signDataStartIndex;
  880. $encryptParseItem->endIndex = $signDataEndIndex;
  881. return $encryptParseItem;
  882. }
  883. // 获取加密内容
  884. private function encryptXMLSignSource($request, $responseContent)
  885. {
  886. $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
  887. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  888. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  889. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  890. return $bodyIndexContent . $bizContent . $bodyEndContent;
  891. }
  892. private function parserEncryptXMLSignSource($request, $responseContent)
  893. {
  894. $apiName = $request->getApiMethodName();
  895. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  896. $rootIndex = strpos($responseContent, $rootNodeName);
  897. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  898. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  899. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  900. if ($rootIndex > 0) {
  901. return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
  902. } else if ($errorIndex > 0) {
  903. return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  904. } else {
  905. return null;
  906. }
  907. }
  908. private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex)
  909. {
  910. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  911. $xmlStartNode = "<" . $this->ENCRYPT_XML_NODE_NAME . ">";
  912. $xmlEndNode = "</" . $this->ENCRYPT_XML_NODE_NAME . ">";
  913. $indexOfXmlNode = strpos($responseContent, $xmlEndNode);
  914. if ($indexOfXmlNode < 0) {
  915. $item = new EncryptParseItem();
  916. $item->encryptContent = null;
  917. $item->startIndex = 0;
  918. $item->endIndex = 0;
  919. return $item;
  920. }
  921. $startIndex = $signDataStartIndex + strlen($xmlStartNode);
  922. $bizContentLen = $indexOfXmlNode - $startIndex;
  923. $bizContent = substr($responseContent, $startIndex, $bizContentLen);
  924. $encryptParseItem = new EncryptParseItem();
  925. $encryptParseItem->encryptContent = $bizContent;
  926. $encryptParseItem->startIndex = $signDataStartIndex;
  927. $encryptParseItem->endIndex = $indexOfXmlNode + strlen($xmlEndNode);
  928. return $encryptParseItem;
  929. }
  930. function echoDebug($content)
  931. {
  932. if ($this->debugInfo) {
  933. echo "<br/>" . $content;
  934. }
  935. }
  936. }