AopClient.php 40 KB

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