AopClient.php 41 KB

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