AopCertClient.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. <?php
  2. namespace addons\Alitopay\common\jdk\alipay;
  3. use addons\Alitopay\common\jdk\alipay\AopEncrypt;
  4. use addons\Alitopay\common\jdk\alipay\EncryptParseItem;
  5. use addons\Alitopay\common\jdk\alipay\EncryptResponseData;
  6. use addons\Alitopay\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. if(!$this->checkEmpty($this->targetServiceUrl)){
  549. $sysParams["ws_service_url"] = $this->targetServiceUrl;
  550. }
  551. //获取业务参数
  552. $apiParams = $request->getApiParas();
  553. if (method_exists($request,"getNeedEncrypt") && $request->getNeedEncrypt()){
  554. $sysParams["encrypt_type"] = $this->encryptType;
  555. if ($this->checkEmpty($apiParams['biz_content'])) {
  556. throw new \Exception(" api request Fail! The reason : encrypt request is not supperted!");
  557. }
  558. if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
  559. throw new \Exception(" encryptType and encryptKey must not null! ");
  560. }
  561. if ("AES" != $this->encryptType) {
  562. throw new \Exception("加密类型只支持AES");
  563. }
  564. // 执行加密
  565. $enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
  566. $apiParams['biz_content'] = $enCryptContent;
  567. }
  568. //签名
  569. $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
  570. //系统参数放入GET请求串
  571. $requestUrl = $this->gatewayUrl . "?";
  572. foreach ($sysParams as $sysParamKey => $sysParamValue) {
  573. $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
  574. }
  575. $requestUrl = substr($requestUrl, 0, -1);
  576. //发起HTTP请求
  577. try {
  578. $resp = $this->curl($requestUrl, $apiParams);
  579. } catch (Exception $e) {
  580. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
  581. return false;
  582. }
  583. //解析AOP返回结果
  584. $respWellFormed = false;
  585. // 将返回结果转换本地文件编码
  586. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  587. $signData = null;
  588. if ("json" == strtolower($this->format)) {
  589. $respObject = json_decode($r);
  590. if (null !== $respObject) {
  591. $respWellFormed = true;
  592. $signData = $this->parserJSONSignData($request, $resp, $respObject);
  593. }
  594. } else if ("xml" == $this->format) {
  595. $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
  596. $respObject = @ simplexml_load_string($resp);
  597. if (false !== $respObject) {
  598. $respWellFormed = true;
  599. $signData = $this->parserXMLSignData($request, $resp);
  600. }
  601. libxml_disable_entity_loader($disableLibxmlEntityLoader);
  602. }
  603. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  604. if (false === $respWellFormed) {
  605. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
  606. return false;
  607. }
  608. // 验签
  609. $this->checkResponseSign($request, $signData, $resp, $respObject);
  610. // 解密
  611. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  612. if ("json" == strtolower($this->format)) {
  613. $resp = $this->encryptJSONSignSource($request, $resp);
  614. // 将返回结果转换本地文件编码
  615. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  616. $respObject = json_decode($r);
  617. }else{
  618. $resp = $this->encryptXMLSignSource($request, $resp);
  619. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  620. $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
  621. $respObject = @ simplexml_load_string($r);
  622. libxml_disable_entity_loader($disableLibxmlEntityLoader);
  623. }
  624. }
  625. return $respObject;
  626. }
  627. /**
  628. * 设置编码格式
  629. * @param $request
  630. */
  631. private function setupCharsets($request) {
  632. if ($this->checkEmpty($this->postCharset)) {
  633. $this->postCharset = 'UTF-8';
  634. }
  635. $str = preg_match('/[\x80-\xff]/', $this->appId) ? $this->appId : print_r($request, true);
  636. $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == 'UTF-8' ? 'UTF-8' : 'GBK';
  637. }
  638. /**
  639. * 校验$value是否非空
  640. * if not set ,return true;
  641. * if is null , return true;
  642. **/
  643. protected function checkEmpty($value) {
  644. if (!isset($value))
  645. return true;
  646. if ($value === null)
  647. return true;
  648. if (trim($value) === "")
  649. return true;
  650. return false;
  651. }
  652. /**
  653. * 加签
  654. * @param $params
  655. * @param string $signType
  656. * @return mixed
  657. */
  658. public function generateSign($params, $signType = "RSA") {
  659. return $this->sign($this->getSignContent($params), $signType);
  660. }
  661. public function rsaSign($params, $signType = "RSA") {
  662. return $this->sign($this->getSignContent($params), $signType);
  663. }
  664. protected function sign($data, $signType = "RSA") {
  665. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  666. $priKey=$this->rsaPrivateKey;
  667. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  668. wordwrap($priKey, 64, "\n", true) .
  669. "\n-----END RSA PRIVATE KEY-----";
  670. }else {
  671. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  672. $res = openssl_get_privatekey($priKey);
  673. }
  674. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  675. if ("RSA2" == $signType) {
  676. openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
  677. } else {
  678. openssl_sign($data, $sign, $res);
  679. }
  680. if(!$this->checkEmpty($this->rsaPrivateKeyFilePath)){
  681. openssl_free_key($res);
  682. }
  683. $sign = base64_encode($sign);
  684. return $sign;
  685. }
  686. public function getSignContent($params) {
  687. ksort($params);
  688. $stringToBeSigned = "";
  689. $i = 0;
  690. foreach ($params as $k => $v) {
  691. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  692. // 转换成目标字符集
  693. $v = $this->characet($v, $this->postCharset);
  694. if ($i == 0) {
  695. $stringToBeSigned .= "$k" . "=" . "$v";
  696. } else {
  697. $stringToBeSigned .= "&" . "$k" . "=" . "$v";
  698. }
  699. $i++;
  700. }
  701. }
  702. unset ($k, $v);
  703. return $stringToBeSigned;
  704. }
  705. /**
  706. * RSA单独签名方法,未做字符串处理,字符串处理见getSignContent()
  707. * @param $data 待签名字符串
  708. * @param $privatekey 商户私钥,根据keyfromfile来判断是读取字符串还是读取文件,false:填写私钥字符串去回车和空格 true:填写私钥文件路径
  709. * @param $signType 签名方式,RSA:SHA1 RSA2:SHA256
  710. * @param $keyfromfile 私钥获取方式,读取字符串还是读文件
  711. * @return string
  712. */
  713. public function alonersaSign($data,$privatekey,$signType = "RSA",$keyfromfile=false) {
  714. if(!$keyfromfile){
  715. $priKey=$privatekey;
  716. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  717. wordwrap($priKey, 64, "\n", true) .
  718. "\n-----END RSA PRIVATE KEY-----";
  719. }
  720. else{
  721. $priKey = file_get_contents($privatekey);
  722. $res = openssl_get_privatekey($priKey);
  723. }
  724. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  725. if ("RSA2" == $signType) {
  726. openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
  727. } else {
  728. openssl_sign($data, $sign, $res);
  729. }
  730. if($keyfromfile){
  731. openssl_free_key($res);
  732. }
  733. $sign = base64_encode($sign);
  734. return $sign;
  735. }
  736. /**
  737. * 转换字符集编码
  738. * @param $data
  739. * @param $targetCharset
  740. * @return string
  741. */
  742. function characet($data, $targetCharset) {
  743. if (!empty($data)) {
  744. $fileType = $this->fileCharset;
  745. if (strcasecmp($fileType, $targetCharset) != 0) {
  746. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  747. }
  748. }
  749. return $data;
  750. }
  751. /**
  752. * 发送curl请求
  753. * @param $url
  754. * @param null $postFields
  755. * @return bool|string
  756. * @throws Exception
  757. */
  758. protected function curl($url, $postFields = null) {
  759. $ch = curl_init();
  760. curl_setopt($ch, CURLOPT_URL, $url);
  761. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  762. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  763. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  764. $postBodyString = "";
  765. $encodeArray = Array();
  766. $postMultipart = false;
  767. if (is_array($postFields) && 0 < count($postFields)) {
  768. foreach ($postFields as $k => $v) {
  769. if ("@" != substr($v, 0, 1)) //判断是不是文件上传
  770. {
  771. $postBodyString .= "$k=" . urlencode($this->characet($v, $this->postCharset)) . "&";
  772. $encodeArray[$k] = $this->characet($v, $this->postCharset);
  773. } else //文件上传用multipart/form-data,否则用www-form-urlencoded
  774. {
  775. $postMultipart = true;
  776. $encodeArray[$k] = new \CURLFile(substr($v, 1));
  777. }
  778. }
  779. unset ($k, $v);
  780. curl_setopt($ch, CURLOPT_POST, true);
  781. if ($postMultipart) {
  782. curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray);
  783. } else {
  784. curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
  785. }
  786. }
  787. if (!$postMultipart) {
  788. $headers = array('content-type: application/x-www-form-urlencoded;charset=' . $this->postCharset);
  789. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  790. }
  791. $reponse = curl_exec($ch);
  792. if (curl_errno($ch)) {
  793. throw new \Exception(curl_error($ch), 0);
  794. } else {
  795. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  796. if (200 !== $httpStatusCode) {
  797. throw new \Exception($reponse, $httpStatusCode);
  798. }
  799. }
  800. curl_close($ch);
  801. return $reponse;
  802. }
  803. protected function getMillisecond() {
  804. list($s1, $s2) = explode(' ', microtime());
  805. return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
  806. }
  807. /**
  808. * 打印日志信息
  809. * @param $apiName
  810. * @param $requestUrl
  811. * @param $errorCode
  812. * @param $responseTxt
  813. */
  814. protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt) {
  815. $logData = array(
  816. date("Y-m-d H:i:s"),
  817. $apiName,
  818. $this->appId,
  819. PHP_OS,
  820. $this->alipaySdkVersion,
  821. $requestUrl,
  822. $errorCode,
  823. str_replace("\n", "", $responseTxt)
  824. );
  825. echo json_encode($logData);
  826. }
  827. /**
  828. * Json格式签名内容
  829. * @param $request
  830. * @param $responseContent
  831. * @param $responseJSON
  832. * @return SignData
  833. */
  834. function parserJSONSignData($request, $responseContent, $responseJSON) {
  835. $signData = new SignData();
  836. $signData->sign = $this->parserJSONSign($responseJSON);
  837. $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
  838. return $signData;
  839. }
  840. function parserJSONSign($responseJSon) {
  841. return $responseJSon->sign;
  842. }
  843. function parserJSONSignSource($request, $responseContent) {
  844. $apiName = $request->getApiMethodName();
  845. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  846. $rootIndex = strpos($responseContent, $rootNodeName);
  847. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  848. if ($rootIndex > 0) {
  849. return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
  850. } else if ($errorIndex > 0) {
  851. return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  852. } else {
  853. return null;
  854. }
  855. }
  856. function parserJSONSource($responseContent, $nodeName, $nodeIndex) {
  857. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  858. if(strrpos($responseContent, $this->ALIPAY_CERT_SN)){
  859. $signIndex = strrpos($responseContent, "\"" . $this->ALIPAY_CERT_SN . "\"");
  860. }else{
  861. $signIndex = strrpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  862. }
  863. // 签名前-逗号
  864. $signDataEndIndex = $signIndex - 1;
  865. $indexLen = $signDataEndIndex - $signDataStartIndex;
  866. if ($indexLen < 0) {
  867. return null;
  868. }
  869. return substr($responseContent, $signDataStartIndex, $indexLen);
  870. }
  871. /**
  872. * XML格式签名内容
  873. * @param $request
  874. * @param $responseContent
  875. * @return SignData
  876. */
  877. function parserXMLSignData($request, $responseContent) {
  878. $signData = new SignData();
  879. $signData->sign = $this->parserXMLSign($responseContent);
  880. $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
  881. return $signData;
  882. }
  883. function parserXMLSign($responseContent) {
  884. if(strrpos($responseContent, $this->ALIPAY_CERT_SN)){
  885. $signNodeName = "<" . $this->ALIPAY_CERT_SN . ">";
  886. $signEndNodeName = "</" . $this->ALIPAY_CERT_SN . ">";
  887. }else{
  888. $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
  889. $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
  890. }
  891. $indexOfSignNode = strpos($responseContent, $signNodeName);
  892. $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
  893. if ($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
  894. return null;
  895. }
  896. $nodeIndex = ($indexOfSignNode + strlen($signNodeName));
  897. $indexLen = $indexOfSignEndNode - $nodeIndex;
  898. if ($indexLen < 0) {
  899. return null;
  900. }
  901. // 签名
  902. return substr($responseContent, $nodeIndex, $indexLen);
  903. }
  904. function parserXMLSignSource($request, $responseContent) {
  905. $apiName = $request->getApiMethodName();
  906. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  907. $rootIndex = strpos($responseContent, $rootNodeName);
  908. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  909. if ($rootIndex > 0) {
  910. return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
  911. } else if ($errorIndex > 0) {
  912. return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  913. } else {
  914. return null;
  915. }
  916. }
  917. function parserXMLSource($responseContent, $nodeName, $nodeIndex) {
  918. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  919. if(strrpos($responseContent, $this->ALIPAY_CERT_SN)){
  920. $signIndex = strrpos($responseContent, "<" . $this->ALIPAY_CERT_SN . ">");
  921. }else{
  922. $signIndex = strrpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
  923. }
  924. // 签名前-逗号
  925. $signDataEndIndex = $signIndex - 1;
  926. $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
  927. if ($indexLen < 0) {
  928. return null;
  929. }
  930. return substr($responseContent, $signDataStartIndex, $indexLen);
  931. }
  932. /**
  933. * 验签
  934. * @param $request
  935. * @param $signData
  936. * @param $resp
  937. * @param $respObject
  938. * @throws Exception
  939. */
  940. public function checkResponseSign($request, $signData, $resp, $respObject) {
  941. if (!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
  942. if ($signData == null || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
  943. throw new \Exception(" check sign Fail! The reason : signData is Empty");
  944. }
  945. // 获取结果sub_code
  946. $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
  947. if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign))) {
  948. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  949. if (!$checkResult) {
  950. //请求网关下载新的支付宝公钥证书
  951. if(!$respObject->alipay_cert_sn && ($request->getApiMethodName()=="alipay.open.app.alipaycert.download")){
  952. throw new \Exception(" check sign Fail! The reason : alipay_cert_sn is Empty");
  953. }
  954. //组装系统参数
  955. $sysParams["app_id"] = $this->appId;
  956. $sysParams["format"] = $this->format;
  957. $sysParams["sign_type"] = $this->signType;
  958. $sysParams["method"] = "alipay.open.app.alipaycert.download";
  959. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  960. $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
  961. $sysParams["terminal_type"] = $request->getTerminalType();
  962. $sysParams["terminal_info"] = $request->getTerminalInfo();
  963. $sysParams["prod_code"] = $request->getProdCode();
  964. $sysParams["notify_url"] = $request->getNotifyUrl();
  965. $sysParams["charset"] = $this->postCharset;
  966. $sysParams["app_cert_sn"] = $this->appCertSN;
  967. $sysParams["alipay_root_cert_sn"] = $this->alipayRootCertSN;
  968. //获取业务参数
  969. $apiParas = array();
  970. $apiParas["biz_content"] = "{\"alipay_cert_sn\":\"".$respObject->alipay_cert_sn."\"}";
  971. $apiParams = $apiParas;
  972. //签名
  973. $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
  974. //系统参数放入GET请求串
  975. $requestUrl = $this->gatewayUrl . "?";
  976. foreach ($sysParams as $sysParamKey => $sysParamValue) {
  977. $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
  978. }
  979. $requestUrl = substr($requestUrl, 0, -1);
  980. //发起HTTP请求
  981. try {
  982. $resp = $this->curl($requestUrl, $apiParams);
  983. } catch (Exception $e) {
  984. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
  985. return false;
  986. }
  987. // 将返回结果转换本地文件编码
  988. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  989. $respObject = json_decode($r);
  990. $resultCode = $respObject->alipay_open_app_alipaycert_download_response->code;
  991. $certContent = $respObject->alipay_open_app_alipaycert_download_response->alipay_cert_content;
  992. if (!empty($resultCode) && $resultCode == 10000 && !empty($certContent)) {
  993. $cert = base64_decode($certContent);
  994. $certCheck = true;
  995. if(!empty($this->alipayRootCertContent) && $this->isCheckAlipayPublicCert){
  996. $certCheck = isTrusted($cert,$this->alipayRootCertContent);
  997. }
  998. if($certCheck){
  999. $pkey = openssl_pkey_get_public($cert);
  1000. $keyData = openssl_pkey_get_details($pkey);
  1001. $public_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $keyData['key']);
  1002. $public_key = trim(str_replace('-----END PUBLIC KEY-----', '', $public_key));
  1003. $this->alipayrsaPublicKey = $public_key;
  1004. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayrsaPublicKey, $this->signType);
  1005. }else{
  1006. //如果下载下来的支付宝公钥证书使用根证书检查失败直接抛异常
  1007. throw new \Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  1008. }
  1009. }
  1010. if(!$checkResult){
  1011. if (strpos($signData->signSourceData, "\\/") > 0) {
  1012. $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
  1013. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  1014. if (!$checkResult) {
  1015. throw new \Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  1016. }
  1017. } else {
  1018. throw new \Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }
  1024. }
  1025. function parserResponseSubCode($request, $responseContent, $respObject, $format) {
  1026. if ("json" == strtolower($format)) {
  1027. $apiName = $request->getApiMethodName();
  1028. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  1029. $errorNodeName = $this->ERROR_RESPONSE;
  1030. $rootIndex = strpos($responseContent, $rootNodeName);
  1031. $errorIndex = strpos($responseContent, $errorNodeName);
  1032. if ($rootIndex > 0) {
  1033. // 内部节点对象
  1034. $rInnerObject = $respObject->$rootNodeName;
  1035. } elseif ($errorIndex > 0) {
  1036. $rInnerObject = $respObject->$errorNodeName;
  1037. } else {
  1038. return null;
  1039. }
  1040. // 存在属性则返回对应值
  1041. if (isset($rInnerObject->sub_code)) {
  1042. return $rInnerObject->sub_code;
  1043. } else {
  1044. return null;
  1045. }
  1046. } elseif ("xml" == $format) {
  1047. // xml格式sub_code在同一层级
  1048. return $respObject->sub_code;
  1049. }
  1050. }
  1051. function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA') {
  1052. if($this->checkEmpty($this->alipayPublicKey)){
  1053. $pubKey= $this->alipayrsaPublicKey;
  1054. $res = "-----BEGIN PUBLIC KEY-----\n" .
  1055. wordwrap($pubKey, 64, "\n", true) .
  1056. "\n-----END PUBLIC KEY-----";
  1057. }else {
  1058. //读取公钥文件
  1059. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  1060. //转换为openssl格式密钥
  1061. $res = openssl_get_publickey($pubKey);
  1062. }
  1063. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  1064. //调用openssl内置方法验签,返回bool值
  1065. $result = FALSE;
  1066. if ("RSA2" == $signType) {
  1067. $result = (openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256)===1);
  1068. } else {
  1069. $result = (openssl_verify($data, base64_decode($sign), $res)===1);
  1070. }
  1071. if(!$this->checkEmpty($this->alipayPublicKey)) {
  1072. //释放资源
  1073. openssl_free_key($res);
  1074. }
  1075. return $result;
  1076. }
  1077. // 获取加密内容
  1078. private function encryptJSONSignSource($request, $responseContent) {
  1079. $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
  1080. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  1081. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  1082. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  1083. return $bodyIndexContent . $bizContent . $bodyEndContent;
  1084. }
  1085. private function parserEncryptJSONSignSource($request, $responseContent) {
  1086. $apiName = $request->getApiMethodName();
  1087. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  1088. $rootIndex = strpos($responseContent, $rootNodeName);
  1089. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  1090. if ($rootIndex > 0) {
  1091. return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
  1092. } else if ($errorIndex > 0) {
  1093. return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  1094. } else {
  1095. return null;
  1096. }
  1097. }
  1098. private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex) {
  1099. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  1100. if(strrpos($responseContent, $this->ALIPAY_CERT_SN)){
  1101. $signIndex = strpos($responseContent, "\"" . $this->ALIPAY_CERT_SN . "\"");
  1102. }else{
  1103. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  1104. }
  1105. // 签名前-逗号
  1106. $signDataEndIndex = $signIndex - 1;
  1107. if ($signDataEndIndex < 0) {
  1108. $signDataEndIndex = strlen($responseContent)-1 ;
  1109. }
  1110. $indexLen = $signDataEndIndex - $signDataStartIndex;
  1111. $encContent = substr($responseContent, $signDataStartIndex+1, $indexLen-2);
  1112. $encryptParseItem = new EncryptParseItem();
  1113. $encryptParseItem->encryptContent = $encContent;
  1114. $encryptParseItem->startIndex = $signDataStartIndex;
  1115. $encryptParseItem->endIndex = $signDataEndIndex;
  1116. return $encryptParseItem;
  1117. }
  1118. // 获取加密内容
  1119. private function encryptXMLSignSource($request, $responseContent) {
  1120. $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
  1121. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  1122. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  1123. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  1124. return $bodyIndexContent . $bizContent . $bodyEndContent;
  1125. }
  1126. private function parserEncryptXMLSignSource($request, $responseContent) {
  1127. $apiName = $request->getApiMethodName();
  1128. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  1129. $rootIndex = strpos($responseContent, $rootNodeName);
  1130. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  1131. if ($rootIndex > 0) {
  1132. return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
  1133. } else if ($errorIndex > 0) {
  1134. return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  1135. } else {
  1136. return null;
  1137. }
  1138. }
  1139. private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex) {
  1140. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  1141. $xmlStartNode="<".$this->ENCRYPT_XML_NODE_NAME.">";
  1142. $xmlEndNode="</".$this->ENCRYPT_XML_NODE_NAME.">";
  1143. $indexOfXmlNode=strpos($responseContent,$xmlEndNode);
  1144. if($indexOfXmlNode<0){
  1145. $item = new EncryptParseItem();
  1146. $item->encryptContent = null;
  1147. $item->startIndex = 0;
  1148. $item->endIndex = 0;
  1149. return $item;
  1150. }
  1151. $startIndex=$signDataStartIndex+strlen($xmlStartNode);
  1152. $bizContentLen=$indexOfXmlNode-$startIndex;
  1153. $bizContent=substr($responseContent,$startIndex,$bizContentLen);
  1154. $encryptParseItem = new EncryptParseItem();
  1155. $encryptParseItem->encryptContent = $bizContent;
  1156. $encryptParseItem->startIndex = $signDataStartIndex;
  1157. $encryptParseItem->endIndex = $indexOfXmlNode+strlen($xmlEndNode);
  1158. return $encryptParseItem;
  1159. }
  1160. function echoDebug($content) {
  1161. if ($this->debugInfo) {
  1162. echo "<br/>" . $content;
  1163. }
  1164. }
  1165. }