/**
  * @param string   $key
  * @param Api      $api
  * @param Customer $customer
  *
  * @throws ApiException
  * @throws Exception
  */
 public function update($key, $api, $customer)
 {
     $this->info('начинаем сбор информации о клиенте: ' . $customer->id . ' [' . $customer->agbis_id . ']');
     Reporter::aggregateExternalInfoStart($key, $customer->agbis_id, $customer->id);
     $client = $api->ContrInfo($key);
     $this->line('... общая информация');
     $client['key'] = $key;
     try {
         $promo = $api->PromoCodeUse($key);
         $this->line('... промокод');
     } catch (ApiException $e) {
         if ($e->isDataError()) {
             $promo = null;
         } else {
             throw $e;
         }
     }
     $client['promo'] = $promo;
     $client['bonus'] = $api->Bonus($key)['bonus'];
     $this->line('... бонус');
     $client['deposit'] = $api->Deposit($key)['deposit'];
     $this->line('... депозитный счет');
     $client['orders'] = $api->Orders($key)['orders'];
     $this->line('... заказы');
     $client['history'] = $api->OrdersHistory($key)['orders'];
     $this->line('... история заказов');
     $client['tokens'] = $api->TokenPayList($key)['tokens'];
     $this->line('... токены платежей');
     Reporter::aggregateExternalInfoEnd($customer->id);
     $component = \Dryharder\Components\Customer::instance()->initByExternalId($client['id']);
     $this->line('... обновляем информацию в нашей базе данных');
     $component->updateExternalInfo($client);
     $this->info('закончили работу с клиентом');
 }
Beispiel #2
0
 public function show()
 {
     $customer = $this->getCustomer();
     if (!$customer) {
         return $this->responseError(['Данные не доступны'], 'Требуется авторизация', 401);
     }
     $api = new Api();
     try {
         $key = $api->key();
         Reporter::aggregateExternalInfoStart($key, $api->id(), $customer->get()->id);
         $client = $api->_cache_customer_info($key);
         $client['key'] = $key;
         try {
             $promo = $api->PromoCodeUse($key);
         } catch (ApiException $e) {
             if ($e->isDataError()) {
                 $promo = null;
             } else {
                 throw $e;
             }
         }
         $client['promo'] = $promo;
         Reporter::aggregateExternalInfoEnd($customer->get()->id);
         $customer->updateExternalInfo($client);
         return $this->responseSuccess($client, 'Данные клиента');
     } catch (ApiException $e) {
         $api->cleanup();
         return $this->responseException($e, 'Не удалось получить данные', 'customer');
     }
 }
Beispiel #3
0
 protected function getCustomer()
 {
     $api = new Api();
     Customer::instance()->closeIfNotMember();
     // ключ из запроса
     $keyRequest = Input::get('key');
     // наш ключ клиента
     $keyCustomer = Customer::instance()->key();
     // id сессии агбиса
     $keyAgbis = $api->key();
     // при наличии нашего ключа плюс ключа агбиса
     // это значит что мы держим вполне живую сессию
     if ($keyCustomer && $keyAgbis) {
         $customer = Customer::instance()->initByKey();
         Reporter::customerTouchKey($keyCustomer, $keyAgbis, $customer->get()->agbis_id);
         return $customer;
     }
     Reporter::customerEmptyKey($keyCustomer, $keyAgbis);
     // нет своего ключа но есть ключ агбис или ключ запроса (он же ключ агбис)
     // это значит что свой ключ мы еще не выдали по какой то причине
     // поэтому работаем по ключу агбиса (из запроса - приоритетнее)
     Reporter::customerTouchExternalKey($keyRequest, $keyAgbis);
     $keyAgbis = $keyRequest ? $keyRequest : $keyAgbis;
     if ($keyAgbis) {
         try {
             $user = $api->_cache_customer_info($keyAgbis);
             $api->memory((object) ['id' => $user['id'], 'key' => $keyAgbis]);
             // получили человека по агбису, найдем его у нас и создадим свою сессию
             $customer = Customer::instance()->initByExternalId($user['id']);
             if ($customer) {
                 $key = $customer->startSession();
                 Reporter::loginNewKey($customer->get()->agbis_id, $key);
                 return $customer;
             }
             // иначе это значит, что в нашей базе пользователя нет
             // придется его выбросить и пусть авторизуется заново
             Reporter::customerLostExternalKey($keyAgbis);
         } catch (ApiException $e) {
             Reporter::customerFailExternalKey($keyAgbis);
         }
     } else {
         Reporter::customerEmptyExternalKey();
     }
     Customer::instance()->destroySession();
     return null;
 }
 /**
  * ответ успешно на check
  */
 private function responseSuccess()
 {
     $method = Input::get('action') == 'checkOrder' ? 'checkOrder' : 'paymentAviso';
     $params = $this->parameters();
     Reporter::payResponseSuccess($params['customer_id'], $params['order_id'], $params['payment_id']);
     $dt = date('Y-m-d\\TH:i:s+04:00');
     $response = '<?xml version="1.0" encoding="UTF-8"?><' . $method . 'Response performedDatetime="' . $dt . '" code="0" invoiceId="' . Input::get('invoiceId') . '" shopId="' . Config::get('cloud.yam.shopId') . '"/>';
     \Log::debug('response', [$response]);
     return \Response::make($response, 200, ['Content-Type' => 'application/xml']);
 }
