新版订单消耗系统

AopCertClient.php 46KB

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