AopClient.php 30 KB

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