index.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <?php
  2. /*
  3. * Фронтенд для получения уведомлений о платежах от Приватбанка
  4. * Протокол: https://docs.google.com/document/d/1JrH84x2p4FOjm89q3xArvnEfsFXRnbIoa6qJFNq2VYw/edit#
  5. *
  6. * Возможно получение запросов как в виде отдельной POST переменной, так и в виде HTTP_RAW_POST_DATA
  7. * Идентификация абонента по лицевому счету в виде paymentID материализующемуся из вьюшки вида:
  8. * CREATE VIEW op_customers (realid,virtualid) AS SELECT users.login, CRC32(users.login) FROM `users`;
  9. */
  10. $agentData = parse_ini_file('agentdata.ini', true);
  11. /////////// Секция настроек
  12. // Имя POST переменной в которой должны приходить запросы, либо raw в случае получения
  13. // запросов в виде HTTP_RAW_POST_DATA.
  14. define('PBX_REQUEST_MODE', 'raw');
  15. //Режим отладки - заставляет данные подгружаться из файла debug.xml
  16. //(Да-да, ложите туда запрос и смотрите в браузере как на него отвечает фронтенд)
  17. define('PBX_DEBUG_MODE', 0);
  18. //Текст уведомлений и екзепшнов
  19. define('USER_BALANCE_DECIMALS', -1); // Сколько знаков после запятой возвращать в балансе абонента 0 - возвращать только целую часть
  20. //Исключения
  21. define('PBX_EX_NOT_FOUND', 'Абонент не найден');
  22. define('PBX_EX_DUPLICATE', 'Дублирование платежа');
  23. define('PBX_AGENT_NOT_FOUND', 'Критическая ошибка. Не найден агент, которому пренадлежит абонент');
  24. // подключаем API OpenPayz
  25. include ("../../libs/api.openpayz.php");
  26. error_reporting(E_ALL);
  27. // Send main headers
  28. header('Last-Modified: ' . gmdate('r'));
  29. header('Content-Type: text/html; charset=utf-8');
  30. header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
  31. header("Pragma: no-cache");
  32. /**
  33. * Gets user associated agent data by ID
  34. *
  35. * @param string $userlogin
  36. *
  37. * @return string
  38. */
  39. function getAgentDataByID($customer_id) {
  40. global $agentData;
  41. $result = 'DEFAULT';
  42. $avaibleTags = array_keys($agentData);
  43. if (!empty($avaibleTags)) {
  44. $where = '';
  45. foreach ($avaibleTags as $tag) {
  46. if($tag != end($avaibleTags)) {
  47. $where.= "`tagid` = '" . trim($tag) . "' OR ";
  48. } else {
  49. $where.= "`tagid` = '" . trim($tag) . "'";
  50. }
  51. }
  52. $customer_id_m = mysql_real_escape_string($customer_id);
  53. $query = "SELECT `tagid` FROM `tags` INNER JOIN `op_customers` ON (`tags`.`login`= `op_customers`.`realid`) WHERE `op_customers`.`virtualid` = '" . $customer_id_m . "' AND (" . $where . ")";
  54. $data = simple_query($query);
  55. if (!empty($data)) {
  56. $result = $data['tagid'];
  57. }
  58. }
  59. return ($result);
  60. }
  61. /**
  62. * Check for POST have needed variables
  63. *
  64. * @param $params array of POST variables to check
  65. * @return bool
  66. *
  67. */
  68. function pbx_CheckPost($params) {
  69. $result = true;
  70. if (!empty($params)) {
  71. foreach ($params as $eachparam) {
  72. if (isset($_POST[$eachparam])) {
  73. if (empty($_POST[$eachparam])) {
  74. $result = false;
  75. }
  76. } else {
  77. $result = false;
  78. }
  79. }
  80. }
  81. return ($result);
  82. }
  83. /**
  84. * Returns request data
  85. *
  86. * @return string
  87. */
  88. function pbx_RequestGet() {
  89. $result = '';
  90. if (PBX_REQUEST_MODE != 'raw') {
  91. if (pbx_CheckPost(array(PBX_REQUEST_MODE))) {
  92. $result = $_POST[PBX_REQUEST_MODE];
  93. }
  94. } else {
  95. //$result = $HTTP_RAW_POST_DATA;
  96. $result = file_get_contents('php://input');
  97. }
  98. return ($result);
  99. }
  100. /**
  101. * Returns all user RealNames
  102. *
  103. * @return array
  104. */
  105. function pbx_UserGetAllRealnames() {
  106. $query = "SELECT * from `realname`";
  107. $all = simple_queryall($query);
  108. $result = array();
  109. if (!empty($all)) {
  110. foreach ($all as $io => $each) {
  111. $result[$each['login']] = $each['realname'];
  112. }
  113. }
  114. return($result);
  115. }
  116. /**
  117. * Returns user stargazer data by login
  118. *
  119. * @param string $login existing stargazer login
  120. *
  121. * @return array
  122. */
  123. function pbx_UserGetStargazerData($login) {
  124. $login = mysql_real_escape_string($login);
  125. $query = "SELECT * from `users` WHERE `login`='" . $login . "';";
  126. $result = simple_query($query);
  127. return ($result);
  128. }
  129. /**
  130. * Returns all user mobile phones
  131. *
  132. * @return array
  133. */
  134. function pbx_UserGetAllMobiles() {
  135. $query = "SELECT * from `phones`";
  136. $all = simple_queryall($query);
  137. $result = array();
  138. if (!empty($all)) {
  139. foreach ($all as $io => $each) {
  140. $result[$each['login']] = $each['mobile'];
  141. }
  142. }
  143. return($result);
  144. }
  145. /**
  146. * Returns random numeric string, which will be used as unique transaction hash
  147. *
  148. * @param int $size
  149. * @return int
  150. */
  151. function pbx_GenerateHash($size = 12) {
  152. $characters = '0123456789';
  153. $string = "";
  154. for ($p = 0; $p < $size; $p++) {
  155. $string.= $characters[mt_rand(0, (strlen($characters) - 1))];
  156. }
  157. return ($string);
  158. }
  159. /**
  160. * Returns array of availble user address as login=>address
  161. *
  162. * @return array
  163. */
  164. function pbx_AddressGetFulladdresslist() {
  165. //наглая заглушка
  166. $alterconf['ZERO_TOLERANCE'] = 0;
  167. $alterconf['CITY_DISPLAY'] = 0;
  168. $result = array();
  169. $query_full = "
  170. SELECT `address`.`login`,`city`.`cityname`,`street`.`streetname`,`build`.`buildnum`,`apt`.`apt` FROM `address`
  171. INNER JOIN `apt` ON `address`.`aptid`= `apt`.`id`
  172. INNER JOIN `build` ON `apt`.`buildid`=`build`.`id`
  173. INNER JOIN `street` ON `build`.`streetid`=`street`.`id`
  174. INNER JOIN `city` ON `street`.`cityid`=`city`.`id`";
  175. $full_adress = simple_queryall($query_full);
  176. if (!empty($full_adress)) {
  177. foreach ($full_adress as $ArrayData) {
  178. // zero apt handle
  179. if ($alterconf['ZERO_TOLERANCE']) {
  180. $apartment_filtered = ($ArrayData['apt'] == 0) ? '' : '/' . $ArrayData['apt'];
  181. } else {
  182. $apartment_filtered = '/' . $ArrayData['apt'];
  183. }
  184. if ($alterconf['CITY_DISPLAY']) {
  185. $result[$ArrayData['login']] = $ArrayData['cityname'] . ' ' . $ArrayData['streetname'] . ' ' . $ArrayData['buildnum'] . $apartment_filtered;
  186. } else {
  187. $result[$ArrayData['login']] = $ArrayData['streetname'] . ' ' . $ArrayData['buildnum'] . $apartment_filtered;
  188. }
  189. }
  190. }
  191. return($result);
  192. }
  193. /**
  194. * Returns presearch reply
  195. *
  196. * @return string
  197. */
  198. function pbx_ReplyPresearch($customerid) {
  199. $allcustomers = op_CustomersGetAll();
  200. if (isset($allcustomers[$customerid])) {
  201. $customerLogin = $allcustomers[$customerid];
  202. $allrealnames = pbx_UserGetAllRealnames();
  203. //normal search reply
  204. $templateOk = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  205. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Presearch">
  206. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="PayersTable">
  207. <Headers>
  208. <Header name="fio"/>
  209. <Header name="ls"/>
  210. </Headers>
  211. <Columns>
  212. <Column>
  213. <Element>' . @$allrealnames[$customerLogin] . '</Element>
  214. </Column>
  215. <Column>
  216. <Element>' . $customerid . '</Element>
  217. </Column>
  218. </Columns>
  219. </Data>
  220. </Transfer>';
  221. $result = $templateOk;
  222. } else {
  223. //search fail reply template
  224. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  225. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Presearch">
  226. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="99">
  227. <Message>' . PBX_EX_NOT_FOUND . '</Message>
  228. </Data>
  229. </Transfer>';
  230. $result = $templateFail;
  231. }
  232. $result = trim($result);
  233. return ($result);
  234. }
  235. /**
  236. * Returns search reply
  237. *
  238. * @return string
  239. */
  240. function pbx_ReplySearch($customerid, $UsrBalanceDecimals = -1) {
  241. global $agentData;
  242. $allcustomers = op_CustomersGetAll();
  243. if (isset($allcustomers[$customerid])) {
  244. $customerLogin = $allcustomers[$customerid];
  245. $allrealnames = pbx_UserGetAllRealnames();
  246. $alladdress = pbx_AddressGetFulladdresslist();
  247. $allmobiles = pbx_UserGetAllMobiles();
  248. $userdata = pbx_UserGetStargazerData($customerLogin);
  249. if (!empty($agentData) and isset($agentData['DEFAULT'])) {
  250. $agentId = getAgentDataByID($customerLogin);
  251. $ispServiceCode = $agentData[$agentId]['serviceCode'];
  252. $ispServiceName = $agentData[$agentId]['serviceName'];
  253. $companyData = '
  254. <CompanyInfo mfo="' . $agentData[$agentId]['bankcode'] . '" okpo="' . $agentData[$agentId]['edrpo'] . '" account="' . $agentData[$agentId]['bankacc'] . '" >
  255. <CompanyCode>' . $agentData[$agentId]['kodificator'] . '</CompanyCode>
  256. <CompanyName>' . $agentData[$agentId]['contrname'] . '</CompanyName>
  257. </CompanyInfo>
  258. ';
  259. $userBalance = ($UsrBalanceDecimals < 0) ? $userdata['Cash'] : (($UsrBalanceDecimals == 0) ? intval($userdata['Cash'], 10) : round($userdata['Cash'], $UsrBalanceDecimals, PHP_ROUND_HALF_EVEN));
  260. //normal reply
  261. $templateOk = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  262. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Search">
  263. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="DebtPack" billPeriod="' . date("Ym") . '">
  264. <PayerInfo billIdentifier="' . $customerid . '">
  265. <Fio>' . @$allrealnames[$customerLogin] . '</Fio>
  266. <Phone>' . @$allmobiles[$customerLogin] . '</Phone>
  267. <Address>' . @$alladdress[$customerLogin] . '</Address>
  268. </PayerInfo>
  269. <ServiceGroup>
  270. <DebtService serviceCode="' . $ispServiceCode . '" >
  271. ' . $companyData . '
  272. <DebtInfo>
  273. <Balance>' . $userBalance . '</Balance>
  274. </DebtInfo>
  275. <ServiceName>' . $ispServiceName . '</ServiceName>
  276. <PayerInfo billIdentifier="' . $customerid . '" ls="' . $customerid . '">
  277. <Fio>' . @$allrealnames[$customerLogin] . '</Fio>
  278. <Phone>' . @$allmobiles[$customerLogin] . '</Phone>
  279. <Address>' . @$alladdress[$customerLogin] . '</Address>
  280. </PayerInfo>
  281. </DebtService>
  282. </ServiceGroup>
  283. </Data>
  284. </Transfer>
  285. ';
  286. $result = $templateOk;
  287. } else {
  288. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  289. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Pay">
  290. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="8">
  291. <Message>' . PBX_AGENT_NOT_FOUND . '</Message>
  292. </Data>
  293. </Transfer>';
  294. $result = $templateFail;
  295. }
  296. } else {
  297. //reply fail
  298. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  299. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Search">
  300. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="2">
  301. <Message>' . PBX_EX_NOT_FOUND . '</Message>
  302. </Data>
  303. </Transfer>';
  304. $result = $templateFail;
  305. }
  306. $result = trim($result);
  307. return ($result);
  308. }
  309. /**
  310. * Function that gets last id from table
  311. *
  312. * @param string $tablename
  313. * @return int
  314. */
  315. function pbx_simple_get_lastid($tablename) {
  316. $tablename = mysql_real_escape_string($tablename);
  317. $query = "SELECT `id` from `" . $tablename . "` ORDER BY `id` DESC LIMIT 1";
  318. $result = simple_query($query);
  319. return ($result['id']);
  320. }
  321. /**
  322. * Returns payment possibility reply
  323. *
  324. * @return string
  325. */
  326. function pbx_ReplyCheck($customerid) {
  327. $allcustomers = op_CustomersGetAll();
  328. if (isset($allcustomers[$customerid])) {
  329. $customerLogin = $allcustomers[$customerid];
  330. $reference = pbx_GenerateHash();
  331. // following method may cause reference ID collisions
  332. // $reference = pbx_simple_get_lastid('op_transactions') + 1;
  333. $templateOk = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  334. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Check">
  335. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Gateway" reference="' . $reference . '" />
  336. </Transfer>
  337. ';
  338. $result = $templateOk;
  339. } else {
  340. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  341. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Check">
  342. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="2">
  343. <Message>' . PBX_EX_NOT_FOUND . '</Message>
  344. </Data>
  345. </Transfer>
  346. ';
  347. $result = $templateFail;
  348. }
  349. $result = trim($result);
  350. return ($result);
  351. }
  352. /**
  353. * Checks is reference unique?
  354. *
  355. * @param int $rawhash reference number to check
  356. *
  357. * @return bool
  358. */
  359. function pbx_CheckHash($rawhash) {
  360. $rawhash = mysql_real_escape_string($rawhash);
  361. $hash = 'PBX_' . $rawhash;
  362. $query = "SELECT * from `op_transactions` WHERE `hash`='" . $hash . "';";
  363. $data = simple_query($query);
  364. if (empty($data)) {
  365. return (true);
  366. } else {
  367. return (false);
  368. }
  369. }
  370. /**
  371. * Returns payment processing reply
  372. *
  373. * @return string
  374. */
  375. function pbx_ReplyPayment($customerid, $summ, $rawhash) {
  376. global $agentData;
  377. $allcustomers = op_CustomersGetAll();
  378. if (isset($allcustomers[$customerid])) {
  379. if (pbx_CheckHash($rawhash)) {
  380. if (!empty($agentData) and isset($agentData['DEFAULT'])) {
  381. // Check tags id by agent
  382. $agentId = getAgentDataByID($customerid);
  383. $ispServiceCode = $agentData[$agentId]['serviceCode'];
  384. //do the payment
  385. $hash = 'PBX_' . $rawhash;
  386. $paysys = 'PBANKX' . $ispServiceCode;
  387. $note = 'inputreference: ' . $rawhash;
  388. op_TransactionAdd($hash, $summ, $customerid, $paysys, $note);
  389. op_ProcessHandlers();
  390. $templateOk = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  391. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Pay">
  392. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Gateway" reference="' . $rawhash . '">
  393. </Data>
  394. </Transfer>';
  395. $result = $templateOk;
  396. } else {
  397. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  398. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Pay">
  399. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="8">
  400. <Message>' . PBX_AGENT_NOT_FOUND . '</Message>
  401. </Data>
  402. </Transfer>';
  403. $result = $templateFail;
  404. }
  405. } else {
  406. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  407. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Pay">
  408. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="7">
  409. <Message>' . PBX_EX_DUPLICATE . '</Message>
  410. </Data>
  411. </Transfer>';
  412. $result = $templateFail;
  413. }
  414. } else {
  415. $templateFail = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  416. <Transfer xmlns="http://debt.privatbank.ua/Transfer" interface="Debt" action="Pay">
  417. <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ErrorInfo" code="2">
  418. <Message>' . PBX_EX_NOT_FOUND . '</Message>
  419. </Data>
  420. </Transfer>';
  421. $result = $templateFail;
  422. }
  423. $result = trim($result);
  424. return ($result);
  425. }
  426. /*
  427. * Controller part
  428. */
  429. if (!PBX_DEBUG_MODE) {
  430. $xmlRequest = pbx_RequestGet();
  431. } else {
  432. if (file_exists('debug.xml')) {
  433. $xmlRequest = file_get_contents('debug.xml');
  434. } else {
  435. die('PBX_DEBUG_MODE requires existing debug.xml file');
  436. }
  437. }
  438. //raw xml data received
  439. if (!empty($xmlRequest)) {
  440. $xmlParse = xml2array($xmlRequest);
  441. if (!empty($xmlParse)) {
  442. // Presearch action handling (deprecated?)
  443. if (isset($xmlParse['Transfer']['Data']['Unit_attr']['name'])) {
  444. if ($xmlParse['Transfer']['Data']['Unit_attr']['name'] == 'ls') {
  445. if (isset($xmlParse['Transfer']['Data']['Unit_attr']['value'])) {
  446. $customerid = vf($xmlParse['Transfer']['Data']['Unit_attr']['value'], 3);
  447. die(pbx_ReplyPresearch($customerid));
  448. }
  449. }
  450. }
  451. // Main search
  452. if (isset($xmlParse['Transfer']['Data']['Unit_attr']['name'])) {
  453. if ($xmlParse['Transfer']['Data']['Unit_attr']['name'] == 'bill_identifier') {
  454. if (isset($xmlParse['Transfer']['Data']['Unit_attr']['value'])) {
  455. if ($xmlParse['Transfer_attr']['action'] == 'Search') {
  456. $customerid = vf($xmlParse['Transfer']['Data']['Unit_attr']['value'], 3);
  457. die(pbx_ReplySearch($customerid, USER_BALANCE_DECIMALS));
  458. }
  459. }
  460. }
  461. }
  462. // Check payment possibility
  463. if (isset($xmlParse['Transfer_attr']['action'])) {
  464. if ($xmlParse['Transfer_attr']['action'] == 'Check') {
  465. if (isset($xmlParse['Transfer']['Data']['PayerInfo_attr']['billIdentifier'])) {
  466. $customerid = vf($xmlParse['Transfer']['Data']['PayerInfo_attr']['billIdentifier'], 3);
  467. die(pbx_ReplyCheck($customerid));
  468. }
  469. }
  470. }
  471. // Pay transaction handling
  472. if (isset($xmlParse['Transfer_attr']['action'])) {
  473. if ($xmlParse['Transfer_attr']['action'] == 'Pay') {
  474. if (isset($xmlParse['Transfer']['Data']['PayerInfo_attr']['billIdentifier'])) {
  475. $customerid = vf($xmlParse['Transfer']['Data']['PayerInfo_attr']['billIdentifier'], 3);
  476. $summ = $xmlParse['Transfer']['Data']['TotalSum'];
  477. $summ = str_replace(',', '.', $summ);
  478. $rawhash = $xmlParse['Transfer']['Data']['CompanyInfo']['CheckReference'];
  479. die(pbx_ReplyPayment($customerid, $summ, $rawhash));
  480. }
  481. }
  482. }
  483. } else {
  484. die('XML_PARSER_FAIL');
  485. }
  486. }
  487. ?>