AopClient.php 34 KB

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