AopCertClient.php 48 KB

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