AopClient.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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-20161101";
  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. foreach($para_temp as $key => $val) {
  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. $respObject = @ simplexml_load_string($resp);
  392. if (false !== $respObject) {
  393. $respWellFormed = true;
  394. $signData = $this->parserXMLSignData($request, $resp);
  395. }
  396. }
  397. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  398. if (false === $respWellFormed) {
  399. $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
  400. return false;
  401. }
  402. // 验签
  403. $this->checkResponseSign($request, $signData, $resp, $respObject);
  404. // 解密
  405. if (method_exists($request,"getNeedEncrypt") &&$request->getNeedEncrypt()){
  406. if ("json" == $this->format) {
  407. $resp = $this->encryptJSONSignSource($request, $resp);
  408. // 将返回结果转换本地文件编码
  409. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  410. $respObject = json_decode($r);
  411. }else{
  412. $resp = $this->encryptXMLSignSource($request, $resp);
  413. $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
  414. $respObject = @ simplexml_load_string($r);
  415. }
  416. }
  417. return $respObject;
  418. }
  419. /**
  420. * 转换字符集编码
  421. * @param $data
  422. * @param $targetCharset
  423. * @return string
  424. */
  425. function characet($data, $targetCharset) {
  426. if (!empty($data)) {
  427. $fileType = $this->fileCharset;
  428. if (strcasecmp($fileType, $targetCharset) != 0) {
  429. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  430. // $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
  431. }
  432. }
  433. return $data;
  434. }
  435. public function exec($paramsArray) {
  436. if (!isset ($paramsArray["method"])) {
  437. trigger_error("No api name passed");
  438. }
  439. $inflector = new LtInflector;
  440. $inflector->conf["separator"] = ".";
  441. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  442. if (!class_exists($requestClassName)) {
  443. trigger_error("No such api: " . $paramsArray["method"]);
  444. }
  445. $session = isset ($paramsArray["session"]) ? $paramsArray["session"] : null;
  446. $req = new $requestClassName;
  447. foreach ($paramsArray as $paraKey => $paraValue) {
  448. $inflector->conf["separator"] = "_";
  449. $setterMethodName = $inflector->camelize($paraKey);
  450. $inflector->conf["separator"] = ".";
  451. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  452. if (method_exists($req, $setterMethodName)) {
  453. $req->$setterMethodName ($paraValue);
  454. }
  455. }
  456. return $this->execute($req, $session);
  457. }
  458. /**
  459. * 校验$value是否非空
  460. * if not set ,return true;
  461. * if is null , return true;
  462. **/
  463. protected function checkEmpty($value) {
  464. if (!isset($value))
  465. return true;
  466. if ($value === null)
  467. return true;
  468. if (trim($value) === "")
  469. return true;
  470. return false;
  471. }
  472. /** rsaCheckV1 & rsaCheckV2
  473. * 验证签名
  474. * 在使用本方法前,必须初始化AopClient且传入公钥参数。
  475. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  476. **/
  477. public function rsaCheckV1($params, $rsaPublicKeyFilePath,$signType='RSA') {
  478. $sign = $params['sign'];
  479. $params['sign_type'] = null;
  480. $params['sign'] = null;
  481. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath,$signType);
  482. }
  483. public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType='RSA') {
  484. $sign = $params['sign'];
  485. $params['sign'] = null;
  486. return $this->verify($this->getSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
  487. }
  488. function verify($data, $sign, $rsaPublicKeyFilePath, $signType = 'RSA') {
  489. if($this->checkEmpty($this->alipayPublicKey)){
  490. $pubKey= $this->alipayrsaPublicKey;
  491. $res = "-----BEGIN PUBLIC KEY-----\n" .
  492. wordwrap($pubKey, 64, "\n", true) .
  493. "\n-----END PUBLIC KEY-----";
  494. }else {
  495. //读取公钥文件
  496. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  497. //转换为openssl格式密钥
  498. $res = openssl_get_publickey($pubKey);
  499. }
  500. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  501. //调用openssl内置方法验签,返回bool值
  502. if ("RSA2" == $signType) {
  503. $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
  504. } else {
  505. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  506. }
  507. if(!$this->checkEmpty($this->alipayPublicKey)) {
  508. //释放资源
  509. openssl_free_key($res);
  510. }
  511. return $result;
  512. }
  513. /**
  514. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  515. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  516. **/
  517. public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt, $signType='RSA') {
  518. $charset = $params['charset'];
  519. $bizContent = $params['biz_content'];
  520. if ($isCheckSign) {
  521. if (!$this->rsaCheckV2($params, $rsaPublicKeyPem, $signType)) {
  522. echo "<br/>checkSign failure<br/>";
  523. exit;
  524. }
  525. }
  526. if ($isDecrypt) {
  527. return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
  528. }
  529. return $bizContent;
  530. }
  531. /**
  532. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  533. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  534. **/
  535. public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign, $signType='RSA') {
  536. // 加密,并签名
  537. if ($isEncrypt && $isSign) {
  538. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  539. $sign = $this->sign($encrypted, $signType);
  540. $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>";
  541. return $response;
  542. }
  543. // 加密,不签名
  544. if ($isEncrypt && (!$isSign)) {
  545. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  546. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$encrypted</response><encryption_type>$signType</encryption_type></alipay>";
  547. return $response;
  548. }
  549. // 不加密,但签名
  550. if ((!$isEncrypt) && $isSign) {
  551. $sign = $this->sign($bizContent, $signType);
  552. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$bizContent</response><sign>$sign</sign><sign_type>$signType</sign_type></alipay>";
  553. return $response;
  554. }
  555. // 不加密,不签名
  556. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?>$bizContent";
  557. return $response;
  558. }
  559. /**
  560. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  561. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  562. **/
  563. public function rsaEncrypt($data, $rsaPublicKeyPem, $charset) {
  564. if($this->checkEmpty($this->alipayPublicKey)){
  565. //读取字符串
  566. $pubKey= $this->alipayrsaPublicKey;
  567. $res = "-----BEGIN PUBLIC KEY-----\n" .
  568. wordwrap($pubKey, 64, "\n", true) .
  569. "\n-----END PUBLIC KEY-----";
  570. }else {
  571. //读取公钥文件
  572. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  573. //转换为openssl格式密钥
  574. $res = openssl_get_publickey($pubKey);
  575. }
  576. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  577. $blocks = $this->splitCN($data, 0, 30, $charset);
  578. $chrtext  = null;
  579. $encodes  = array();
  580. foreach ($blocks as $n => $block) {
  581. if (!openssl_public_encrypt($block, $chrtext , $res)) {
  582. echo "<br/>" . openssl_error_string() . "<br/>";
  583. }
  584. $encodes[] = $chrtext ;
  585. }
  586. $chrtext = implode(",", $encodes);
  587. return base64_encode($chrtext);
  588. }
  589. /**
  590. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  591. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  592. **/
  593. public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset) {
  594. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  595. //读字符串
  596. $priKey=$this->rsaPrivateKey;
  597. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  598. wordwrap($priKey, 64, "\n", true) .
  599. "\n-----END RSA PRIVATE KEY-----";
  600. }else {
  601. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  602. $res = openssl_get_privatekey($priKey);
  603. }
  604. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  605. //转换为openssl格式密钥
  606. $decodes = explode(',', $data);
  607. $strnull = "";
  608. $dcyCont = "";
  609. foreach ($decodes as $n => $decode) {
  610. if (!openssl_private_decrypt($decode, $dcyCont, $res)) {
  611. echo "<br/>" . openssl_error_string() . "<br/>";
  612. }
  613. $strnull .= $dcyCont;
  614. }
  615. return $strnull;
  616. }
  617. function splitCN($cont, $n = 0, $subnum, $charset) {
  618. //$len = strlen($cont) / 3;
  619. $arrr = array();
  620. for ($i = $n; $i < strlen($cont); $i += $subnum) {
  621. $res = $this->subCNchar($cont, $i, $subnum, $charset);
  622. if (!empty ($res)) {
  623. $arrr[] = $res;
  624. }
  625. }
  626. return $arrr;
  627. }
  628. function subCNchar($str, $start = 0, $length, $charset = "gbk") {
  629. if (strlen($str) <= $length) {
  630. return $str;
  631. }
  632. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  633. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  634. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  635. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  636. preg_match_all($re[$charset], $str, $match);
  637. $slice = join("", array_slice($match[0], $start, $length));
  638. return $slice;
  639. }
  640. function parserResponseSubCode($request, $responseContent, $respObject, $format) {
  641. if ("json" == $format) {
  642. $apiName = $request->getApiMethodName();
  643. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  644. $errorNodeName = $this->ERROR_RESPONSE;
  645. $rootIndex = strpos($responseContent, $rootNodeName);
  646. $errorIndex = strpos($responseContent, $errorNodeName);
  647. if ($rootIndex > 0) {
  648. // 内部节点对象
  649. $rInnerObject = $respObject->$rootNodeName;
  650. } elseif ($errorIndex > 0) {
  651. $rInnerObject = $respObject->$errorNodeName;
  652. } else {
  653. return null;
  654. }
  655. // 存在属性则返回对应值
  656. if (isset($rInnerObject->sub_code)) {
  657. return $rInnerObject->sub_code;
  658. } else {
  659. return null;
  660. }
  661. } elseif ("xml" == $format) {
  662. // xml格式sub_code在同一层级
  663. return $respObject->sub_code;
  664. }
  665. }
  666. function parserJSONSignData($request, $responseContent, $responseJSON) {
  667. $signData = new SignData();
  668. $signData->sign = $this->parserJSONSign($responseJSON);
  669. $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
  670. return $signData;
  671. }
  672. function parserJSONSignSource($request, $responseContent) {
  673. $apiName = $request->getApiMethodName();
  674. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  675. $rootIndex = strpos($responseContent, $rootNodeName);
  676. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  677. if ($rootIndex > 0) {
  678. return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
  679. } else if ($errorIndex > 0) {
  680. return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  681. } else {
  682. return null;
  683. }
  684. }
  685. function parserJSONSource($responseContent, $nodeName, $nodeIndex) {
  686. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  687. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  688. // 签名前-逗号
  689. $signDataEndIndex = $signIndex - 1;
  690. $indexLen = $signDataEndIndex - $signDataStartIndex;
  691. if ($indexLen < 0) {
  692. return null;
  693. }
  694. return substr($responseContent, $signDataStartIndex, $indexLen);
  695. }
  696. function parserJSONSign($responseJSon) {
  697. return $responseJSon->sign;
  698. }
  699. function parserXMLSignData($request, $responseContent) {
  700. $signData = new SignData();
  701. $signData->sign = $this->parserXMLSign($responseContent);
  702. $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
  703. return $signData;
  704. }
  705. function parserXMLSignSource($request, $responseContent) {
  706. $apiName = $request->getApiMethodName();
  707. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  708. $rootIndex = strpos($responseContent, $rootNodeName);
  709. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  710. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  711. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  712. if ($rootIndex > 0) {
  713. return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
  714. } else if ($errorIndex > 0) {
  715. return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  716. } else {
  717. return null;
  718. }
  719. }
  720. function parserXMLSource($responseContent, $nodeName, $nodeIndex) {
  721. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  722. $signIndex = strpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
  723. // 签名前-逗号
  724. $signDataEndIndex = $signIndex - 1;
  725. $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
  726. if ($indexLen < 0) {
  727. return null;
  728. }
  729. return substr($responseContent, $signDataStartIndex, $indexLen);
  730. }
  731. function parserXMLSign($responseContent) {
  732. $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
  733. $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
  734. $indexOfSignNode = strpos($responseContent, $signNodeName);
  735. $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
  736. if ($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
  737. return null;
  738. }
  739. $nodeIndex = ($indexOfSignNode + strlen($signNodeName));
  740. $indexLen = $indexOfSignEndNode - $nodeIndex;
  741. if ($indexLen < 0) {
  742. return null;
  743. }
  744. // 签名
  745. return substr($responseContent, $nodeIndex, $indexLen);
  746. }
  747. /**
  748. * 验签
  749. * @param $request
  750. * @param $signData
  751. * @param $resp
  752. * @param $respObject
  753. * @throws Exception
  754. */
  755. public function checkResponseSign($request, $signData, $resp, $respObject) {
  756. if (!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
  757. if ($signData == null || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
  758. throw new Exception(" check sign Fail! The reason : signData is Empty");
  759. }
  760. // 获取结果sub_code
  761. $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
  762. if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign))) {
  763. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  764. if (!$checkResult) {
  765. if (strpos($signData->signSourceData, "\\/") > 0) {
  766. $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
  767. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  768. if (!$checkResult) {
  769. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  770. }
  771. } else {
  772. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  773. }
  774. }
  775. }
  776. }
  777. }
  778. private function setupCharsets($request) {
  779. if ($this->checkEmpty($this->postCharset)) {
  780. $this->postCharset = 'UTF-8';
  781. }
  782. $str = preg_match('/[\x80-\xff]/', $this->appId) ? $this->appId : print_r($request, true);
  783. $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == 'UTF-8' ? 'UTF-8' : 'GBK';
  784. }
  785. // 获取加密内容
  786. private function encryptJSONSignSource($request, $responseContent) {
  787. $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
  788. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  789. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  790. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  791. return $bodyIndexContent . $bizContent . $bodyEndContent;
  792. }
  793. private function parserEncryptJSONSignSource($request, $responseContent) {
  794. $apiName = $request->getApiMethodName();
  795. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  796. $rootIndex = strpos($responseContent, $rootNodeName);
  797. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  798. if ($rootIndex > 0) {
  799. return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
  800. } else if ($errorIndex > 0) {
  801. return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  802. } else {
  803. return null;
  804. }
  805. }
  806. private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex) {
  807. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  808. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  809. // 签名前-逗号
  810. $signDataEndIndex = $signIndex - 1;
  811. if ($signDataEndIndex < 0) {
  812. $signDataEndIndex = strlen($responseContent)-1 ;
  813. }
  814. $indexLen = $signDataEndIndex - $signDataStartIndex;
  815. $encContent = substr($responseContent, $signDataStartIndex+1, $indexLen-2);
  816. $encryptParseItem = new EncryptParseItem();
  817. $encryptParseItem->encryptContent = $encContent;
  818. $encryptParseItem->startIndex = $signDataStartIndex;
  819. $encryptParseItem->endIndex = $signDataEndIndex;
  820. return $encryptParseItem;
  821. }
  822. // 获取加密内容
  823. private function encryptXMLSignSource($request, $responseContent) {
  824. $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
  825. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  826. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  827. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  828. return $bodyIndexContent . $bizContent . $bodyEndContent;
  829. }
  830. private function parserEncryptXMLSignSource($request, $responseContent) {
  831. $apiName = $request->getApiMethodName();
  832. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  833. $rootIndex = strpos($responseContent, $rootNodeName);
  834. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  835. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  836. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  837. if ($rootIndex > 0) {
  838. return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
  839. } else if ($errorIndex > 0) {
  840. return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  841. } else {
  842. return null;
  843. }
  844. }
  845. private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex) {
  846. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  847. $xmlStartNode="<".$this->ENCRYPT_XML_NODE_NAME.">";
  848. $xmlEndNode="</".$this->ENCRYPT_XML_NODE_NAME.">";
  849. $indexOfXmlNode=strpos($responseContent,$xmlEndNode);
  850. if($indexOfXmlNode<0){
  851. $item = new EncryptParseItem();
  852. $item->encryptContent = null;
  853. $item->startIndex = 0;
  854. $item->endIndex = 0;
  855. return $item;
  856. }
  857. $startIndex=$signDataStartIndex+strlen($xmlStartNode);
  858. $bizContentLen=$indexOfXmlNode-$startIndex;
  859. $bizContent=substr($responseContent,$startIndex,$bizContentLen);
  860. $encryptParseItem = new EncryptParseItem();
  861. $encryptParseItem->encryptContent = $bizContent;
  862. $encryptParseItem->startIndex = $signDataStartIndex;
  863. $encryptParseItem->endIndex = $indexOfXmlNode+strlen($xmlEndNode);
  864. return $encryptParseItem;
  865. }
  866. function echoDebug($content) {
  867. if ($this->debugInfo) {
  868. echo "<br/>" . $content;
  869. }
  870. }
  871. }