/**
  * @Route ("/subscription/process")
  * @Secure ({"USER"})
  *
  * We were redirected here from PayPal after the buyer approved/cancelled the payment
  *
  * @param array $params
  * @return string
  * @throws Exception
  * @throws \Destiny\Common\Utils\FilterParamsException
  * TODO clean this method up
  */
 public function subscriptionProcess(array $params)
 {
     FilterParams::required($params, 'subscriptionId');
     FilterParams::required($params, 'token');
     FilterParams::declared($params, 'success');
     $userId = Session::getCredentials()->getUserId();
     $userService = UserService::instance();
     $ordersService = OrdersService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     $payPalApiService = PayPalApiService::instance();
     $chatIntegrationService = ChatIntegrationService::instance();
     $authenticationService = AuthenticationService::instance();
     $log = Application::instance()->getLogger();
     $subscription = $subscriptionsService->getSubscriptionById($params['subscriptionId']);
     if (empty($subscription) || strcasecmp($subscription['status'], SubscriptionStatus::_NEW) !== 0) {
         throw new Exception('Invalid subscription record');
     }
     try {
         $subscriptionType = $subscriptionsService->getSubscriptionType($subscription['subscriptionType']);
         $user = $userService->getUserById($subscription['userId']);
         if ($user['userId'] != $userId && $subscription['gifter'] != $userId) {
             throw new Exception('Invalid subscription');
         }
         if ($params['success'] == '0' || $params['success'] == 'false' || $params['success'] === false) {
             throw new Exception('Order request failed');
         }
         if (!$payPalApiService->retrieveCheckoutInfo($params['token'])) {
             throw new Exception('Failed to retrieve express checkout details');
         }
         FilterParams::required($params, 'PayerID');
         // if the order status is an error, the payerID is not returned
         Session::set('subscriptionId');
         Session::set('token');
         // Create the payment profile
         // Payment date is 1 day before subscription rolls over.
         if ($subscription['recurring'] == 1 || $subscription['recurring'] == true) {
             $startPaymentDate = Date::getDateTime();
             $nextPaymentDate = Date::getDateTime();
             $nextPaymentDate->modify('+' . $subscriptionType['billingFrequency'] . ' ' . strtolower($subscriptionType['billingPeriod']));
             $nextPaymentDate->modify('-1 DAY');
             $reference = $subscription['userId'] . '-' . $subscription['subscriptionId'];
             $paymentProfileId = $payPalApiService->createRecurringPaymentProfile($params['token'], $reference, $user['username'], $nextPaymentDate, $subscriptionType);
             if (empty($paymentProfileId)) {
                 throw new Exception('Invalid recurring payment profileId returned from Paypal');
             }
             $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'paymentStatus' => PaymentStatus::ACTIVE, 'paymentProfileId' => $paymentProfileId, 'billingStartDate' => $startPaymentDate->format('Y-m-d H:i:s'), 'billingNextDate' => $nextPaymentDate->format('Y-m-d H:i:s')));
         }
         // Record the payments as well as check if any are not in the completed state
         // we put the subscription into "PENDING" state if a payment is found not completed
         $subscriptionStatus = SubscriptionStatus::ACTIVE;
         $DoECResponse = $payPalApiService->getECPaymentResponse($params['PayerID'], $params['token'], $subscriptionType['amount']);
         $payments = $payPalApiService->getResponsePayments($DoECResponse);
         foreach ($payments as $payment) {
             $payment['subscriptionId'] = $subscription['subscriptionId'];
             $payment['payerId'] = $params['PayerID'];
             $ordersService->addPayment($payment);
             // TODO: Payment provides no way of telling if the transaction with ALL payments was successful
             if ($payment['paymentStatus'] != PaymentStatus::COMPLETED) {
                 $subscriptionStatus = SubscriptionStatus::PENDING;
             }
         }
         // Update subscription status
         $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'status' => $subscriptionStatus));
     } catch (Exception $e) {
         $subscriptionsService->updateSubscription(array('subscriptionId' => $subscription['subscriptionId'], 'status' => SubscriptionStatus::ERROR));
         $log->critical($e->getMessage(), $subscription);
         return 'redirect: /subscription/' . urlencode($subscription['subscriptionId']) . '/error';
     }
     // only unban the user if the ban is non-permanent or the tier of the subscription is >= 2
     // we unban the user if no ban is found because it also unmutes
     $ban = $userService->getUserActiveBan($user['userId']);
     if (empty($ban) or (!empty($ban['endtimestamp']) or $subscriptionType['tier'] >= 2)) {
         $chatIntegrationService->sendUnban($user['userId']);
     }
     // Broadcast
     $randomEmote = Config::$a['chat']['customemotes'][array_rand(Config::$a['chat']['customemotes'])];
     if (!empty($subscription['gifter'])) {
         $gifter = $userService->getUserById($subscription['gifter']);
         $userName = $gifter['username'];
         $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! gifted by %s %s", $user['username'], $subscriptionType['tierLabel'], $gifter['username'], $randomEmote));
     } else {
         $userName = $user['username'];
         $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! %s", $user['username'], $subscriptionType['tierLabel'], $randomEmote));
     }
     $subMessage = Session::set('subMessage');
     if (!empty($subMessage)) {
         $chatIntegrationService->sendBroadcast(sprintf("%s: %s", $userName, $subMessage));
     }
     // Update the user
     $authenticationService->flagUserForUpdate($user['userId']);
     // Redirect to completion page
     return 'redirect: /subscription/' . urlencode($subscription['subscriptionId']) . '/complete';
 }
 /**
  * @Route ("/subscription/process")
  * @Secure ({"USER"})
  * @Transactional
  *
  * We were redirected here from PayPal after the buyer approved/cancelled the payment
  *
  * @param array $params
  */
 public function subscriptionProcess(array $params, ViewModel $model)
 {
     FilterParams::required($params, 'orderId');
     FilterParams::required($params, 'token');
     FilterParams::declared($params, 'success');
     $ordersService = OrdersService::instance();
     $userService = UserService::instance();
     $subscriptionsService = SubscriptionsService::instance();
     $payPalApiService = PayPalApiService::instance();
     $chatIntegrationService = ChatIntegrationService::instance();
     $authenticationService = AuthenticationService::instance();
     $userId = Session::getCredentials()->getUserId();
     // Get the order
     $order = $ordersService->getOrderByIdAndUserId($params['orderId'], $userId);
     if (empty($order) || strcasecmp($order['state'], OrderStatus::_NEW) !== 0) {
         throw new Exception('Invalid order record');
     }
     try {
         // If we got a failed response URL
         if ($params['success'] == '0' || $params['success'] == 'false' || $params['success'] === false) {
             throw new Exception('Order request failed');
         }
         // Get the subscription from the order
         $orderSubscription = $subscriptionsService->getSubscriptionByOrderId($order['orderId']);
         $subscriptionUser = $userService->getUserById($orderSubscription['userId']);
         // Make sure the subscription is valid
         if (empty($orderSubscription)) {
             throw new Exception('Invalid order subscription');
         }
         // Make sure the subscription is either owned or gifted by the user
         if ($subscriptionUser['userId'] != $userId && $orderSubscription['gifter'] != $userId) {
             throw new Exception('Invalid order subscription');
         }
         $subscriptionType = $subscriptionsService->getSubscriptionType($orderSubscription['subscriptionType']);
         $paymentProfile = $ordersService->getPaymentProfileByOrderId($order['orderId']);
         // Get the checkout info
         $ecResponse = $payPalApiService->retrieveCheckoutInfo($params['token']);
         if (!isset($ecResponse) || $ecResponse->Ack != 'Success') {
             throw new Exception('Failed to retrieve express checkout details');
         }
         // Moved this down here, as if the order status is error, the payerID is not returned
         FilterParams::required($params, 'PayerID');
         // Point of no return - we only every want a person to get here if their order was a successful sequence
         Session::set('token');
         Session::set('orderId');
         // Recurring payment
         if (!empty($paymentProfile)) {
             $createRPProfileResponse = $payPalApiService->createRecurringPaymentProfile($paymentProfile, $params['token'], $subscriptionType);
             if (!isset($createRPProfileResponse) || $createRPProfileResponse->Ack != 'Success') {
                 throw new Exception('Failed to create recurring payment request');
             }
             $paymentProfileId = $createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileID;
             $paymentStatus = $createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileStatus;
             if (empty($paymentProfileId)) {
                 throw new Exception('Invalid recurring payment profileId returned from Paypal');
             }
             // Set the payment profile to active, and paymetProfileId
             $ordersService->updatePaymentProfileId($paymentProfile['profileId'], $paymentProfileId, $paymentStatus);
             // Update the payment profile
             $subscriptionsService->updateSubscriptionPaymentProfile($orderSubscription['subscriptionId'], $paymentProfile['profileId'], true);
         }
         // Complete the checkout
         $DoECResponse = $payPalApiService->getECPaymentResponse($params['PayerID'], $params['token'], $order);
         if (isset($DoECResponse) && $DoECResponse->Ack == 'Success') {
             if (isset($DoECResponse->DoExpressCheckoutPaymentResponseDetails->PaymentInfo)) {
                 $payPalApiService->recordECPayments($DoECResponse, $params['PayerID'], $order);
                 $ordersService->updateOrderState($order['orderId'], $order['state']);
             } else {
                 throw new Exception('No payments for express checkout order');
             }
         } else {
             throw new Exception($DoECResponse->Errors[0]->LongMessage);
         }
         // If the user already has a subscription and ONLY if this subscription was NOT a gift
         if (!isset($orderSubscription['gifter']) || empty($orderSubscription['gifter'])) {
             $activeSubscription = $subscriptionsService->getUserActiveSubscription($subscriptionUser['userId']);
             if (!empty($activeSubscription)) {
                 // Cancel any attached payment profiles
                 $ordersService = OrdersService::instance();
                 $paymentProfile = $ordersService->getPaymentProfileById($activeSubscription['paymentProfileId']);
                 if (!empty($paymentProfile)) {
                     $payPalApiService->cancelPaymentProfile($activeSubscription, $paymentProfile);
                     $subscriptionsService->updateSubscriptionRecurring($activeSubscription['subscriptionId'], false);
                 }
                 // Cancel the active subscription
                 $subscriptionsService->updateSubscriptionState($activeSubscription['subscriptionId'], SubscriptionStatus::CANCELLED);
             }
         }
         // Check if this is a gift, check that the giftee is still eligable
         if (!empty($orderSubscription['gifter']) && !$subscriptionsService->getCanUserReceiveGift($userId, $subscriptionUser['userId'])) {
             // Update the state to ERROR and log a critical error
             Application::instance()->getLogger()->critical(sprintf('Duplicate subscription attempt, Gifter: %d GifteeId: %d, OrderId: %d', $userId, $subscriptionUser['userId'], $order['orderId']));
             $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ERROR);
         } else {
             // Unban the user if a ban is found
             $ban = $userService->getUserActiveBan($subscriptionUser['userId']);
             // only unban the user if the ban is non-permanent or the tier of the subscription is >= 2
             // we unban the user if no ban is found because it also unmutes
             if (empty($ban) or (!empty($ban['endtimestamp']) or $orderSubscription['subscriptionTier'] >= 2)) {
                 $chatIntegrationService->sendUnban($subscriptionUser['userId']);
             }
             // Activate the subscription (state)
             $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ACTIVE);
             // Flag the user for 'update'
             $authenticationService->flagUserForUpdate($subscriptionUser['userId']);
             // Random emote
             $randomEmote = Config::$a['chat']['customemotes'][array_rand(Config::$a['chat']['customemotes'])];
             // Broadcast
             if (!empty($orderSubscription['gifter'])) {
                 $gifter = $userService->getUserById($orderSubscription['gifter']);
                 $userName = $gifter['username'];
                 $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! gifted by %s %s", $subscriptionUser['username'], $subscriptionType['tierLabel'], $gifter['username'], $randomEmote));
             } else {
                 $userName = $subscriptionUser['username'];
                 $chatIntegrationService->sendBroadcast(sprintf("%s is now a %s subscriber! %s", $subscriptionUser['username'], $subscriptionType['tierLabel'], $randomEmote));
             }
             // Get the subscription message, and remove it from the session
             $subMessage = Session::set('subMessage');
             if (!empty($subMessage)) {
                 $chatIntegrationService->sendBroadcast(sprintf("%s: %s", $userName, $subMessage));
             }
         }
         // Redirect to completion page
         return 'redirect: /subscription/' . urlencode($order['orderId']) . '/complete';
     } catch (Exception $e) {
         if (!empty($order)) {
             $ordersService->updateOrderState($order['orderId'], OrderStatus::ERROR);
         }
         if (!empty($paymentProfile)) {
             $ordersService->updatePaymentStatus($paymentProfile['paymentId'], PaymentStatus::ERROR);
         }
         if (!empty($orderSubscription)) {
             $subscriptionsService->updateSubscriptionState($orderSubscription['subscriptionId'], SubscriptionStatus::ERROR);
         }
         $log = Application::instance()->getLogger();
         $log->error($e->getMessage(), $order);
         return 'redirect: /subscription/' . urlencode($order['orderId']) . '/error';
     }
 }
