/**
  * Returns a value indicating whether or not the payment method "paypal plus" is available at the moment.
  * It sends a test call to the api and if everything went fine, the method is available.
  * Currently, the main purpose of this function is the SSL and authentication test.
  *
  * @return bool
  */
 public function isAPIAvailable()
 {
     if ($this->restClient === null) {
         return false;
     }
     //Test the SSL Certificate that was provided by sending a simple test call to the PP API.
     //This is required, because in this step no other request will be sent that may be validated.
     //If this call fails, the payment method will not be modified and stay as paypal classic.
     //The method can be extended with several other exceptions to generate a correct result. The existing ones
     //do only check whether or not the SSL setup is correct.
     try {
         $response = $this->restClient->create('invoicing/invoices/next-invoice-number', array());
         if ($response) {
             return true;
         } else {
             return false;
         }
     } catch (ClientException $ce) {
         //Unauthorized: impossible to continue using PayPal plus
         if ($ce->getCode() === 401) {
             return false;
         }
         //Internal server error
         if ($ce->getCode() === 500) {
             return false;
         }
     } catch (RequestException $re) {
         //It's not okay, since it's an SSL exception
         return false;
     }
     return true;
 }
 /**
  * @return array
  */
 private function getProfile()
 {
     if (!isset($this->session['PaypalProfile'])) {
         $profile = $this->getProfileData();
         $uri = 'payment-experience/web-profiles';
         $profileList = array();
         try {
             $profileList = $this->restClient->get($uri);
         } catch (Exception $e) {
             $this->logException('An error occurred getting the experience profiles', $e);
         }
         foreach ($profileList as $entry) {
             if ($entry['name'] == $profile['name']) {
                 $this->restClient->put("{$uri}/{$entry['id']}", $profile);
                 $this->session['PaypalProfile'] = array('id' => $entry['id']);
                 break;
             }
         }
         if (!isset($this->session['PaypalProfile'])) {
             $payPalProfile = null;
             try {
                 $payPalProfile = $this->restClient->create($uri, $profile);
             } catch (Exception $e) {
                 $this->logException('An error occurred on creating an experience profiles', $e);
             }
             $this->session['PaypalProfile'] = $payPalProfile;
         }
     }
     return $this->session['PaypalProfile'];
 }
 /**
  * @param \Enlight_Controller_ActionEventArgs $args
  */
 public function onPreDispatchPaymentPaypal(\Enlight_Controller_ActionEventArgs $args)
 {
     $request = $args->getRequest();
     /** @var \Shopware_Controllers_Frontend_PaymentPaypal $controller */
     $controller = $args->getSubject();
     if ($request->getActionName() != 'return') {
         return;
     }
     $paymentId = $request->get('paymentId');
     if (!$paymentId) {
         return;
     }
     $payerId = $request->getParam('PayerID');
     $uri = 'payments/payment/' . $paymentId;
     $payment = array();
     try {
         $payment = $this->restClient->get($uri, array('payer_id' => $payerId));
     } catch (Exception $e) {
         $this->logException('An error occurred on getting the payment on returning from PayPal', $e);
     }
     if (!empty($payment['transactions'][0]['amount']['total'])) {
         $ppAmount = floatval($payment['transactions'][0]['amount']['total']);
         $ppCurrency = floatval($payment['transactions'][0]['amount']['currency']);
     } else {
         $ppAmount = 0;
         $ppCurrency = '';
     }
     $swAmount = $controller->getAmount();
     $swCurrency = $controller->getCurrencyShortName();
     if (abs($swAmount - $ppAmount) >= 0.01 || $ppCurrency != $swCurrency) {
         $controller->redirect(array('controller' => 'checkout', 'action' => 'confirm'));
         return;
     }
     $paypalConfig = $this->paypalBootstrap->Config();
     $orderNumber = null;
     if ($payment['state'] == 'created') {
         if ($paypalConfig->get('paypalSendInvoiceId')) {
             $orderNumber = $controller->saveOrder($payment['id'], sha1($payment['id']));
             $params = array(array('op' => 'add', 'path' => '/transactions/0/invoice_number', 'value' => $orderNumber));
             $prefix = $paypalConfig->get('paypalPrefixInvoiceId');
             if ($prefix) {
                 // Set prefixed invoice id - Remove special chars and spaces
                 $prefix = str_replace(' ', '', $prefix);
                 $prefix = preg_replace('/[^A-Za-z0-9\\_]/', '', $prefix);
                 $params[0]['value'] = $prefix . $orderNumber;
             }
             $uri = 'payments/payment/' . $paymentId;
             try {
                 $this->restClient->patch($uri, $params);
             } catch (Exception $e) {
                 $this->logException('An error occurred on patching the order number to the payment', $e);
             }
         }
         $uri = "payments/payment/{$paymentId}/execute";
         try {
             $payment = $this->restClient->create($uri, array('payer_id' => $payerId));
         } catch (Exception $e) {
             $this->logException('An error occurred on executing the payment', $e);
         }
     }
     if ($payment['state'] == 'approved') {
         if (!empty($payment['transactions'][0]['related_resources'][0]['sale']['id'])) {
             $transactionId = $payment['transactions'][0]['related_resources'][0]['sale']['id'];
         } else {
             $transactionId = $payment['id'];
         }
         if (!$orderNumber) {
             $orderNumber = $controller->saveOrder($transactionId, sha1($payment['id']));
         } else {
             $sql = 'UPDATE s_order
                     SET transactionID = ?
                     WHERE ordernumber = ?;';
             $controller->get('db')->query($sql, array($transactionId, $orderNumber));
         }
         if (!empty($payment['transactions'][0]['related_resources'][0]['sale']['state'])) {
             $paymentStatus = ucfirst($payment['transactions'][0]['related_resources'][0]['sale']['state']);
             $this->paypalBootstrap->setPaymentStatus($transactionId, $paymentStatus);
         }
         if ($payment['payment_instruction']) {
             $this->saveInvoiceInstructions($orderNumber, $payment);
         }
         try {
             $sql = '
                 INSERT INTO s_order_attributes (orderID, swag_payal_express)
                 SELECT id, 2 FROM s_order WHERE ordernumber = ?
                 ON DUPLICATE KEY UPDATE swag_payal_express = 2
             ';
             $controller->get('db')->query($sql, array($orderNumber));
         } catch (Exception $e) {
         }
         $controller->redirect(array('controller' => 'checkout', 'action' => 'finish', 'sUniqueID' => sha1($payment['id'])));
     }
 }