AopClient.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. <?php
  2. namespace aop;
  3. class AopClient
  4. {
  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. if($res == false) return false;
  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. 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. $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. //调用openssl内置方法验签,返回bool值
  501. if ("RSA2" == $signType) {
  502. $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
  503. } else {
  504. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  505. }
  506. if(!$this->checkEmpty($this->alipayPublicKey)) {
  507. //释放资源
  508. openssl_free_key($res);
  509. }
  510. return $result;
  511. }
  512. /**
  513. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  514. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  515. **/
  516. public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt, $signType='RSA') {
  517. $charset = $params['charset'];
  518. $bizContent = $params['biz_content'];
  519. if ($isCheckSign) {
  520. if (!$this->rsaCheckV2($params, $rsaPublicKeyPem, $signType)) {
  521. echo "<br/>checkSign failure<br/>";
  522. exit;
  523. }
  524. }
  525. if ($isDecrypt) {
  526. return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
  527. }
  528. return $bizContent;
  529. }
  530. /**
  531. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  532. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  533. **/
  534. public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign, $signType='RSA') {
  535. // 加密,并签名
  536. if ($isEncrypt && $isSign) {
  537. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  538. $sign = $this->sign($encrypted, $signType);
  539. $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>";
  540. return $response;
  541. }
  542. // 加密,不签名
  543. if ($isEncrypt && (!$isSign)) {
  544. $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
  545. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$encrypted</response><encryption_type>$signType</encryption_type></alipay>";
  546. return $response;
  547. }
  548. // 不加密,但签名
  549. if ((!$isEncrypt) && $isSign) {
  550. $sign = $this->sign($bizContent, $signType);
  551. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?><alipay><response>$bizContent</response><sign>$sign</sign><sign_type>$signType</sign_type></alipay>";
  552. return $response;
  553. }
  554. // 不加密,不签名
  555. $response = "<?xml version=\"1.0\" encoding=\"$charset\"?>$bizContent";
  556. return $response;
  557. }
  558. /**
  559. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  560. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  561. **/
  562. public function rsaEncrypt($data, $rsaPublicKeyFilePath, $charset) {
  563. if($this->checkEmpty($this->alipayPublicKey)){
  564. //读取字符串
  565. $pubKey= $this->alipayrsaPublicKey;
  566. $res = "-----BEGIN PUBLIC KEY-----\n" .
  567. wordwrap($pubKey, 64, "\n", true) .
  568. "\n-----END PUBLIC KEY-----";
  569. }else {
  570. //读取公钥文件
  571. $pubKey = file_get_contents($rsaPublicKeyFilePath);
  572. //转换为openssl格式密钥
  573. $res = openssl_get_publickey($pubKey);
  574. }
  575. $blocks = $this->splitCN($data, 0, 30, $charset);
  576. $chrtext  = null;
  577. $encodes  = array();
  578. foreach ($blocks as $n => $block) {
  579. if (!openssl_public_encrypt($block, $chrtext , $res)) {
  580. echo "<br/>" . openssl_error_string() . "<br/>";
  581. }
  582. $encodes[] = $chrtext ;
  583. }
  584. $chrtext = implode(",", $encodes);
  585. return base64_encode($chrtext);
  586. }
  587. /**
  588. * 在使用本方法前,必须初始化AopClient且传入公私钥参数。
  589. * 公钥是否是读取字符串还是读取文件,是根据初始化传入的值判断的。
  590. **/
  591. public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset) {
  592. if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
  593. //读字符串
  594. $priKey=$this->rsaPrivateKey;
  595. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  596. wordwrap($priKey, 64, "\n", true) .
  597. "\n-----END RSA PRIVATE KEY-----";
  598. } else {
  599. $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
  600. $res = openssl_get_privatekey($priKey);
  601. }
  602. //转换为openssl格式密钥
  603. $decodes = explode(',', $data);
  604. $strnull = "";
  605. $dcyCont = "";
  606. foreach ($decodes as $n => $decode) {
  607. if (!openssl_private_decrypt($decode, $dcyCont, $res)) {
  608. echo "<br/>" . openssl_error_string() . "<br/>";
  609. }
  610. $strnull .= $dcyCont;
  611. }
  612. return $strnull;
  613. }
  614. function splitCN($cont, $n = 0, $subnum, $charset) {
  615. //$len = strlen($cont) / 3;
  616. $arrr = array();
  617. for ($i = $n; $i < strlen($cont); $i += $subnum) {
  618. $res = $this->subCNchar($cont, $i, $subnum, $charset);
  619. if (!empty ($res)) {
  620. $arrr[] = $res;
  621. }
  622. }
  623. return $arrr;
  624. }
  625. function subCNchar($str, $start = 0, $length, $charset = "gbk") {
  626. if (strlen($str) <= $length) {
  627. return $str;
  628. }
  629. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  630. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  631. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  632. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  633. preg_match_all($re[$charset], $str, $match);
  634. $slice = join("", array_slice($match[0], $start, $length));
  635. return $slice;
  636. }
  637. function parserResponseSubCode($request, $responseContent, $respObject, $format) {
  638. if ("json" == $format) {
  639. $apiName = $request->getApiMethodName();
  640. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  641. $errorNodeName = $this->ERROR_RESPONSE;
  642. $rootIndex = strpos($responseContent, $rootNodeName);
  643. $errorIndex = strpos($responseContent, $errorNodeName);
  644. if ($rootIndex > 0) {
  645. // 内部节点对象
  646. $rInnerObject = $respObject->$rootNodeName;
  647. } elseif ($errorIndex > 0) {
  648. $rInnerObject = $respObject->$errorNodeName;
  649. } else {
  650. return null;
  651. }
  652. // 存在属性则返回对应值
  653. if (isset($rInnerObject->sub_code)) {
  654. return $rInnerObject->sub_code;
  655. } else {
  656. return null;
  657. }
  658. } elseif ("xml" == $format) {
  659. // xml格式sub_code在同一层级
  660. return $respObject->sub_code;
  661. }
  662. }
  663. function parserJSONSignData($request, $responseContent, $responseJSON) {
  664. $signData = new SignData();
  665. $signData->sign = $this->parserJSONSign($responseJSON);
  666. $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
  667. return $signData;
  668. }
  669. function parserJSONSignSource($request, $responseContent) {
  670. $apiName = $request->getApiMethodName();
  671. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  672. $rootIndex = strpos($responseContent, $rootNodeName);
  673. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  674. if ($rootIndex > 0) {
  675. return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
  676. } else if ($errorIndex > 0) {
  677. return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  678. } else {
  679. return null;
  680. }
  681. }
  682. function parserJSONSource($responseContent, $nodeName, $nodeIndex) {
  683. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  684. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  685. // 签名前-逗号
  686. $signDataEndIndex = $signIndex - 1;
  687. $indexLen = $signDataEndIndex - $signDataStartIndex;
  688. if ($indexLen < 0) {
  689. return null;
  690. }
  691. return substr($responseContent, $signDataStartIndex, $indexLen);
  692. }
  693. function parserJSONSign($responseJSon) {
  694. return $responseJSon->sign;
  695. }
  696. function parserXMLSignData($request, $responseContent) {
  697. $signData = new SignData();
  698. $signData->sign = $this->parserXMLSign($responseContent);
  699. $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
  700. return $signData;
  701. }
  702. function parserXMLSignSource($request, $responseContent) {
  703. $apiName = $request->getApiMethodName();
  704. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  705. $rootIndex = strpos($responseContent, $rootNodeName);
  706. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  707. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  708. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  709. if ($rootIndex > 0) {
  710. return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
  711. } else if ($errorIndex > 0) {
  712. return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  713. } else {
  714. return null;
  715. }
  716. }
  717. function parserXMLSource($responseContent, $nodeName, $nodeIndex) {
  718. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  719. $signIndex = strpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
  720. // 签名前-逗号
  721. $signDataEndIndex = $signIndex - 1;
  722. $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
  723. if ($indexLen < 0) {
  724. return null;
  725. }
  726. return substr($responseContent, $signDataStartIndex, $indexLen);
  727. }
  728. function parserXMLSign($responseContent) {
  729. $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
  730. $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
  731. $indexOfSignNode = strpos($responseContent, $signNodeName);
  732. $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
  733. if ($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
  734. return null;
  735. }
  736. $nodeIndex = ($indexOfSignNode + strlen($signNodeName));
  737. $indexLen = $indexOfSignEndNode - $nodeIndex;
  738. if ($indexLen < 0) {
  739. return null;
  740. }
  741. // 签名
  742. return substr($responseContent, $nodeIndex, $indexLen);
  743. }
  744. /**
  745. * 验签
  746. * @param $request
  747. * @param $signData
  748. * @param $resp
  749. * @param $respObject
  750. * @throws Exception
  751. */
  752. public function checkResponseSign($request, $signData, $resp, $respObject) {
  753. if (!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
  754. if ($signData == null || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
  755. throw new Exception(" check sign Fail! The reason : signData is Empty");
  756. }
  757. // 获取结果sub_code
  758. $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
  759. if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign))) {
  760. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  761. if (!$checkResult) {
  762. if (strpos($signData->signSourceData, "\\/") > 0) {
  763. $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
  764. $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
  765. if (!$checkResult) {
  766. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  767. }
  768. } else {
  769. throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
  770. }
  771. }
  772. }
  773. }
  774. }
  775. private function setupCharsets($request) {
  776. if ($this->checkEmpty($this->postCharset)) {
  777. $this->postCharset = 'UTF-8';
  778. }
  779. $str = preg_match('/[\x80-\xff]/', $this->appId) ? $this->appId : print_r($request, true);
  780. $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == 'UTF-8' ? 'UTF-8' : 'GBK';
  781. }
  782. // 获取加密内容
  783. private function encryptJSONSignSource($request, $responseContent) {
  784. $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
  785. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  786. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  787. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  788. return $bodyIndexContent . $bizContent . $bodyEndContent;
  789. }
  790. private function parserEncryptJSONSignSource($request, $responseContent) {
  791. $apiName = $request->getApiMethodName();
  792. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  793. $rootIndex = strpos($responseContent, $rootNodeName);
  794. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  795. if ($rootIndex > 0) {
  796. return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
  797. } else if ($errorIndex > 0) {
  798. return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  799. } else {
  800. return null;
  801. }
  802. }
  803. private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex) {
  804. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
  805. $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
  806. // 签名前-逗号
  807. $signDataEndIndex = $signIndex - 1;
  808. if ($signDataEndIndex < 0) {
  809. $signDataEndIndex = strlen($responseContent)-1 ;
  810. }
  811. $indexLen = $signDataEndIndex - $signDataStartIndex;
  812. $encContent = substr($responseContent, $signDataStartIndex+1, $indexLen-2);
  813. $encryptParseItem = new EncryptParseItem();
  814. $encryptParseItem->encryptContent = $encContent;
  815. $encryptParseItem->startIndex = $signDataStartIndex;
  816. $encryptParseItem->endIndex = $signDataEndIndex;
  817. return $encryptParseItem;
  818. }
  819. // 获取加密内容
  820. private function encryptXMLSignSource($request, $responseContent) {
  821. $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
  822. $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
  823. $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
  824. $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
  825. return $bodyIndexContent . $bizContent . $bodyEndContent;
  826. }
  827. private function parserEncryptXMLSignSource($request, $responseContent) {
  828. $apiName = $request->getApiMethodName();
  829. $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
  830. $rootIndex = strpos($responseContent, $rootNodeName);
  831. $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
  832. // $this->echoDebug("<br/>rootNodeName:" . $rootNodeName);
  833. // $this->echoDebug("<br/> responseContent:<xmp>" . $responseContent . "</xmp>");
  834. if ($rootIndex > 0) {
  835. return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
  836. } else if ($errorIndex > 0) {
  837. return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
  838. } else {
  839. return null;
  840. }
  841. }
  842. private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex) {
  843. $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
  844. $xmlStartNode="<".$this->ENCRYPT_XML_NODE_NAME.">";
  845. $xmlEndNode="</".$this->ENCRYPT_XML_NODE_NAME.">";
  846. $indexOfXmlNode=strpos($responseContent,$xmlEndNode);
  847. if($indexOfXmlNode<0){
  848. $item = new EncryptParseItem();
  849. $item->encryptContent = null;
  850. $item->startIndex = 0;
  851. $item->endIndex = 0;
  852. return $item;
  853. }
  854. $startIndex=$signDataStartIndex+strlen($xmlStartNode);
  855. $bizContentLen=$indexOfXmlNode-$startIndex;
  856. $bizContent=substr($responseContent,$startIndex,$bizContentLen);
  857. $encryptParseItem = new EncryptParseItem();
  858. $encryptParseItem->encryptContent = $bizContent;
  859. $encryptParseItem->startIndex = $signDataStartIndex;
  860. $encryptParseItem->endIndex = $indexOfXmlNode+strlen($xmlEndNode);
  861. return $encryptParseItem;
  862. }
  863. function echoDebug($content) {
  864. if ($this->debugInfo) {
  865. echo "<br/>" . $content;
  866. }
  867. }
  868. }