AopClient.php 39 KB

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