No Description

AopClient.php 34KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. <?php
  2. require_once 'AopEncrypt.php';
  3. class AopClient {
  4. //应用ID
  5. public $appId;
  6. //私钥文件路径
  7. public $rsaPrivateKeyFilePath;
  8. //私钥值
  9. public $rsaPrivateKey;
  10. //网关
  11. public $gatewayUrl = "https://openapi.alipay.com/gateway.do";
  12. //返回数据格式
  13. public $format = "json";
  14. //api版本
  15. public $apiVersion = "1.0";
  16. // 表单提交字符集编码
  17. public $postCharset = "UTF-8";
  18. //使用文件读取文件格式,请只传递该值
  19. public $alipayPublicKey = null;
  20. //使用读取字符串格式,请只传递该值
  21. public $alipayrsaPublicKey;
  22. public $debugInfo = false;
  23. private $fileCharset = "UTF-8";
  24. private $RESPONSE_SUFFIX = "_response";
  25. private $ERROR_RESPONSE = "error_response";
  26. private $SIGN_NODE_NAME = "sign";
  27. //加密XML节点名称
  28. private $ENCRYPT_XML_NODE_NAME = "response_encrypted";
  29. private $needEncrypt = false;
  30. //签名类型
  31. public $signType = "RSA";
  32. //加密密钥和类型
  33. public $encryptKey;
  34. public $encryptType = "AES";
  35. protected $alipaySdkVersion = "alipay-sdk-php-20180705";
  36. public function generateSign($params, $signType = "RSA") {
  37. return $this->sign($this->getSignContent($params), $signType);
  38. }
  39. public function rsaSign($params, $signType = "RSA") {
  40. return $this->sign($this->getSignContent($params), $signType);
  41. }
  42. public function getSignContent($params) {
  43. ksort($params);
  44. $stringToBeSigned = "";
  45. $i = 0;
  46. foreach ($params as $k => $v) {
  47. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  48. // 转换成目标字符集
  49. $v = $this->characet($v, $this->postCharset);
  50. if ($i == 0) {
  51. $stringToBeSigned .= "$k" . "=" . "$v";
  52. } else {
  53. $stringToBeSigned .= "&" . "$k" . "=" . "$v";
  54. }
  55. $i++;
  56. }
  57. }
  58. unset ($k, $v);
  59. return $stringToBeSigned;
  60. }
  61. //此方法对value做urlencode
  62. public function getSignContentUrlencode($params) {
  63. ksort($params);
  64. $stringToBeSigned = "";
  65. $i = 0;
  66. foreach ($params as $k => $v) {
  67. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  68. // 转换成目标字符集
  69. $v = $this->characet($v, $this->postCharset);
  70. if ($i == 0) {
  71. $stringToBeSigned .= "$k" . "=" . urlencode($v);
  72. } else {
  73. $stringToBeSigned .= "&" . "$k" . "=" . urlencode($v);
  74. }
  75. $i++;
  76. }
  77. }
  78. unset ($k, $v);
  79. return $stringToBeSigned;
  80. }
  81. protected function sign($data, $signType = "RSA") {
  82. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  83. $priKey=$this->rsaPrivateKey;
  84. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  85. wordwrap($priKey, 64, "\n", true) .
  86. "\n-----END RSA PRIVATE KEY-----";
  87. }else {
  88. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  89. $res = openssl_get_privatekey($priKey);
  90. }
  91. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  92. if ("RSA2" == $signType) {
  93. openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
  94. } else {
  95. openssl_sign($data, $sign, $res);
  96. }
  97. if(!$this->checkEmpty($this->rsaPrivateKeyFilePath)){
  98. openssl_free_key($res);
  99. }
  100. $sign = base64_encode($sign);
  101. return $sign;
  102. }
  103. /**
  104. * RSA单独签名方法,未做字符串处理,字符串处理见getSignContent()
  105. * @param $data 待签名字符串
  106. * @param $privatekey 商户私钥,根据keyfromfile来判断是读取字符串还是读取文件,false:填写私钥字符串去回车和空格 true:填写私钥文件路径
  107. * @param $signType 签名方式,RSA:SHA1 RSA2:SHA256
  108. * @param $keyfromfile 私钥获取方式,读取字符串还是读文件
  109. * @return string
  110. * @author mengyu.wh
  111. */
  112. public function alonersaSign($data,$privatekey,$signType = "RSA",$keyfromfile=false) {
  113. if(!$keyfromfile){
  114. $priKey=$privatekey;
  115. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  116. wordwrap($priKey, 64, "\n", true) .
  117. "\n-----END RSA PRIVATE KEY-----";
  118. }
  119. else{
  120. $priKey = file_get_contents($privatekey);
  121. $res = openssl_get_privatekey($priKey);
  122. }
  123. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  124. if ("RSA2" == $signType) {
  125. openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
  126. } else {
  127. openssl_sign($data, $sign, $res);
  128. }
  129. if($keyfromfile){
  130. openssl_free_key($res);
  131. }
  132. $sign = base64_encode($sign);
  133. return $sign;
  134. }
  135. protected function curl($url, $postFields = null) {
  136. $ch = curl_init();
  137. curl_setopt($ch, CURLOPT_URL, $url);
  138. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  139. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  140. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  141. $postBodyString = "";
  142. $encodeArray = Array();
  143. $postMultipart = false;
  144. if (is_array($postFields) && 0 < count($postFields)) {
  145. foreach ($postFields as $k => $v) {
  146. if ("@" != substr($v, 0, 1)) //判断是不是文件上传
  147. {
  148. $postBodyString .= "$k=" . urlencode($this->characet($v, $this->postCharset)) . "&";
  149. $encodeArray[$k] = $this->characet($v, $this->postCharset);
  150. } else //文件上传用multipart/form-data,否则用www-form-urlencoded
  151. {
  152. $postMultipart = true;
  153. $encodeArray[$k] = new \CURLFile(substr($v, 1));
  154. }
  155. }
  156. unset ($k, $v);
  157. curl_setopt($ch, CURLOPT_POST, true);
  158. if ($postMultipart) {
  159. curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray);
  160. } else {
  161. curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
  162. }
  163. }
  164. if ($postMultipart) {
  165. $headers = array('content-type: multipart/form-data;charset=' . $this->postCharset . ';boundary=' . $this->getMillisecond());
  166. } else {
  167. $headers = array('content-type: application/x-www-form-urlencoded;charset=' . $this->postCharset);
  168. }
  169. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  170. $reponse = curl_exec($ch);
  171. if (curl_errno($ch)) {
  172. throw new Exception(curl_error($ch), 0);
  173. } else {
  174. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  175. if (200 !== $httpStatusCode) {
  176. throw new Exception($reponse, $httpStatusCode);
  177. }
  178. }
  179. curl_close($ch);
  180. return $reponse;
  181. }
  182. protected function getMillisecond() {
  183. list($s1, $s2) = explode(' ', microtime());
  184. return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
  185. }
  186. protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt) {
  187. $localIp = isset ($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : "CLI";
  188. $logger = new LtLogger;
  189. $logger->conf["log_file"] = rtrim(AOP_SDK_WORK_DIR, '\\/') . '/' . "logs/aop_comm_err_" . $this->appId . "_" . date("Y-m-d") . ".log";
  190. $logger->conf["separator"] = "^_^";
  191. $logData = array(
  192. date("Y-m-d H:i:s"),
  193. $apiName,
  194. $this->appId,
  195. $localIp,
  196. PHP_OS,
  197. $this->alipaySdkVersion,
  198. $requestUrl,
  199. $errorCode,
  200. str_replace("\n", "", $responseTxt)
  201. );
  202. $logger->log($logData);
  203. }
  204. /**
  205. * 生成用于调用收银台SDK的字符串
  206. * @param $request SDK接口的请求参数对象
  207. * @return string
  208. * @author guofa.tgf
  209. */
  210. public function sdkExecute($request) {
  211. $this->setupCharsets($request);
  212. $params['app_id'] = $this->appId;
  213. $params['method'] = $request->getApiMethodName();
  214. $params['format'] = $this->format;
  215. $params['sign_type'] = $this->signType;
  216. $params['timestamp'] = date("Y-m-d H:i:s");
  217. $params['alipay_sdk'] = $this->alipaySdkVersion;
  218. $params['charset'] = $this->postCharset;
  219. $version = $request->getApiVersion();
  220. $params['version'] = $this->checkEmpty($version) ? $this->apiVersion : $version;
  221. if ($notify_url = $request->getNotifyUrl()) {
  222. $params['notify_url'] = $notify_url;
  223. }
  224. $dict = $request->getApiParas();
  225. $params['biz_content'] = $dict['biz_content'];
  226. ksort($params);
  227. $params['sign'] = $this->generateSign($params, $this->signType);
  228. foreach ($params as &$value) {
  229. $value = $this->characet($value, $params['charset']);
  230. }
  231. return http_build_query($params);
  232. }
  233. /*
  234. 页面提交执行方法
  235. @param:跳转类接口的request; $httpmethod 提交方式。两个值可选:post、get
  236. @return:构建好的、签名后的最终跳转URL(GET)或String形式的form(POST)
  237. auther:笙默
  238. */
  239. public function pageExecute($request,$httpmethod = "POST") {
  240. $this->setupCharsets($request);
  241. if (strcasecmp($this->fileCharset, $this->postCharset)) {
  242. // writeLog("本地文件字符集编码与表单提交编码不一致,请务必设置成一样,属性名分别为postCharset!");
  243. throw new Exception("文件编码:[" . $this->fileCharset . "] 与表单提交编码:[" . $this->postCharset . "]两者不一致!");
  244. }
  245. $iv=null;
  246. if(!$this->checkEmpty($request->getApiVersion())){
  247. $iv=$request->getApiVersion();
  248. }else{
  249. $iv=$this->apiVersion;
  250. }
  251. //组装系统参数
  252. $sysParams["app_id"] = $this->appId;
  253. $sysParams["version"] = $iv;
  254. $sysParams["format"] = $this->format;
  255. $sysParams["sign_type"] = $this->signType;
  256. $sysParams["method"] = $request->getApiMethodName();
  257. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  258. $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
  259. $sysParams["terminal_type"] = $request->getTerminalType();
  260. $sysParams["terminal_info"] = $request->getTerminalInfo();
  261. $sysParams["prod_code"] = $request->getProdCode();
  262. $sysParams["notify_url"] = $request->getNotifyUrl();
  263. $sysParams["return_url"] = $request->getReturnUrl();
  264. $sysParams["charset"] = $this->postCharset;
  265. //获取业务参数
  266. $apiParams = $request->getApiParas();
  267. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  268. $sysParams["encrypt_type"] = $this->encryptType;
  269. if ($this->checkEmpty($apiParams['biz_content'])) {
  270. throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
  271. }
  272. if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
  273. throw new Exception(" encryptType and encryptKey must not null! ");
  274. }
  275. if ("AES" != $this->encryptType) {
  276. throw new Exception("加密类型只支持AES");
  277. }
  278. // 执行加密
  279. $enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
  280. $apiParams['biz_content'] = $enCryptContent;
  281. }
  282. //print_r($apiParams);
  283. $totalParams = array_merge($apiParams, $sysParams);
  284. //待签名字符串
  285. $preSignStr = $this->getSignContent($totalParams);
  286. //签名
  287. $totalParams["sign"] = $this->generateSign($totalParams, $this->signType);
  288. if ("GET" == strtoupper($httpmethod)) {
  289. //value做urlencode
  290. $preString=$this->getSignContentUrlencode($totalParams);
  291. //拼接GET请求串
  292. $requestUrl = $this->gatewayUrl."?".$preString;
  293. return $requestUrl;
  294. } else {
  295. //拼接表单字符串
  296. return $this->buildRequestForm($totalParams);
  297. }
  298. }
  299. /**
  300. * 建立请求,以表单HTML形式构造(默认)
  301. * @param $para_temp 请求参数数组
  302. * @return 提交表单HTML文本
  303. */
  304. protected function buildRequestForm($para_temp) {
  305. $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->gatewayUrl."?charset=".trim($this->postCharset)."' method='POST'>";
  306. while (list ($key, $val) = each ($para_temp)) {
  307. if (false === $this->checkEmpty($val)) {
  308. //$val = $this->characet($val, $this->postCharset);
  309. $val = str_replace("'","&apos;",$val);
  310. //$val = str_replace("\"","&quot;",$val);
  311. $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
  312. }
  313. }
  314. //submit按钮控件请不要含有name属性
  315. $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
  316. $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
  317. return $sHtml;
  318. }
  319. public function execute($request, $authToken = null, $appInfoAuthtoken = null) {
  320. $this->setupCharsets($request);
  321. // // 如果两者编码不一致,会出现签名验签或者乱码
  322. if (strcasecmp($this->fileCharset, $this->postCharset)) {
  323. // writeLog("本地文件字符集编码与表单提交编码不一致,请务必设置成一样,属性名分别为postCharset!");
  324. throw new Exception("文件编码:[" . $this->fileCharset . "] 与表单提交编码:[" . $this->postCharset . "]两者不一致!");
  325. }
  326. $iv = null;
  327. if (!$this->checkEmpty($request->getApiVersion())) {
  328. $iv = $request->getApiVersion();
  329. } else {
  330. $iv = $this->apiVersion;
  331. }
  332. //组装系统参数
  333. $sysParams["app_id"] = $this->appId;
  334. $sysParams["version"] = $iv;
  335. $sysParams["format"] = $this->format;
  336. $sysParams["sign_type"] = $this->signType;
  337. $sysParams["method"] = $request->getApiMethodName();
  338. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  339. $sysParams["auth_token"] = $authToken;
  340. $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
  341. $sysParams["terminal_type"] = $request->getTerminalType();
  342. $sysParams["terminal_info"] = $request->getTerminalInfo();
  343. $sysParams["prod_code"] = $request->getProdCode();
  344. $sysParams["notify_url"] = $request->getNotifyUrl();
  345. $sysParams["charset"] = $this->postCharset;
  346. $sysParams["app_auth_token"] = $appInfoAuthtoken;
  347. //获取业务参数
  348. $apiParams = $request->getApiParas();
  349. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  350. $sysParams["encrypt_type"] = $this->encryptType;
  351. if ($this->checkEmpty($apiParams['biz_content'])) {
  352. throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
  353. }
  354. if ($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
  355. throw new Exception(" encryptType and encryptKey must not null! ");
  356. }
  357. if ("AES" != $this->encryptType) {
  358. throw new Exception("加密类型只支持AES");
  359. }
  360. // 执行加密
  361. $enCryptContent = encrypt($apiParams['biz_content'], $this->encryptKey);
  362. $apiParams['biz_content'] = $enCryptContent;
  363. }
  364. //签名
  365. $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
  366. //系统参数放入GET请求串
  367. $requestUrl = $this->gatewayUrl . "?";
  368. foreach ($sysParams as $sysParamKey => $sysParamValue) {
  369. $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
  370. }
  371. $requestUrl = substr($requestUrl, 0, -1);
  372. //发起HTTP请求
  373. try {
  374. $resp = $this->curl($requestUrl, $apiParams);
  375. } catch (Exception $e) {
  376. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
  377. return false;
  378. }
  379. //解析AOP返回结果
  380. $respWellFormed = false;
  381. // 将返回结果转换本地文件编码
  382. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  383. $signData = null;
  384. if ("json" == $this->format) {
  385. $respObject = json_decode($r);
  386. if (null !== $respObject) {
  387. $respWellFormed = true;
  388. $signData = $this->parserJSONSignData($request, $resp, $respObject);
  389. }
  390. } else if ("xml" == $this->format) {
  391. $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
  392. $respObject = @ simplexml_load_string($resp);
  393. if (false !== $respObject) {
  394. $respWellFormed = true;
  395. $signData = $this->parserXMLSignData($request, $resp);
  396. }
  397. libxml_disable_entity_loader($disableLibxmlEntityLoader);
  398. }
  399. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  400. if (false === $respWellFormed) {
  401. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
  402. return false;
  403. }
  404. // 验签
  405. $this->checkResponseSign($request, $signData, $resp, $respObject);
  406. // 解密
  407. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  408. if ("json" == $this->format) {
  409. $resp = $this->encryptJSONSignSource($request, $resp);
  410. // 将返回结果转换本地文件编码
  411. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  412. $respObject = json_decode($r);
  413. }else{
  414. $resp = $this->encryptXMLSignSource($request, $resp);
  415. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  416. $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
  417. $respObject = @ simplexml_load_string($r);
  418. libxml_disable_entity_loader($disableLibxmlEntityLoader);
  419. }
  420. }
  421. return $respObject;
  422. }
  423. /**
  424. * 转换字符集编码
  425. * @param $data
  426. * @param $targetCharset
  427. * @return string
  428. */
  429. function characet($data, $targetCharset) {
  430. if (!empty($data)) {
  431. $fileType = $this->fileCharset;
  432. if (strcasecmp($fileType, $targetCharset) != 0) {
  433. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  434. // $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
  435. }
  436. }
  437. return $data;
  438. }
  439. public function exec($paramsArray) {
  440. if (!isset ($paramsArray["method"])) {
  441. trigger_error("No api name passed");
  442. }
  443. $inflector = new LtInflector;
  444. $inflector->conf["separator"] = ".";
  445. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  446. if (!class_exists($requestClassName)) {
  447. trigger_error("No such api: " . $paramsArray["method"]);
  448. }
  449. $session = isset ($paramsArray["session"]) ? $paramsArray["session"] : null;
  450. $req = new $requestClassName;
  451. foreach ($paramsArray as $paraKey => $paraValue) {
  452. $inflector->conf["separator"] = "_";
  453. $setterMethodName = $inflector->camelize($paraKey);
  454. $inflector->conf["separator"] = ".";
  455. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  456. if (method_exists($req, $setterMethodName)) {
  457. $req->$setterMethodName ($paraValue);
  458. }
  459. }
  460. return $this->execute($req, $session);
  461. }
  462. /**
  463. * 校验$value是否非空
  464. * if not set ,return true;
  465. * if is null , return true;
  466. **/
  467. protected function checkEmpty($value) {
  468. if (!isset($value))
  469. return true;
  470. if ($value === null)
  471. return true;
  472. if (trim($value) === "")
  473. return true;
  474. return false;
  475. }
  476. /** rsaCheckV1 & rsaCheckV2
  477. * 验证签名
  478. * 在使用本方法前,必须初始化AopClient且传入公钥参数。
  479. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  480. **/
  481. public function rsaCheckV1($params, $rsaPublicKeyFilePath,$signType='RSA') {
  482. $sign = $params['sign'];
  483. $params['sign_type'] = null;
  484. $params['sign'] = null;
  485. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath,$signType);
  486. }
  487. public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType='RSA') {
  488. $sign = $params['sign'];
  489. $params['sign'] = null;
  490. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
  491. }
  492. function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA') {
  493. if($this->checkEmpty($this->alipayPublicKey)){
  494. $pubKey= $this->alipayrsaPublicKey;
  495. $res = "-----BEGIN PUBLIC KEY-----\n" .
  496. wordwrap($pubKey, 64, "\n", true) .
  497. "\n-----END PUBLIC KEY-----";
  498. }else {
  499. //读取公钥文件
  500. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  501. //转换为openssl格式密钥
  502. $res = openssl_get_publickey($pubKey);
  503. }
  504. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  505. //调用openssl内置方法验签,返回bool值
  506. $result = FALSE;
  507. if ("RSA2" == $signType) {
  508. $result = (openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256)===1);
  509. } else {
  510. $result = (openssl_verify($data, base64_decode($sign), $res)===1);
  511. }
  512. if(!$this->checkEmpty($this->alipayPublicKey)) {
  513. //释放资源
  514. openssl_free_key($res);
  515. }
  516. return $result;
  517. }
  518. /**
  519. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  520. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  521. **/
  522. public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt, $signType='RSA') {
  523. $charset = $params['charset'];
  524. $bizContent = $params['biz_content'];
  525. if ($isCheckSign) {
  526. if (!$this->rsaCheckV2($params, $rsaPublicKeyPem, $signType)) {
  527. echo "<br/>checkSign failure<br/>";
  528. exit;
  529. }
  530. }
  531. if ($isDecrypt) {
  532. return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
  533. }
  534. return $bizContent;
  535. }
  536. /**
  537. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  538. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  539. **/
  540. public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign, $signType='RSA') {
  541. // 加密,并签名
  542. if ($isEncrypt && $isSign) {
  543. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  544. $sign = $this->sign($encrypted, $signType);
  545. $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>";
  546. return $response;
  547. }
  548. // 加密,不签名
  549. if ($isEncrypt && (!$isSign)) {
  550. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  551. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$encrypted</response><encryption_type>$signType</encryption_type></alipay>";
  552. return $response;
  553. }
  554. // 不加密,但签名
  555. if ((!$isEncrypt) && $isSign) {
  556. $sign = $this->sign($bizContent, $signType);
  557. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$bizContent</response><sign>$sign</sign><sign_type>$signType</sign_type></alipay>";
  558. return $response;
  559. }
  560. // 不加密,不签名
  561. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?>$bizContent";
  562. return $response;
  563. }
  564. /**
  565. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  566. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  567. **/
  568. public function rsaEncrypt($data, $rsaPublicKeyPem, $charset) {
  569. if($this->checkEmpty($this->alipayPublicKey)){
  570. //读取字符串
  571. $pubKey= $this->alipayrsaPublicKey;
  572. $res = "-----BEGIN PUBLIC KEY-----\n" .
  573. wordwrap($pubKey, 64, "\n", true) .
  574. "\n-----END PUBLIC KEY-----";
  575. }else {
  576. //读取公钥文件
  577. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  578. //转换为openssl格式密钥
  579. $res = openssl_get_publickey($pubKey);
  580. }
  581. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  582. $blocks = $this->splitCN($data, 0, 30, $charset);
  583. $chrtext  = null;
  584. $encodes  = array();
  585. foreach ($blocks as $n => $block) {
  586. if (!openssl_public_encrypt($block, $chrtext , $res)) {
  587. echo "<br/>" . openssl_error_string() . "<br/>";
  588. }
  589. $encodes[] = $chrtext ;
  590. }
  591. $chrtext = implode(",", $encodes);
  592. return base64_encode($chrtext);
  593. }
  594. /**
  595. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  596. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  597. **/
  598. public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset) {
  599. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  600. //读字符串
  601. $priKey=$this->rsaPrivateKey;
  602. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  603. wordwrap($priKey, 64, "\n", true) .
  604. "\n-----END RSA PRIVATE KEY-----";
  605. }else {
  606. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  607. $res = openssl_get_privatekey($priKey);
  608. }
  609. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  610. //转换为openssl格式密钥
  611. $decodes = explode(',', $data);
  612. $strnull = "";
  613. $dcyCont = "";
  614. foreach ($decodes as $n => $decode) {
  615. if (!openssl_private_decrypt($decode, $dcyCont, $res)) {
  616. echo "<br/>" . openssl_error_string() . "<br/>";
  617. }
  618. $strnull .= $dcyCont;
  619. }
  620. return $strnull;
  621. }
  622. function splitCN($cont, $n = 0, $subnum, $charset) {
  623. //$len = strlen($cont) / 3;
  624. $arrr = array();
  625. for ($i = $n; $i < strlen($cont); $i += $subnum) {
  626. $res = $this->subCNchar($cont, $i, $subnum, $charset);
  627. if (!empty ($res)) {
  628. $arrr[] = $res;
  629. }
  630. }
  631. return $arrr;
  632. }
  633. function subCNchar($str, $start = 0, $length, $charset = "gbk") {
  634. if (strlen($str) <= $length) {
  635. return $str;
  636. }
  637. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  638. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  639. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  640. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  641. preg_match_all($re[$charset], $str, $match);
  642. $slice = join("", array_slice($match[0], $start, $length));
  643. return $slice;
  644. }
  645. function parserResponseSubCode($request, $responseContent, $respObject, $format) {
  646. if ("json" == $format) {
  647. $apiName = $request->getApiMethodName();
  648. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  649. $errorNodeName = $this->ERROR_RESPONSE;
  650. $rootIndex = strpos($responseContent, $rootNodeName);
  651. $errorIndex = strpos($responseContent, $errorNodeName);
  652. if ($rootIndex > 0) {
  653. // 内部节点对象
  654. $rInnerObject = $respObject->$rootNodeName;
  655. } elseif ($errorIndex > 0) {
  656. $rInnerObject = $respObject->$errorNodeName;
  657. } else {
  658. return null;
  659. }
  660. // 存在属性则返回对应值
  661. if (isset($rInnerObject->sub_code)) {
  662. return $rInnerObject->sub_code;
  663. } else {
  664. return null;
  665. }
  666. } elseif ("xml" == $format) {
  667. // xml格式sub_code在同一层级
  668. return $respObject->sub_code;
  669. }
  670. }
  671. function parserJSONSignData($request, $responseContent, $responseJSON) {
  672. $signData = new SignData();
  673. $signData->sign = $this->parserJSONSign($responseJSON);
  674. $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
  675. return $signData;
  676. }
  677. function parserJSONSignSource($request, $responseContent) {
  678. $apiName = $request->getApiMethodName();
  679. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  680. $rootIndex = strpos($responseContent, $rootNodeName);
  681. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  682. if ($rootIndex > 0) {
  683. return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
  684. } else if ($errorIndex > 0) {
  685. return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  686. } else {
  687. return null;
  688. }
  689. }
  690. function parserJSONSource($responseContent, $nodeName, $nodeIndex) {
  691. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  692. $signIndex = strrpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  693. // 签名前-逗号
  694. $signDataEndIndex = $signIndex - 1;
  695. $indexLen = $signDataEndIndex - $signDataStartIndex;
  696. if ($indexLen < 0) {
  697. return null;
  698. }
  699. return substr($responseContent, $signDataStartIndex, $indexLen);
  700. }
  701. function parserJSONSign($responseJSon) {
  702. return $responseJSon->sign;
  703. }
  704. function parserXMLSignData($request, $responseContent) {
  705. $signData = new SignData();
  706. $signData->sign = $this->parserXMLSign($responseContent);
  707. $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
  708. return $signData;
  709. }
  710. function parserXMLSignSource($request, $responseContent) {
  711. $apiName = $request->getApiMethodName();
  712. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  713. $rootIndex = strpos($responseContent, $rootNodeName);
  714. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  715. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  716. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  717. if ($rootIndex > 0) {
  718. return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
  719. } else if ($errorIndex > 0) {
  720. return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  721. } else {
  722. return null;
  723. }
  724. }
  725. function parserXMLSource($responseContent, $nodeName, $nodeIndex) {
  726. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  727. $signIndex = strrpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
  728. // 签名前-逗号
  729. $signDataEndIndex = $signIndex - 1;
  730. $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
  731. if ($indexLen < 0) {
  732. return null;
  733. }
  734. return substr($responseContent, $signDataStartIndex, $indexLen);
  735. }
  736. function parserXMLSign($responseContent) {
  737. $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
  738. $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
  739. $indexOfSignNode = strpos($responseContent, $signNodeName);
  740. $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
  741. if ($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
  742. return null;
  743. }
  744. $nodeIndex = ($indexOfSignNode + strlen($signNodeName));
  745. $indexLen = $indexOfSignEndNode - $nodeIndex;
  746. if ($indexLen < 0) {
  747. return null;
  748. }
  749. // 签名
  750. return substr($responseContent, $nodeIndex, $indexLen);
  751. }
  752. /**
  753. * 验签
  754. * @param $request
  755. * @param $signData
  756. * @param $resp
  757. * @param $respObject
  758. * @throws Exception
  759. */
  760. public function checkResponseSign($request, $signData, $resp, $respObject) {
  761. if (!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
  762. if ($signData == null || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
  763. throw new Exception(" check sign Fail! The reason : signData is Empty");
  764. }
  765. // 获取结果sub_code
  766. $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
  767. if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign))) {
  768. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  769. if (!$checkResult) {
  770. if (strpos($signData->signSourceData, "\\/") > 0) {
  771. $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
  772. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  773. if (!$checkResult) {
  774. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  775. }
  776. } else {
  777. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  778. }
  779. }
  780. }
  781. }
  782. }
  783. private function setupCharsets($request) {
  784. if ($this->checkEmpty($this->postCharset)) {
  785. $this->postCharset = 'UTF-8';
  786. }
  787. $str = preg_match('/[\x80-\xff]/', $this->appId) ? $this->appId : print_r($request, true);
  788. $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == 'UTF-8' ? 'UTF-8' : 'GBK';
  789. }
  790. // 获取加密内容
  791. private function encryptJSONSignSource($request, $responseContent) {
  792. $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
  793. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  794. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  795. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  796. return $bodyIndexContent . $bizContent . $bodyEndContent;
  797. }
  798. private function parserEncryptJSONSignSource($request, $responseContent) {
  799. $apiName = $request->getApiMethodName();
  800. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  801. $rootIndex = strpos($responseContent, $rootNodeName);
  802. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  803. if ($rootIndex > 0) {
  804. return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
  805. } else if ($errorIndex > 0) {
  806. return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  807. } else {
  808. return null;
  809. }
  810. }
  811. private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex) {
  812. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  813. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  814. // 签名前-逗号
  815. $signDataEndIndex = $signIndex - 1;
  816. if ($signDataEndIndex < 0) {
  817. $signDataEndIndex = strlen($responseContent)-1 ;
  818. }
  819. $indexLen = $signDataEndIndex - $signDataStartIndex;
  820. $encContent = substr($responseContent, $signDataStartIndex+1, $indexLen-2);
  821. $encryptParseItem = new EncryptParseItem();
  822. $encryptParseItem->encryptContent = $encContent;
  823. $encryptParseItem->startIndex = $signDataStartIndex;
  824. $encryptParseItem->endIndex = $signDataEndIndex;
  825. return $encryptParseItem;
  826. }
  827. // 获取加密内容
  828. private function encryptXMLSignSource($request, $responseContent) {
  829. $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
  830. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  831. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  832. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  833. return $bodyIndexContent . $bizContent . $bodyEndContent;
  834. }
  835. private function parserEncryptXMLSignSource($request, $responseContent) {
  836. $apiName = $request->getApiMethodName();
  837. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  838. $rootIndex = strpos($responseContent, $rootNodeName);
  839. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  840. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  841. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  842. if ($rootIndex > 0) {
  843. return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
  844. } else if ($errorIndex > 0) {
  845. return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  846. } else {
  847. return null;
  848. }
  849. }
  850. private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex) {
  851. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  852. $xmlStartNode="<".$this->ENCRYPT_XML_NODE_NAME.">";
  853. $xmlEndNode="</".$this->ENCRYPT_XML_NODE_NAME.">";
  854. $indexOfXmlNode=strpos($responseContent,$xmlEndNode);
  855. if($indexOfXmlNode<0){
  856. $item = new EncryptParseItem();
  857. $item->encryptContent = null;
  858. $item->startIndex = 0;
  859. $item->endIndex = 0;
  860. return $item;
  861. }
  862. $startIndex=$signDataStartIndex+strlen($xmlStartNode);
  863. $bizContentLen=$indexOfXmlNode-$startIndex;
  864. $bizContent=substr($responseContent,$startIndex,$bizContentLen);
  865. $encryptParseItem = new EncryptParseItem();
  866. $encryptParseItem->encryptContent = $bizContent;
  867. $encryptParseItem->startIndex = $signDataStartIndex;
  868. $encryptParseItem->endIndex = $indexOfXmlNode+strlen($xmlEndNode);
  869. return $encryptParseItem;
  870. }
  871. function echoDebug($content) {
  872. if ($this->debugInfo) {
  873. echo "<br/>" . $content;
  874. }
  875. }
  876. }