AopClient.php 36 KB

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