Beispiel #5
0
 private function parsePayTarget($target, $id)
 {
     $api = new Api();
     $id = (int) $id;
     if ($id <= 0) {
         return null;
     }
     // оплата заказа
     if ($target == 'order') {
         return $id;
     }
     // оплата подписки
     if ($target == 'subscription') {
         $customer_id = Customer::instance()->initByExternalId($api->id())->get()->id;
         $subscription_id = $id;
         Reporter::subscriptionPaymentRequest($customer_id, $subscription_id);
         $subscription = Subscription::whereCustomerId($customer_id)->find($subscription_id);
         if (!$subscription) {
             $list = $api->Certificate();
             // ищем эту подписку в агбисе
             foreach ($list as $item) {
                 if ($item->id == $subscription_id) {
                     Reporter::subscriptionFound($customer_id, $subscription_id, $item);
                     // создаем подписку в нашей базе
                     Subscription::unguard();
                     $subscription = Subscription::create(['id' => $item->id, 'name' => $item->name, 'description' => $item->comments, 'price' => $item->price, 'customer_id' => $customer_id, 'order_id' => 0]);
                     Reporter::subscriptionCreated($customer_id, $subscription_id);
                 }
             }
         }
         if (!$subscription) {
             Reporter::subscriptionNotFound($customer_id, $subscription_id);
             return null;
         }
         // если заказ уже был создан, отдаем его для оплаты
         if ($subscription->order_id > 0) {
             return $subscription->order_id;
         }
         // создадим заказа в агбисе
         $order_id = $api->CreatePayCertificate($subscription->id);
         if ($order_id > 0) {
             Reporter::subscriptionOrderCreated($customer_id, $subscription_id, $order_id);
             // отдадим для оплаты
             $subscription->order_id = $order_id;
             $subscription->save();
             return $subscription->order_id;
         }
     }
     return null;
 }
Beispiel #6
0
 public function refundPayment($paymentId, $amount)
 {
     $url = Config::get('cloud.refund');
     $post = ['TransactionId' => $paymentId, 'Amount' => $amount];
     Reporter::refundRequest($paymentId, $amount);
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
     curl_setopt($ch, CURLOPT_USERPWD, Config::get('cloud.PublicId') . ':' . Config::get('cloud.SecretKey'));
     $result = curl_exec($ch);
     $error = curl_error($ch);
     $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     curl_close($ch);
     $response = @json_decode($result);
     $paySuccess = false;
     Reporter::refundResponse($paymentId, $amount, $response, $error);
     // есть нормальный ответ
     if (!$error && !empty($response) && is_object($response)) {
         // ошибка
         if ($response->Success) {
             $paySuccess = true;
         } else {
             $error = !empty($response->Message) ? $response->Message : 'Ошибка операции во время возврата платежа';
         }
     }
     if ($paySuccess) {
         Reporter::refundSuccess($paymentId, $amount);
         return (object) ['success' => true, 'message' => 'Возврат платежа выполнен успешно'];
     }
     $error = trim($error . ' [code=' . $code . ']');
     Reporter::refundError($paymentId, $amount, $error);
     return (object) ['success' => false, 'message' => $error];
 }
