AopCertClient.php 49 KB

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