AopCertClient.php 49 KB

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