AopCertClient.php 47 KB

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