AopCertClient.php 48 KB

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