Ejemplo n.º 1
0
 /**
  * Set credentials from database according to SandBox Mode
  *
  * @param ConfigInterface $config Variable
  *
  * @throws \InvalidArgumentException
  */
 protected function setDefaultCredentials(ConfigInterface $config)
 {
     $paypalApiManager = new PaypalApiManager($config);
     if ($paypalApiManager->isModeSandbox()) {
         $username = $config->getLoginSandbox() != null ? $config->getLoginSandbox() : "";
         $password = $config->getPasswordSandbox() != null ? $config->getPasswordSandbox() : "";
         $signature = $config->getSignatureSandbox() != null ? $config->getSignatureSandbox() : "";
     } else {
         $username = $config->getLogin() != null ? $config->getLogin() : "";
         $password = $config->getPassword() != null ? $config->getPassword() : "";
         $signature = $config->getSignature() != null ? $config->getSignature() : "";
     }
     if (empty($username)) {
         throw new \InvalidArgumentException(Translator::getInstance()->trans('The username option must be set.'));
     }
     if (empty($password)) {
         throw new \InvalidArgumentException(Translator::getInstance()->trans('The password option must be set.'));
     }
     if (empty($signature)) {
         throw new \InvalidArgumentException(Translator::getInstance()->trans('The signature option must be set.'));
     }
     $this->apiUsername = $username;
     $this->apiPassword = $password;
     $this->apiSignature = $signature;
 }
 /**
  * Send request via Curl
  *
  * @return string APÏ response
  */
 public function send()
 {
     $config = new PaypalConfig();
     $config->pushValues();
     $paypalApiManager = new PaypalApiManager($config);
     $url = $paypalApiManager->getApiUrl() . '?' . $this->message;
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $response = curl_exec($ch);
     return $response;
 }
Ejemplo n.º 3
0
 /**
  * Parse and log the return of the Paypal NVP API
  *
  * @param string $transaction A special string returned by the NVP API
  */
 public function logTransaction($transaction)
 {
     $this->setTLogPaypal();
     /*
      * Then write
      */
     $logLine = '';
     $parsedTransaction = PaypalApiManager::nvpToArray($transaction);
     $date = new \DateTime($parsedTransaction['TIMESTAMP']);
     $logLine .= $date->format('Y-m-d H:i:s') . ' ';
     $logLine .= 'Transaction ' . $parsedTransaction['ACK'] . ' ';
     $logLine .= 'correlationId: ' . $parsedTransaction['CORRELATIONID'] . ' ';
     if ($parsedTransaction !== null && array_key_exists('L_ERRORCODE0', $parsedTransaction)) {
         $logLine .= 'error: ';
         $logLine .= '[' . $parsedTransaction['L_ERRORCODE0'] . '] ';
         $logLine .= '<' . $parsedTransaction['L_SHORTMESSAGE0'] . '> ';
         $logLine .= $parsedTransaction['L_LONGMESSAGE0'] . ' ';
     }
     $this->log->info($logLine);
     $this->getBackToPreviousState();
 }
