AopClient.php 33 KB

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