AopClient.php 41 KB

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