AopClient.php 42 KB

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