Amount charged for shipping. 10 characters max with support for 2 decimal places.
public setShipping ( string | double $shipping ) | ||
$shipping | string | double |
function test() { global $apiContext; // IncludeConfig('paypal/bootstrap.php'); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $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)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5); $amount = new Amount(); $amount->setCurrency("USD")->setTotal(20)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $baseUrl = getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/donate.php/execute_payment_test?success=true")->setCancelUrl("{$baseUrl}/donate.php/execute_payment_test?success=false"); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $request = clone $payment; 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); } $approvalUrl = $payment->getApprovalLink(); ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='{$approvalUrl}' >{$approvalUrl}</a>", $request, $payment); return $payment; }
/** * @return Payment * @throws CheckoutException */ public function startPayment() { $total_amount = ($this->request->amount + $this->request->tax_amount - $this->request->discount_amount) * 100; $apiContext->setConfig(array('service.EndPoint' => "https://test-api.sandbox.paypal.com")); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item1 = new Item(); $item1->setName('Product1')->setCurrency('EUR')->setPrice(10.0)->setQuantity(2)->setTax(3.0); $itemList = new ItemList(); $itemList->setItems(array($item1)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5); $amount = new Amount(); $amount->setCurrency('EUR')->setTotal(20)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription('Payment')->setInvoiceNumber('transactionid'); $baseUrl = getBaseUrl(); $redir = new RedirectUrls(); $redir->setReturnUrl($baseUrl . '/'); $redir->setCancelUrl($baseUrl . '/'); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redir)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($apiContext); } catch (\Exception $e) { throw new CheckoutException('Paypal error', 500, $e); } $approvalUrl = $payment->getApprovalLink(); ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='{$approvalUrl}' >{$approvalUrl}</a>", $request, $payment); return $payment; }
/** * @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; }
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; }
public function postBuy(Request $request) { $data = $request->all(); $customer = $this->customer->getByToken(); $shopping_cart = $this->cart->getByToken(); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $paypal_items = []; $total = 0; foreach ($shopping_cart->shopping_cart_products as $shopping_cart_product) { $item = new Item(); $item->setName($shopping_cart_product->product_collection_name . " // " . $shopping_cart_product->product_variant_name . " // " . $shopping_cart_product->product_color_name)->setCurrency(config('shop.default_currency'))->setQuantity($shopping_cart_product->quantity)->setPrice($shopping_cart_product->price_brut / 100); array_push($paypal_items, $item); $total += $shopping_cart_product->price_brut / 100 * $shopping_cart_product->quantity; } $subtotal = $total; $total += config('shop.default_shipping_cost') / 100; $item_list = new ItemList(); $item_list->setItems($paypal_items); $details = new Details(); $details->setShipping(config('shop.default_shipping_cost') / 100)->setSubtotal($subtotal); $amount = new Amount(); $amount->setCurrency(config('shop.default_currency'))->setTotal($total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Einkauf bei ZWEI :: Taschen'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(url(config('app.locale') . '/paypal/thankyou'))->setCancelUrl(url(config('app.locale') . '/paypal/cancellation')); $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('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); exit; } else { die(trans('shop.some_error_occurred')); } } foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } $this->cart->update(['id' => $shopping_cart->id, 'paypal_payment_id' => $payment->getId(), 'remarks' => $data['remarks'], 'customer_id' => $customer->id]); if (isset($redirect_url)) { return redirect($redirect_url); } return redirect()->route(config('app.locale') . '/feedback/paypal-error')->with('error', trans('shop.some_error_occurred')); }
/** * Cria o pagamento Paypal: passos 2/3 * * @access public * @param * @return error string */ public function create_payment($items_array, $details_array) { $payer = new Payer(); $payer->setPaymentMethod("paypal"); // define os items $i = 0; foreach ($items_array as $item) { $items[$i] = new Item(); $items[$i]->setName($item['name'])->setCurrency(PAYPAL_CURRENCY)->setQuantity($item['quantity'])->setPrice($item['price']); $i++; } $itemList = new ItemList(); $itemList->setItems($items); // Define os totais $details = new Details(); $details->setShipping($details_array['shipping'])->setTax($details_array['tax'])->setSubtotal($details_array['subtotal']); // Define a quantidade $amount = new Amount(); $amount->setCurrency(PAYPAL_CURRENCY)->setTotal($details_array['total'])->setDetails($details); // cria a transação $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription(""); // cria o URL $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl(SITE_PATH . "success.php")->setCancelUrl(SITE_PATH . "cart.php"); // cria o pagamento $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $payment->create($this->api_context); } catch (PayPal\Exception\PPConnectionException $ex) { return $ex->getMessage(); } // busca o URL de redirecionamento foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirectUrl = $link->getHref(); break; } } // redireciona $_SESSION['payment_id'] = $payment->getId(); if (isset($redirectUrl)) { header("Location: {$redirectUrl}"); exit; } }
/** * Called by shop to charge order's amount. * * @param Cart $cart Cart. * * @return bool */ public function onCharge($order) { $this->statusCode = 'pending'; // Begin paypal try { if ($order->total <= 0) { $this->statusCode = 'completed'; $this->detail = 'Order total is 0; no PayPal transaction required.'; $this->transactionId = uniqid(); return true; } $this->setContext(); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $list = new ItemList(); $list->setItems($this->toPayPalItems($order)); $details = new Details(); $details->setShipping($order->totalShipping)->setTax($order->totalTax)->setSubtotal($order->totalPrice); $amount = new Amount(); $amount->setCurrency(Config::get('shop.currency'))->setTotal($order->total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($list)->setDescription(sprintf('%s payment, Order #%d', Config::get('shop.name'), $order->id))->setInvoiceNumber($order->id); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->callbackSuccess)->setCancelUrl($this->callbackFail); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]); //$request = clone $payment; $payment->create($this->apiContext); $this->approvalUrl = $payment->getApprovalLink(); $this->detail = sprintf('Pending approval: %s', $this->approvalUrl); return true; } catch (PayPalConnectionException $e) { $response = json_decode($e->getData()); throw new GatewayException(sprintf('%s: %s', $response->name, isset($response->message) ? $response->message : 'Paypal payment Failed.'), 1001, $e); } catch (\Exception $e) { throw new GatewayException($e->getMessage(), 1000, $e); } return false; }
public function process($orderData, $cartProducts = []) { $this->setApiContext(); $this->_apiContext->setConfig(['mode' => Configuration::getConfiguration('paypal_payment_mode'), 'service.EndPoint' => Configuration::getConfiguration('paypal_payment_url'), 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => Configuration::getConfiguration('paypal_payment_log'), 'log.FileName' => storage_path('logs/paypal.log'), 'log.LogLevel' => 'FINE']); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $itemList = new ItemList(); $subTotal = 0; $taxTotal = 0; foreach ($cartProducts as $product) { $item = new Item(); $model = $product['model']; $item->setName($model->title)->setCurrency('USD')->setQuantity($product['qty'])->setSku($model->sku)->setPrice($product['price']); $itemList->addItem($item); $subTotal += $product['price'] * $product['qty']; $taxTotal += $product['tax_amount'] * $product['qty']; } $total = $subTotal + $taxTotal; $shippingOption = $orderData['shipping_method']; $shipping = Shipping::get($shippingOption); $details = new Details(); $details->setShipping($shipping->getAmount())->setTax($taxTotal)->setSubtotal($subTotal); $amount = new Amount(); $amount->setCurrency('USD')->setTotal($total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription('Payment description')->setInvoiceNumber(uniqid()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl(route('paypal.store')); $redirectUrls->setCancelUrl(route('paypal.cancel')); $payment = new Payment(); $payment->setIntent('sale'); $payment->setPayer($payer); $payment->setRedirectUrls($redirectUrls); $payment->setTransactions([$transaction]); $response = $payment->create($this->_apiContext); $redirectUrl = $response->links[1]->href; return $redirectUrl; }
public function sendRequest() { $details = new Details(); $details->setShipping(0)->setTax(0)->setSubtotal($this->totalAmount); $amount = new Amount(); $amount->setCurrency($this->currencyCode)->setTotal($this->totalAmount)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($this->itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $baseUrl = 'http://localhost/'; $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/ExecutePayment.php?success=true")->setCancelUrl("{$baseUrl}/ExecutePayment.php?success=false"); $payment = new Payment(); $payment->setIntent("sale")->setPayer($this->payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $payment->create($this->apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY var_dump($ex); exit(1); } $approvalUrl = $payment->getApprovalLink(); header('Location: ' . $approvalUrl); quit(); }
use PayPal\Api\Payer; use PayPal\Api\Details; use PayPal\Api\Amount; use PayPal\Api\Transaction; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Exception\PPConnectionException; require '../src/start.php'; $payer = new Payer(); $details = new Details(); $amount = new Amount(); $transaction = new Transaction(); $payment = new Payment(); $redirectUrls = new RedirectUrls(); $payer->setPaymentMethod('paypal'); $details->setShipping('2.00')->setTax('0.00')->setSubtotal('20.00'); $amount->setCurrency('GBP')->setTotal('22.00')->setDetails($details); $transaction->setAmount($amount)->setDescription('Membership'); $payment->setIntent('sale')->setPayer($payer)->setTransactions([$transaction]); $redirectUrls->setReturnUrl('http://localhost/paypal/paypal/pay.php?approved=true')->setCancelUrl('http://localhost/paypal/paypal/pay.php?approved=false'); $payment->setRedirectUrls($redirectUrls); try { $payment->create($api); $hash = md5($payment->getId()); // var_dump($hash); die(); $_SESSION['paypal_hash'] = $hash; $store = $db->prepare("INSERT INTO transaction_paypal VALUES('',?,?,?,?)"); $store->bindValue(1, $_SESSION['user_id'], PDO::PARAM_INT); $store->bindValue(2, $payment->getId(), PDO::PARAM_INT); $store->bindValue(3, $hash, PDO::PARAM_INT); $store->bindValue(4, 0, PDO::PARAM_INT);
/** * 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; }
public function postPayment() { $paypal_conf = Config::get('paypal'); $apiContext = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret'])); $apiContext->setConfig($paypal_conf['settings']); $card = new CreditCard(); $card->setType("visa")->setNumber("4148529247832259")->setExpireMonth("11")->setExpireYear("2019")->setCvv2("012")->setFirstName("Joe")->setLastName("Shopper"); $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi)); $item1 = new Item(); $item1->setName('Ground Coffee 40 oz')->setDescription('Ground Coffee 40 oz')->setCurrency('USD')->setQuantity(1)->setTax(0.3)->setPrice(7.5); $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)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5); $amount = new Amount(); $amount->setCurrency("USD")->setTotal(20)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setTransactions(array($transaction)); 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); var_dump($payment); echo "string"; /*exit; $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item_1 = new Item(); $item_1->setName('Item 1') // item name ->setCurrency('USD') ->setQuantity(2) ->setPrice('15'); // unit price $item_2 = new Item(); $item_2->setName('Item 2') ->setCurrency('USD') ->setQuantity(4) ->setPrice('7'); $item_3 = new Item(); $item_3->setName('Item 3') ->setCurrency('USD') ->setQuantity(1) ->setPrice('20'); // add item to list $item_list = new ItemList(); $item_list->setItems(array($item_1, $item_2, $item_3)); $amount = new Amount(); $amount->setCurrency('USD') ->setTotal(78); $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')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); 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');*/ }
public function postPayment() { $payer = new Payer(); $payer->setPaymentMethod('paypal'); //==================== LIST ITEMS IN SHOPPING CART ========= // $_contentCart = Cart::instance('shopping')->content(); $_itemsCount = Cart::instance('shopping')->count(); $_arryItems = array(); $_i = 0; foreach ($_contentCart as $row) { if ($_i < $_itemsCount) { $item = new Item(); $item->setName($row->name)->setDescription($row->name)->setCurrency('AUD')->setQuantity((double) $row->qty)->setTax((double) ($row->price * 10) / 100)->setPrice((double) $row->price); //$435.00 $_arryItems[$_i] = $item; $_i++; } } $item_list = new ItemList(); $item_list->setItems(array($_arryItems)); // add item to list $item_list = new ItemList(); $item_list->setItems($_arryItems); //==================== LIST ITEMS IN SHOPPING CART ========= // $details = new Details(); $details->setShipping("0")->setTax((string) (Cart::instance('shopping')->total() * 10) / 100)->setSubtotal((string) Cart::instance('shopping')->total()); $amount = new Amount(); $amount->setCurrency("AUD")->setTotal((string) Cart::instance('shopping')->total() + Cart::instance('shopping')->total() * 10 / 100)->setDetails($details); // ### Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. Transaction is created with // a `Payee` and `Amount` types $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($item_list)->setDescription('QLM Shopping Cart'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(URL::to('/payment/status'))->setCancelUrl(URL::to('/payments/cancel')); $payment = new Payment(); $payment->setIntent('Sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction)); try { //$this->createInvoice(); $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); 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 View::make('pages.shoppingcart')->with('error', 'Unknown error occurred'); }
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); } }
use PayPal\Exception\PayPalConnectionException; if (!isset($_POST['product'], $_POST['price'])) { die("lose some params"); } $product = $_POST['product']; $price = $_POST['price']; $shipping = 2.0; $total = $price + $shipping; $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item = new Item(); $item->setName($product)->setCurrency('USD')->setQuantity(1)->setPrice($price); $itemList = new ItemList(); $itemList->setItems([$item]); $details = new Details(); $details->setShipping($shipping)->setSubTotal($price); $amount = new Amount(); $amount->setCurrency('USD')->setTotal($total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("description for pay.")->setInvoiceNumber(uniqid()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl(SITE_URL . '/pay.php?success=true')->setCancelUrl(SITE_URL . 'pay.php?success=false'); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]); try { $payment->create($paypal); } catch (PayPalConnectionException $e) { echo $e->getData(); die; } $approvalUrl = $payment->getApprovalLink();
$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.50'); $item2 = new Item(); $item2->setName('Granola bars')->setCurrency('USD')->setQuantity(5)->setPrice('2.00'); $itemList = new ItemList(); $itemList->setItems(array($item1)); // ### Additional payment details // Use this optional field to set additional // payment information such as tax, shipping // charges etc. $details = new Details(); $details->setShipping('1.20')->setTax('1.30')->setSubtotal('7.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("10.00")->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"); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation.
public function actionPay() { $return = []; $total = 0; if (isset(Yii::$app->user->id)) { $cart = Cart::findOne(['user_id' => Yii::$app->user->id, 'status' => 'CREATED']); if ($cart) { $items = []; foreach ($cart->productscarts as $k => $productCart) { $aux = []; $aux['name'] = $productCart->product->name; $aux['quantity'] = $productCart->quantity; $aux['stock'] = $productCart->product->stock; $aux['price'] = $productCart->product->price; $aux['image'] = $productCart->product->image1; $aux['total'] = $productCart->product->price * $productCart->quantity; $aux['won'] = $productCart->won; $return[$productCart->product->id] = $aux; $total += $productCart->product->price * $productCart->quantity; $item = new Item(); $item->setName($aux['name'])->setCurrency('USD')->setQuantity($aux['quantity'])->setPrice($aux['price']); $items[] = $item; } /* paypal */ $clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS'; $clientSecret = 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL'; $apiContext = $this->getApiContext($clientId, $clientSecret); $payer = new Payer(); $payer->setPaymentMethod("paypal"); /*$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($items); $details = new Details(); $details->setShipping(5)->setSubtotal($total); $amount = new Amount(); $amount->setCurrency("USD")->setTotal($total + 5)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Compra en Mosaico")->setInvoiceNumber('1234567890'); $baseUrl = Url::base(true); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/site/pay?success=true")->setCancelUrl("{$baseUrl}/site/pay?success=false"); $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->render('pay', ['total' => $total, 'cart' => $return, 'aurl' => $approvalUrl]); }
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); } }
use PayPal\Api\Payer; use PayPal\Api\Details; use PayPal\Api\Amount; use PayPal\Api\Transaction; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName('Ground Coffee 40 oz')->setCurrency('USD')->setQuantity(1)->setSku("123123")->setPrice(100); $item2 = new Item(); $item2->setName('Granola bars')->setCurrency('USD')->setQuantity(1)->setSku("321321")->setPrice(100); $itemList = new ItemList(); $itemList->setItems(array($item1, $item2)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(200); $fakeTotal = 200 + 1.2 + 1.3; $amount = new Amount(); $amount->setCurrency("USD")->setTotal($fakeTotal)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl('http://localhost:9090/member/executePayment.php?success=true')->setCancelUrl('http://localhost:9090/member/executePayment.php?success=false'); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($api); echo 'payment'; } catch (Exception $ex) { echo 'error';
// 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)); // ### Additional payment details // Use this optional field to set additional // payment information such as tax, shipping // charges etc. $details = new Details(); $details->setShipping($shipping)->setTax($tax)->setSubtotal($amount); // ### Amount // Lets you specify a payment amount. // You can also specify additional details // such as shipping, tax. $amount = new Amount(); $amount->setCurrency("USD")->setTotal($total)->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)->setInvoiceNumber(uniqid()); // ### Payment // A Payment Resource; create one using // the above types and intent set to sale 'sale'
/** * Called by shop to charge order's amount. * * @param Cart $cart Cart. * * @return bool */ public function onCharge($order) { if (!isset($this->creditCard)) { throw new GatewayException('Credit Card is not set.', 0); } try { if ($order->total <= 0) { $this->detail = 'Order total is 0; no PayPal transaction required.'; $this->transactionId = uniqid(); return true; } $this->setContext(); $instrument = new FundingInstrument(); $instrument->setCreditCard($this->creditCard); $payer = new Payer(); $payer->setPaymentMethod('credit_card')->setFundingInstruments([$instrument]); $list = new ItemList(); $list->setItems($this->toPayPalItems($order)); $details = new Details(); $details->setShipping($order->totalShipping)->setTax($order->totalTax)->setSubtotal($order->totalPrice); $amount = new Amount(); $amount->setCurrency(Config::get('shop.currency'))->setTotal($order->total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($list)->setDescription(sprintf('%s payment, Order #%d', Config::get('shop.name'), $order->id))->setInvoiceNumber($order->id); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setTransactions([$transaction]); //$request = clone $payment; $payment->create($this->apiContext); $this->transactionId = $payment->id; $this->detail = 'Success'; return true; } catch (PayPalConnectionException $e) { $response = json_decode($e->getData()); throw new GatewayException(sprintf('%s: %s', $response->name, isset($response->message) ? $response->message : 'Paypal payment Failed.'), 1001, $e); } catch (\Exception $e) { throw new ShopException($e->getMessage(), 1000, $e); } return false; }
private function pagoPaypal($id_participante, $id_evento, $costo_evento, $total_asistencia, $tipo_asistencia) { $precio = $costo_evento * $total_asistencia; $setTax = 0; $setShipping = 0; $apiContext = new ApiContext(new OAuthTokenCredential("AZ3IGQMWrIJfatlyB2q31xGf6DyNwuPdhO1Pq5gHaOtNEbv9kfVXBTZdYfrW1Md5D44HenTCFZhAh1jq", "ECeakgz-CnwYFIYspPmmwYri92RGJcV5As7EoH1kZbMyGg47BRRyOIGz0y3qlr2W0pBDNKXw9R7ADDOq")); $apiContext->setConfig(array('mode' => 'sandbox', 'log.LogEnabled' => false, 'log.FileName' => PATH_SITE . "public/PayPal.log", 'log.LogLevel' => 'DEBUG', 'validation.level' => 'log')); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName("Asistencia a evento")->setCurrency('MXN')->setQuantity(1)->setPrice($precio); $itemList = new ItemList(); $itemList->setItems(array($item1)); $details = new Details(); $details->setShipping($setShipping)->setTax($setTax)->setSubtotal($precio); $total = $precio + $setShipping + $setTax; $amount = new Amount(); $amount->setCurrency("MXN")->setTotal($total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("PAGO POR ASISTIR A EVENTO")->setInvoiceNumber(uniqid()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl(PATH_SITE . "success/?id_participante=" . $id_participante . "&id_evento=" . $id_evento . "&precio=" . $precio . "&tipo=" . $tipo_asistencia)->setCancelUrl(PATH_SITE . "cancel/"); $payment = new Payment(); $payment->setIntent("order")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $payment->create($apiContext); $approvalUrl = $payment->getApprovalLink(); header("Location: " . $approvalUrl); } catch (Exception $ex) { echo $ex->getMessage(); $this->cargarVista("ERROR AL PROCESAR EL PAGO.", "danger", "fa fa-thumbs-o-down"); } }
$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)->setSku("123123")->setPrice(7.5); $item2 = new Item(); $item2->setName('Granola bars')->setCurrency('USD')->setQuantity(5)->setSku("321321")->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()); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation.
public function postPayment() { $payer = new Payer(); $payer->setPaymentMethod('paypal'); //==================== LIST ITEMS IN SHOPPING CART ========= // $_contentCart = Cart::instance('shopping')->content(); $_itemsCount = Cart::instance('shopping')->count(); $_arryItems = array(); $_i = 0; foreach ($_contentCart as $row) { if ($_i < $_itemsCount) { $item = new Item(); $item->setName($row->name)->setDescription($row->name)->setCurrency('USD')->setQuantity((double) $row->qty)->setTax((double) ($row->price * 10) / 100)->setPrice((double) $row->price); //$435.00 $_arryItems[$_i] = $item; $_i++; } } $item_list = new ItemList(); $item_list->setItems(array($_arryItems)); // add item to list $item_list = new ItemList(); $item_list->setItems($_arryItems); //==================== LIST ITEMS IN SHOPPING CART ========= // $details = new Details(); $details->setShipping("0")->setTax((string) (Cart::instance('shopping')->total() * 10) / 100)->setSubtotal((string) Cart::instance('shopping')->total()); $amount = new Amount(); $amount->setCurrency("USD")->setTotal((string) Cart::instance('shopping')->total() + Cart::instance('shopping')->total() * 10 / 100)->setDetails($details); // ### Transaction // A transaction defines the contract of a // payment - what is the payment for and who // is fulfilling it. Transaction is created with // a `Payee` and `Amount` types $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\PayPalConnectionException $ex) { echo $ex->getCode(); // Prints the Error Code echo $ex->getData(); // Prints the detailed error message die($ex); } catch (Exception $ex) { die($ex); } 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 View::make('pages.home'); }
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 CreatePayment($items = false, $data = false) { $apiContext = $this->getApiContext(); $data = (object) $data; #die(print_r($data)); // ### Payer // A resource representing a Payer that funds a payment // For paypal account payments, set payment method // to 'paypal'. $payer = new Payer(); $payer->setPaymentMethod("paypal"); // ### Itemized information // (Optional) Lets you specify item wise // information $cart = array(); $total = 0; /*foreach($items as $item) { $itemC = new Item(); $itemC->setName($item->name) ->setCurrency('EUR') ->setQuantity($item->items) ->setSku($item->code ? $item->code : $item->id) ->setPrice(round($item->cost,2)); $cart[] = $itemC; $total += $item->items * $item->cost; } $itemList = new ItemList(); $itemList->setItems($cart);*/ // ### Additional payment details // Use this optional field to set additional // payment information such as tax, shipping // charges etc. $details = new Details(); $details->setShipping(round($data->shipping, 2))->setTax(round($data->tax, 2))->setSubtotal(round($data->subtotal, 2)); // ### Amount // Lets you specify a payment amount. // You can also specify additional details // such as shipping, tax. $amount = new Amount(); $amount->setCurrency("EUR")->setTotal(round($data->total, 2))->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)->setDescription("Compra actual - " . round($data->total, 2) . " EUR")->setInvoiceNumber(uniqid()); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation. $baseUrl = base_url(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}cart/paypal?success=true")->setCancelUrl("{$baseUrl}cart/paypal-ko"); // ### 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)); // ### 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) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY die(print_r($ex->getData())); 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->getApprovalLink(); // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY redirect($approvalUrl); return $payment; }
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 }
public function preparePaypal($itemList) { $apiContext = new \PayPal\Rest\ApiContext(new \PayPal\Auth\OAuthTokenCredential('AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS', 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL')); $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.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()); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation. //$baseUrl = getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("http://www.akarmi.ro/ExecutePayment.php?success=true")->setCancelUrl("http://www.akarmi.ro/ExecutePayment.php?success=false"); // ### 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)); // 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->getApprovalLink(); // ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment); return $payment; //END SAMPLE 3 }
public function order() { $paypalConf = $this->config->item('paypal'); $clientId = $paypalConf['clientId']; $clientSecret = $paypalConf['clientSecret']; $appName = $paypalConf['appName']; $price = $paypalConf['price']; $shiping = 0; $tax = 0; $mode = "sandbox"; //or live $apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret)); $apiContext->setConfig(array('mode' => $mode, 'log.LogEnabled' => false)); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName($appName)->setCurrency('USD')->setQuantity(1)->setPrice($price); $itemList = new ItemList(); $itemList->setItems(array($item1)); $details = new Details(); $details->setShipping($shiping)->setTax($tax)->setSubtotal($price); $amount = new Amount(); $amount->setCurrency("USD")->setTotal($price + $shiping + $tax)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $token = $this->createToken(); $baseUrl = getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/paypal/ordersucess?success=true&tk1=" . $token[0] . "&tk2=" . $token[1])->setCancelUrl("{$baseUrl}/paypal/orderfailed?success=false"); $payment = new Payment(); $payment->setIntent("order")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); // For Sample Purposes Only. $request = clone $payment; try { $payment->create($apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printError("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex); exit(1); } $approvalUrl = $payment->getApprovalLink(); header("Location: " . $approvalUrl . ""); die; }
public function credit_card() { return "Hello?"; $card = new CreditCard(); $card->setType("visa")->setNumber("4148529247832259")->setExpireMonth("11")->setExpireYear("2019")->setCvv2("012")->setFirstName("Joe")->setLastName("Shopper"); $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi)); $item1 = new Item(); $item1->setName('Ground Coffee 40 oz')->setDescription('Ground Coffee 40 oz')->setCurrency('USD')->setQuantity(1)->setTax(0.3)->setPrice(7.5); $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)); $details = new Details(); $details->setShipping(1.2)->setTax(1.3)->setSubtotal(17.5); $amount = new Amount(); $amount->setCurrency("USD")->setTotal(20)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setTransactions(array($transaction)); $request = clone $payment; 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; }