AopClient.php 41 KB

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