Ejemplo n.º 4
0
 public function go($order_id)
 {
     /*
      * vars used for setExpressCheckout
      * $order Order The order object, which is used to get products and prices
      * $config ConfigInterface Object that contains configuration
      * $api PaypalApiCredentials Class used by the library to store and use 3T login(username, password, signature)
      * $redirect_api PaypalApiManager Instance of PaypalApiManager, only used to get checkout url ( and redirect to paypal )
      * $sandbox bool true if sandbox is enabled
      * $products array(array) 2D array that stores products in usable NVP format.
      * $i int counter
      * $logger PaypalApiLogManager used to log transactions with paypal
      */
     $order = OrderQuery::create()->findPk($order_id);
     $config = new PaypalConfig();
     $config->pushValues();
     $api = new PaypalApiCredentials($config);
     $redirect_api = new PaypalApiManager($config);
     $sandbox = $api->getConfig()->getSandbox();
     $products = array(array());
     $i = 0;
     $logger = new PaypalApiLogManager();
     /*
      * Store products into 2d array $products
      */
     $products_amount = 0;
     foreach ($order->getOrderProducts() as $product) {
         if ($product !== null) {
             $amount = floatval($product->getWasInPromo() ? $product->getPromoPrice() : $product->getPrice());
             foreach ($product->getOrderProductTaxes() as $tax) {
                 $amount += $product->getWasInPromo() ? $tax->getPromoAmount() : $tax->getAmount();
             }
             $products_amount += $amount * $product->getQuantity();
             $products[0]["NAME" . $i] = urlencode($product->getTitle());
             $products[0]["AMT" . $i] = urlencode(round($amount, 2));
             $products[0]["QTY" . $i] = urlencode($product->getQuantity());
             $i++;
         }
     }
     /*
      * Compute difference between prodcts total and cart amount
      * -> get Coupons.
      */
     $delta = round($products_amount - $order->getTotalAmount($useless, false), 2);
     if ($delta > 0) {
         $products[0]["NAME" . $i] = Translator::getInstance()->trans("Discount");
         $products[0]["AMT" . $i] = -$delta;
         $products[0]["QTY" . $i] = 1;
     }
     /*
      * Create setExpressCheckout request
      */
     $setExpressCheckout = new PaypalNvpOperationsSetExpressCheckout($api, round($order->getTotalAmount(), 2), $order->getCurrency()->getCode(), Paypal::getPaypalURL('paiement', $order_id), Paypal::getPaypalURL('cancel', $order_id), 0, array("L_PAYMENTREQUEST" => $products, "PAYMENTREQUEST" => array(array("SHIPPINGAMT" => round($order->getPostage(), 2), "ITEMAMT" => round($order->getTotalAmount($useless, false), 2)))));
     /*
      * Try to get customer's delivery address
      */
     $address = OrderAddressQuery::create()->findPk($order->getDeliveryOrderAddressId());
     if ($address !== null) {
         /*
          * If address is found, set address in setExpressCheckout request
          */
         $setExpressCheckout->setCustomerDeliveryAddress($address->getLastname(), $address->getAddress1(), $address->getAddress2(), $address->getCity(), "", $address->getZipcode(), CountryQuery::create()->findPk($address->getCountryId())->getIsoalpha2());
         /*
          * $sender PaypalNvpMessageSender Instance of the class that sends requests
          * $response string NVP response of paypal for setExpressCheckout request
          * $req array array cast of NVP response
          */
         $sender = new PaypalNvpMessageSender($setExpressCheckout, $sandbox);
         $response = $sender->send();
         $logger->logTransaction($response);
         $response = PaypalApiManager::nvpToArray($response);
         /*
          * if setExpressCheckout is correct, store values in the session & redirect to paypal checkout page
          * else print error. ( return $this->render ... )
          */
         if (isset($response['ACK']) && $response['ACK'] === "Success" && isset($response['TOKEN']) && !empty($response['TOKEN'])) {
             $sess = $this->getRequest()->getSession();
             $sess->set("Paypal.token", $response['TOKEN']);
             return new RedirectResponse($redirect_api->getExpressCheckoutUrl($response['TOKEN']));
         }
     }
     return $this->render("gotopaypalfail", array(), 500);
 }