Beispiel #7
0
 /**
  * авторизация
  * @return \Response
  */
 public function login()
 {
     Validation::prepareInput(['phone']);
     $phone = \Input::get('phone');
     $password = \Input::get('password');
     $selfPassword = null;
     $validator = Validation::validator(['phone', 'password']);
     if ($validator->fails()) {
         Reporter::loginFailValidate($validator);
         return $this->responseError($validator, 'Некорректные данные');
     }
     Reporter::loginStart($phone, $password);
     // ключ который мы должны в итоге выдать фронтенду
     $key = null;
     // находим у себя
     $customer = Customer::instance()->initByPhone($phone);
     if ($customer) {
         Reporter::loginFoundSelf($customer->get()->agbis_id);
         // авторизуем по своему паролю
         if ($customer->checkPassword($password)) {
             Reporter::loginPasswordSelf($customer->get()->agbis_id);
             // наш пароль
             $selfPassword = $password;
             // в агбис будем входить по внешнему паролю
             $password = $customer->getExternalPassword();
         }
     }
     // получаем сессию агбиса
     try {
         $api = new Api();
         $user = $api->Login_con($phone, $password);
         $api->memory($user);
         // запомним отдельно в сессии api
         if (Input::get('remember')) {
             $cookie = Customer::instance()->getForeverCookie();
         } else {
             $cookie = Customer::instance()->getTemporaryCookie();
         }
         Reporter::loginExternal($user->id, $phone);
         // для нас - новый человек
         if (!$customer) {
             // пробуем найти по id агбиса
             $customer = Customer::instance()->initByExternalId($user->id);
             if ($customer) {
                 // если нашли, это значит изменился телефон, обновим всю информацию
                 $customer->updateCustomerByExternal($phone, $password);
             } else {
                 // создадим нового
                 $customer = Customer::instance()->createCustomerByExternal($user->id, $phone, $password);
             }
         }
         // устанавливаем пароль в соответствии с успешным входом
         $customer->doChangePasswordSoft($password, $selfPassword);
         // по итогу, у нас есть "наш" человек
         // и мы начинам свою сессию
         $key = $customer->startSession();
         Reporter::loginNewKey($customer->get()->id, $key);
         $invite = new InviteComponent();
         $invite->registerInvite($customer->get());
         // обновляем дату-время последнего входа
         $customer->renewRegisterAt();
         // и именно наш ключ отдаем клиенту
         $response = $this->responseSuccess(['key' => $key], 'Успешная авторизация')->withCookie($cookie);
         return $response;
     } catch (\Exception $e) {
         Reporter::loginFailException($e);
         return $this->responseException($e, 'Ошибка авторизации', null, 401);
     }
 }
Beispiel #8
0
 /**
  * временная запись инвайта для внешнего id клиента
  *
  * @param string $phone внешний id клиента
  *
  * @return null|\Symfony\Component\HttpFoundation\Cookie
  */
 public function registerInviteExternal($phone)
 {
     $code = Cookie::get('dh_invite');
     $phone = Customer::instance()->phone($phone);
     if (!$code) {
         return null;
     }
     $cookie = Cookie::forget('dh_invite');
     $owner = $this->findByCode($code);
     if (!$owner) {
         return $cookie;
     }
     // нельзя приглашать самого себя
     if ($owner->phone == $phone) {
         return $cookie;
     }
     Reporter::inviteCodeFoundExternal($phone, $owner->id, $code);
     $invite = CustomerInviteExternal::create(['phone' => $phone, 'owner_id' => $owner->id, 'source_id' => self::C_LINK]);
     Reporter::inviteCodeRegisteredExternal($phone, $owner->id, $invite->id, $code);
     return $cookie;
 }
 /**
  * ответ успешно
  */
 private function responseSuccess()
 {
     $data = ['code' => 0];
     Reporter::payResponseSuccess($this->params['customer_id'], $this->params['payment_id'], $this->params['order_id']);
     Response::json($data)->send();
     die;
 }
Beispiel #10
0
 /**
  * когда обнаружили, что изменились внешние данные пользователя
  *
  * @param string $phone    новый телефон
  * @param string $password новый пароль
  *
  * @return Customer
  */
 public function updateCustomerByExternal($phone, $password)
 {
     Reporter::customerUpdateExternalStart($this->customer->id, $phone, $password);
     $this->customer->phone = $this->phone($phone);
     $this->customer->save();
     $this->customer->credential->agbis_password = $password;
     $this->customer->credential->password = $this->hash($password);
     $this->customer->credential->save();
     Reporter::customerUpdateExternalEnd($this->customer->id);
     return $this;
 }