AopCertClient.php 51 KB

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