新版订单消耗系统

AopClient.php 34KB

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