You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1192 lines
34 KiB

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