AopCertClient.php 48 KB

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