Ejemplo n.º 5
0
 /**
  * @param $order_id
  * @return \Thelia\Core\HttpFoundation\Response
  */
 public function ok($order_id)
 {
     /*
      * Check if token&order are valid
      */
     $token = null;
     $order = $this->checkorder($order_id, $token);
     /*
      * $payerid string value returned by paypal
      * $logger PaypalApiLogManager used to log transctions with paypal
      */
     $payerid = $this->getRequest()->get('PayerID');
     $logger = new PaypalApiLogManager();
     if (!empty($payerid)) {
         /*
          * $config ConfigInterface Object that contains configuration
          * $api PaypalApiCredentials Class used by the library to store and use 3T login(username, password, signature)
          * $sandbox bool true if sandbox is enabled
          */
         $config = new PaypalConfig();
         $config->pushValues();
         $api = new PaypalApiCredentials($config);
         $sandbox = $api->getConfig()->getSandbox();
         /*
          * Send getExpressCheckout & doExpressCheckout
          * empty cart
          */
         $getExpressCheckout = new PaypalNvpOperationsGetExpressCheckoutDetails($api, $token);
         $request = new PaypalNvpMessageSender($getExpressCheckout, $sandbox);
         $response = $request->send();
         $logger->logTransaction($response);
         $response = PaypalApiManager::nvpToArray($response);
         if (isset($response['ACK']) && $response['ACK'] === 'Success' && isset($response['PAYERID']) && $response['PAYERID'] === $payerid && isset($response['TOKEN']) && $response['TOKEN'] === $token) {
             $doExpressCheckout = new PaypalNvpOperationsDoExpressCheckoutPayment($api, round($order->getTotalAmount(), 2), $order->getCurrency()->getCode(), $payerid, PaypalApiManager::PAYMENT_TYPE_SALE, $token, URL::getInstance()->absoluteUrl("/module/paypal/listen"));
             $request = new PaypalNvpMessageSender($doExpressCheckout, $token);
             $response = $request->send();
             $logger->logTransaction($response);
             $response = PaypalApiManager::nvpToArray($response);
             /*
              * In case of pending status, log the reason to get usefull information (multi-currency problem, ...)
              */
             if (isset($response['ACK']) && $response['ACK'] === "Success" && isset($response['PAYMENTINFO_0_PAYMENTSTATUS']) && $response['PAYMENTINFO_0_PAYMENTSTATUS'] === "Pending") {
                 $logger->logText('Paypal transaction is pending. Reason: ' . $response['PAYMENTINFO_0_PENDINGREASON'], 'NOTICE');
             }
             /*
              * In case of success, go to success page
              * In case of error, show it
              */
             if (isset($response['ACK']) && $response['ACK'] === "Success" && isset($response['PAYMENTINFO_0_PAYMENTSTATUS']) && $response['PAYMENTINFO_0_PAYMENTSTATUS'] === "Completed" && isset($response['TOKEN']) && $response['TOKEN'] === $token) {
                 /*
                  * Set order status as paid
                  */
                 $event = new OrderEvent($order);
                 $event->setStatus(OrderStatusQuery::getPaidStatus()->getId());
                 $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
                 $this->redirectToSuccessPage($order_id);
             }
         }
     }
     /*
      * If no redirection done ( === error ): Empty cart
      */
     return $this->render("order-failed", ["failed_order_id" => $order_id]);
 }
 /**
  * {@inheritdoc }
  */
 public function getRequest()
 {
     $request = parent::getRequest();
     $request .= '&PAYMENTREQUEST_0_AMT=' . urlencode(PaypalApiManager::convertFloatToNvpFormat($this->amount));
     $request .= '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($this->currencyId);
     $request .= '&RETURNURL=' . urlencode($this->returnUrl);
     $request .= '&CANCELURL=' . urlencode($this->cancelUrl);
     if ($this->isPaypalAddressOverrided) {
         $request .= '&ADDROVERRIDE=1';
         $request .= '&PAYMENTREQUEST_0_SHIPTONAME=' . urlencode($this->name);
         $request .= '&PAYMENTREQUEST_0_SHIPTOSTREET=' . urlencode($this->street);
         $request .= '&PAYMENTREQUEST_0_SHIPTOSTREET2=' . urlencode($this->street2);
         $request .= '&PAYMENTREQUEST_0_SHIPTOCITY=' . urlencode($this->city);
         $request .= '&PAYMENTREQUEST_0_SHIPTOSTATE=' . urlencode($this->state);
         $request .= '&PAYMENTREQUEST_0_SHIPTOZIP=' . urlencode($this->zip);
         $request .= '&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=' . urlencode($this->countryCode);
     }
     if ($this->billingAgreement != 0) {
         $request .= '&L_BILLINGTYPE0=MerchantInitiatedBillingSingleAgreement';
     }
     if (!empty($this->payload)) {
         $request .= '&' . PaypalApiManager::arrayToNvp($this->payload);
     }
     return $request;
 }