Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?
- /**
- * TB
- * Класс по работе TWO
- *
- * @package
- * @author TheRabbit
- * @copyright 2013
- * @version $Id$
- * @access public
- */
- class TB {
- // Параметры подключения к сервису
- private $serviceHost;
- private $servicePort;
- private $masterKey;
- public $dataNamespace;
- public $soapNamespace;
- // Объекты сеанса
- protected $debug = 0;
- // Параметры сеанса
- private $PAN;
- private $keyId;
- private $STAN;
- private $PIN;
- private $dynamicPassword;
- private $prevTranId;
- private $personId;
- private $personName;
- private $textLogin;
- private $extraAuthLevel;
- private $lastLogon;
- private $birthDay;
- private $WorkKey;
- private $responseCode;
- /**
- * TB::__construct()
- * Конструктор сессии телебанка.
- *
- * @return void
- */
- public function __construct() {
- $arrT = Config::get('vtbi');
- $this->serviceHost = Config::get('vtbi.host');
- $this->servicePort = Config::get('vtbi.port');
- $this->masterKey = $arrT['masterKey'];
- $this->dataNamespace = Config::get('vtbi.xmlns');
- $this->soapNamespace = Config::get('vtbi.wsdl');
- // Начальное значени параметров сеанса
- /*$this->PAN = null;
- $this->keyId = 0;
- $this->STAN = 0;
- $this->PIN = null;
- $this->dynamicPassword = null;
- $this->prevTranId = null;
- $this->personId = null;
- $this->textLogin = null;
- $this->personName = null;
- $this->lastLogon = null;
- $this->birthDay = null;
- $this->extraAuthLevel = 0;
- $this->responseCode = 0;*/
- // Получим данные из сессии и установим начальные значения
- $this->getKey2Session('PAN', null);
- $this->getKey2Session('keyId', 0);
- $this->getKey2Session('STAN', 0);
- $this->getKey2Session('PIN', null);
- $this->getKey2Session('dynamicPassword', null);
- $this->getKey2Session('prevTranId', null);
- $this->getKey2Session('personId', null);
- $this->getKey2Session('textLogin', null);
- $this->getKey2Session('personName', null);
- $this->getKey2Session('lastLogon', null);
- $this->getKey2Session('birthDay', null);
- $this->getKey2Session('extraAuthLevel', 0);
- $this->getKey2Session('responseCode', 0);
- }//\\ __construct
- /**
- * Запрос имени клиента
- * @return имя клиента
- */
- public function getPersonName() {
- return $this->personName;
- }//\\ getPersonName
- /**
- * Запрос карты телебанк-пользователя
- * @return
- */
- public function getPAN() {
- return $this->PAN;
- }//\\ getPAN
- /**
- * Запрос динамического пароля
- * @return
- */
- public function getDynamicPassword() {
- return $this->dynamicPassword;
- }//\\ getDynamicPassword
- /**
- * Установка динамического пароля
- * @param value
- */
- public function setDynamicPassword($value) {
- $this->dynamicPassword = $value;
- }//\\ setDynamicPassword
- /**
- * Запрос пердыдущей транзакции по динамаческому паролю
- * @return
- */
- public function getPrevTranId() {
- return $this->prevTranId;
- }//\\ getPrevTranId
- /**
- * Установка динамического пароля
- * @param value
- */
- public function setPrevTranId($value) {
- $this->prevTranId = $value;
- }//\\ setPrevTranId
- /**
- * Запрос идентификатора клиента
- * @return идентификатор клиента
- */
- public function getPersonId() {
- return $this->personId;
- }//\\ getPersonId
- /**
- * Вернуть последний вход в систему
- * @return
- */
- public function getLastLogon() {
- return $this->lastLogon;
- }//\\ getLastLogon
- /**
- * Вернуть день рождения
- * @return
- */
- public function getBirthDay() {
- return $this->birthDay;
- }//\\ getBirthDay
- /**
- * Запрос текстового логина
- * @return текстовый логин
- */
- public function getTextLogin() {
- return $this->textLogin;
- }//\\ getTextLogin
- /**
- * Получить уровень дополнительной авторизации
- * @return
- */
- public function getExtraAuthLevel() {
- return $this->extraAuthLevel;
- }//\\ getExtraAuthLevel
- /**
- * TB::exec()
- * Вызов метода интерфейса VTBI.
- *
- * @return string
- */
- public function exec($strName, $strXML = '', $booUseCache = false) {
- //var_dump($this->PAN);
- //var_dump($this->masterKey);
- $objResult = false;
- // Инициализируем переменные ошибок
- $this->intError = 0;
- $this->strErrorTech = '';
- //echo 'PAN-'.$this->PAN."\r\n";
- // Вычислим хеш динамического пароля
- $strDynamicPassword = null;
- if ($this->dynamicPassword != null) {
- $strDynamicPassword = $this->calcDynamicPassword();
- $this->dynamicPassword = null;
- //$this->setKey2Session('STAN', $this->STAN);
- }//\\ if
- // Формируем XML для SOAP запроса
- if (strlen($strXML))
- $strData = '<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><'.$strName.'Rq xmlns="http://schemas.compassplus.ru/telebank/1.0/telebank.wsdl"><Request'.($strDynamicPassword != null ? ' DynamicPassword="'.$strDynamicPassword.'"' : '').(intval($this->keyId) ? ' KeyId="'.$this->keyId.'"' : '').($this->PAN != null ? ' PAN="'.$this->PAN.'"' : '').($this->PIN != null ? ' PIN="'.$this->PIN.'"' : '').($this->prevTranId != null ? ' PrevTranId="'.$this->prevTranId.'"' : '').' Product="TB"'.(intval($this->STAN) ? ' STAN="'.$this->STAN.'"' : '').' Ver="5.0" xmlns="">'.$strXML.'</Request></'.$strName.'Rq></SOAP-ENV:Body></SOAP-ENV:Envelope>';
- else
- $strData = '<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><'.$strName.'Rq xmlns="http://schemas.compassplus.ru/telebank/1.0/telebank.wsdl"><Request'.($strDynamicPassword != null ? ' DynamicPassword="'.$strDynamicPassword.'"' : '').(intval($this->keyId) ? ' KeyId="'.$this->keyId.'"' : '').($this->PAN != null ? ' PAN="'.$this->PAN.'"' : '').($this->PIN != null ? ' PIN="'.$this->PIN.'"' : '').($this->prevTranId != null ? ' PrevTranId="'.$this->prevTranId.'"' : '').' Product="TB"'.(intval($this->STAN) ? ' STAN="'.$this->STAN.'"' : '').' Ver="5.0" xmlns=""/></'.$strName.'Rq></SOAP-ENV:Body></SOAP-ENV:Envelope>';
- //var_dump($strData);
- /*if ($objRequest = fsockopen('192.168.190.6', 8080, $errno, $errstr)) {
- socket_set_timeout($objRequest, 60);
- // Отошлем запрос
- $strPost = "POST /proxy.jsp HTTP/1.1\r\n";
- $strPost .= "Host: 192.168.190.6:8080\r\n";
- $strPost .= "Content-Type: text/xml\r\n";
- $strPost .= "Accept-Language: en-us, en;q=0.50\r\n";
- $strPost .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
- $strPost .= "Keep-Alive: 300\r\n";
- $strPost .= "Connection: keep-alive\r\n";
- $strPost .= "Cache-Control: max-age=0\r\n";
- $strPost .= "Content-Type: application/x-www-form-urlencoded\r\n";
- $strPost .= "Content-Length: ".strlen($strData)."\r\n";
- $strPost .= "\r\n";
- $strPost .= 'xml='.urlencode($strData);
- fwrite($objRequest, $strPost);*/
- // Получим ключ для кеша
- if ($this->PAN != null) $strCacheKey = md5($this->PAN.'_'.$strName.'_'.$strXML);
- else $strCacheKey = md5('0000000000000000_'.$strName.'_'.$strXML);
- if ($booUseCache && Cache::has($strCacheKey)) {
- $strOutData = Cache::get($strCacheKey);
- }//\\ if
- if (!$booUseCache || ($booUseCache && !Cache::has($strCacheKey))) {
- // Делаем запрос в TWO
- if ($objRequest = fsockopen($this->serviceHost, $this->servicePort, $errno, $errstr, Config::get('vtbi.timeout'))) {
- stream_set_blocking ($objRequest, 0);
- //$cryptPassword = CryptUtils::CryptBlock($strWorkKey, $strPasswordHash, true);
- socket_set_timeout($objRequest, Config::get('vtbi.timeout'));
- // Отошлем запрос
- $strPost = "POST / HTTP/1.1\r\n";
- $strPost .= "Host: ".$this->serviceHost.':'.$this->servicePort."\r\n";
- $strPost .= "Connection: keep-alive\r\n";
- $strPost .= "User-Agent: Java/1.6.0_06\r\n";
- $strPost .= "Content-Type: text/xml; charset=utf-8\r\n";
- //$strPost .= "Accept-Language: en-us, en;q=0.50\r\n";
- $strPost .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
- //$strPost .= "Keep-Alive: 300\r\n";
- //$strPost .= "Cache-Control: max-age=0\r\n";
- //$strPost .= "MIME-Version: 1.0\r\n";
- $strPost .= "SOAPAction: \"\"\r\n";
- $strPost .= "Content-Length: ".strlen($strData)."\r\n";
- //$strPost .= "Ver: 9.1\r\n";
- //$strPost .= "Product: FIMI\r\n";
- //$strPost .= "Clerk: anushka\r\n";
- //$strPost .= "Password: ".$cryptPassword."\r\n";
- $strPost .= "\r\n";
- $strPost .= $strData;
- fwrite($objRequest, $strPost);
- //fputs($objRequest, $strPost);
- // Логируем запрос
- Log::Request($strData);
- if (Request::cli()) var_dump($strData);
- // Получим заголовок ответа
- $strHeader = '';
- do $strHeader .= fread($objRequest, 1);
- while (!preg_match('/\\r\\n\\r\\n$/',$strHeader));
- //var_dump($strHeader);
- $strOutData = '';
- if (preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$strHeader,$matches)) {
- //echo '$matches[1]-'.$matches[1]."\n\r";
- $strOutData = fread($objRequest, $matches[1]);
- if (strlen($strOutData) != $matches[1]) {
- while (!feof($objRequest)) {
- $strOutData .= fread($objRequest, 512);
- //var_dump($strOutData);
- if (strlen($strOutData) >= $matches[1]) break;
- }//\\ while
- }//\\ if
- } else {
- // not a nice way to do it (may also result in extra CRLF which trails the real content???)
- while (!feof($objRequest)) {
- $strOutData .= fread($objRequest, 512);
- //var_dump($strOutData);
- }
- }
- //echo 'strlen-'.strlen($strOutData)."\n\r";
- // Логируем ответ
- Log::Response($strOutData);
- fclose($objRequest);
- } else {
- $this->responseCode = 54;
- throw new Exception(MessagesVtbi::getResponseMessage($this->responseCode), $this->responseCode);
- }//\\ if
- // Сохраним в кеше
- if ($booUseCache) Cache::put($strCacheKey, $strOutData, 60);
- }//\\ if
- // Ошибок нет, поэтому парсим ответ
- if (!$this->intError) {
- if ($this->STAN >= 1) {
- $this->STAN++;
- $this->setKey2Session('STAN', $this->STAN);
- }//\\ if
- if (Request::cli()) var_dump($strOutData);
- try {
- if (!strlen($strOutData)) {
- $this->responseCode = 54;
- throw new Exception(MessagesVtbi::getResponseMessage($this->responseCode), $this->responseCode);
- }
- $strOutData = str_replace('<m0:', '<', $strOutData);
- $strOutData = str_replace('</m0:', '</', $strOutData);
- $strOutData = str_replace('<m:', '<', $strOutData);
- $strOutData = str_replace('</m:', '</', $strOutData);
- // Проверим наличие сообщения об ошибке
- $objXml = simplexml_load_string($strOutData);
- $objResult = $objXml->xpath('//SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault/SOAP-ENV:Code/SOAP-ENV:Value');
- if (count($objResult)) {
- // Проверим существование номера транзакции
- $objResultTranId = $objXml->xpath('//SOAP-ENV:Envelope/SOAP-ENV:Body/SOAP-ENV:Fault/SOAP-ENV:Detail/TranId');
- if (count($objResultTranId)) {
- $this->setKey2Session('prevTranId', (integer)$objResultTranId[0]);
- }//\\ if
- $this->responseCode = (integer)$objResult[0];
- throw new Exception(MessagesVtbi::getResponseMessage($this->responseCode), $this->responseCode);
- }
- // Парсим ответ
- $objXml = simplexml_load_string($strOutData);
- $objResult = $objXml->xpath('//SOAP-ENV:Body/'.$strName.'Rp/Response');
- if (count($objResult)) {
- $this->responseCode = (integer)$objResult[0]->attributes()->Response;
- if ($this->responseCode == 1) $objResult = $objResult[0];
- else {
- throw new Exception(MessagesVtbi::getResponseMessage($this->responseCode), $this->responseCode);
- }
- } else {
- $this->responseCode = 54;
- throw new Exception(MessagesVtbi::getResponseMessage($this->responseCode), $this->responseCode);
- }
- } catch (Exception $e) {
- throw $e;
- }//\\ try
- }//\\ if
- //var_dump($objResult);
- //exit;
- return $objResult;
- }//\\ exec
- /**
- * Получение PAN кода по текстовому логину
- * @param $strTextLogin логин телебанка
- * @return
- */
- public function getTextLoginPAN($strTextLogin) {
- try {
- $objGetPAN = $this->exec('GetPAN', '<TextLogin>'.$strTextLogin.'</TextLogin>', true);
- // $objGetPAN = $this->exec('GetPAN', '<TextLogin>'.$strTextLogin.'</TextLogin>');
- $strNewPAN = '';
- if (isset($objGetPAN->PAN) && strlen((string)$objGetPAN->PAN) == 12 && strpos((string)$objGetPAN->PAN, '7788') === 0) {
- $strNewPAN = (string)$objGetPAN->PAN;
- }
- //$this->extraAuthLevel = (integer)$objGetPAN->ExtraAuthLevel;
- $this->setKey2Session('extraAuthLevel', (integer)$objGetPAN->ExtraAuthLevel);
- return $strNewPAN;
- } catch (Exception $e) {
- throw $e;
- }//\\ try
- }//\\ getTextLoginPAN
- /**
- * TB::setKey2Session()
- * Сохраняет в свойствах класса и в сессии данные.
- *
- * @param mixed $strKey
- * @param mixed $strValue
- * @return
- */
- public function setKey2Session($strKey, $strValue) {
- $this->{$strKey} = $strValue;
- if (!Request::cli()) Session::put($strKey, $strValue);
- return $this->{$strKey};
- }//\\ getPAN
- /**
- * TB::getKey2Session()
- * Возвращает значение из сессии.
- *
- * @param mixed $strKey
- * @param mixed $strValue
- * @return
- */
- public function getKey2Session($strKey, $strValue = null) {
- if (!Request::cli() && Session::has($strKey)) {
- $this->{$strKey} = Session::get($strKey);
- } else $this->{$strKey} = $strValue;
- return $this->{$strKey};
- }//\\ getPAN
- /**
- * TB::execLogoff()
- * Осуществляет выход из сессии TWO.
- *
- * @return
- */
- public function execLogoff() {
- if ($this->PAN == null) {
- return false;
- }//\\ if
- try {
- $objLogoff = $this->exec('Logoff');
- } catch (Exception $e) {
- throw $e;
- }//\\ try
- $this->setKey2Session('personId', null);
- $this->setKey2Session('textLogin', null);
- $this->setKey2Session('personName', null);
- $this->setKey2Session('lastLogon', null);
- $this->setKey2Session('birthDay', null);
- $this->setKey2Session('PIN', null);
- $this->setKey2Session('keyId', 0);
- $this->setKey2Session('PAN', null);
- $this->setKey2Session('dynamicPassword', null);
- $this->setKey2Session('prevTranId', null);
- $this->setKey2Session('extraAuthLevel', 0);
- $this->setKey2Session('STAN', 0);
- }//\\ execLogoff
- /**
- * Telebank logon by PAN
- * @param Login user name
- * @param Password password
- */
- public function logonByPAN($strPAN, $strPassword) {
- try {
- if (!strlen($strPassword))
- throw new Exception(MessagesVtbi::getError(5003), 5003);
- if (!strlen($strPAN))
- throw new Exception(MessagesVtbi::getError(5004), 5004);
- else {
- // Если пользователь авторизован, то сбросим сессию
- if (!Request::cli() && Auth::check()) {
- $this->execLogoff();
- Auth::logout();
- Session::flush();
- }//\\ if
- $this->setKey2Session('PAN', $strPAN);
- // Получим ключ
- //$objGetKey = $this->exec('CreateSession');
- $objGetKey = $this->exec('GetKey');
- $strSessionKey = (string)$objGetKey->Key;
- //$this->keyId = intval((integer)$objGetKey->KeyId);
- $this->setKey2Session('keyId', (string)$objGetKey->KeyId);
- /*$this->setKey2Session('keyId', 373859);
- $strSessionKey = '74697C17B9FFC062';
- var_dump($this->masterKey);*/
- $strWorkKey = CryptUtils::CryptBlock($this->masterKey, $strSessionKey, false);
- //var_dump($strWorkKey);
- $strPasswordHash = CryptUtils::MakePinBlock($this->PAN, $strPassword);
- //var_dump($strPasswordHash);
- $strPIN = CryptUtils::CryptBlock($strWorkKey, $strPasswordHash, true);
- $this->setKey2Session('PIN', $strPIN);
- //var_dump($this->PIN);
- //$this->STAN = 1;
- $this->setKey2Session('STAN', 1);
- // Регистрация пользователя
- $objLogon = $this->exec('Logon');
- /*$this->personId = (integer)$objLogon->PersonId;
- $this->personName = (string)$objLogon->Name;
- $this->lastLogon = (string)$objLogon->LastLogonTime;
- $this->birthDay = (string)$objLogon->BirthDay;*/
- $this->setKey2Session('personId', (integer)$objLogon->PersonId);
- $this->setKey2Session('personName', (string)$objLogon->Name);
- $this->setKey2Session('lastLogon', (string)$objLogon->LastLogonTime);
- $this->setKey2Session('birthDay', (string)$objLogon->BirthDay);
- //$this->setKey2Session('BirthPlace', (string)$objLogon->BirthPlace);
- //$this->setKey2Session('ExpDate', (string)$objLogon->ExpDate);
- /*var_dump($this->personId);
- var_dump($this->personName);
- var_dump($this->lastLogon);
- var_dump($this->birthDay);*/
- return $this->personId;
- }//\\ if
- } catch (Exception $e) {
- throw $e;
- }//\\ try
- return false;
- }//\\ logonByPAN
- /**
- * Вход в телебанк по текстовому логину
- * @param $strTextLogin логин телебанка
- * @param $strPassword пароль
- */
- public function logonByTextLogin($strTextLogin, $strPassword) {
- try {
- if (!strlen($strTextLogin))
- throw new Exception(MessagesVtbi::getError(5002), 5002);
- else {
- // Запомнить имя регисрации
- //$this->textLogin = $strTextLogin;
- $this->setKey2Session('textLogin', $strTextLogin);
- // Регистрация по PAN
- $this->logonByPAN($this->getTextLoginPAN($strTextLogin), $strPassword);
- }//\\ if
- } catch (Exception $e) {
- throw $e;
- }//\\ try
- }//\\ logonByTextLogin
- /**
- * TB::calcDynamicPassword()
- * Вычисляет динамический пароль.
- *
- * @return void
- */
- public function calcDynamicPassword() {
- $strDynamicPassword = $this->dynamicPassword;
- $strPassword = Str::upper($strDynamicPassword);
- if (strlen($strPassword) >= 8) $strPassword8 = substr($strPassword, 0, 8);
- else $strPassword8 = $strPassword.substr(' ', 0, 8-strlen($strPassword));
- if (strlen($strPassword) >= 16) $strPassword16 = substr($strPassword, 0, 16);
- else $strPassword16 = $strPassword.substr(' ', 0, 16-strlen($strPassword));
- $strPasswordHash = CryptUtils::CryptBlock(bin2hex($strPassword16), bin2hex($strPassword8), true);
- return $strPasswordHash;
- }//\\ calcDynamicPassword
- /**
- * TB::getBackOfficeInfo()
- * Делает запрос в Back office.
- *
- * @param mixed $strInfoType
- * @param mixed $strIdentType
- * @param mixed $strIdent
- * @param mixed $strFormat
- * @param mixed $strAddParams
- * @return
- */
- public function getBackOfficeInfo($strInfoType, $strIdentType, $strIdent, $strFormat, $strAddParams = null){
- $strXML = '<InfoType>'.$strInfoType.'</InfoType><IdentType>'.$strIdentType.'</IdentType><Ident>'.$strIdent.'</Ident><Format>'.$strFormat.'</Format>';
- if ($strAddParams != null) $strXML = '<AddParams>'.$strAddParams.'</AddParams>';
- $objXml = $this->exec('GetBackOfficeInfo', $strXML);
- $objResult = $objXml->xpath('//Value');
- if (count($objResult)) {
- $strValue = (string)$objResult[0];
- $strValue = base64_decode($strValue);
- /*if (strpos($strValue, 'encoding="windows-1251"') !== false)
- $strValue = iconv('windows-1251', 'UTF-8', $strValue);*/
- }//\\ if
- return $strValue;
- }//\\ getBackOfficeInfo
- /**
- * TB::getDynAuthAddressList()
- * Возвращает список получателей динамической аунтификации.
- *
- * @return
- */
- public function getDynAuthAddressList(){
- $arrAddressList = array();
- $objXml = $this->exec('DynAuthAddressList');
- $objResult = $objXml->xpath('//List/Row');
- if (count($objResult)) {
- foreach($objResult as $objT) {
- if ((integer)$objT->Lock == 0)
- $arrAddressList[] = array(
- 'Channel' => (string)$objT->Channel,
- 'Provider' => (string)$objT->Provider,
- 'Address' => (string)$objT->Address,
- 'FullAddress' => (string)$objT->FullAddress,
- 'Title' => (string)$objT->Title,
- 'Default' => ((integer)$objT->Default == 1),
- );
- }//\\ foreach
- }//\\ if
- return $arrAddressList;
- }//\\ getDynAuthAddressList
- public function getCardLimits($strPAN, $strMBR) {
- $arrLimits = array();
- $objXml = $this->exec('CardLimits', '<PAN>'.$strPAN.'</PAN><MBR>'.$strMBR.'</MBR>');
- $objResult = $objXml->xpath('//Limits/Row');
- if (count($objResult)) {
- foreach($objResult as $objT) {
- $arrLimits[] = array(
- 'Id' => (integer)$objT->Id,
- 'Title' => (string)$objT->Title,
- 'Max' => (string)$objT->Max,
- 'Current' => (integer)$objT->Current,
- 'AtMomentCurrent' => (integer)$objT->AtMomentCurrent,
- 'IsCounter' => (integer)$objT->IsCounter,
- 'PeriodType' => (string)$objT->PeriodType,
- 'Period' => (string)$objT->Period,
- 'PermanentMax' => (string)$objT->PermanentMax,
- );
- }//\\ foreach
- }//\\ if
- return $arrLimits;
- }//\\ getCardLimits
- }//\\ TB
Add Comment
Please, Sign In to add comment