AopClient.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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-20161101";
  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. $response = 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($response, $httpStatusCode);
  177. }
  178. }
  179. curl_close($ch);
  180. return $response;
  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. // while (list ($key, $val) = each ($para_temp)) {
  307. // 更改原因:PHP 7.2 Deprecated: The each() function is deprecated
  308. // https://github.com/sebastianbergmann/phpunit/issues/2887
  309. if (is_array($para_temp) && !empty($para_temp)){
  310. foreach($para_temp as $key => $val){
  311. if (false === $this->checkEmpty($val)) {
  312. //$val = $this->characet($val, $this->postCharset);
  313. $val = str_replace("'","&apos;",$val);
  314. //$val = str_replace("\"","&quot;",$val);
  315. $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
  316. }
  317. }
  318. }
  319. //submit按钮控件请不要含有name属性
  320. $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
  321. $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
  322. return $sHtml;
  323. }
  324. public function execute($request, $authToken = null, $appInfoAuthtoken = null) {
  325. $this->setupCharsets($request);
  326. // // 如果两者编码不一致,会出现签名验签或者乱码
  327. if (strcasecmp($this->fileCharset, $this->postCharset)) {
  328. // writeLog("本地文件字符集编码与表单提交编码不一致,请务必设置成一样,属性名分别为postCharset!");
  329. throw new Exception("文件编码:[" . $this->fileCharset . "] 与表单提交编码:[" . $this->postCharset . "]两者不一致!");
  330. }
  331. $iv = null;
  332. if (!$this->checkEmpty($request->getApiVersion())) {
  333. $iv = $request->getApiVersion();
  334. } else {
  335. $iv = $this->apiVersion;
  336. }
  337. //组装系统参数
  338. $sysParams["app_id"] = $this->appId;
  339. $sysParams["version"] = $iv;
  340. $sysParams["format"] = $this->format;
  341. $sysParams["sign_type"] = $this->signType;
  342. $sysParams["method"] = $request->getApiMethodName();
  343. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  344. $sysParams["auth_token"] = $authToken;
  345. $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
  346. $sysParams["terminal_type"] = $request->getTerminalType();
  347. $sysParams["terminal_info"] = $request->getTerminalInfo();
  348. $sysParams["prod_code"] = $request->getProdCode();
  349. $sysParams["notify_url"] = $request->getNotifyUrl();
  350. $sysParams["charset"] = $this->postCharset;
  351. $sysParams["app_auth_token"] = $appInfoAuthtoken;
  352. //获取业务参数
  353. $apiParams = $request->getApiParas();
  354. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  355. $sysParams["encrypt_type"] = $this->encryptType;
  356. if ($this->checkEmpty($apiParams['biz_content'])) {
  357. throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
  358. }
  359. if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
  360. throw new Exception(" encryptType and encryptKey must not null! ");
  361. }
  362. if ("AES" != $this->encryptType) {
  363. throw new Exception("加密类型只支持AES");
  364. }
  365. // 执行加密
  366. $enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
  367. $apiParams['biz_content'] = $enCryptContent;
  368. }
  369. //签名
  370. $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
  371. //系统参数放入GET请求串
  372. $requestUrl = $this->gatewayUrl . "?";
  373. foreach ($sysParams as $sysParamKey => $sysParamValue) {
  374. $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
  375. }
  376. $requestUrl = substr($requestUrl, 0, -1);
  377. //发起HTTP请求
  378. try {
  379. $resp = $this->curl($requestUrl, $apiParams);
  380. } catch (Exception $e) {
  381. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
  382. return false;
  383. }
  384. //解析AOP返回结果
  385. $respWellFormed = false;
  386. // 将返回结果转换本地文件编码
  387. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  388. $signData = null;
  389. if ("json" == $this->format) {
  390. $respObject = json_decode($r);
  391. if (null !== $respObject) {
  392. $respWellFormed = true;
  393. $signData = $this->parserJSONSignData($request, $resp, $respObject);
  394. }
  395. } else if ("xml" == $this->format) {
  396. $respObject = @ simplexml_load_string($resp);
  397. if (false !== $respObject) {
  398. $respWellFormed = true;
  399. $signData = $this->parserXMLSignData($request, $resp);
  400. }
  401. }
  402. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  403. if (false === $respWellFormed) {
  404. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
  405. return false;
  406. }
  407. // 验签
  408. $this->checkResponseSign($request, $signData, $resp, $respObject);
  409. // 解密
  410. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  411. if ("json" == $this->format) {
  412. $resp = $this->encryptJSONSignSource($request, $resp);
  413. // 将返回结果转换本地文件编码
  414. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  415. $respObject = json_decode($r);
  416. }else{
  417. $resp = $this->encryptXMLSignSource($request, $resp);
  418. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  419. $respObject = @ simplexml_load_string($r);
  420. }
  421. }
  422. return $respObject;
  423. }
  424. /**
  425. * 转换字符集编码
  426. * @param $data
  427. * @param $targetCharset
  428. * @return string
  429. */
  430. function characet($data, $targetCharset) {
  431. if (!empty($data)) {
  432. $fileType = $this->fileCharset;
  433. if (strcasecmp($fileType, $targetCharset) != 0) {
  434. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  435. // $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
  436. }
  437. }
  438. return $data;
  439. }
  440. public function exec($paramsArray) {
  441. if (!isset ($paramsArray["method"])) {
  442. trigger_error("No api name passed");
  443. }
  444. $inflector = new LtInflector;
  445. $inflector->conf["separator"] = ".";
  446. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  447. if (!class_exists($requestClassName)) {
  448. trigger_error("No such api: " . $paramsArray["method"]);
  449. }
  450. $session = isset ($paramsArray["session"]) ? $paramsArray["session"] : null;
  451. $req = new $requestClassName;
  452. foreach ($paramsArray as $paraKey => $paraValue) {
  453. $inflector->conf["separator"] = "_";
  454. $setterMethodName = $inflector->camelize($paraKey);
  455. $inflector->conf["separator"] = ".";
  456. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  457. if (method_exists($req, $setterMethodName)) {
  458. $req->$setterMethodName ($paraValue);
  459. }
  460. }
  461. return $this->execute($req, $session);
  462. }
  463. /**
  464. * 校验$value是否非空
  465. * if not set ,return true;
  466. * if is null , return true;
  467. **/
  468. protected function checkEmpty($value) {
  469. if (!isset($value))
  470. return true;
  471. if ($value === null)
  472. return true;
  473. if (trim($value) === "")
  474. return true;
  475. return false;
  476. }
  477. /** rsaCheckV1 & rsaCheckV2
  478. * 验证签名
  479. * 在使用本方法前,必须初始化AopClient且传入公钥参数。
  480. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  481. **/
  482. public function rsaCheckV1($params, $rsaPublicKeyFilePath,$signType='RSA') {
  483. $sign = $params['sign'];
  484. $params['sign_type'] = null;
  485. $params['sign'] = null;
  486. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath,$signType);
  487. }
  488. public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType='RSA') {
  489. $sign = $params['sign'];
  490. $params['sign'] = null;
  491. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
  492. }
  493. function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA') {
  494. if($this->checkEmpty($this->alipayPublicKey)){
  495. $pubKey= $this->alipayrsaPublicKey;
  496. $res = "-----BEGIN PUBLIC KEY-----\n" .
  497. wordwrap($pubKey, 64, "\n", true) .
  498. "\n-----END PUBLIC KEY-----";
  499. }else {
  500. //读取公钥文件
  501. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  502. //转换为openssl格式密钥
  503. $res = openssl_get_publickey($pubKey);
  504. }
  505. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  506. //调用openssl内置方法验签,返回bool值
  507. if ("RSA2" == $signType) {
  508. $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
  509. } else {
  510. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  511. }
  512. if(!$this->checkEmpty($this->alipayPublicKey)) {
  513. //释放资源
  514. openssl_free_key($res);
  515. }
  516. return $result;
  517. }
  518. /**
  519. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  520. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  521. **/
  522. public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt, $signType='RSA') {
  523. $charset = $params['charset'];
  524. $bizContent = $params['biz_content'];
  525. if ($isCheckSign) {
  526. if (!$this->rsaCheckV2($params, $rsaPublicKeyPem, $signType)) {
  527. echo "<br/>checkSign failure<br/>";
  528. exit;
  529. }
  530. }
  531. if ($isDecrypt) {
  532. return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
  533. }
  534. return $bizContent;
  535. }
  536. /**
  537. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  538. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  539. **/
  540. public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign, $signType='RSA') {
  541. // 加密,并签名
  542. if ($isEncrypt && $isSign) {
  543. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  544. $sign = $this->sign($encrypted, $signType);
  545. $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>";
  546. return $response;
  547. }
  548. // 加密,不签名
  549. if ($isEncrypt && (!$isSign)) {
  550. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  551. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$encrypted</response><encryption_type>$signType</encryption_type></alipay>";
  552. return $response;
  553. }
  554. // 不加密,但签名
  555. if ((!$isEncrypt) && $isSign) {
  556. $sign = $this->sign($bizContent, $signType);
  557. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$bizContent</response><sign>$sign</sign><sign_type>$signType</sign_type></alipay>";
  558. return $response;
  559. }
  560. // 不加密,不签名
  561. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?>$bizContent";
  562. return $response;
  563. }
  564. /**
  565. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  566. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  567. **/
  568. public function rsaEncrypt($data, $rsaPublicKeyPem, $charset) {
  569. if($this->checkEmpty($this->alipayPublicKey)){
  570. //读取字符串
  571. $pubKey= $this->alipayrsaPublicKey;
  572. $res = "-----BEGIN PUBLIC KEY-----\n" .
  573. wordwrap($pubKey, 64, "\n", true) .
  574. "\n-----END PUBLIC KEY-----";
  575. }else {
  576. //读取公钥文件
  577. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  578. //转换为openssl格式密钥
  579. $res = openssl_get_publickey($pubKey);
  580. }
  581. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  582. $blocks = $this->splitCN($data, 0, 30, $charset);
  583. $chrtext  = null;
  584. $encodes  = array();
  585. foreach ($blocks as $n => $block) {
  586. if (!openssl_public_encrypt($block, $chrtext , $res)) {
  587. echo "<br/>" . openssl_error_string() . "<br/>";
  588. }
  589. $encodes[] = $chrtext ;
  590. }
  591. $chrtext = implode(",", $encodes);
  592. return base64_encode($chrtext);
  593. }
  594. /**
  595. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  596. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  597. **/
  598. public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset) {
  599. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  600. //读字符串
  601. $priKey=$this->rsaPrivateKey;
  602. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  603. wordwrap($priKey, 64, "\n", true) .
  604. "\n-----END RSA PRIVATE KEY-----";
  605. }else {
  606. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  607. $res = openssl_get_privatekey($priKey);
  608. }
  609. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  610. //转换为openssl格式密钥
  611. $decodes = explode(',', $data);
  612. $strnull = "";
  613. $dcyCont = "";
  614. foreach ($decodes as $n => $decode) {
  615. if (!openssl_private_decrypt($decode, $dcyCont, $res)) {
  616. echo "<br/>" . openssl_error_string() . "<br/>";
  617. }
  618. $strnull .= $dcyCont;
  619. }
  620. return $strnull;
  621. }
  622. function splitCN($cont, $n = 0, $subnum, $charset) {
  623. //$len = strlen($cont) / 3;
  624. $arrr = array();
  625. for ($i = $n; $i < strlen($cont); $i += $subnum) {
  626. $res = $this->subCNchar($cont, $i, $subnum, $charset);
  627. if (!empty ($res)) {
  628. $arrr[] = $res;
  629. }
  630. }
  631. return $arrr;
  632. }
  633. function subCNchar($str, $start = 0, $length, $charset = "gbk") {
  634. if (strlen($str) <= $length) {
  635. return $str;
  636. }
  637. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  638. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  639. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  640. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  641. preg_match_all($re[$charset], $str, $match);
  642. $slice = join("", array_slice($match[0], $start, $length));
  643. return $slice;
  644. }
  645. function parserResponseSubCode($request, $responseContent, $respObject, $format) {
  646. if ("json" == $format) {
  647. $apiName = $request->getApiMethodName();
  648. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  649. $errorNodeName = $this->ERROR_RESPONSE;
  650. $rootIndex = strpos($responseContent, $rootNodeName);
  651. $errorIndex = strpos($responseContent, $errorNodeName);
  652. if ($rootIndex > 0) {
  653. // 内部节点对象
  654. $rInnerObject = $respObject->$rootNodeName;
  655. } elseif ($errorIndex > 0) {
  656. $rInnerObject = $respObject->$errorNodeName;
  657. } else {
  658. return null;
  659. }
  660. // 存在属性则返回对应值
  661. if (isset($rInnerObject->sub_code)) {
  662. return $rInnerObject->sub_code;
  663. } else {
  664. return null;
  665. }
  666. } elseif ("xml" == $format) {
  667. // xml格式sub_code在同一层级
  668. return $respObject->sub_code;
  669. }
  670. }
  671. function parserJSONSignData($request, $responseContent, $responseJSON) {
  672. $signData = new SignData();
  673. $signData->sign = $this->parserJSONSign($responseJSON);
  674. $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
  675. return $signData;
  676. }
  677. function parserJSONSignSource($request, $responseContent) {
  678. $apiName = $request->getApiMethodName();
  679. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  680. $rootIndex = strpos($responseContent, $rootNodeName);
  681. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  682. if ($rootIndex > 0) {
  683. return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
  684. } else if ($errorIndex > 0) {
  685. return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  686. } else {
  687. return null;
  688. }
  689. }
  690. function parserJSONSource($responseContent, $nodeName, $nodeIndex) {
  691. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  692. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  693. // 签名前-逗号
  694. $signDataEndIndex = $signIndex - 1;
  695. $indexLen = $signDataEndIndex - $signDataStartIndex;
  696. if ($indexLen < 0) {
  697. return null;
  698. }
  699. return substr($responseContent, $signDataStartIndex, $indexLen);
  700. }
  701. function parserJSONSign($responseJSon) {
  702. return $responseJSon->sign;
  703. }
  704. function parserXMLSignData($request, $responseContent) {
  705. $signData = new SignData();
  706. $signData->sign = $this->parserXMLSign($responseContent);
  707. $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
  708. return $signData;
  709. }
  710. function parserXMLSignSource($request, $responseContent) {
  711. $apiName = $request->getApiMethodName();
  712. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  713. $rootIndex = strpos($responseContent, $rootNodeName);
  714. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  715. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  716. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  717. if ($rootIndex > 0) {
  718. return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
  719. } else if ($errorIndex > 0) {
  720. return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  721. } else {
  722. return null;
  723. }
  724. }
  725. function parserXMLSource($responseContent, $nodeName, $nodeIndex) {
  726. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  727. $signIndex = strpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
  728. // 签名前-逗号
  729. $signDataEndIndex = $signIndex - 1;
  730. $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
  731. if ($indexLen < 0) {
  732. return null;
  733. }
  734. return substr($responseContent, $signDataStartIndex, $indexLen);
  735. }
  736. function parserXMLSign($responseContent) {
  737. $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
  738. $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
  739. $indexOfSignNode = strpos($responseContent, $signNodeName);
  740. $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
  741. if ($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
  742. return null;
  743. }
  744. $nodeIndex = ($indexOfSignNode + strlen($signNodeName));
  745. $indexLen = $indexOfSignEndNode - $nodeIndex;
  746. if ($indexLen < 0) {
  747. return null;
  748. }
  749. // 签名
  750. return substr($responseContent, $nodeIndex, $indexLen);
  751. }
  752. /**
  753. * 验签
  754. * @param $request
  755. * @param $signData
  756. * @param $resp
  757. * @param $respObject
  758. * @throws Exception
  759. */
  760. public function checkResponseSign($request, $signData, $resp, $respObject) {
  761. if (!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
  762. if ($signData == null || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
  763. throw new Exception(" check sign Fail! The reason : signData is Empty");
  764. }
  765. // 获取结果sub_code
  766. $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
  767. if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign))) {
  768. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  769. if (!$checkResult) {
  770. if (strpos($signData->signSourceData, "\\/") > 0) {
  771. $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
  772. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  773. if (!$checkResult) {
  774. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  775. }
  776. } else {
  777. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  778. }
  779. }
  780. }
  781. }
  782. }
  783. private function setupCharsets($request) {
  784. if ($this->checkEmpty($this->postCharset)) {
  785. $this->postCharset = 'UTF-8';
  786. }
  787. $str = preg_match('/[\x80-\xff]/', $this->appId) ? $this->appId : print_r($request, true);
  788. $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == 'UTF-8' ? 'UTF-8' : 'GBK';
  789. }
  790. // 获取加密内容
  791. private function encryptJSONSignSource($request, $responseContent) {
  792. $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
  793. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  794. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  795. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  796. return $bodyIndexContent . $bizContent . $bodyEndContent;
  797. }
  798. private function parserEncryptJSONSignSource($request, $responseContent) {
  799. $apiName = $request->getApiMethodName();
  800. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  801. $rootIndex = strpos($responseContent, $rootNodeName);
  802. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  803. if ($rootIndex > 0) {
  804. return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
  805. } else if ($errorIndex > 0) {
  806. return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  807. } else {
  808. return null;
  809. }
  810. }
  811. private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex) {
  812. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  813. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  814. // 签名前-逗号
  815. $signDataEndIndex = $signIndex - 1;
  816. if ($signDataEndIndex < 0) {
  817. $signDataEndIndex = strlen($responseContent)-1 ;
  818. }
  819. $indexLen = $signDataEndIndex - $signDataStartIndex;
  820. $encContent = substr($responseContent, $signDataStartIndex+1, $indexLen-2);
  821. $encryptParseItem = new EncryptParseItem();
  822. $encryptParseItem->encryptContent = $encContent;
  823. $encryptParseItem->startIndex = $signDataStartIndex;
  824. $encryptParseItem->endIndex = $signDataEndIndex;
  825. return $encryptParseItem;
  826. }
  827. // 获取加密内容
  828. private function encryptXMLSignSource($request, $responseContent) {
  829. $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
  830. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  831. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  832. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  833. return $bodyIndexContent . $bizContent . $bodyEndContent;
  834. }
  835. private function parserEncryptXMLSignSource($request, $responseContent) {
  836. $apiName = $request->getApiMethodName();
  837. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  838. $rootIndex = strpos($responseContent, $rootNodeName);
  839. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  840. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  841. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  842. if ($rootIndex > 0) {
  843. return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
  844. } else if ($errorIndex > 0) {
  845. return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  846. } else {
  847. return null;
  848. }
  849. }
  850. private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex) {
  851. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  852. $xmlStartNode="<".$this->ENCRYPT_XML_NODE_NAME.">";
  853. $xmlEndNode="</".$this->ENCRYPT_XML_NODE_NAME.">";
  854. $indexOfXmlNode=strpos($responseContent,$xmlEndNode);
  855. if($indexOfXmlNode<0){
  856. $item = new EncryptParseItem();
  857. $item->encryptContent = null;
  858. $item->startIndex = 0;
  859. $item->endIndex = 0;
  860. return $item;
  861. }
  862. $startIndex=$signDataStartIndex+strlen($xmlStartNode);
  863. $bizContentLen=$indexOfXmlNode-$startIndex;
  864. $bizContent=substr($responseContent,$startIndex,$bizContentLen);
  865. $encryptParseItem = new EncryptParseItem();
  866. $encryptParseItem->encryptContent = $bizContent;
  867. $encryptParseItem->startIndex = $signDataStartIndex;
  868. $encryptParseItem->endIndex = $indexOfXmlNode+strlen($xmlEndNode);
  869. return $encryptParseItem;
  870. }
  871. function echoDebug($content) {
  872. if ($this->debugInfo) {
  873. echo "<br/>" . $content;
  874. }
  875. }
  876. }