Пример #1
0
 public function request()
 {
     $api = new Api();
     $data = [];
     if ($api->key()) {
         try {
             $data = $api->ContrInfo();
         } catch (\Exception $e) {
         }
     }
     $rules = ['address1' => 'required', 'address2' => 'required', 'orderText' => 'required', 'comment' => ''];
     // тип формы "новый клиент" (иначе - авторизованный)
     if (!$api->key()) {
         Validation::prepareInput(['phone']);
         $rules['phone'] = 'required|phone';
         $rules['email'] = 'required|email';
     }
     Input::merge(array_map('trim', Input::all()));
     $validator = \Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return $this->responseError($validator, $validator->errors()->first());
     }
     $fields = array_keys($rules);
     foreach ($fields as $key) {
         $data[$key] = Input::get($key);
     }
     Mailer::requestOrderMessage($data);
     OrderRequest::unguard();
     OrderRequest::create(['email' => $data['email'], 'phone' => Customer::instance()->phone($data['phone']), 'address1' => $data['address1'], 'address2' => $data['address2'], 'orderText' => $data['orderText'], 'comment' => $data['comment']]);
     return $this->responseSuccess(['email' => $data['email'], 'phone' => Customer::instance()->phone($data['phone']), 'address' => $data['address1']], 'Заказ оформлен');
 }
Пример #2
0
 /**
  * @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('закончили работу с клиентом');
 }
Пример #3
0
 private function notifyOrderInfo(NotifyOrder $notify)
 {
     $this->log('consume notify', $notify->getAttributes());
     $customerId = $notify->customer_id;
     $orderId = $notify->order_id;
     $customer = Customer::instance()->initByExternalId($customerId);
     if (!$customer) {
         $this->log('Customer is not initialized', ['customer_id' => $customerId]);
         return;
     }
     if (!$customer->get()->email) {
         $this->log('Email is empty', ['customer_id' => $customerId]);
         $notify->sent = 1;
         $notify->save();
         return;
     }
     $password = $customer->get()->credential->agbis_password;
     if (!$password) {
         $this->log('Customer password is not exists', ['customer_id' => $customerId]);
         return;
     }
     if (isset($this->keys[$customerId])) {
         $key = $this->keys[$customerId];
     } else {
         try {
             $user = $this->api->Login_con('+7' . $customer->get()->phone, $password);
         } catch (ApiException $e) {
             $this->log($e->getMessage(), [$customerId]);
             $notify->sent = 1;
             $notify->save();
             return;
         }
         $this->keys[$customerId] = $user->key;
         $key = $user->key;
     }
     $order = $this->api->getOrder($orderId, $key);
     $services = (new OrderServiceComponent())->parseOrderService($orderId, $key);
     $email = $customer->get()->email;
     $name = $customer->get()->name;
     $this->log('ready data send', ['services' => count($services)]);
     try {
         $attach = self::createClothesFile($order, $services, $name);
         Mailer::notifyNewOrder($order, $services, $email, $name, $attach);
         $notify->sent = 1;
         $notify->save();
         OrderRequest::markAsCompleted($customer->get()->phone, $orderId);
     } catch (\Exception $e) {
         $this->log('send mail error', ['email' => $customer->get()->email, 'id' => $customer->get()->id, 'message' => $e->getMessage()]);
     }
 }
Пример #4
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;
 }
Пример #5
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;
 }
Пример #6
0
 /**
  * @param Customer $customer
  * @param $password
  * @param $key
  *
  * @return array
  */
 public function initSessionKey(Customer $customer, $password, $key)
 {
     $api = new Api();
     $user = $api->Login_con('+7' . $customer->get()->phone, $password);
     $sessionId = $user->key;
     Cache::put($key, $sessionId, 500);
     $this->log('get new session', ['customer' => $customer->get()->id, 'session' => $sessionId]);
     return $sessionId;
 }
Пример #7
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;
 }
Пример #8
0
 public function lastDayOrders()
 {
     $customer = Customer::instance()->initByPhone('9104775209');
     $password = $customer->get()->credential->agbis_password;
     $user = $this->Login_con('+79104775209', $password);
     $params = urlencode('{"inc": "1", "part":"day"}');
     $url = 'LastOrders=' . $params . '&SessionID=' . $user->key . '&json=yes';
     $orders = $this->curl($url, 'json', 'last_orders');
     return $orders;
 }
Пример #9
0
 public function __construct($type)
 {
     $this->type = $type;
     $this->methodName = $this->getMethodName($type);
     $this->user = Customer::instance()->initByKey()->get();
 }
Пример #10
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);
     }
 }
Пример #11
0
 /**
  * @param Customer $customer
  * @param array $order
  * @param PaymentCloud $token
  */
 public static function errorAutoPay($customer, $order, $token)
 {
     $data = ['infobox' => Config::get('mail.infobox'), 'number' => $order['doc_number'], 'amount' => $order['amount'], 'email' => $customer->get()->email, 'name' => $customer->get()->name, 'subject' => 'Ошибка автоплатежа с вашей карты по заказу номер ' . $order['doc_number'], 'pan' => '...' . substr($token->card_pan, -4), 'type' => $token->card_type];
     Mail::send('mailer::customer.account.autopay_error', $data, function (Message $message) use($data) {
         $message->from($data['infobox'], Config::get('mail.name'))->to($data['email'], $data['name'])->subject($data['subject']);
     });
 }