AopCertClient.php 51 KB

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