AopClient.php 34 KB

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