AopClient.php 30 KB

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