Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Qiwi
- *
- * Класс для прямой работы с QIWI кошельком
- *
- * @link http://phpcurlqiwi.com/
- */
- use DOMDocument;
- use DOMXpath;
- use Exception;
- class QiwiApi
- {
- /**
- *
- * @var int $requestId Содержит в себе номер транзакции при обнаружении поля с SMS подтверждением при платеже
- * Содержит в себе номер заявки на изменение настроек безопасности, если нужно СМС подтверждение отключения
- *
- */
- public $requestId = 0;
- /**
- *
- * @var string $cookieFile Путь к файлу с куками
- *
- * @see Qiwi::setCookieFile()
- *
- */
- public $cookieFile = __DIR__.'/cookie_qiwi.txt';
- /**
- *
- * @var string $proxy Строка с адресом и типом прокси, например socks5://127.0.0.1:9050
- *
- * @see Qiwi::setProxy()
- *
- */
- private $proxy = '';
- private $proxyScheme = '';
- /**
- * @var $aBalances Переменная для совместимости с другим классом
- */
- public $aBalances;
- /**
- *
- * Конструктор
- *
- * Не передавайте этому методу параметры. Они добавлены для совместимости с другим классом.
- * Используйте QiwiWallet::login() и QiwiWallet::setCookieFile() для логина и установки пути к файлу с куками
- *
- * @param string $compatL Сделано для совместимости с другим классом. Используйте Qiwi::login()
- * @param string $compatP Сделано для совместимости с другим классом. Используйте Qiwi::login()
- * @param string $compatC Сделано для совместимости с другим классом. Используйте Qiwi::setCookieFile()
- *
- */
- public function __construct( $compatL = null, $compatP = null, $compatC = '')
- {
- libxml_use_internal_errors(true);
- if( $compatC != '' )
- {
- $this->cookieFile = $compatC;
- }
- if( !is_null( $compatL ) )
- {
- $this->login( $compatL, $compatP );
- $this->aBalances = $this->wallets();
- }
- }
- /**
- *
- * Авторизуется в кошельке, предварительно проверив, что еще не авторизован в нем.
- *
- * @param string $phone Телефон QIWI кошелька
- * @param string $passwd Пароль QIWI кошелька
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function login( $phone, $passwd )
- {
- // Есть ли файл с куками?
- if( !file_exists( $this->cookieFile ) )
- {
- $path = dirname( $this->cookieFile );
- // Если нет, то можно ли писать в папку?
- if( !is_writable( $path ) )
- {
- throw new Exception( 'Не могу создать файл cookie в ' . $path );
- }
- // можно ли в файл писать?
- } elseif( !is_writable( $this->cookieFile ) ) {
- throw new Exception( 'Не могу записать cookie в ' . $this->cookieFile );
- }
- if( $phone[ 0 ] != '+' )
- $phone = '+' . $phone;
- if( $this->isAuthenticated( $phone ) )
- {
- return true;
- }
- // Получение первого тикета
- $loginData = array(
- 'login' => $phone,
- 'password' => $passwd
- );
- $json = @json_decode( $this->requestJSON( 'https://sso.qiwi.com/cas/tgts', $loginData ) );
- // На случай неправильного пароля
- if( isset( $json->entity->error->message ) )
- {
- throw new Exception( $json->entity->error->message );
- }
- if( !isset( $json->entity->ticket ) )
- {
- throw new Exception( 'Failed to get first ticket' );
- }
- // Получение второго тикета
- $loginData = array(
- 'ticket' => $json->entity->ticket,
- 'service' => 'https://qiwi.com/j_spring_cas_security_check',
- );
- $json = @json_decode( $this->requestJSON( 'https://sso.qiwi.com/cas/sts', $loginData ) );
- if( !isset( $json->entity->ticket ) )
- {
- throw new Exception( 'Failed to get second ticket' );
- }
- // Проверка тикета
- $this->request( 'https://qiwi.com/j_spring_cas_security_check?ticket=' . $json->entity->ticket, NULL, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- ),
- )
- );
- if( !$this->isAuthenticated( $phone ) )
- {
- throw new Exception( 'Неизвестная ошибка авторизации' );
- }
- }
- /**
- *
- * Проверяет, авторизован ли кошелек в QIWI
- *
- * @param string $phone Номер кошелька
- *
- * @return bool
- *
- */
- public function isAuthenticated( $phone )
- {
- // Почему-то иногда устаревают куки от https://sso.qiwi.com/cas/tgts и он перестает отдавать тикеты.
- // Проблема решается переавторизацией(TODO: без нее)
- $info = $this->info();
- $json = @json_decode(
- $this->requestJSON( 'https://sso.qiwi.com/cas/tgts', NULL, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/vnd.qiwi.sso-v1+json',
- 'Content-Type: application/json',
- 'DNT: 1',
- )
- )
- )
- );
- if( isset( $info->data->person ) && $info->data->person == floatval( $phone ) && isset( $json->entity->ticket ) && $json->entity->ticket != '' )
- {
- return true;
- }
- return false;
- }
- /**
- *
- * Получает номер телефона(без плюса) с сайта QIWI
- *
- * @throws Exception Выкинет соответствующее исключение, если не авторизован
- *
- * @return string
- *
- */
- public function getPerson()
- {
- $info = $this->info();
- if( isset( $info->data->person ) )
- {
- return $info->data->person;
- } else {
- throw new Exception( 'Я не авторизован в QIWI кошельке' );
- }
- }
- /**
- *
- * Получает информацию о кошельке с сайта QIWI
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return array
- *
- */
- public function info()
- {
- $json = @json_decode(
- $this->requestJSON( 'https://qiwi.com/person/state.action', array(), array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'X-Requested-With: XMLHttpRequest',
- 'DNT: 1',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'QIWI не отвечает (не удается получить инфомацию об аккаунте)' );
- }
- return $json;
- }
- /**
- *
- * Совершает платеж на QIWI кошелек
- *
- * @param string $phone Телефон получателя
- * @param float $amount Сумма
- * @param string $amountCurrency Валюта суммы (RUB, KZT, USD, EUR)
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentQiwi( $phone, $amount, $amountCurrency, $sourceCurrency, $comment = '' )
- {
- if( $phone[ 0 ] != '+' )
- $phone = '+' . $phone;
- $fields = array(
- 'account' => $phone
- );
- return $this->paymentNew( 99, $amount, $amountCurrency, $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на Яндекс.Деньги
- *
- * @param string $account Счет получателя
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentYandex( $account, $amount, $sourceCurrency, $comment = '' )
- {
- $fields = array(
- 'account' => $account
- );
- return $this->paymentNew( 26476, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на рублевый кошелек WebMoney
- *
- * @param string $account Кошелек в формате R1234567890
- * @param float $amount Сумма в рублях
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentWebMoney( $account, $amount, $sourceCurrency, $comment = '' )
- {
- $fields = array(
- 'account' => $account
- );
- return $this->paymentNew( 56, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на банковскую карту
- *
- * @param int $cardNumber номер карточки
- * @param float $amount сумма(float)
- * @param string $amountCurrency Валюта суммы (RUB, KZT, USD, EUR)
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment комментарий к платежу
- * @param string $recieverFirstName имя получателя (нужно только для MasterCard)
- * @param string $recieverLastName фамилия получателя (нужно только для MasterCard)
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentCard( $cardNumber, $amount, $amountCurrency, $sourceCurrency, $comment, $recieverFirstName = '', $recieverLastName = '' )
- {
- // Проверка номера и определение VISA/MC
- $data = array(
- 'cardNumber' => $cardNumber
- );
- $json = @json_decode( $this->request( 'https://qiwi.com/card/detect.action', $data ) );
- if( !isset( $json->code->value ) || !property_exists( $json, 'message' ) )
- {
- throw new Exception( 'Не удалось определить банк получателя' );
- } elseif( $json->code->value != '0' ) {
- throw new Exception( $json->message );
- }
- $provider = $json->message;
- $fields = array(
- 'account' => (string)$cardNumber,
- 'termsId' => (string)$provider,
- 'reg_name_f' => $recieverFirstName,
- 'reg_name' => $recieverLastName
- );
- return $this->paymentNew( $provider, $amount, $amountCurrency, $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет Промсвязьбанка
- *
- * @param int $account Номер счета
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentPromsvyaz( $account, $amount, $sourceCurrency, $comment = '' )
- {
- $fields = array(
- 'account_type' => '9',
- 'mfo' => '044525555',
- 'account' => (string)$account
- );
- return $this->paymentNew( 821, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет Сбербанка
- *
- * @param int $account Номер счета
- * @param int $bik БИК банка
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param int $urgent 0/1 - обычный/срочный платеж
- * @param string $lname Имя
- * @param string $fname Фамилия
- * @param string $mname Отчество
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentSberbank( $account, $bik, $amount, $sourceCurrency, $urgent, $lname, $fname, $mname, $comment = '' )
- {
- $fields = array(
- 'account_type' => '2',
- 'mfo' => (string)$bik,
- 'account' => (string)$account,
- 'urgent' => (string)$urgent,
- 'lname' => $lname,
- 'fname' => $fname,
- 'mname' => $mname
- );
- return $this->paymentNew( 870, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет Альфабанка
- *
- * @param int $account Номер счета
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentAlfabank( $account, $amount, $sourceCurrency, $comment = '' )
- {
- $fields = array(
- 'account_type' => '2',
- 'mfo' => '044525593',
- 'account' => (string)$account
- );
- return $this->paymentNew( 464, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет РусскогоСтандарт'а
- *
- * @param int $account Номер счета
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentRusskiyStandart( $account, $amount, $sourceCurrency, $comment = '' )
- {
- $fields = array(
- 'account_type' => '2',
- 'mfo' => '044583151',
- 'account' => (string)$account
- );
- return $this->paymentNew( 815, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет ВТБ24
- *
- * @param int $account Номер счета
- * @param int $bik БИК банка
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param int $urgent 0/1 - обычный/срочный платеж
- * @param string $lname Имя
- * @param string $fname Фамилия
- * @param string $mname Отчество
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentVtb24( $account, $bik, $amount, $sourceCurrency, $urgent, $lname, $fname, $mname, $comment = '' )
- {
- $fields = array(
- 'account_type' => '2',
- 'mfo' => (string)$bik,
- 'account' => (string)$account,
- 'urgent' => (string)$urgent,
- 'lname' => $lname,
- 'fname' => $fname,
- 'mname' => $mname
- );
- return $this->paymentNew( 816, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет в "Открытие"
- *
- * @param int $account Номер счета
- * @param int $bik БИК банка
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param int $urgent 0/1 - обычный/срочный платеж
- * @param string $lname Имя
- * @param string $fname Фамилия
- * @param string $mname Отчество
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentOtkritie( $account, $bik, $amount, $sourceCurrency, $urgent, $lname, $fname, $mname, $comment = '' )
- {
- $fields = array(
- 'account_type' => '2',
- 'mfo' => (string)$bik,
- 'account' => (string)$account,
- 'urgent' => (string)$urgent,
- 'lname' => $lname,
- 'fname' => $fname,
- 'mname' => $mname
- );
- return $this->paymentNew( 876, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет в Skype
- *
- * @param string $login Логин Skype
- * @param float $amount Сумма в USD
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentSkype( $login, $amount, $sourceCurrency, $comment = '' )
- {
- $fields = array(
- 'account' => $login
- );
- return $this->paymentNew( 23195, $amount, 'USD', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Совершает платеж на счет мобильного телефона
- *
- * @param string $phone Телефон
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentMobile( $phone, $amount, $sourceCurrency, $comment = '' )
- {
- if( $phone[ 0 ] != '+' )
- $phone = '+' . $phone;
- // Загрузить форму
- $response = $this->request( 'https://qiwi.com/payment/mobile.action' );
- // Определить оператора
- $data = array(
- 'phone' => $phone,
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/mobile/detect.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'DNT: 1'
- )
- )
- )
- );
- if( !isset( $json->code->value ) || !property_exists( $json, 'message' ) )
- {
- throw new Exception( 'Не удается определить оператора' );
- } elseif( $json->code->value !== '0' ) {
- throw new Exception( $json->message );
- }
- $provider = $json->message;
- $fields = array(
- 'account' => $this->removeCountryCode( $phone )
- );
- return $this->paymentNew( $provider, $amount, 'RUB', $sourceCurrency, $comment, $fields );
- }
- /**
- *
- * Подтверждает начатый ранее платеж SMS кодом
- *
- * @param int $transaction Номер транзакции для подтверждения получается отловом исключения с текстом AwaitingSMSConfirmation из метода payment.
- * После этого исключения номер окажется в свойстве Qiwi::$transactionForSms
- * @param int $smsCode Код из SMS
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::$transactionForSms
- *
- */
- public function paymentSmsConfirmation( $transaction, $smsCode )
- {
- $data = array(
- 'smsCode' => (string)$smsCode
- );
- $json = @json_decode( $this->requestJSON( 'https://qiwi.com/user/sinap/payments/' . $transaction . '/confirm/proxy.action', $data ) );
- if( !isset( $json->data->status ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI' );
- } elseif( $json->data->status != '200' ) {
- // Если есть ошибка от КИВИ
- if( isset( $json->data->body->message ) )
- {
- throw new Exception( $json->data->body->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при подтверждении платежа' );
- }
- } elseif( !isset( $json->data->body->transaction->state->code ) ) {
- throw new Exception( 'Изменился формат ответа QIWI при подтверждении смской' );
- } elseif( $json->data->body->transaction->state->code != 'Accepted' ) {
- throw new Exception( 'Неизвестная ошибка при подтверждении платежа смской' );
- } elseif( !isset( $json->data->body->paymentId ) ) {
- throw new Exception( 'QIWI больше не отдает номер транзакции при платеже. Платеж совершен.' );
- } else {
- return $json->data->body->paymentId;
- }
- }
- /**
- *
- * Общий платежный метод, используется всеми остальными
- *
- * @param int $provider Код организации получателя
- * @param float $amount Сумма
- * @param string $comment Комментарий
- * @param array $fields Массив с параметрами платежа
- *
- * @throws Exception В случае ошибок выкидывает исключения
- * При обнаружении СМС подтверждения выкидывает исключение с текстом AwaitingSMSConfirmation
- *
- * @return int Возвращает номер транзакции в случае успешного завершения
- *
- * @see Qiwi::paymentSmsConfirmation()
- *
- */
- public function paymentNew( $provider, $amount, $amountCurrency, $sourceCurrency, $comment, $fields )
- {
- $amountCurrencyCode = $this->getCurrencyCode( $amountCurrency );
- $sourceCurrencyCode = $this->getCurrencyCode( $sourceCurrency );
- $data = array(
- 'id' => time() . rand(100, 999),
- 'sum' => array(
- 'amount' => (string)$amount,
- 'currency' => (string)$amountCurrencyCode
- ),
- 'source' => 'account_' . $sourceCurrencyCode,
- 'paymentMethod' => array(
- 'type' => 'Account',
- 'accountId' => (string)$sourceCurrencyCode
- ),
- 'comment' => (string)$comment,
- 'fields' => $fields
- );
- // Сама оплата
- $data[ 'fields' ][ '_meta_pay_partner' ] = '';
- $json = @json_decode(
- $this->requestJSON( 'https://qiwi.com/user/sinap/api/terms/' . $provider . '/payments/proxy.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/vnd.qiwi.v2+json',
- 'Content-Type: application/json; charset=UTF-8',
- 'DNT: 1'
- )
- )
- )
- );
- // на случай ошибок/включенного смс
- if( !isset( $json->data->status ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI' );
- } elseif( $json->data->status != '200' ) {
- if( isset( $json->data->body->message ) )
- {
- throw new Exception( $json->data->body->message );
- } else {
- throw new Exception( 'Неизвестная ошибка QIWI' );
- }
- } elseif( !isset( $json->data->body->transaction->state->code ) ) {
- throw new Exception( 'Изменился формат ответа QIWI' );
- } elseif ( $json->data->body->transaction->state->code == 'AwaitingSMSConfirmation' ) {
- $this->requestId = $json->data->body->id;
- throw new Exception( 'AwaitingSMSConfirmation' );
- } elseif( !isset( $json->data->body->transaction->state->code ) ) {
- throw new Exception( 'Изменился формат ответа QIWI при обычном подтверждении платежа' );
- } elseif( $json->data->body->transaction->state->code != 'Accepted' ) {
- throw new Exception( 'Неизвестная ошибка при обычном подтверждении платежа' );
- } elseif( !isset( $json->data->body->id ) ) {
- throw new Exception( 'QIWI больше не отдает номер транзакции при платеже. Платеж совершен.' );
- } else {
- return $json->data->body->id;;
- }
- }
- /**
- *
- * Переводит валюту между внутренними счетами QIWI
- *
- * @param int $from Откуда (RUB, KZT, USD, EUR)
- * @param int $to Куда (RUB, KZT, USD, EUR)
- * @param float $amount Сумма в конечной валюте
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function convertCurrency( $from, $to, $amount )
- {
- $cash = explode( '.', number_format( $amount, 2 ) );
- // Загрузить форму
- $this->request( 'https://qiwi.com/settings/account/transfer.action?paymentModeType=QIWI' );
- // Получить первый токен
- $data = array(
- 'extra' => array(
- '\'account\'' => $this->getPerson()
- ),
- 'source' => 'qiwi_' . $from,
- 'amountInteger' => $cash[ 0 ],
- 'amountFraction' => $cash[ 1 ],
- 'currency' => $to,
- 'state' => 'CONFIRM',
- 'protected' => 'true',
- 'destination' => 'qiwi_' . $to,
- );
- $response = $this->request( 'https://qiwi.com/user/person/account/state.action', $data );
- if( !preg_match( '/name=\"token\" value=\"([\-0-9]+)\"/i', $response, $matches ) )
- {
- throw new Exception( 'Не удалось получить токен для начала платежа' );
- }
- // Отправить токен
- $data[ 'token' ] = $matches[ 1 ];
- $response = $this->request( 'https://qiwi.com/user/person/account/state.action', $data );
- // Получить второй токен
- $data = array(
- 'state' => 'PAY'
- );
- $response = $this->request( 'https://qiwi.com/user/person/account/state.action', $data );
- if( !preg_match( '/name=\"token\" value=\"([\-0-9]+)\"/i', $response, $matches ) )
- {
- throw new Exception( 'Не удалось получить токен для начала платежа' );
- }
- // Подтверждение перевода
- $data[ 'token' ] = $matches[ 1 ];
- $response = $this->request( 'https://qiwi.com/user/person/account/state.action', $data );
- if( mb_strpos( $response, 'transaction":"' ) === false )
- {
- throw new Exception( 'Неизвестная ошибка при переводе между счетами' );
- }
- }
- /**
- *
- * Получает список транзакций
- *
- * @param string $direction Направление - in/out/inout (входящие/исходящие/все)
- * @param string $from От какой даты в формате ДД.ММ.ГГГГ
- * @param string $to До какой даты в формате ДД.ММ.ГГГГ
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return array Возвращает массив с транзакциями
- *
- */
- public function transactions( $direction, $from, $to )
- {
- $transactionsData = array(
- 'daterange' => 'true',
- 'start' => $from,
- 'finish' => $to
- );
- // todo
- if( $direction != 'inout' )
- {
- $transactionsData[ 'settings' ] = 'true';
- $transactionsData[ 'conditions.directions' ] = $direction;
- }
- $response = $this->request( 'https://qiwi.com/user/report/list.action', $transactionsData );
- if( $response == '' )
- {
- throw new Exception( 'Не удалось получить список транзакций' );
- }
- $doc = new DOMDocument();
- if( !@$doc->loadHTML( mb_convert_encoding( $response, 'HTML-ENTITIES', 'UTF-8' ) ) )
- {
- foreach ( libxml_get_errors() as $error )
- {
- throw new Exception( $error->message );
- }
- libxml_clear_errors();
- }
- $transactions = array( );
- // Собсно блоки с транзакциями
- $xpath = new DOMXpath( $doc );
- $results = $xpath->query( '//div[@class="reportsLine status_SUCCESS"]' );
- if( $results->length > 0 )
- {
- foreach( $results as $row)
- {
- $transaction = array( );
- // Номер транзакции
- $result = $xpath->query( './/div[@class="transaction"]', $row );
- $transaction[ 'transaction' ] = trim( $result->item( 0 )->nodeValue );
- // Дата транзакции в формате ДД.ММ.ГГГГ
- $result = $xpath->query( './/span[@class="date"]', $row );
- $transaction[ 'date' ] = trim( $result->item( 0 )->nodeValue );
- // Время транзакции в формате ЧЧ.ММ.СС
- $result = $xpath->query( './/span[@class="time"]', $row );
- $transaction[ 'time' ] = trim( $result->item( 0 )->nodeValue );
- // Сумма
- $result = $xpath->query( './/div[@class="cash"]', $row );
- $transaction[ 'cash' ] = str_replace( ',', '.', $this->parseFloatFromCash( trim( $result->item( 0 )->nodeValue ) ) );
- // Валюта прихода
- $transaction[ 'currency' ] = $this->determineCurrencyFromCash( $result->item( 0 )->nodeValue );
- // Сумма в оригинальной валюте
- $result = $xpath->query( './/div[@class="originalExpense"]/span', $row );
- $transaction[ 'originalCash' ] = str_replace( ',', '.', $this->parseFloatFromCash( trim( $result->item( 0 )->nodeValue ) ) );
- // Оригинальная валюта
- $transaction[ 'originalCurrency' ] = $this->determineCurrencyFromCash( $result->item( 0 )->nodeValue );
- // Иденификатор отправителя(как правило телефон)
- $result = $xpath->query( './/span[@class="opNumber"]', $row );
- $transaction[ 'opNumber' ] = trim( $result->item( 0 )->nodeValue );
- // Провайдер
- $result = $xpath->query( './/div[@class="provider"]/span[1]', $row );
- $transaction[ 'provider' ] = trim( $result->item( 0 )->nodeValue );
- // Комментарий
- $result = $xpath->query( './/div[@class="comment"]', $row );
- $transaction[ 'comment' ] = trim( $result->item( 0 )->nodeValue );
- // Направление
- $result = $xpath->query( './/div[@class="IncomeWithExpend income"]', $row );
- $transaction[ 'incoming' ] = ( $result->length > 0 ) ? true : false;
- $transactions[] = $transaction;
- }
- }
- return $transactions;
- }
- /**
- *
- * Покупает ваучер
- *
- * @param float $amount Сумма
- * @param string $sourceCurrency Счет, с которого будет произведена оплата(RUB, KZT, USD, EUR)
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return string Возвращает код купленного ваучера
- *
- */
- public function buyEgg( $amount, $sourceCurrency, $comment = '' )
- {
- // Проверка валюты
- $this->getCurrencyCode( $sourceCurrency );
- // $ и центы
- $cash = explode( '.', number_format( $amount, 2, '.', '' ) );
- // Загрузить форму
- $response = $this->request( 'https://qiwi.com/eggs/buy/content/form.action' );
- // Получить первый токен
- $data = array(
- 'extra' => array(
- '\'to_account\'' => '',
- '\'to_account_type\'' => 'undefind',
- '\'account\'' => '708',
- '\'comment\'' => $comment
- ),
- 'source' => 'qiwi_' . $sourceCurrency,
- 'amountInteger' => $cash[ 0 ],
- 'amountFraction' => $cash[ 1 ],
- 'currency' => 'RUB',
- 'state' => 'CONFIRM',
- 'protected' => 'true'
- );
- $response = $this->request( 'https://qiwi.com/user/payment/form/state.action', $data );
- if( !preg_match( '/name=\"token\" value=\"([\-0-9]+)\"/i', $response, $matches ) )
- {
- throw new Exception( 'Не удалось получить токен для открытия подтверждения покупки ваучера' );
- }
- $data[ 'token' ] = $matches[ 1 ];
- $data[ 'expire_days' ] = '2';
- // Точно ли это страница с кнопкой подтвердить
- $response = $this->request( 'https://qiwi.com/user/payment/form/state.action', $data );
- if( strpos( 'Подтвердить', $response ) )
- {
- throw new Exception( 'Не удалось перейти к подтверждению покупки ваучера' );
- }
- // И собственно подтверждение перевода
- $data = array(
- 'state' => 'PAY'
- );
- $response = $this->request( 'https://qiwi.com/user/payment/form/state.action', $data );
- if( !preg_match( '/name=\"token\" value=\"([\-0-9]+)\"/i', $response, $matches ) )
- {
- throw new Exception( 'Не удалось получить токен для подтверждения оплаты ваучера' );
- }
- $data[ 'token' ] = $matches[ 1 ];
- // Получение кода ваучера
- $response = $this->request( 'https://qiwi.com/user/payment/form/state.action', $data );
- if( !preg_match( '/Код ваучера: ([a-z0-9]+)/i', $response, $matches ) )
- {
- throw new Exception( 'Не удалось получить токен для подтверждения оплаты ваучера' );
- }
- return $matches[ 1 ];
- }
- /**
- *
- * Активирует ваучер
- *
- * @param string $code Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return array Возвращает массив c информацией об активированном ваучере
- *
- */
- public function activateEgg( $code )
- {
- // Активация
- $data = array(
- 'code' => $code
- );
- $response = $this->request( 'https://qiwi.com/user/eggs/activate/content/form.action', $data );
- if( !preg_match( '/name=\"token\" value=\"([\-0-9]+)\"/i', $response, $matches ) )
- {
- throw new Exception( 'Не удалось получить токен для открытия подтверждения активации ваучера' );
- }
- $data[ 'token' ] = $matches[ 1 ];
- $response = $this->request( 'https://qiwi.com/user/eggs/activate/content/form.action', $data );
- if( !preg_match( '/<h2>(.*)<\/h2>/is', $response, $matches ) )
- {
- throw new Exception( 'Не удалось определить сумму ваучера' );
- }
- $info = array(
- 'cash' => $this->parseFloatFromCash( $matches[ 1 ] ),
- 'currency' => $this->determineCurrencyFromCash( $matches[ 1 ] )
- );
- $json = @json_decode( $this->request( 'https://qiwi.com/user/eggs/activate/content/activate.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'DNT: 1'
- )
- )
- )
- );
- if( !isset( $json->code->value ) || $json->code->value != '0' )
- {
- throw new Exception( 'Не удалось активировать ваучер' );
- }
- return $info;
- }
- /**
- *
- * Выставляет счет
- *
- * @param string $to Кому выставляется счет
- * @param float $amount Сумма
- * @param string $currency Валюта
- * @param string $comment Необязательный комментарий
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function createInvoice( $to, $amount, $currency, $comment = '' )
- {
- // Загрузить форму
- $this->request( 'https://qiwi.com/order/form.action' );
- // Рубли и копейки
- $cash = explode( '.', number_format( $amount, 2, '.', '' ) );
- // Получение токена
- $data = array(
- 'to' => $to,
- 'value' => $cash[ 0 ],
- 'change' => $cash[ 1 ],
- 'amount' => $amount,
- 'currency' => $currency,
- 'comment' => $comment
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/order/create.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->data->token ) || !preg_match( '/([0-9]+)/', $json->data->token ) )
- {
- throw new Exception( 'Не удалось получить токен для выставления счета' );
- }
- // Собственно выставление
- $data[ 'token' ] = $json->data->token;
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/order/create.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI при выставлении счета' );
- } elseif( $json->code->value != '0' ) {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при выставлении счета' );
- }
- }
- }
- /**
- *
- * Получает список входящих счетов
- *
- * @param string $start От какой даты
- * @param string $finish До какой даты
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return array Возвращает массив со счетами
- *
- */
- public function listInvoices( $start, $finish )
- {
- // Текущий номер
- $person = $this->getPerson();
- $data = array(
- 'daterange' => 'true',
- 'start' => $start,
- 'finish' => $finish
- );
- $data[ 'conditions.directions' ][] = 'in';
- $data[ 'conditions.directions' ][] = 'out';
- $response = $this->request( 'https://qiwi.com/user/order/list.action', $data );
- $doс = new DOMDocument();
- if( !$doс->loadHTML( mb_convert_encoding( $response, 'HTML-ENTITIES', 'UTF-8' ) ) )
- {
- foreach ( libxml_get_errors() as $error )
- {
- throw new Exception( $error->message );
- }
- libxml_clear_errors();
- }
- $unpaid = array();
- // Оплаченные, отмененные, неоплаченные
- $xpath = new DOMXpath( $doс );
- $results = $xpath->query('//div[contains(@class, "PAID") or contains(@class, "CANCELED")]');
- if( $results->length > 0 )
- {
- foreach( $results as $row )
- {
- $invoice = array( );
- $invoice[ 'state' ] = substr( $row->getAttribute( 'class' ), 18 );
- // ID (есть только у неоплаченных)
- if( $invoice[ 'state' ] == 'NOT_PAID' )
- {
- $result = $xpath->query( './/div[@class="cancelOperation"]', $row );
- $data_params_attribute = $result->item( 0 )->getAttribute( 'data-params' );
- if( !preg_match( '/{"data":{"order":"([0-9]+)"}}/', $data_params_attribute, $matches ) )
- {
- continue;
- }
- $invoice[ 'id' ] = $matches[ 1 ];
- } else {
- $invoice[ 'id' ] = 0;
- }
- // Номер транзакции
- $result = $xpath->query( './/div[@class="transaction"]', $row );
- $invoice[ 'transaction' ] = trim( $result->item( 0 )->nodeValue );
- // Кому
- $result = $xpath->query( './/div[@class="to"]', $row );
- $to = $result->item( 0 )->nodeValue;
- if( $to == '' )
- {
- $invoice[ 'direction' ] = 'in';
- } else {
- $invoice[ 'direction' ] = 'out';
- }
- $invoice[ 'to' ] = $to;
- // Создано
- $result = $xpath->query( './/div[@class="orderCreationDate"]', $row );
- $invoice[ 'orderCreationDate' ] = trim( $result->item( 0 )->nodeValue );
- // От кого
- $result = $xpath->query( './/div[@class="from"]/span', $row );
- $invoice[ 'from' ] = trim( $result->item( 0 )->nodeValue );
- // Комментарий
- $result = $xpath->query( './/span[@class="commentItem"]', $row );
- $invoice[ 'comment' ] = trim( $result->item( 0 )->nodeValue );
- // Сумма
- $result = $xpath->query( './/div[@class="amount"]', $row );
- $invoice[ 'cash' ] = str_replace( ',', '.', $this->parseFloatFromCash( trim( $result->item( 0 )->nodeValue ) ) );
- // Валюта прихода
- $invoice[ 'currency' ] = $this->determineCurrencyFromCash( $result->item( 0 )->nodeValue );
- $unpaid[] = $invoice;
- }
- }
- return $unpaid;
- }
- /**
- *
- * Оплачивает счет
- *
- * @param int $id ID счета
- * @param string $currency Валюта
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function payInvoice( $id, $currency = 'RUB' )
- {
- // Загрузка формы оплаты
- $data = array(
- 'order' => $id
- );
- $this->request( 'https://qiwi.com/user/order/payment.action', $data );
- // Получение токена
- $data[ 'source' ] = 'qiwi_' . $currency;
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/order/accept.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->data->token ) || !preg_match( '/([0-9]+)/', $json->data->token ) )
- {
- throw new Exception( 'Не удалось получить токен для выставления счета' );
- }
- // Собственно выставление
- $data[ 'token' ] = $json->data->token;
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/order/accept.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI при выставлении счета' );
- } elseif( $json->code->value != '5' ) {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при выставлении счета' );
- }
- }
- }
- /**
- *
- * Первый этап регистрации.
- *
- * Загружает форму и картику с кодом. Картинка по умолчанию сохраняется в signup_captcha.png.
- *
- * @param string $path Путь к картинке
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function signupStepOne( $path = 'signup_captcha.png' )
- {
- // Есть ли файл уже?
- if( !file_exists( $path ) )
- {
- $pathDir = dirname( $path );
- // Если нет, то можно ли писать в папку?
- if( !is_writable( $pathDir ) )
- {
- throw new Exception( 'Не могу сохранить картинку с капчей в ' . $path );
- }
- // можно ли в файл писать?
- } elseif( !is_writable( $path ) ) {
- throw new Exception( 'Не могу сохранить картинку с капчей в ' . $path );
- }
- // Загрузка формы
- $response = $this->request( 'https://qiwi.com/register/form.action' );
- // Загрузка капчи
- file_put_contents( $path, $this->request( 'https://qiwi.com/register/captcha.action?random=0.' . time() ) );
- // Проверка капчи
- $finfo = finfo_open( FILEINFO_MIME_TYPE );
- $mime = finfo_file( $finfo, $path );
- if( $mime != 'image/png' )
- {
- throw new Exception( 'Не удалось загрузить картинку с капчей' );
- }
- }
- /**
- *
- * Второй этап регистрации.
- *
- * Отправляет заявку на регистрацию.
- *
- * @param string $phone Телефон
- * @param string $captcha Код с картинки из Qiwi::signupStepOne()
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return int Уникальный идентификатор заявки на регистрацию. Нужен для ее завершения в Qiwi::signupStepThree()
- *
- */
- public function signupStepTwo( $phone, $captcha )
- {
- if( $phone[ 0 ] != '+' )
- $phone = '+' . $phone;
- $data = array(
- 'login' => $phone,
- 'captcha' => $captcha,
- 'agreement' => 'true'
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/register/main.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->data->token ) || !preg_match( '/([0-9]+)/', $json->data->token ) )
- {
- throw new Exception( 'Не удалось получить токен для начала регистрации' );
- }
- // Собственно выставление
- $data[ 'token' ] = $json->data->token;
- $json = @json_decode(
- $this->request( 'https://qiwi.com/register/main.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->data ) || is_object( $json->data ) || !preg_match( '/([0-9]+)/', $json->data ) )
- {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Не удалось получить уникальный идентификатор этого процесса регистрации' );
- }
- }
- return $json->data;
- }
- /**
- *
- * Третий этап регистрации.
- *
- * Подтверждает регистрацию с SMS.
- *
- * @param int $identifier Код, полученный из Qiwi::signupStepTwo()
- * @param int $smsCode Код из SMS
- * @param string $phone Телефон
- * @param string $passwd Пароль
- * @param int $period Cрок действия 1/3/6/12 месяцев
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function signupStepThree( $identifier, $smsCode, $phone, $passwd, $period = 12 )
- {
- $periodCodes = array(
- 1 => 1,
- 3 => 2,
- 6 => 3,
- 12 => 4
- );
- if( $phone[ 0 ] != '+' )
- $phone = '+' . $phone;
- $data = array(
- 'identifier' => $identifier,
- 'type' => 'REGISTER',
- 'phone' => $phone,
- 'code' => $smsCode,
- 'data[\'login\']' => $phone,
- 'data[\'newPassword\']' => $passwd,
- 'data[\'newPasswordRepeat\']' => $passwd,
- 'data[\'period\']' => $periodCodes[ $period ],
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/confirmation/confirm.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- 'Referer: https://qiwi.com/register/password.action?identifier=' . $identifier
- )
- )
- )
- );
- if( !isset( $json->code->value ) || $json->code->value != '0' )
- {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при регистрации' );
- }
- }
- }
- /**
- *
- * Запрос привязки почты
- *
- * @param string $email Почта
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function requestEmailConfirmation( $email )
- {
- // Получение токена
- $data = array(
- 'mail' => $email,
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/person/email/create/send.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->data->token ) || !preg_match( '/([0-9]+)/', $json->data->token ) )
- {
- throw new Exception( 'Не удалось получить токен для запроса привязки почты' );
- }
- // Собственно запрос
- $data[ 'token' ] = $json->data->token;
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/person/email/create/send.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI при запросе привязки почты' );
- } elseif( $json->code->value != '0' ) {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при запросе привязки почты' );
- }
- }
- }
- /**
- *
- * Подтверждает привязку почты
- *
- * @param string $code Код подтверждения с почты
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function confirmEmail( $code )
- {
- $response = $this->request( 'https://qiwi.com/settings/options/security/email/create.action?code=' . $code );
- if( !strpos( $response, 'привязана' ) )
- {
- throw new Exception( 'Ошибка при привязке почты' );
- }
- }
- /**
- *
- * Запрос на изменение настроек безопасности
- *
- * SMS_CONFIRMATION - Подтверждение платежей по SMS
- * TOKEN - Приложения Visa QIWI Wallet
- * PIN - Доступ в терминалах QIWI по PIN коду
- * SMS_PAYMENT - SMS платежи
- * CALL_CONFIRMATION - Подтверждение по USSD (Терминалы QIWI)
- *
- * @param string $type Код настройки(SMS_CONFIRMATION/TOKEN/PIN/SMS_PAYMENT/CALL_CONFIRMATION)
- * @param string $value true/false
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return int Идентификатор заявки на отлючение
- *
- * @see Qiwi::confirmSecurityChange()
- *
- */
- public function requestSecurityChange( $type, $value )
- {
- // Получение токена
- $data = array(
- 'type' => $type,
- 'value' => $value
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/person/change/security.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->data->token ) || !preg_match( '/([0-9]+)/', $json->data->token ) )
- {
- throw new Exception( 'Не удалось получить токен для запроса на отключение ' . $type );
- }
- // Собственно запрос
- $data[ 'token' ] = $json->data->token;
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/person/change/security.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI при запросе на отключение ' . $type );
- } elseif( $json->code->value == '0' && isset( $json->identifier ) ) {
- return $json->identifier;
- } elseif( $json->code->value == '4' && isset( $json->identifier ) ) {
- $this->requestId = $json->identifier;
- throw new Exception( 'AwaitingSMSConfirmation' );
- } else {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при запросе на отключение ' . $type );
- }
- }
- }
- /**
- *
- * Подтверждение изменения настроек безопасности
- *
- * SMS_CONFIRMATION - Подтверждение платежей по SMS
- * TOKEN - Приложения Visa QIWI Wallet
- * PIN - Доступ в терминалах QIWI по PIN коду
- * SMS_PAYMENT - SMS платежи
- * CALL_CONFIRMATION - Подтверждение по USSD (Терминалы QIWI)
- *
- * @param string $type Код настройки(SMS_CONFIRMATION/TOKEN/PIN/SMS_PAYMENT/CALL_CONFIRMATION)
- * @param int $identifier Идентивикатор заявки, полученный из Qiwi::requestSecurityChange()
- * @param int $smsCode Код из SMS
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- * @see Qiwi::requestSecurityChange()
- *
- */
- public function confirmSecurityChange( $type, $identifier, $smsCode )
- {
- $data = array(
- 'identifier' => $identifier,
- 'type' => $type,
- 'code' => $smsCode
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/confirmation/confirm.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI при подтверждении изменения ' . $type );
- } elseif( $json->code->value != '0' ) {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при подтверждении изменения ' . $type );
- }
- }
- }
- /**
- *
- * Создает заявку на смену пароля.
- *
- * Полученный идентификатор заявки надо передать в QiwiWallet::confirmPasswordChange()
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return int Идентификатор заявки
- *
- * @see QiwiWallet::confirmPasswordChange()
- *
- */
- public function requestPasswordChange( )
- {
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/person/change/password.action', array( 0 ), array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->identifier ) || !preg_match( '/([0-9]+)/', $json->identifier ) )
- {
- throw new Exception( 'Не удалось создать заявку на смену пароля' );
- }
- return $json->identifier;
- }
- /**
- *
- * Подтверждает заявку на смену пароля.
- *
- * @param int $identifier Идентификатор заявки, полученный в QiwiWallet::requestPasswordChange()
- * @param string $old Старый пароль
- * @param string $new Новый пароль
- * @param int $period Cрок действия 1/3/6/12 месяцев
- * @param int $code Код из SMS
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- * @see QiwiWallet::confirmPasswordChange()
- *
- */
- public function confirmPasswordChange( $identifier, $old, $new, $period, $code )
- {
- $periodCodes = array(
- 1 => 1,
- 3 => 2,
- 6 => 3,
- 12 => 4
- );
- $data = array(
- 'identifier' => $identifier,
- 'type' => 'PASSWORD_CHANGE',
- 'code' => $code,
- 'data[\'oldPassword\']' => $old,
- 'data[\'newPassword\']' => $new,
- 'data[\'period\']' => $periodCodes[ $period ],
- );
- $json = @json_decode(
- $this->request( 'https://qiwi.com/user/confirmation/confirm.action', $data, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json, text/javascript, */*; q=0.01',
- 'DNT: 1',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- )
- )
- )
- );
- if( !isset( $json->code->value ) )
- {
- throw new Exception( 'Неверный формат ответа QIWI при подтверждении изменения ' . $type );
- } elseif( $json->code->value != '0' ) {
- if( isset( $json->message ) )
- {
- throw new Exception( $json->message );
- } else {
- throw new Exception( 'Неизвестная ошибка при подтверждении изменения ' . $type );
- }
- }
- }
- /**
- *
- * Отправляет данные о пользователе для упрощенной идентификации
- *
- * @param string $firstName Имя
- * @param string $lastName Фамилия
- * @param string $middleName Отчество
- * @param string $birthDate Дата рождения (ДД.ММ.ГГГГ)
- * @param int $passport Номер и серия паспорта
- * @param int $inn ИНН
- * @param int $snils СНИЛС
- * @param int $oms Полис ОМС
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return void
- *
- */
- public function identificationLevelTwo( $firstName, $lastName, $middleName, $birthDate, $passport, $inn, $snils, $oms )
- {
- // Запрос тикета
- $json = @json_decode( $this->requestJSON( 'https://sso.qiwi.com/cas/tgts' ) );
- if( !isset( $json->entity->ticket ) || !isset( $json->links[0]->href ) )
- {
- throw new Exception( 'QIWI не отвечает (sso tgts при идентификации)' );
- }
- $tgtsTicket = $json->entity->ticket;
- // Отправка тикета
- $data = array(
- 'ticket' => $tgtsTicket,
- 'service' => 'https://qiwi.com/j_spring_cas_security_check'
- );
- $json = @json_decode( $this->requestJSON( 'https://sso.qiwi.com/cas/sts', $data ) );
- if( !isset( $json->entity->ticket ) )
- {
- throw new Exception( 'QIWI не отвечает (sso sts при идентификации)' );
- }
- // PUT
- $data = array(
- 'firstName' => $firstName,
- 'lastName' => $lastName,
- 'middleName' => $middleName,
- 'birthDate' => $birthDate,
- 'passport' => $passport,
- );
- $string = json_encode( $data, JSON_FORCE_OBJECT );
- // Тут нужно отправить тикет, полученный в предыдущем запросе
- $response = $this->requestPUT( 'https://qiwi.com/rest/identifications/' . $this->getPerson(), $string, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json',
- 'Content-Type: application/json',
- 'Authorization: Token ' . $json->entity->ticket,
- 'Content-Length: ' . strlen( $string ),
- 'DNT: 1'
- )
- )
- );
- if( $response !== 200 )
- {
- throw new Exception( 'Ошибка при отправке первой пачки данных идентификации' );
- }
- // Запрос тикета
- $json = @json_decode( $this->requestJSON( 'https://sso.qiwi.com/cas/tgts' ) );
- if( !isset( $json->entity->ticket ) || !isset( $json->links[0]->href ) )
- {
- throw new Exception( 'QIWI не отвечает (sso tgts при идентификации)' );
- }
- $tgtsTicket = $json->entity->ticket;
- // Отправка тикета
- $data = array(
- 'ticket' => $tgtsTicket,
- 'service' => 'https://qiwi.com/j_spring_cas_security_check'
- );
- $json = @json_decode( $this->requestJSON( 'https://sso.qiwi.com/cas/sts', $data ) );
- if( !isset( $json->entity->ticket ) )
- {
- throw new Exception( 'QIWI не отвечает (sso sts при идентификации)' );
- }
- // PUT
- $data = array(
- 'inn' => $inn,
- 'snils' => $snils,
- 'oms' => $oms,
- );
- $string = json_encode( $data, JSON_FORCE_OBJECT );
- // Тут нужно отправить тикет, полученный в предыдущем запросе
- $response = $this->requestPUT( 'https://qiwi.com/rest/identifications/' . $this->getPerson() . '/docs', $string, array(
- CURLOPT_HTTPHEADER => array(
- 'Accept: application/json',
- 'Content-Type: application/json',
- 'Authorization: Token ' . $json->entity->ticket,
- 'Content-Length: ' . strlen( $string ),
- 'DNT: 1'
- )
- )
- );
- if( $response !== 200 )
- {
- throw new Exception( 'Ошибка при отправке второй пачки данных идентификации' );
- }
- }
- /**
- *
- * Определяет, включено ли СМС подтверждение
- *
- * Возвращает true, если смс подтверждение включено и false в противном случае(даже если не удалось загрузить страницу настроек).
- * ВНИМАНИЕ! Киви продолжает отдавать старый статус смс подтверждения вплоть до перелогина.
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return bool
- *
- */
- public function isSmsOn ()
- {
- $response = $this->request( 'https://qiwi.com/settings/options/security.action' );
- if( $response == '' )
- {
- return false;
- }
- $doс = new DOMDocument();
- if( !$doс->loadHTML( mb_convert_encoding( $response, 'HTML-ENTITIES', 'UTF-8' ) ) )
- {
- foreach ( libxml_get_errors() as $error )
- {
- throw new Exception( $error->message );
- }
- libxml_clear_errors();
- }
- $xpath = new DOMXpath( $doс );
- $results = $xpath->query('//div[@class="security-settings-item type_SMS_CONFIRMATION"]/div[@data-container-name="option-enabled"]');
- if( $results->length > 0 )
- {
- if( $results->item(0)->getAttribute( 'style' ) == '' )
- {
- return true;
- }
- }
- return false;
- }
- /**
- *
- * Получает информацию о деньгах на счетах
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return array
- *
- */
- public function wallets()
- {
- $info = $this->info();
- if( $info->code->value !== '0' || !isset( $info->data->balances ) )
- {
- throw new Exception( 'Не удалось получить баланс кошелька' );
- }
- return (array)$info->data->balances;
- }
- /**
- *
- * Определяет статус идентификации
- *
- * @throws Exception В случае ошибок выкидывает исключения
- *
- * @return string|bool Если все хорошо, вернет anonymous/standart/maximum.
- * Если не удалось определить, вернет false
- *
- */
- public function getStatus()
- {
- $response = $this->request( 'https://qiwi.com/settings.action' );
- $types = array( 'anonymous', 'standart', 'maximum', false );
- $doс = new DOMDocument();
- if( !$doс->loadHTML( mb_convert_encoding( $response, 'HTML-ENTITIES', 'UTF-8' ) ) )
- {
- foreach ( libxml_get_errors() as $error )
- {
- throw new Exception( $error->message );
- }
- libxml_clear_errors();
- }
- $xpath = new DOMXpath( $doс );
- $results = $xpath->query( '//ul[@class="list_three_cols types_list"]/li' );
- $i = 0;
- if( $results->length > 0 )
- {
- foreach( $results as $node )
- {
- if( strpos( $node->getAttribute( 'class' ), 'active' ) !== false )
- {
- break;
- }
- $i++;
- }
- } else {
- $i = 3;
- }
- return $types[ $i ];
- }
- /**
- *
- * Задает прокси
- *
- * @param string $string Например socks5://127.0.0.1:9050
- *
- * @return void
- *
- */
- public function setProxy( $string )
- {
- $params = parse_url( $string );
- $this->proxyScheme = $params[ 'scheme' ];
- $this->proxy = $string;
- }
- /**
- *
- * Устанавливает путь к файлу с куками
- *
- * @param string $path
- *
- * @return void
- *
- */
- public function setCookieFile( $path )
- {
- $this->cookieFile = $path;
- }
- /**
- *
- * Удаляет файл с куками
- *
- * @return void
- *
- */
- public function removeCookieFile( )
- {
- unlink( $this->cookieFile );
- }
- /**
- *
- * Делает обыкновенный запрос, заворачивая данные в http_build_query
- *
- * При POST запросе отсылает следующие заголовки:
- * 'Accept: text/html, *\/ *; q=0.01'
- * 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
- * 'X-Requested-With: XMLHttpRequest'
- * 'DNT: 1'
- *
- * @param string $url Адрес
- * @param array $postArray Массив данных
- * @param array $options Массив параметров CURL
- *
- * @return string|bool
- *
- */
- public function request( $url, $postArray = null, $options = null )
- {
- if( is_array( $postArray ) )
- {
- $postArray = http_build_query( $postArray );
- $postArray = preg_replace( '/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $postArray );
- }
- $curl = curl_init();
- curl_setopt( $curl, CURLOPT_URL, $url );
- curl_setopt( $curl, CURLOPT_COOKIEFILE, $this->cookieFile );
- curl_setopt( $curl, CURLOPT_COOKIEJAR, $this->cookieFile );
- curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
- curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, false );
- curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
- curl_setopt( $curl, CURLOPT_HEADER, 0 );
- curl_setopt( $curl, CURLOPT_PROXY, $this->proxy );
- if( $this->proxyScheme == 'socks5' )
- {
- curl_setopt( $curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5 );
- }
- if( $postArray )
- {
- curl_setopt( $curl, CURLOPT_POST, 1 );
- curl_setopt( $curl, CURLOPT_POSTFIELDS, $postArray );
- curl_setopt( $curl, CURLOPT_HTTPHEADER, array (
- 'Accept: text/html, */*; q=0.01',
- 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- 'DNT: 1'
- )
- );
- }
- if( is_array( $options ) && count( $options ) )
- {
- curl_setopt_array( $curl, $options );
- }
- $response = curl_exec( $curl );
- curl_close( $curl );
- if( $response === false )
- {
- throw new Exception( 'QIWI не отвечает на запрос' );
- }
- return $response;
- }
- /**
- *
- * Делает PUT запрос
- *
- * @param string $url Адрес
- * @param string $fields Строка с данными
- * @param array $options Массив параметров CURL
- *
- * @return int HTTP статус ответа
- *
- */
- public function requestPUT( $url, $fields, $options )
- {
- if( $curl = curl_init( $url ) )
- {
- curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'PUT' );
- curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
- curl_setopt( $curl, CURLOPT_POSTFIELDS, $fields );
- curl_setopt( $curl, CURLOPT_PROXY, $this->proxy );
- if( $this->proxyScheme == 'socks5' )
- {
- curl_setopt( $curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5 );
- }
- if( is_array( $options ) && count( $options ) )
- {
- curl_setopt_array( $curl, $options );
- }
- curl_exec( $curl );
- $status = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
- curl_close( $curl );
- return (int) $status;
- } else {
- return false;
- }
- }
- /**
- *
- * Делает обыкновенный запрос, заворачивая данные в json_encode
- *
- * При POST запросе отсылает следующие заголовки:
- * 'Accept: application/vnd.qiwi.sso-v1+json'
- * 'Content-Type: application/json; charset=UTF-8'
- * 'X-Requested-With: XMLHttpRequest'
- * 'DNT: 1'
- *
- * @param string $url Адрес
- * @param array $postArray Массив данных
- * @param array $options Массив параметров CURL
- *
- * @return string|bool
- *
- */
- public function requestJSON( $url, $postArray = null, $options = null )
- {
- if( is_array( $postArray ) )
- $postArray = json_encode( $postArray, JSON_FORCE_OBJECT );
- $curl = curl_init();
- curl_setopt( $curl, CURLOPT_URL, $url );
- curl_setopt( $curl, CURLOPT_COOKIEFILE, $this->cookieFile );
- curl_setopt( $curl, CURLOPT_COOKIEJAR, $this->cookieFile );
- curl_setopt( $curl, CURLOPT_HTTPHEADER, array (
- 'Accept: application/vnd.qiwi.sso-v1+json',
- 'Content-Type: application/json; charset=UTF-8',
- 'X-Requested-With: XMLHttpRequest',
- 'DNT: 1'
- )
- );
- curl_setopt( $curl, CURLOPT_HEADER, 0 );
- curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
- curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, false );
- curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
- curl_setopt( $curl, CURLOPT_PROXY, $this->proxy );
- if( $this->proxyScheme == 'socks5' )
- {
- curl_setopt( $curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5 );
- }
- if( $postArray )
- {
- curl_setopt( $curl, CURLOPT_POST, 1 );
- curl_setopt( $curl, CURLOPT_POSTFIELDS, $postArray );
- }
- if( is_array( $options ) && count( $options ) )
- {
- curl_setopt_array( $curl, $options );
- }
- $response = curl_exec( $curl );
- curl_close( $curl );
- if( $response === false )
- {
- throw new Exception( 'QIWI не отвечает на запрос' );
- }
- return $response;
- }
- /**
- *
- * Вытаскивает из строки вида 1 000 000, 13 руб только числа и запятую, например 100000,13
- *
- * @param string $str
- *
- * @return string
- *
- */
- public function parseFloatFromCash( $str )
- {
- $out = '';
- $symbol = null;
- for( $i = 0; $i < strlen( $str ); $i++ )
- {
- $symbol = $str[ $i ];
- if( is_numeric( $symbol ) || $symbol == ',' )
- $out .= $symbol;
- }
- return $out;
- }
- /**
- *
- * Определяет валюту по строке вида 1 000 000, 13 руб
- *
- * @param string $str
- *
- * @return string|null RUB, EUR, KZT, USD
- *
- */
- public function determineCurrencyFromCash( $str )
- {
- $list = array( 'руб' => 'RUB', 'евро' => 'EUR', 'тенге' => 'KZT', 'долл' => 'USD' );
- foreach( $list as $key => $value )
- {
- if( strpos( $str, $key ) !== false )
- {
- return $value;
- }
- }
- return null;
- }
- /**
- *
- * Убирает из номера телефона код страны
- *
- * @param string $phone Номер телефона в формате 79991231212
- *
- * @throws Exception Если не удалось найти соответствующий код, кидает исключение
- *
- * @return string|null
- *
- */
- public function removeCountryCode( $phone )
- {
- $codes = array( array( 7, 1 ), array( 93, 2 ), array( 355, 3 ), array( 213, 3 ), array( 1684, 4 ), array( 376, 3 ), array( 244, 3 ), array( 1264, 4 ), array( 1268, 4 ), array( 54, 2 ), array( 374, 3 ), array( 297, 3 ), array( 61, 2 ), array( 43, 2 ), array( 994, 3 ), array( 1242, 4 ), array( 973, 3 ), array( 880, 3 ), array( 1246, 4 ), array( 375, 3 ), array( 32, 2 ), array( 501, 3 ), array( 229, 3 ), array( 1441, 4 ), array( 975, 3 ), array( 591, 3 ), array( 387, 3 ), array( 267, 3 ), array( 55, 2 ), array( 246, 3 ), array( 1284, 4 ), array( 673, 3 ), array( 359, 3 ), array( 226, 3 ), array( 257, 3 ), array( 855, 3 ), array( 237, 3 ), array( 1, 1 ), array( 238, 3 ), array( 599, 3 ), array( 1345, 4 ), array( 236, 3 ), array( 235, 3 ), array( 56, 2 ), array( 86, 2 ), array( 61, 2 ), array( 61, 2 ), array( 57, 2 ), array( 269, 3 ), array( 243, 3 ), array( 242, 3 ), array( 682, 3 ), array( 506, 3 ), array( 225, 3 ), array( 385, 3 ), array( 53, 2 ), array( 599, 3 ), array( 357, 3 ), array( 420, 3 ), array( 45, 2 ), array( 253, 3 ), array( 1767, 4 ), array( 1, 1 ), array( 593, 3 ), array( 20, 2 ), array( 503, 3 ), array( 240, 3 ), array( 291, 3 ), array( 372, 3 ), array( 251, 3 ), array( 500, 3 ), array( 298, 3 ), array( 679, 3 ), array( 358, 3 ), array( 33, 2 ), array( 594, 3 ), array( 689, 3 ), array( 241, 3 ), array( 220, 3 ), array( 995, 3 ), array( 49, 2 ), array( 233, 3 ), array( 350, 3 ), array( 30, 2 ), array( 299, 3 ), array( 1473, 4 ), array( 590, 3 ), array( 1671, 4 ), array( 502, 3 ), array( 44, 2 ), array( 224, 3 ), array( 245, 3 ), array( 592, 3 ), array( 509, 3 ), array( 504, 3 ), array( 852, 3 ), array( 36, 2 ), array( 354, 3 ), array( 91, 2 ), array( 62, 2 ), array( 98, 2 ), array( 964, 3 ), array( 353, 3 ), array( 44, 2 ), array( 972, 3 ), array( 39, 2 ), array( 1876, 4 ), array( 81, 2 ), array( 44, 2 ), array( 962, 3 ), array( 7, 1 ), array( 254, 3 ), array( 686, 3 ), array( 965, 3 ), array( 996, 3 ), array( 856, 3 ), array( 371, 3 ), array( 961, 3 ), array( 266, 3 ), array( 231, 3 ), array( 218, 3 ), array( 423, 3 ), array( 370, 3 ), array( 352, 3 ), array( 853, 3 ), array( 389, 3 ), array( 261, 3 ), array( 265, 3 ), array( 60, 2 ), array( 960, 3 ), array( 223, 3 ), array( 356, 3 ), array( 692, 3 ), array( 596, 3 ), array( 222, 3 ), array( 230, 3 ), array( 262, 3 ), array( 52, 2 ), array( 691, 3 ), array( 373, 3 ), array( 377, 3 ), array( 976, 3 ), array( 382, 3 ), array( 1664, 4 ), array( 212, 3 ), array( 258, 3 ), array( 95, 2 ), array( 264, 3 ), array( 674, 3 ), array( 977, 3 ), array( 31, 2 ), array( 687, 3 ), array( 64, 2 ), array( 505, 3 ), array( 227, 3 ), array( 234, 3 ), array( 683, 3 ), array( 672, 3 ), array( 850, 3 ), array( 1670, 4 ), array( 47, 2 ), array( 968, 3 ), array( 92, 2 ), array( 680, 3 ), array( 970, 3 ), array( 507, 3 ), array( 675, 3 ), array( 595, 3 ), array( 51, 2 ), array( 63, 2 ), array( 48, 2 ), array( 351, 3 ), array( 1, 1 ), array( 974, 3 ), array( 262, 3 ), array( 40, 2 ), array( 250, 3 ), array( 590, 3 ), array( 290, 3 ), array( 1869, 4 ), array( 1758, 4 ), array( 590, 3 ), array( 508, 3 ), array( 1784, 4 ), array( 685, 3 ), array( 378, 3 ), array( 239, 3 ), array( 966, 3 ), array( 221, 3 ), array( 381, 3 ), array( 248, 3 ), array( 232, 3 ), array( 65, 2 ), array( 1721, 4 ), array( 421, 3 ), array( 386, 3 ), array( 677, 3 ), array( 252, 3 ), array( 27, 2 ), array( 82, 2 ), array( 211, 3 ), array( 34, 2 ), array( 94, 2 ), array( 249, 3 ), array( 597, 3 ), array( 47, 2 ), array( 268, 3 ), array( 46, 2 ), array( 41, 2 ), array( 963, 3 ), array( 886, 3 ), array( 992, 3 ), array( 255, 3 ), array( 66, 2 ), array( 670, 3 ), array( 228, 3 ), array( 690, 3 ), array( 676, 3 ), array( 1868, 4 ), array( 216, 3 ), array( 90, 2 ), array( 993, 3 ), array( 1649, 4 ), array( 688, 3 ), array( 1340, 4 ), array( 256, 3 ), array( 380, 3 ), array( 971, 3 ), array( 44, 2 ), array( 1, 1 ), array( 598, 3 ), array( 998, 3 ), array( 678, 3 ), array( 39, 2 ), array( 58, 2 ), array( 84, 2 ), array( 681, 3 ), array( 212, 3 ), array( 967, 3 ), array( 260, 3 ), array( 263, 3 ), array( 358, 3 ) );
- foreach( $codes as $item )
- {
- if( substr( $phone, 1, $item[ 1 ] ) == $item[ 0 ] )
- {
- return substr( $phone, ( 1 + $item[ 1 ] ) );
- }
- }
- throw new Exception( 'Не удается определить страну номера телефона' );
- }
- public function getCurrencyCode( $name )
- {
- $list = array(
- 'RUB' => 643,
- 'KZT' => 398,
- 'USD' => 840,
- 'EUR' => 978
- );
- if( !array_key_exists( $name, $list ) )
- {
- throw new Exception( 'Выбрана неподдерживаемая валюта для платежа' );
- }
- return $list[ $name ];
- }
- /**
- *
- * Метод-обертка, добавленный для совместимости с другим классом.
- * По факту вызывает методо Qiwi::transactions()
- * Не используйте его без необходимости
- *
- * @return mixed
- *
- */
- public function getHistory( $from, $to )
- {
- $in = $this->transactions( 'in', $from, $to );
- $out = $this->transactions( 'out', $from, $to );
- foreach( $in as $key => $transaction )
- {
- $in[ $key ][ 'iID' ] = $transaction[ 'transaction' ];
- $in[ $key ][ 'sDate' ] = $transaction[ 'date' ];
- $in[ $key ][ 'sTime' ] = $transaction[ 'time' ];
- $in[ $key ][ 'sWithExpend' ] = $transaction[ 'cash' ];
- $in[ $key ][ 'dWithExpend' ] = $transaction[ 'cash' ];
- $in[ $key ][ 'sType' ] = 'INCOME';
- $in[ $key ][ 'sCurrency' ] = $transaction[ 'originalCurrency' ];
- $in[ $key ][ 'sStatus' ] = 'SUCCESS';
- $in[ $key ][ 'dAmount' ] = $transaction[ 'originalCash' ];
- $in[ $key ][ 'sAmount' ] = $transaction[ 'originalCash' ];
- $in[ $key ][ 'sComment' ] = $transaction[ 'comment' ];
- $in[ $key ][ 'sProvider' ] = $transaction[ 'provider' ];
- $in[ $key ][ 'iOpponentPhone' ] = (int)$transaction[ 'opNumber' ];
- }
- foreach( $out as $key => $transaction )
- {
- $out[ $key ][ 'iID' ] = $transaction[ 'transaction' ];
- $out[ $key ][ 'sDate' ] = $transaction[ 'date' ];
- $out[ $key ][ 'sTime' ] = $transaction[ 'time' ];
- $out[ $key ][ 'sWithExpend' ] = $transaction[ 'cash' ];
- $out[ $key ][ 'dWithExpend' ] = $transaction[ 'cash' ];
- $out[ $key ][ 'sType' ] = 'EXPENDITURE';
- $out[ $key ][ 'sCurrency' ] = $transaction[ 'originalCurrency' ];
- $out[ $key ][ 'sStatus' ] = 'SUCCESS';
- $out[ $key ][ 'dAmount' ] = $transaction[ 'originalCash' ];
- $out[ $key ][ 'sAmount' ] = $transaction[ 'originalCash' ];
- $out[ $key ][ 'sComment' ] = $transaction[ 'comment' ];
- $out[ $key ][ 'sProvider' ] = $transaction[ 'provider' ];
- $out[ $key ][ 'iOpponentPhone' ] = (int)$transaction[ 'opNumber' ];
- }
- return array_merge( $in, $out );
- }
- /**
- *
- * Метод-обертка, добавленный для совместимости с другим классом.
- * По факту вызывает методо Qiwi::isSmsOn()
- * Не используйте его без необходимости
- *
- * @return mixed
- *
- */
- public function isSMSActive()
- {
- return $this->isSmsOn();
- }
- /**
- *
- * Метод-обертка, добавленный для совместимости с другим классом.
- * По факту вызывает методо Qiwi::isSmsOn()
- * Не используйте его без необходимости
- *
- * @return mixed
- *
- */
- public function isSMSAcive()
- {
- return $this->isSmsOn();
- }
- /**
- *
- * Метод-обертка, добавленный для совместимости с другим классом.
- * По факту вызывает методо Qiwi::paymentQiwi()
- * Не используйте его без необходимости
- *
- * @return mixed
- *
- */
- public function transfer( $phone, $amount, $currency, $comment )
- {
- return $this->paymentQiwi( $phone, $amount, $currency, $currency, $comment );
- }
- /**
- *
- * Метод-обертка, добавленный для совместимости с другим классом.
- * По факту вызывает методо Qiwi::paymentQiwi()
- * Не используйте его без необходимости
- *
- * @return mixed
- *
- */
- public function SendMoney( $phone, $amount, $currency, $comment )
- {
- return $this->paymentQiwi( $phone, $amount, $currency, $currency, $comment );
- }
- /**
- *
- * Метод-обертка, добавленный для совместимости с другим классом.
- * По факту вызывает методо Qiwi::wallets()
- * Не используйте его без необходимости
- *
- * @return mixed
- *
- */
- public function GetBalances()
- {
- return $this->wallets();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement