setSubtotal() public method

Amount of the subtotal of the items. **Required** if line items are specified. 10 characters max, with support for 2 decimal places.
public setSubtotal ( string | double $subtotal )
$subtotal string | double
 public function postPayment($producto_id)
 {
     $producto = Producto::find($producto_id);
     if (is_null($producto)) {
         App::abort(404);
     }
     $productoYaComprado = User::find(Auth::user()->id)->Productos()->whereProducto_id($producto->id)->first();
     if (!is_null($productoYaComprado)) {
         App::abort(404);
     }
     \Session::put('producto_id', $producto_id);
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     $items = array();
     $subtotal = 0;
     $currency = 'MXN';
     $item = new Item();
     $item->setName($producto->nombre)->setCurrency($currency)->setDescription($producto->nombre)->setQuantity(1)->setPrice($producto->precio);
     $items[] = $item;
     $subtotal += $producto->precio;
     $item_list = new ItemList();
     $item_list->setItems($items);
     $details = new Details();
     $details->setSubtotal($subtotal);
     //->setShipping(100);
     //$total = $subtotal + 100;
     $total = $subtotal;
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($total)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('');
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(\URL::route('payment.status'))->setCancelUrl(\URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (\PayPal\Exception\PPConnectionException $ex) {
         if (\Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             exit;
         } else {
             return \Redirect::route('home')->with('message', 'Algo salió mal, inténtalo de nuevo más tarde.');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     \Session::put('paypal_payment_id', $payment->getId());
     if (isset($redirect_url)) {
         // redirect to paypal
         return \Redirect::away($redirect_url);
     }
     return \Redirect::route('home')->with('message', 'Ups! Error desconocido. Inténtalo de nuevo más tarde.');
 }
Example #2
0
 public function success()
 {
     $paymentId = request('paymentId');
     $payment = Payment::get($paymentId, $this->paypal);
     $execution = new PaymentExecution();
     $execution->setPayerId(request('PayerID'));
     $transaction = new Transaction();
     $amount = new Amount();
     $details = new Details();
     $productsSum = 0.0;
     foreach ($this->order->getProducts() as $product) {
         $productsSum += $product->getTotal();
     }
     $details->setSubtotal($productsSum);
     $total = $productsSum;
     if ($delivery = $this->order->getDelivery()) {
         $details->setShipping($delivery);
         $total += $delivery;
     }
     if ($vat = $this->order->getVat()) {
         $details->setTax($vat);
         $total += $vat;
     }
     $amount->setCurrency($this->order->getCurrency())->setTotal($total)->setDetails($details);
     $transaction->setAmount($amount);
     $execution->addTransaction($transaction);
     try {
         $payment->execute($execution, $this->paypal);
     } catch (\Exception $e) {
         $this->log($e);
         throw $e;
     } finally {
         Payment::get($paymentId, $this->paypal);
     }
 }
Example #3
0
 /**
  * @param float $shippingPrice
  * @param float $taxPrice
  * @param float $subtotal
  *
  * @return Details
  */
 public static function createDetails($shippingPrice, $taxPrice, $subtotal)
 {
     $details = new Details();
     $details->setShipping($shippingPrice);
     $details->setTax($taxPrice);
     $details->setSubtotal($subtotal);
     return $details;
 }
Example #4
0
 public static function createAmountDetails()
 {
     $amountDetails = new Details();
     $amountDetails->setSubtotal(self::$subtotal);
     $amountDetails->setTax(self::$tax);
     $amountDetails->setShipping(self::$shipping);
     $amountDetails->setFee(self::$fee);
     return $amountDetails;
 }
Example #5
0
 public function pay()
 {
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     //agregar items de base de datos
     $items = array();
     $subtotal = 0;
     $productos = DB::table('carrito')->Join('producto', 'carrito.ItemCode', '=', 'producto.ItemCode')->where('carrito.user_id', Auth::user()->id)->get();
     //dd(Auth::user()->id);
     $currency = 'MXN';
     foreach ($productos as $key => $p) {
         $pIva = $p->precio * 0.16;
         $precioIva = $p->precio + $pIva;
         $item = new Item();
         $item->setName($p->ItemName)->setCurrency($currency)->setDescription($p->tipo)->setQuantity($p->cantidad)->setPrice($precioIva);
         $items[$key] = $item;
         $subtotal += $p->cantidad * $precioIva;
     }
     // add item to list
     $item_list = new ItemList();
     $item_list->setItems($items);
     $details = new Details();
     $details->setSubtotal($subtotal)->setShipping(100);
     $total = $subtotal + 100;
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($total)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Your transaction description');
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(URL::route('payment.status'))->setCancelUrl(URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (\PayPal\Exception\PPConnectionException $ex) {
         if (\Config::get('app.debug')) {
             return Redirect::route('carrito.failed');
             exit;
         } else {
             return Redirect::route('carrito.failed');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     Session::put('paypal_payment_id', $payment->getId());
     if (isset($redirect_url)) {
         // redirect to paypal
         return Redirect::away($redirect_url);
     }
     return Redirect::route('carrito.failed');
 }
 public function postPayment()
 {
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     $items = array();
     $subtotal = 0;
     $cart = \Session::get('cart');
     $currency = 'MXN';
     foreach ($cart as $producto) {
         $item = new Item();
         $item->setName($producto->name)->setCurrency($currency)->setDescription($producto->extract)->setQuantity($producto->quantity)->setPrice($producto->price);
         $items[] = $item;
         $subtotal += $producto->quantity * $producto->price;
     }
     $item_list = new ItemList();
     $item_list->setItems($items);
     //costo de envio de la compra
     $details = new Details();
     $details->setSubtotal($subtotal)->setShipping(100);
     //total de envio sumando el subtotal mas el envio
     $total = $subtotal + 100;
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($total)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Pedido de prueba con laravel para La Central Mueblera');
     //la ruta  para direccionar si se cancela o se envia conrectamente el pedido
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(\URL::route('payment.status'))->setCancelUrl(\URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (\PayPal\Exception\PPConnectionException $ex) {
         if (\Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             exit;
         } else {
             die('Ups! Algo salió mal');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     \Session::put('paypal_payment_id', $payment->getId());
     if (isset($redirect_url)) {
         // redirect to paypal
         return \Redirect::away($redirect_url);
     }
     return \Redirect::route('cart-show')->with('error', 'Ups! Error desconocido.');
 }
 public function postPayment()
 {
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     $items = array();
     $subtotal = 0;
     $cart = \Session::get('product');
     $currency = 'USD';
     $item = new Item();
     $item->setName($cart->name)->setCurrency($currency)->setDescription($cart->description)->setQuantity(1)->setPrice($cart->price);
     $items[] = $item;
     $subtotal += $cart->price;
     $item_list = new ItemList();
     $item_list->setItems($items);
     $details = new Details();
     $details->setSubtotal($subtotal)->setShipping(0);
     $total = $subtotal + 0;
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($total)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Order plan in hdsports.in');
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(\URL::route('payment.status'))->setCancelUrl(\URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (\PayPal\Exception\PPConnectionException $ex) {
         if (\Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             exit;
         } else {
             die('Ups! something went wrong');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     \Session::put('paypal_payment_id', $payment->getId());
     if (isset($redirect_url)) {
         // redirect to paypal
         return \Redirect::away($redirect_url);
     }
     return \Redirect::to('/')->with('message', 'Ups! Unknown mistake.');
 }
 /**
  * Creates PayPal payment details from given order
  *
  * @param OrderInterface $order
  *
  * @return Details
  */
 protected function createDetails(OrderInterface $order) : Details
 {
     $details = new Details();
     $details->setShipping($order->getShippingTotal()->getNetAmount());
     $details->setTax($order->getOrderTotal()->getTaxAmount());
     $details->setSubtotal($order->getProductTotal()->getNetAmount());
     return $details;
 }
Example #9
0
 public function submit($ordernumber)
 {
     $order = Order::where('ordernumber', "=", $ordernumber)->first();
     if ($order->payment_method == self::PAYMENT_BANK) {
         Mail::send('emails.moneyorder', ['order' => $order], function ($message) use($order) {
             $message->from(self::$shopmail, 'LEAF Music');
             $message->subject('LEAF Music Order ' . $order->ordernumber . ' - waiting for payment');
             $message->to($order->email)->bcc(self::$shopmail)->replyTo(self::$shopmail);
         });
         Mail::send('emails.kaatmail', ['order' => $order], function ($message) use($order) {
             $message->from(self::$shopmail, 'LEAF Music');
             $message->subject('LEAF Music Order ' . $order->ordernumber . ' - waiting for payment');
             $message->to(self::$shopmail);
         });
         $order->status = Order::STATUS_WAITING;
         $order->save();
         return Redirect::action('WelcomeController@result', [$order->ordernumber]);
     } else {
         // setup PayPal api context
         $paypal_conf = \Config::get('paypal');
         $api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
         $api_context->setConfig($paypal_conf['settings']);
         $payer = new Payer();
         $payer->setPaymentMethod("paypal");
         $itemarray = [];
         $details = new Details();
         $subtotal = 0;
         foreach ($order->orderitems as $orderitem) {
             //http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html
             //http://learninglaravel.net/integrate-paypal-sdk-into-laravel-4-laravel-5/link
             if ($orderitem->item_id != Item::SHIPPING) {
                 $item = new \PayPal\Api\Item();
                 $item->setName($orderitem->item->title)->setCurrency('EUR')->setQuantity($orderitem->amount)->setSku($orderitem->item_id)->setPrice($orderitem->itemprice);
                 $itemarray[] = $item;
                 $subtotal += $orderitem->amount * $orderitem->itemprice;
             } else {
                 $details->setShipping($orderitem->itemprice)->setTax(0);
             }
         }
         $details->setSubtotal($subtotal);
         $itemlist = new ItemList();
         $itemlist->setItems($itemarray);
         $transaction = new Transaction();
         $amount = new Amount();
         $amount->setCurrency("EUR")->setTotal($order->totalamount)->setDetails($details);
         $transaction->setAmount($amount)->setItemList($itemlist)->setDescription("Payment description")->setInvoiceNumber($order->order_number);
         $redirectUrls = new RedirectUrls();
         $redirectUrls->setReturnUrl(action('WelcomeController@paypalReturn', [self::PAYPAL_OK, $order->ordernumber]))->setCancelUrl(action('WelcomeController@paypalReturn', [self::PAYPAL_PROBLEM, $order->ordernumber]));
         $payment = new Payment();
         $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));
         try {
             $payment->create($api_context);
         } catch (\PayPal\Exception\PayPalConnectionException $pce) {
             // Don't spit out errors or use "exit" like this in production code
             return view('problem', ["order" => $order]);
         }
         $approvalUrl = $payment->getApprovalLink();
         return Redirect::to($approvalUrl);
     }
 }
Example #10
0
 public function actionPay($id)
 {
     $return = [];
     $total = 0;
     if (isset(Yii::$app->user->id)) {
         $user = User::findOne(Yii::$app->user->id);
         $race = Race::findOne($id);
         if ($user && $race) {
             /* paypal */
             $clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS';
             $clientSecret = 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL';
             $apiContext = $this->getApiContext($clientId, $clientSecret);
             $payer = new Payer();
             $payer->setPaymentMethod("paypal");
             $total = $race->cost;
             $item1 = new Item();
             $item1->setName('Inscripción ' . $race->name)->setCurrency('USD')->setQuantity(1)->setPrice($total);
             /*$item1 = new Item();
               $item1->setName('Ground Coffee 40 oz')
                   ->setCurrency('USD')
                   ->setQuantity(1)
                   ->setPrice(7.5);
               $item2 = new Item();
               $item2->setName('Granola bars')
                   ->setCurrency('USD')
                   ->setQuantity(5)
                   ->setPrice(2);*/
             $itemList = new ItemList();
             $itemList->setItems(array($item1));
             $details = new Details();
             /*$details->setShipping(5)
               // ->setTax(1.3)
               ->setSubtotal($total);*/
             $details->setSubtotal($total);
             $amount = new Amount();
             $amount->setCurrency("USD")->setTotal($total)->setDetails($details);
             $transaction = new Transaction();
             $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Inscripción en Aurasur")->setInvoiceNumber('1234567890');
             $baseUrl = Url::base(true);
             $redirectUrls = new RedirectUrls();
             $redirectUrls->setReturnUrl($baseUrl . "/user/view?id=" . $user->id . "&r=ins")->setCancelUrl($baseUrl . "/race/pay?success=false&id=" . $id);
             $payment = new Payment();
             $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));
             try {
                 $payment->create($apiContext);
             } catch (Exception $ex) {
                 print_r($ex);
                 exit(1);
             }
             $approvalUrl = $payment->getApprovalLink();
             /* --- */
         }
     } else {
         return $this->redirect(Yii::getAlias('@web') . '/site/login?ins=' . $id);
     }
     return $this->render('pay', ['race' => $race, 'aurl' => $approvalUrl]);
 }
 private function createDetails(OrderInterface $order) : Details
 {
     $shippingCosts = $order->getModifier('shipping_cost');
     $details = new Details();
     $details->setShipping($shippingCosts->getNetAmount());
     $details->setTax($order->getSummary()->getTaxAmount());
     $details->setSubtotal($order->getProductTotal()->getNetPrice());
     return $details;
 }
 /**
  * Gets link for account payment
  *
  * @access public
  * @param array $settings
  * @return null
  */
 public static function get_link(array $settings)
 {
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     $data = self::get_data($settings['payment_type'], $settings['object_id']);
     $item = new Item();
     $item->setName($data['title'])->setDescription($data['description'])->setCurrency($data['currency_code'])->setQuantity(1)->setPrice($data['price']);
     $item_list = new ItemList();
     $item_list->setItems(array($item));
     $details = new Details();
     $details->setSubtotal($data['price']);
     $amount = new Amount();
     $amount->setCurrency($data['currency_code'])->setTotal($data['price'])->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription($data['description'])->setInvoiceNumber(uniqid());
     $redirectUrls = new RedirectUrls();
     $url = self::get_paypal_process_url(get_current_user_id(), $settings['payment_type'], $settings['object_id']);
     $redirectUrls->setReturnUrl($url)->setCancelUrl(plugins_url() . '/realestate/includes/paypal-payment.php?success=false&payment_type=' . $settings['payment_type'] . '&object_id=' . $settings['object_id'] . '&user_id=' . get_current_user_id());
     $payment = new Payment();
     $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));
     try {
         $api_context = self::get_paypal_context();
         $payment->create($api_context);
     } catch (Exception $ex) {
         var_dump($ex);
         die;
         return null;
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             wp_redirect($link->getHref());
             exit;
         }
     }
     return null;
 }
Example #13
0
 public function setPaypalDetails($shipping, $tax, $subtotal)
 {
     $subtotal = number_format($subtotal, 2);
     $shipping = number_format($shipping, 2);
     $tax = number_format($tax, 2);
     $details = new Details();
     $details->setSubtotal($subtotal);
     $details->setShipping($shipping);
     $details->setTax($tax);
     return $details;
 }
 public function teszt($amount, $description)
 {
     $apiContext = new \PayPal\Rest\ApiContext(new \PayPal\Auth\OAuthTokenCredential('AfikH2WfU1x0YF1ThuSkBaMKqDh-rxE5NEBpLWOF3UVmii-P97WdgJCUhoH1ff5pMHToHnB-sXoejgGv', 'EM7ObD_onQ1EqaeiVBFvSId9AIQevTlsYcLPi-3SeVivyQ9A361Ov5jx4KlFkamOsh_c6I25VM1Ck4ZX'));
     //SAMPLE 1
     // $card = new CreditCard();
     // $card->setType("visa")
     //     ->setNumber("4148529247832259")
     //     ->setExpireMonth("11")
     //     ->setExpireYear("2019")
     //     ->setCvv2("012")
     //     ->setFirstName("Joe")
     //     ->setLastName("Shopper");
     // // ### FundingInstrument
     // // A resource representing a Payer's funding instrument.
     // // For direct credit card payments, set the CreditCard
     // // field on this object.
     // $fi = new FundingInstrument();
     // $fi->setCreditCard($card);
     // // ### Payer
     // // A resource representing a Payer that funds a payment
     // // For direct credit card payments, set payment method
     // // to 'credit_card' and add an array of funding instruments.
     // $payer = new Payer();
     // $payer->setPaymentMethod("credit_card")
     //     ->setFundingInstruments(array($fi));
     // // ### Itemized information
     // // (Optional) Lets you specify item wise
     // // information
     // $item1 = new Item();
     // $item1->setName('Ground Coffee 40 oz')
     //     ->setDescription('Ground Coffee 40 oz')
     //     ->setCurrency('USD')
     //     ->setQuantity(1)
     //     ->setTax(0.3)
     //     ->setPrice(7.50);
     // $item2 = new Item();
     // $item2->setName('Granola bars')
     //     ->setDescription('Granola Bars with Peanuts')
     //     ->setCurrency('USD')
     //     ->setQuantity(5)
     //     ->setTax(0.2)
     //     ->setPrice(2);
     // $itemList = new ItemList();
     // $itemList->setItems(array($item1, $item2));
     // // ### Additional payment details
     // // Use this optional field to set additional
     // // payment information such as tax, shipping
     // // charges etc.
     // $details = new Details();
     // $details->setShipping(1.2)
     //     ->setTax(1.3)
     //     ->setSubtotal(17.5);
     // // ### Amount
     // // Lets you specify a payment amount.
     // // You can also specify additional details
     // // such as shipping, tax.
     // $amount = new Amount();
     // $amount->setCurrency("USD")
     //     ->setTotal(20)
     //     ->setDetails($details);
     // // ### Transaction
     // // A transaction defines the contract of a
     // // payment - what is the payment for and who
     // // is fulfilling it.
     // $transaction = new Transaction();
     // $transaction->setAmount($amount)
     //     ->setItemList($itemList)
     //     ->setDescription("Payment description")
     //     ->setInvoiceNumber(uniqid());
     // // ### Payment
     // // A Payment Resource; create one using
     // // the above types and intent set to sale 'sale'
     // $payment = new Payment();
     // $payment->setIntent("sale")
     //     ->setPayer($payer)
     //     ->setTransactions(array($transaction));
     // // For Sample Purposes Only.
     // $request = clone $payment;
     // // ### Create Payment
     // // Create a payment by calling the payment->create() method
     // // with a valid ApiContext (See bootstrap.php for more on `ApiContext`)
     // // The return object contains the state.
     // try {
     //     $payment->create($apiContext);
     // } catch (Exception $ex) {
     //    // ResultPrinter::printError('Create Payment Using Credit Card. If 500 Exception, try creating a new Credit Card using <a href="https://ppmts.custhelp.com/app/answers/detail/a_id/750">Step 4, on this link</a>, and using it.', 'Payment', null, $request, $ex);
     //     exit(1);
     // }
     //ResultPrinter::printResult('Create Payment Using Credit Card', 'Payment', $payment->getId(), $request, $payment);
     //return $payment;
     //END SAMPLE 1
     //SAMPLE 2
     // $creditCard = new \PayPal\Api\CreditCard();
     // $creditCard->setType("visa")
     //     ->setNumber("4417119669820331")
     //     ->setExpireMonth("11")
     //     ->setExpireYear("2019")
     //     ->setCvv2("012")
     //     ->setFirstName("Joe")
     //     ->setLastName("Shopper");
     // try {
     //     $creditCard->create($apiContext);
     //     echo '<pre>';
     //     print_r($creditCard);
     // }
     // catch (\PayPal\Exception\PayPalConnectionException $ex) {
     //     echo $ex;
     // }
     //END SAMPLE 2
     //SAMPLE 3
     $payer = new Payer();
     $payer->setPaymentMethod("paypal");
     // ### Itemized information
     // (Optional) Lets you specify item wise
     // information
     $item1 = new Item();
     $item1->setName('Ground Coffee 40 oz')->setCurrency('USD')->setQuantity(1)->setPrice(7.5);
     $item2 = new Item();
     $item2->setName('Granola bars')->setCurrency('USD')->setQuantity(5)->setPrice(2);
     $itemList = new ItemList();
     $itemList->setItems(array($item1, $item2));
     // ### Additional payment details
     // Use this optional field to set additional
     // payment information such as tax, shipping
     // charges etc.
     /* $details = new Details();
     $details->setShipping(1.2)
         ->setTax(1.3)
         ->setSubtotal(17.50); */
     // ### Amount
     // Lets you specify a payment amount.
     // You can also specify additional details
     // such as shipping, tax.
     /* $amount = new Amount();
     $amount->setCurrency("USD")
         ->setTotal(20)
         ->setDetails($details); */
     // ### Transaction
     // A transaction defines the contract of a
     // payment - what is the payment for and who
     // is fulfilling it.
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description");
     // ->setInvoiceNumber('134');
     //>setInvoiceNumber(uniqid());
     // ### Redirect urls
     // Set the urls that the buyer must be redirected to after
     // payment approval/ cancellation.
     //$baseUrl = getBaseUrl();
     $redirectUrls = new RedirectUrls();
     $redirectUrls->setReturnUrl("http://localhost/yii-application/frontend/web/index.php?r=/cart/default/ordered")->setCancelUrl("http://localhost/yii-application/frontend/web/index.php?r=/cart/default/index");
     // ### Payment
     // A Payment Resource; create one using
     // the above types and intent set to 'sale'
     /* $payment = new Payment();
     $payment->setIntent("sale")
         ->setPayer($payer)
         ->setRedirectUrls($redirectUrls)
         ->setTransactions(array($transaction)); */
     $addr = new Address();
     $addr->setLine1('52 N Main ST');
     $addr->setCity('Johnstown');
     $addr->setCountryCode('US');
     $addr->setPostalCode('43210');
     $addr->setState('OH');
     $card = new CreditCard();
     $card->setNumber('5110929378020149');
     $card->setType('MASTERCARD');
     $card->setExpireMonth('08');
     $card->setExpireYear('2020');
     $card->setCvv2('874');
     $card->setFirstName('Nishanth');
     $card->setLastName('Pininti');
     $card->setBillingAddress($addr);
     $fi = new FundingInstrument();
     $fi->setCreditCard($card);
     $payer = new Payer();
     $payer->setPaymentMethod('credit_card');
     $payer->setFundingInstruments(array($fi));
     $amountDetails = new \PayPal\Api\Details();
     $amountDetails->setSubtotal('7.41');
     $amountDetails->setTax('0.03');
     $amountDetails->setShipping('0.03');
     $amount = new Amount();
     $amount->setCurrency('USD');
     $amount->setTotal('7.47');
     $amount->setDetails($amountDetails);
     $transaction = new Transaction();
     $transaction->setAmount($amount);
     $transaction->setDescription('This is the payment transaction description.');
     $payment = new Payment();
     $payment->setIntent('sale');
     $payment->setPayer($payer);
     $payment->setTransactions(array($transaction));
     // For Sample Purposes Only.
     $request = clone $payment;
     // ### Create Payment
     // Create a payment by calling the 'create' method
     // passing it a valid apiContext.
     // (See bootstrap.php for more on `ApiContext`)
     // The return object contains the state and the
     // url to which the buyer must be redirected to
     // for payment approval
     try {
         $payment->create($apiContext);
     } catch (Exception $ex) {
         ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
         exit(1);
     }
     // ### Get redirect url
     // The API response provides the url that you must redirect
     // the buyer to. Retrieve the url from the $payment->getApprovalLink()
     // method
     //$approvalUrl = $payment->getRedirectUrls();
     // ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment);
     var_dump($payment);
     return $payment;
     //END SAMPLE 3
 }
Example #15
0
 public function postPayment($type)
 {
     \Session::forget('pagos_id');
     $pagos_id = \Session::get('pagos_id');
     //\Session::put('pagos_id', $pagos_id);
     \Session::forget('pagos_data');
     $pagos_data = \Session::get('pagos_data');
     //\Session::put('pagos_data', $pagos_data);
     $user_id = $this->auth->user()->id;
     $month = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
     $cta = $this->auth->user()->type;
     $cuota = Cuotas::find($cta);
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     $items = array();
     $subtotal = 0;
     $currency = 'MXN';
     $price = $cuota->amount;
     $descuento = false;
     $discount = -$price;
     $qty = 1;
     $shipp = 0;
     $items_arr = array();
     $pago_hasta = 0;
     $lmt = 0;
     $m = 1;
     //mes de inicio 1-12
     $y = 2016;
     //año de inicio
     $d = date('d');
     $ultimo_p = DB::table('pagos')->where('id_user', $this->auth->user()->id)->where('status', 1)->orderBy('date', 'dsc')->get();
     foreach ($ultimo_p as $pay) {
         $pago_hasta = explode("-", $pay->date);
         $m = intval($pago_hasta[1]);
         $y = intval($pago_hasta[0]);
         $m++;
         if ($m == 13) {
             $m = 1;
             $y++;
         }
         break;
     }
     $prueba = '';
     // 1-mensual
     // 2-semestral
     // 3-anual
     // 4-saldo vencido
     if ($type == 1) {
         $lmt = 1;
     } else {
         if ($type == 2) {
             $lmt = 6;
         } else {
             if ($type == 3) {
                 $lmt = 12;
                 $descuento = true;
             } else {
                 if ($type == 4) {
                     $vencidos = DB::table('pagos')->where('id_user', $this->auth->user()->id)->where('status', 0)->orderBy('date', 'asc')->get();
                     $vence_date = explode("-", $vencidos[0]->date);
                     $m = intval($vence_date[1]);
                     $y = intval($vence_date[0]);
                     //[0]2014 [1]mes [2]dia
                     foreach ($vencidos as $vence) {
                         $pagos_id[] = $vence->id;
                         \Session::put('pagos_id', $pagos_id);
                         $lmt++;
                     }
                 }
             }
         }
     }
     //populate items array
     for ($i = 0; $i < $lmt; $i++) {
         $items_arr[$i] = $month[$m - 1] . " " . $y;
         //se llena con fechas -> yyyy-mm-dd
         if ($m < 10) {
             $pagos_data[$i] = $y . '-0' . $m . '-' . $d;
             \Session::put('pagos_data', $pagos_data);
         } else {
             $pagos_data[$i] = $y . '-' . $m . '-' . $d;
             \Session::put('pagos_data', $pagos_data);
         }
         $m++;
         if ($m == 13) {
             $m = 1;
             $y++;
         }
     }
     //crear los items
     foreach ($items_arr as $pago) {
         $item = new Item();
         $item->setName($pago)->setCurrency($currency)->setDescription('item description')->setQuantity($qty)->setPrice($price);
         $items[] = $item;
         $subtotal += $price * $qty;
     }
     //descuento
     if ($descuento) {
         $item = new Item();
         $item->setName('Descuento Pago Anual(1 mes)')->setCurrency($currency)->setDescription('item description')->setQuantity($qty)->setPrice($discount);
         $items[] = $item;
         $subtotal += $discount * $qty;
     }
     $item_list = new ItemList();
     $item_list->setItems($items);
     $details = new Details();
     $details->setSubtotal($subtotal)->setShipping($shipp);
     $total = $subtotal + $shipp;
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($total)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Pedido de prueba en mi Laravel App');
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(\URL::route('payment.status'))->setCancelUrl(\URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     /*		
     		try {
     			$payment->create($this->_api_context);
     		} catch (PayPal\Exception\PayPalConnectionException $ex) {
     		    //echo $ex->getCode(); // Prints the Error Code
     		    //echo $ex->getData(); // Prints the detailed error message 
     		    die($ex);
     		} catch (Exception $ex) {
     		    die($ex);
     		}
     */
     try {
         $payment->create($this->_api_context);
     } catch (\PayPal\Exception\PPConnectionException $ex) {
         if (\Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             exit;
         } else {
             die('Ups! Algo salió mal');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     \Session::put('paypal_payment_id', $payment->getId());
     if (isset($redirect_url)) {
         // redirect to paypal
         return \Redirect::away($redirect_url);
     }
     return redirect()->to('micuenta')->with('error', 'Ha ocurrido un error. Volver a intentar.');
 }
Example #16
0
 public function payDemo()
 {
     $addr = new Address();
     $addr->setLine1('52 N Main ST');
     $addr->setCity('Johnstown');
     $addr->setCountryCode('US');
     $addr->setPostalCode('43210');
     $addr->setState('OH');
     $card = new CreditCard();
     $card->setNumber('4417119669820331');
     $card->setType('visa');
     $card->setExpireMonth('11');
     $card->setExpireYear('2018');
     $card->setCvv2('874');
     $card->setFirstName('Joe');
     $card->setLastName('Shopper');
     $card->setBillingAddress($addr);
     $fi = new FundingInstrument();
     $fi->setCreditCard($card);
     $payer = new Payer();
     $payer->setPaymentMethod('credit_card');
     $payer->setFundingInstruments(array($fi));
     $amountDetails = new Details();
     $amountDetails->setSubtotal('15.99');
     $amountDetails->setTax('0.03');
     $amountDetails->setShipping('0.03');
     $amount = new Amount();
     $amount->setCurrency('USD');
     $amount->setTotal('7.47');
     $amount->setDetails($amountDetails);
     $transaction = new Transaction();
     $transaction->setAmount($amount);
     $transaction->setDescription('This is the payment transaction description.');
     $payment = new Payment();
     $payment->setIntent('sale');
     $payment->setPayer($payer);
     $payment->setTransactions(array($transaction));
     return $payment->create($this->_apiContext);
 }
 public function createPayment($addressee, $order)
 {
     // Order Totals
     $subTotal = $order->total;
     $shippingCharges = $order->shipping;
     $tax = $order->tax;
     $grandTotal = $order->grandTotal;
     // Get Context
     $context = $this->getApiContext();
     // Payer
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     // Cart Items
     $itemList = $this->generateItemsList($order);
     // Shipping Address
     if ($this->properties->isSendAddress()) {
         $shippingAddress = $this->generateShippingAddress($addressee, $cart);
         $itemList->setShippingAddress($shippingAddress);
     }
     // Details
     $details = new Details();
     $details->setSubtotal($subTotal);
     $details->setShipping($shippingCharges);
     $details->setTax($tax);
     // Amount
     $amount = new Amount();
     $amount->setCurrency($this->properties->getCurrency());
     $amount->setTotal($grandTotal);
     $amount->setDetails($details);
     // Transaction
     $transaction = new Transaction();
     $transaction->setAmount($amount);
     if (isset($order->description)) {
         $transaction->setDescription($order->description);
     }
     $transaction->setItemList($itemList);
     // Status URLs
     $redirectUrls = new RedirectUrls();
     $redirectUrls->setReturnUrl($this->successUrl);
     $redirectUrls->setCancelUrl($this->failureUrl);
     // Payment
     $payment = new Payment();
     $payment->setRedirectUrls($redirectUrls);
     $payment->setIntent("sale");
     $payment->setPayer($payer);
     $payment->setTransactions([$transaction]);
     $payment->create($context);
     return $payment;
 }
 public function postPayment(Request $request)
 {
     $data = $request->all();
     $error = false;
     //Verificacion de existencia de variables
     if (!isset($data["mount"]) || !isset($data["quantity"])) {
         $error = true;
     }
     $mount = round(floatval($data["mount"]), 2);
     $quantity = intval($data["quantity"]);
     //Verificacion del tipo de dato
     if ($quantity <= 0 || $mount <= 0) {
         $error = true;
     }
     //Verificacion de cuantias minimas
     if ($quantity < intval(PayM::PAY_MIN_QUANTITY) || $mount < round(floatval(PayM::PAY_PRICE_PER_DAY * PayM::PAY_MIN_QUANTITY), 2)) {
         $error = true;
     }
     //Verificacion de la integridad de los valores
     if ($mount / $quantity != PayM::PAY_PRICE_PER_DAY) {
         $error = true;
     }
     if ($error) {
         return redirect()->back()->with(UI::modalMessage("¡OOUPS ALGO SALIO MAL!", "<div class='text-center'><img width='100px;' src='" . url('assets/images/alert.png') . "'><p style='font-size: 15pt;margin-top:20px;'>Parece que ocurrio un error en la integridad de la información enviada. Por favor intentalo de nuevo. Si el problema persiste intentalo de nuevo más tarde.</p></div>", "¡OK!"));
     }
     $payer = new Payer();
     $payer->setPaymentMethod(PayM::METHOD_PAYPAL);
     $items = array();
     $subtotal = 0;
     $currency = PayM::MONEY_CURRENT;
     $price = $mount;
     //Descripción del item a comprar
     $item = new Item();
     $item->setName(PayM::PAY_NAME)->setCurrency($currency)->setDescription("x " . $quantity . " días")->setQuantity(PayM::PAY_QUANTITY)->setPrice($price);
     $items[] = $item;
     $subtotal = $price;
     //Totales
     $item_list = new ItemList();
     $item_list->setItems($items);
     $details = new Details();
     $details->setSubtotal($subtotal);
     $total = $subtotal;
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($total)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription("Bandicot.com");
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(url('premium/payment/status'))->setCancelUrl(url('premium/payment/status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (\PayPal\Exception\PPConnectionException $ex) {
         if (\Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             exit;
         } else {
             return redirect()->back()->with(UI::modalMessage("¡OOUPS ALGO SALIO MAL!", "<div class='text-center'><img width='100px;' src='" . url('assets/images/alert.png') . "'><p style='font-size: 15pt;margin-top:20px;'>Parece que ocurrio un error al tratar de conectarse con el servidor pagos Paypal. Por favor intentalo de nuevo. Si el problema persiste intentalo de nuevo más tarde.</p></div>", "¡OK!"));
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     Session::put('paypal_payment_id', $payment->getId());
     Session::put('payment_quantity', $quantity);
     if (isset($redirect_url)) {
         // redirect to paypal
         return \Redirect::away($redirect_url);
     }
     return redirect()->back()->with(UI::modalMessage("¡OOUPS ALGO SALIO MAL!", "<div class='text-center'><img width='100px;' src='" . url('assets/images/alert.png') . "'><p style='font-size: 15pt;margin-top:20px;'>Parece que ocurrio un error al tratar de conectarse con el servidor pagos Paypal. Por favor intentalo de nuevo. Si el problema persiste intentalo de nuevo más tarde.</p></div>", "¡OK!"));
 }
Example #19
0
 public function postPayment()
 {
     $data = Input::get('option');
     foreach ($data as $key => $value) {
         $id_books[] = $key;
         $article[$key] = array('option' => $value[0], 'days' => $value['day'], 'id' => $key);
     }
     $books = Book::select('id', 'title', 'price_day', 'price_bail', 'price_sale')->find($id_books);
     $payer = new Payer();
     $payer->setPaymentMethod('paypal');
     $items = array();
     $subtotal = 0;
     $currency = 'EUR';
     foreach ($books as $producto) {
         if ($article[$producto->id]['option'] == 'rent' && $article[$producto->id]['days'] > 0) {
             $price = $producto->price_day * $article[$producto->id]['days'] + $producto->price_bail;
         } else {
             $price = $producto->price_sale;
         }
         $item = new Item();
         $item->setName($producto->title)->setCurrency($currency)->setDescription($producto->title)->setQuantity(1)->setPrice($price)->setSku($producto->id);
         $items[] = $item;
         $subtotal += $price;
     }
     $item_list = new ItemList();
     $item_list->setItems($items);
     $details = new Details();
     $details->setSubtotal($subtotal)->setShipping(0);
     $amount = new Amount();
     $amount->setCurrency($currency)->setTotal($subtotal)->setDetails($details);
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Pedido de prueba en mi Laravel App Store');
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(URL::route('payment.status'))->setCancelUrl(URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (PayPal\Exception\PPConnectionException $ex) {
         if (Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             exit;
         } else {
             die('Ups! Algo salió mal');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     Session::put('paypal_payment_id', $payment->getId());
     Session::put('articles', $article);
     if (isset($redirect_url)) {
         // redirect to paypal
         return Redirect::away($redirect_url);
     }
     return Redirect::route('cart-show')->with('error', 'Ups! Error desconocido.');
 }
 function get_approvalurl()
 {
     try {
         // try a payment request
         $PaymentData = AngellEYE_Gateway_Paypal::calculate(null, $this->send_items);
         $OrderItems = array();
         if ($this->send_items) {
             foreach ($PaymentData['order_items'] as $item) {
                 $_item = new Item();
                 $_item->setName($item['name'])->setCurrency(get_woocommerce_currency())->setQuantity($item['qty'])->setPrice($item['amt']);
                 array_push($OrderItems, $_item);
             }
         }
         $redirectUrls = new RedirectUrls();
         $redirectUrls->setReturnUrl(add_query_arg(array('pp_action' => 'executepay'), home_url()));
         $redirectUrls->setCancelUrl($this->cancel_url);
         $payer = new Payer();
         $payer->setPaymentMethod("paypal");
         $details = new Details();
         if (isset($PaymentData['shippingamt'])) {
             $details->setShipping($PaymentData['shippingamt']);
         }
         if (isset($PaymentData['taxamt'])) {
             $details->setTax($PaymentData['taxamt']);
         }
         $details->setSubtotal($PaymentData['itemamt']);
         $amount = new Amount();
         $amount->setCurrency(PP_CURRENCY);
         $amount->setTotal(WC()->cart->total);
         $amount->setDetails($details);
         $items = new ItemList();
         $items->setItems($OrderItems);
         $transaction = new Transaction();
         $transaction->setAmount($amount);
         $transaction->setDescription('');
         $transaction->setItemList($items);
         //$transaction->setInvoiceNumber($this->invoice_prefix.$order_id);
         $payment = new Payment();
         $payment->setRedirectUrls($redirectUrls);
         $payment->setIntent("sale");
         $payment->setPayer($payer);
         $payment->setTransactions(array($transaction));
         $payment->create($this->getAuth());
         $this->add_log(print_r($payment, true));
         //if payment method was PayPal, we need to redirect user to PayPal approval URL
         if ($payment->state == "created" && $payment->payer->payment_method == "paypal") {
             WC()->session->paymentId = $payment->id;
             //set payment id for later use, we need this to execute payment
             return $payment->links[1]->href;
         }
     } catch (PayPal\Exception\PayPalConnectionException $ex) {
         wc_add_notice(__("Error processing checkout. Please try again. ", 'woocommerce'), 'error');
         $this->add_log($ex->getData());
     } catch (Exception $ex) {
         wc_add_notice(__('Error processing checkout. Please try again. ', 'woocommerce'), 'error');
         $this->add_log($ex->getMessage());
     }
 }
 public function postPayment()
 {
     $payer = new Payer();
     $i = [];
     $input = Input::all();
     $membership_discount = Session::has('reservation.customerdiscount') ? number_format(Session::get('reservation.customerdiscountprice'), 2) : 0;
     $coupon_discount = 0;
     $total_discount = 0;
     $i['checkin'] = Session::get('reservation')['checkin'];
     $i['checkout'] = Session::get('reservation')['checkout'];
     $i['total_nights'] = Session::get('reservation')['nights'];
     $total_price = 0;
     $tax_price = 0;
     $item = [];
     $payer->setPaymentMethod('paypal');
     foreach (Session::get('reservation')['reservation_room'] as $roomKey => $rooms) {
         $total_price += $rooms['room_details']['price'] * $i['total_nights'] * $rooms['quantity'];
         $room_id = $rooms['room_details']['id'];
         $available_rooms = [];
         $room_qty = RoomQty::with(array('roomPrice', 'roomReserved' => function ($query) use($i, $room_id) {
             $query->where(function ($query2) use($i, $room_id) {
                 $query2->whereBetween('check_in', array($i['checkin'], $i['checkout']))->orWhereBetween('check_out', array($i['checkin'], $i['checkout']))->orWhereRaw('"' . $i["checkin"] . '" between check_in and check_out')->orWhereRaw('"' . $i["checkout"] . '" between check_in and check_out');
             })->where('status', '!=', 5);
         }))->where('room_id', $room_id)->get();
         foreach ($room_qty as $available) {
             if ($available->roomReserved == '[]') {
                 $item[$roomKey] = new Item();
                 $item[$roomKey]->setName($rooms['room_details']['name'])->setDescription("Room \"" . $rooms['room_details']['name'] . "\". P " . $rooms['room_details']['price'] . " per night (" . $i['total_nights'] . " nights)")->setCurrency('PHP')->setQuantity($rooms['quantity'])->setPrice($rooms['room_details']['price'] * $i['total_nights']);
             }
         }
     }
     if (isset($input['discountCode'])) {
         $discount = Discount::where('code', $input['discountCode'])->first();
         if ($discount) {
             if ($discount->used == null || $discount->used == '') {
                 $coupon_discount = $discount->calculateDiscount($total_price, $discount->effect, $discount->effect_type);
                 $discount->used = date('Y-m-d H:i:s');
                 $discount->save();
             }
         }
     }
     $total_discount = -$membership_discount - $coupon_discount;
     $total_price += $total_discount;
     Session::put('total_price', $total_price);
     if ($membership_discount != 0) {
         Session::put('hasMembershipDiscount', $membership_discount);
     }
     if ($coupon_discount != 0) {
         Session::put('hasCouponDiscount', $coupon_discount);
     }
     $discount1 = new Item();
     $discount1->setName('Discount')->setDescription("Reservation Discount")->setCurrency('PHP')->setQuantity(1)->setPrice($total_discount);
     array_push($item, $discount1);
     $item_list = new ItemList();
     $item_list->setItems($item);
     $tax_price = $total_price * 0.12;
     /*set tax*/
     $details = new Details();
     $details->setSubtotal($total_price);
     /*computing the amout*/
     $amount = new Amount();
     $amount->setCurrency('PHP')->setDetails($details)->setTotal($total_price);
     /*creation of transaction starts here*/
     $transaction = new Transaction();
     $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Filigans Hotel Reservation');
     $redirect_urls = new RedirectUrls();
     $redirect_urls->setReturnUrl(URL::route('payment.status'))->setCancelUrl(URL::route('payment.status'));
     $payment = new Payment();
     $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction));
     try {
         $payment->create($this->_api_context);
     } catch (PayPal\Exception\PayPalConnectionException $ex) {
         if (\Config::get('app.debug')) {
             echo "Exception: " . $ex->getMessage() . PHP_EOL;
             $err_data = json_decode($ex->getData(), true);
             return $err_data;
             exit;
         } else {
             die('Some error occur, sorry for inconvenient');
         }
     }
     foreach ($payment->getLinks() as $link) {
         if ($link->getRel() == 'approval_url') {
             $redirect_url = $link->getHref();
             break;
         }
     }
     // add payment ID to session
     Session::put('paypal_payment_id', $payment->getId());
     if (isset($redirect_url)) {
         // redirect to paypal
         return Redirect::away($redirect_url);
     }
     return Redirect::route('original.route')->with('error', 'Unknown error occurred');
 }