AopCertClient.php 48 KB

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