Example #3
0
 /**
  * Update/add a address
  *
  * @Route ("/profile/address/update")
  * @HttpMethod ({"POST"})
  * @Secure ({"USER"})
  *
  * @param array $params
  * @return string
  */
 public function updateAddress(array $params)
 {
     FilterParams::required($params, 'fullName');
     FilterParams::required($params, 'line1');
     FilterParams::declared($params, 'line2');
     FilterParams::required($params, 'city');
     FilterParams::required($params, 'region');
     FilterParams::required($params, 'zip');
     FilterParams::required($params, 'country');
     $userService = UserService::instance();
     $userId = Session::getCredentials()->getUserId();
     $address = $userService->getAddressByUserId($userId);
     if (empty($address)) {
         $address = array();
         $address['userId'] = $userId;
     }
     $address['fullName'] = $params['fullName'];
     $address['line1'] = $params['line1'];
     $address['line2'] = $params['line2'];
     $address['city'] = $params['city'];
     $address['region'] = $params['region'];
     $address['zip'] = $params['zip'];
     $address['country'] = $params['country'];
     if (!isset($address['id']) || empty($address['id'])) {
         $userService->addAddress($address);
     } else {
         $userService->updateAddress($address);
     }
     Session::set('modelSuccess', 'Your address has been updated');
     return 'redirect: /profile';
 }
