index.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. /*
  3. * Фронтенд для получения оплат от CITY24 в виде GET запроса
  4. * Версия API: Protocol_City-Pay_20v.3.03.02.pdf
  5. */
  6. //Использовать ли внешний кодификатор контрагентов из agentcodes.ini?
  7. define('CPAYX_USE_AGENTCODES', 1);
  8. //URL вашего работающего Ubilling
  9. define('API_URL', 'http://127.0.0.1/billing/');
  10. //И его серийный номер
  11. define('API_KEY', 'UB0000000000000000000000');
  12. error_reporting(E_ALL);
  13. // подключаем API OpenPayz
  14. include ("../../libs/api.openpayz.php");
  15. /**
  16. *
  17. * Check for GET have needed variables
  18. *
  19. * @param $params array of GET variables to check
  20. * @return bool
  21. *
  22. */
  23. function cpay_CheckGet($params) {
  24. $result = true;
  25. if (!empty($params)) {
  26. foreach ($params as $eachparam) {
  27. if (isset($_GET[$eachparam])) {
  28. if (empty($_GET[$eachparam])) {
  29. $result = false;
  30. }
  31. } else {
  32. $result = false;
  33. }
  34. }
  35. }
  36. return ($result);
  37. }
  38. /*
  39. * Gets last transaction ID from database by hash
  40. *
  41. * @param $hash - transaction hash with prefix
  42. *
  43. * @return int
  44. */
  45. function cpay_GetTransactionID($hash) {
  46. $hash = mysql_real_escape_string($hash);
  47. $query = "SELECT `id` from `op_transactions` WHERE `hash`='" . $hash . "';";
  48. $rawData = simple_query($query);
  49. if (!empty($rawData)) {
  50. $result = $rawData['id'];
  51. } else {
  52. $result = false;
  53. }
  54. return ($result);
  55. }
  56. /*
  57. * Check is transaction unique?
  58. *
  59. * @param $hash - prepared transaction hash with prefix
  60. *
  61. * @return bool
  62. */
  63. function cpay_CheckTransaction($hash) {
  64. $hash = mysql_real_escape_string($hash);
  65. $query = "SELECT `id` from `op_transactions` WHERE `hash`='" . $hash . "'";
  66. $data = simple_query($query);
  67. if (empty($data)) {
  68. return (true);
  69. } else {
  70. return (false);
  71. }
  72. }
  73. /*
  74. * find substring into string
  75. *
  76. * @param $string - target string
  77. * @param $search - needle
  78. *
  79. * @return bool
  80. */
  81. function cpay_ispos($string,$search) {
  82. if (strpos($string,$search)===false) {
  83. return(false);
  84. } else {
  85. return(true);
  86. }
  87. }
  88. /**
  89. * Returns all user RealNames
  90. *
  91. * @return array
  92. */
  93. function cpay_UserGetAllRealnames() {
  94. $query_fio = "SELECT * from `realname`";
  95. $allfioz = simple_queryall($query_fio);
  96. $fioz = array();
  97. if (!empty($allfioz)) {
  98. foreach ($allfioz as $ia => $eachfio) {
  99. $fioz[$eachfio['login']] = $eachfio['realname'];
  100. }
  101. }
  102. return($fioz);
  103. }
  104. //ищем агента
  105. if (!empty($agentData)) {
  106. $agentData = json_decode($agentData, true);
  107. if (!empty($agentData)) {
  108. $agentCode = '';
  109. $agentsOverrides = parse_ini_file('agentcodes.ini');
  110. if (IBX_USE_AGENTCODES) {
  111. if (isset($agentsOverrides[$agentData['id']])) {
  112. $agentCode = $agentsOverrides[$agentData['id']];
  113. } else {
  114. $agentCode = $agentData['id'];
  115. }
  116. } else {
  117. $agentCode = $agentData['id'];
  118. }
  119. }
  120. return($fioz);
  121. }
  122. //Выбираем все адреса в формате Ubilling
  123. function cpay_AddressGetFulladdresslist() {
  124. $result=array();
  125. $apts=array();
  126. $builds=array();
  127. //наглая заглушка
  128. $alterconf['ZERO_TOLERANCE']=0;
  129. $alterconf['CITY_DISPLAY']=0;
  130. $city_q="SELECT * from `city`";
  131. $adrz_q="SELECT * from `address`";
  132. $apt_q="SELECT * from `apt`";
  133. $build_q="SELECT * from build";
  134. $streets_q="SELECT * from `street`";
  135. $alladdrz=simple_queryall($adrz_q);
  136. $allapt=simple_queryall($apt_q);
  137. $allbuilds=simple_queryall($build_q);
  138. $allstreets=simple_queryall($streets_q);
  139. if (!empty ($alladdrz)) {
  140. foreach ($alladdrz as $io1=>$eachaddress) {
  141. $address[$eachaddress['id']]=array('login'=>$eachaddress['login'],'aptid'=>$eachaddress['aptid']);
  142. }
  143. foreach ($allapt as $io2=>$eachapt) {
  144. $apts[$eachapt['id']]=array('apt'=>$eachapt['apt'],'buildid'=>$eachapt['buildid']);
  145. }
  146. foreach ($allbuilds as $io3=>$eachbuild) {
  147. $builds[$eachbuild['id']]=array('buildnum'=>$eachbuild['buildnum'],'streetid'=>$eachbuild['streetid']);
  148. }
  149. foreach ($allstreets as $io4=>$eachstreet) {
  150. $streets[$eachstreet['id']]=array('streetname'=>$eachstreet['streetname'],'cityid'=>$eachstreet['cityid']);
  151. }
  152. foreach ($address as $io5=>$eachaddress) {
  153. $apartment=$apts[$eachaddress['aptid']]['apt'];
  154. $building=$builds[$apts[$eachaddress['aptid']]['buildid']]['buildnum'];
  155. $streetname=$streets[$builds[$apts[$eachaddress['aptid']]['buildid']]['streetid']]['streetname'];
  156. $cityid=$streets[$builds[$apts[$eachaddress['aptid']]['buildid']]['streetid']]['cityid'];
  157. // zero apt handle
  158. if ($alterconf['ZERO_TOLERANCE']) {
  159. if ($apartment==0) {
  160. $apartment_filtered='';
  161. } else {
  162. $apartment_filtered='/'.$apartment;
  163. }
  164. } else {
  165. $apartment_filtered='/'.$apartment;
  166. }
  167. if (!$alterconf['CITY_DISPLAY']) {
  168. $result[$eachaddress['login']]=$streetname.' '.$building.$apartment_filtered;
  169. } else {
  170. $result[$eachaddress['login']]=$cities[$cityid].' '.$streetname.' '.$building.$apartment_filtered;
  171. }
  172. }
  173. }
  174. return($result);
  175. }
  176. /*
  177. * returns XML formatted transactions by interval in yyyyMMddHHmmss
  178. *
  179. * @param $start - time start
  180. * @param @end - time end
  181. *
  182. * @return string
  183. */
  184. function cpay_GetRevise($start,$end) {
  185. $start= strtotime($start);
  186. $start=date('Y:m:d H:i:s',$start);
  187. $end= strtotime($end);
  188. $end=date('Y:m:d H:i:s',$end);
  189. $payments='';
  190. $query="SELECT * from `op_transactions` WHERE `paysys` = 'CITY24' AND `date` BETWEEN '".$start."' AND '".$end."';";
  191. $rawData= simple_queryall($query);
  192. if (!empty($rawData)) {
  193. foreach ($rawData as $io=>$each) {
  194. if (cpay_ispos($each['note'], 'date:')) {
  195. $tmpDate=explode('date:',$each['note']);
  196. $transDate=trim($tmpDate[1]);
  197. } else {
  198. $transDate= strtotime($each['date']);
  199. $transDate= date("YmdHis",$transDate);
  200. }
  201. $cleanHash= str_replace('CITY24_', '', $each['hash']);
  202. $payments.='
  203. <Payment>
  204. <TransactionId>'.$cleanHash.'</TransactionId>
  205. <Account>'.$each['customerid'].'</Account>
  206. <TransactionDate>'.$transDate.'</TransactionDate>
  207. <Amount>'.$each['summ'].'</Amount>
  208. </Payment>
  209. ';
  210. }
  211. }
  212. $result='
  213. <?xml version="1.0" encoding="UTF-8"?>
  214. <Response>
  215. '.$payments.'
  216. </Response>
  217. ';
  218. $result=trim($result);
  219. print($result);
  220. }
  221. $requiredCheck = array('QueryType', 'TransactionId', 'Account');
  222. //проверяем наличие сильно объязательных параметров
  223. if (cpay_CheckGet($requiredCheck)) {
  224. $allcustomers = op_CustomersGetAll();
  225. $hash = $_GET['TransactionId'];
  226. $hashPrepared = 'CITY24_' . $hash;
  227. $paysys = 'CITY24';
  228. $customerid = trim($_GET['Account']);
  229. // Ловим запрос на проверку существования абонента
  230. if ($_GET['QueryType'] == 'check') {
  231. if (isset($allcustomers[$customerid])) {
  232. $resultCode = 0;
  233. $customerLogin = $allcustomers[$customerid];
  234. $userlogin = $allcustomers[$customerid];
  235. $userData = simple_query("SELECT * from `users` WHERE `login`='" . $userlogin . "'");
  236. $allrealnames = cpay_UserGetAllRealnames();
  237. $alladdress = cpay_AddressGetFulladdresslist();
  238. //$agentData = getAgentData($customerLogin);
  239. // if (!empty($agentData)) {
  240. // $agentData = json_decode($agentData, true);
  241. // if (!empty($agentData)) {
  242. // $agentCode = '';
  243. // $agentsOverrides = parse_ini_file('agentcodes.ini');
  244. // if (CPAYX_USE_AGENTCODES) {
  245. // if (isset($agentsOverrides[$agentData['id']])) {
  246. // $agentCode = $agentsOverrides[$agentData['id']];
  247. // } else {
  248. // $agentCode = $agentData['id'];
  249. // }
  250. // } else {
  251. // $agentCode = $agentData['id'];
  252. $resultCode = 0;
  253. } else {
  254. $resultCode = 21;
  255. }
  256. $reply = '
  257. <?xml version="1.0" encoding="UTF-8"?>
  258. <Response>
  259. <TransactionId>' . $hash . '</TransactionId>
  260. <ResultCode>' . $resultCode . '</ResultCode>
  261. <fields>
  262. <field1 name="balance">' . @$userData['Cash'] . '</field1>
  263. // это когда включаю дает ошибку <field2 name="LegalCode">' . $agentCode . '</field2>
  264. <field3 name="name">' . @$allrealnames[$userlogin] . '</field3>
  265. <field4 name="address">' . @$alladdress[$userlogin] . '</field4>
  266. </fields>
  267. <Comment>OK</Comment>
  268. </Response>';
  269. $reply = trim($reply);
  270. die($reply);
  271. }
  272. //ловим запрос на пополнение счета
  273. if ($_GET['QueryType'] == 'pay') {
  274. if (cpay_CheckGet(array('Amount', 'TransactionDate'))) {
  275. $amount = $_GET['Amount'];
  276. $payDate = $_GET['TransactionDate'];
  277. //если абонент найден по платежному ID регистрируем транзакцию
  278. if (isset($allcustomers[$customerid])) {
  279. $note = 'hash:' . mysql_real_escape_string($hash) . ' date:' . mysql_real_escape_string($payDate);
  280. if (cpay_CheckTransaction($hashPrepared)) {
  281. //регистрируем новую транзакцию
  282. op_TransactionAdd($hashPrepared, $amount, $customerid, $paysys, $note);
  283. //вызываем обработчики необработанных транзакций
  284. op_ProcessHandlers();
  285. }
  286. //выцепляем ее внутренний ID
  287. $transactionExtID = cpay_GetTransactionID($hashPrepared);
  288. $resultPayCode = 0;
  289. } else {
  290. $resultPayCode = 21;
  291. $transactionExtID = '';
  292. }
  293. $reply = '<?xml version="1.0" encoding="UTF-8"?>
  294. <Response>
  295. <TransactionId>' . $hash . '</TransactionId>
  296. <TransactionExt>' . $transactionExtID . '</TransactionExt>
  297. <Amount>' . $amount . '</Amount>
  298. <ResultCode>' . $resultPayCode . '</ResultCode>
  299. <Comment>:)</Comment>
  300. </Response>';
  301. $reply = trim($reply);
  302. die($reply);
  303. } else {
  304. throw new Exception('EX_NO_REQUIRED_PARAMS');
  305. }
  306. }
  307. } else {
  308. //если это не поиск абонента либо пополнение счета
  309. //будем считать, что это автоматическая сверка транзакций
  310. if (cpay_CheckGet(array('CheckDateBegin', 'CheckDateEnd'))) {
  311. cpay_GetRevise($_GET['CheckDateBegin'],$_GET['CheckDateEnd']);
  312. }
  313. }
  314. ?>