AopCertClient.php 51 KB

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