Example #4
0
 /**
  * @Route ("/admin/user/{id}/subscription/{subscriptionId}/save")
  * @Route ("/admin/user/{id}/subscription/save")
  * @Secure ({"ADMIN"})
  * @HttpMethod ({"POST"})
  *
  * @param array $params
  * @return string
  * @throws Exception
  * @throws \Destiny\Common\Utils\FilterParamsException
  */
 public function subscriptionSave(array $params)
 {
     FilterParams::required($params, 'subscriptionType');
     FilterParams::required($params, 'status');
     FilterParams::required($params, 'createdDate');
     FilterParams::required($params, 'endDate');
     FilterParams::declared($params, 'gifter');
     $subscriptionsService = SubscriptionsService::instance();
     $subscriptionType = $subscriptionsService->getSubscriptionType($params['subscriptionType']);
     $subscription = array();
     $subscription['subscriptionType'] = $subscriptionType['id'];
     $subscription['subscriptionTier'] = $subscriptionType['tier'];
     $subscription['status'] = $params['status'];
     $subscription['createdDate'] = $params['createdDate'];
     $subscription['endDate'] = $params['endDate'];
     $subscription['userId'] = $params['id'];
     $subscription['subscriptionSource'] = isset($params['subscriptionSource']) && !empty($params['subscriptionSource']) ? $params['subscriptionSource'] : Config::$a['subscriptionType'];
     if (!empty($params['gifter'])) {
         $subscription['gifter'] = $params['gifter'];
     }
     if (isset($params['subscriptionId']) && !empty($params['subscriptionId'])) {
         $subscription['subscriptionId'] = $params['subscriptionId'];
         $subscriptionId = $subscription['subscriptionId'];
         $subscriptionsService->updateSubscription($subscription);
         Session::set('modelSuccess', 'Subscription updated!');
     } else {
         $subscriptionId = $subscriptionsService->addSubscription($subscription);
         Session::set('modelSuccess', 'Subscription created!');
     }
     $authService = AuthenticationService::instance();
     $authService->flagUserForUpdate($params['id']);
     return 'redirect: /admin/user/' . urlencode($params['id']) . '/subscription/' . urlencode($subscriptionId) . '/edit';
 }