/** * Generate the approval link for a PayPal payment * @param $amountToPay * @return mixed */ public function generateApprovalLink($amountToPay) { $amountToPay = number_format($amountToPay, 2, ".", ""); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $amount = new Amount(); $amount->setCurrency($this->currency)->setTotal($amountToPay); $transaction = new Transaction(); $transaction->setAmount($amount)->setDescription(trans("billing.paymentToCompany", ['company_name' => Config::get("customer_portal.company_name")]))->setInvoiceNumber(uniqid(true)); //This is not a payment on a specific invoice, so we'll just generate a unique string, which is what PayPal requires $tempToken = new PaypalTemporaryToken(['account_id' => get_user()->account_id, 'token' => uniqid(true)]); $tempToken->save(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl(action("PayPalController@completePayment", ['temporary_token' => $tempToken->token]))->setCancelUrl(action("PayPalController@cancelPayment", ['temporary_token' => $tempToken->token])); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]); $payment->create($this->apiContext); return $payment->getApprovalLink(); }
function CreateTransaction($transactionType, $itemArray, $details) { $payer = new Payer(); $payer->setPaymentMethod($GLOBALS['PAYPAL']['payment_method']); $itemList = new ItemList(); $itemList->setItems($itemArray); $amount = new Amount(); $amount->setCurrency($GLOBALS['PAYPAL']['currency'])->setTotal(GetDetailsTotal($details))->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription($GLOBALS['TRANSACTION_TYPE']['DONATION']['payment_desc'])->setInvoiceNumber(uniqid()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($GLOBALS['TRANSACTION_TYPE']['DONATION']['return_url'])->setCancelUrl($GLOBALS['TRANSACTION_TYPE']['DONATION']['cancel_url']); $payment = new Payment(); $payment->setIntent($GLOBALS['TRANSACTION_TYPE']['DONATION']['intent'])->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($GLOBALS['PAYPAL']['api_context']); } catch (Exception $ex) { ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex); return false; } $approvalUrl = $payment->getApprovalLink(); echo $approvalUrl; return array('request' => $request, 'payment' => $payment, 'approvalUrl' => $approvalUrl); }
/** * @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 PaymentInterface $payment */ public function init(PaymentInterface $payment) { $credentials = new OAuthTokenCredential($this->options['client_id'], $this->options['secret']); $apiContext = new ApiContext($credentials); $apiContext->setConfig(['mode' => $this->options['mode']]); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $amount = new Amount(); $amount->setCurrency($this->options['currency']); $amount->setTotal($payment->getPaymentSum()); $item = new Item(); $item->setName($payment->getDescription()); $item->setCurrency($amount->getCurrency()); $item->setQuantity(1); $item->setPrice($amount->getTotal()); $itemList = new ItemList(); $itemList->addItem($item); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setDescription($payment->getDescription()); $transaction->setItemList($itemList); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($payment->getExtraData('return_url')); $redirectUrls->setCancelUrl($payment->getExtraData('cancel_url')); $paypalPayment = new Payment(); $paypalPayment->setIntent('sale'); $paypalPayment->setPayer($payer); $paypalPayment->setTransactions([$transaction]); $paypalPayment->setRedirectUrls($redirectUrls); $paypalPayment->create($apiContext); $payment->setExtraData('paypal_payment_id', $paypalPayment->getId()); $payment->setExtraData('approval_link', $paypalPayment->getApprovalLink()); }
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; }
public function getPayTaskUrl($task) { $apiContext = $this->apiContext; $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName($task->title)->setCurrency($this->currency)->setQuantity(1)->setSku($task->id)->setPrice($task->total); $itemList = new ItemList(); $itemList->setItems(array($item1)); $amount = new Amount(); $amount->setCurrency($this->currency)->setTotal($task->total); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment for " . $task->title)->setInvoiceNumber($task->id . '_' . date('YmdHis')); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->redirectSuccess . '/' . $task->id)->setCancelUrl($this->redirectFail . '/' . $task->id); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $payment->create($apiContext); $this->storePaymentSession($payment->getId(), $task->id); return $payment->getApprovalLink(); }
/** * {@inheritdoc} */ public function processPayment(PaymentInterface $payment) : PaymentInterface { $order = $payment->getOrder(); $payer = $this->createPayer('paypal'); $redirectUrls = $this->createRedirectUrls($payment); $transaction = $this->createTransaction($order); $payPalPayment = new Payment(); $payPalPayment->setIntent("sale"); $payPalPayment->setPayer($payer); $payPalPayment->setRedirectUrls($redirectUrls); $payPalPayment->setTransactions([$transaction]); try { $payPalPayment->create($apiContext); } catch (\Exception $e) { echo $e->getMessage(); } $payment->setApprovalUrl($payPalPayment->getApprovalLink()); $payment->setState($payPalPayment->getState()); $payment->setToken($payPalPayment->getId()); $this->paymentManager->updateResource($payment); return $payment; }
/** * 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 getRefillUrl($amount, User $user) { $paymentTitle = Config::get('services.paypal.payment_title'); $amount = floatval($amount); $apiContext = $this->apiContext; $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName($paymentTitle)->setCurrency($this->currency)->setQuantity(1)->setSku('1')->setPrice($amount); $itemList = new ItemList(); $itemList->setItems(array($item1)); $amountObj = new Amount(); $amountObj->setCurrency($this->currency)->setTotal($amount); $transaction = new Transaction(); $transaction->setAmount($amountObj)->setItemList($itemList)->setDescription($paymentTitle)->setInvoiceNumber($user->id . '_' . date('YmdHis')); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->redirectSuccess . '/' . $user->id)->setCancelUrl($this->redirectFail . '/' . $user->id); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $payment->create($apiContext); $this->storePaymentSession($payment->getId(), $user->id, $amount, $this->currency, $itemList); return $payment->getApprovalLink(); }
/** * @return mixed */ public function takePayment() { $payer = new Payer(); $payer->setPaymentMethod("paypal"); $transaction = $this->buildTransaction(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->returnUrl)->setCancelUrl($this->cancelUrl); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $payment->create($this->apiContext); return $payment->getApprovalLink(); } catch (PayPalConnectionException $e) { $response = json_decode($e->getData()); switch ($response->name) { case 'VALIDATION_ERROR': throw new Exception('Oops! ' . trans('vendirun::checkout.invalidPostcode')); break; default: throw new Exception(trans('vendirun::checkout.paypalUnavailable')); } } }
public function callCreate($clientId, $clientSecret, $orderId, $amount, $currency, $description, $returnUrl, $cancelUrl) { $oauthCredential = new OAuthTokenCredential($clientId, $clientSecret); $apiContext = new ApiContext($oauthCredential); $apiContext->setConfig(['mode' => $this->mode]); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item = new Item(); $item->setName($description); $item->setCurrency($currency); $item->setPrice($amount); $item->setQuantity(1); $itemList = new ItemList(); $itemList->setItems(array($item)); $amountObject = new Amount(); $amountObject->setCurrency($currency); $amountObject->setTotal($amount); $transaction = new Transaction(); $transaction->setItemList($itemList); $transaction->setAmount($amountObject); $transaction->setDescription($description); $transaction->setInvoiceNumber($orderId); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($returnUrl)->setCancelUrl($cancelUrl); $payment = new Payment(); $payment->setIntent('sale'); $payment->setPayer($payer); $payment->setRedirectUrls($redirectUrls); $payment->setTransactions(array($transaction)); try { $payment->create($apiContext); } catch (\Exception $e) { throw new PaymentException('PayPal Exception: ' . $e->getMessage()); } $approvalUrl = $payment->getApprovalLink(); return $approvalUrl; }
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(); }
public function createPayment($amount, $description, $redirectUrl) { $apiContext = $this->getPayPal(); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $amountObject = new Amount(); $amountObject->setCurrency("USD")->setTotal($amount); $transaction = new Transaction(); $transaction->setAmount($amountObject)->setDescription($description); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($redirectUrl . "?success=true")->setCancelUrl($redirectUrl . "?success=false"); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $data = array("amount" => $amount, "description" => $description, "redirectUrl" => $redirectUrl, "method" => $this->paymentMethod, "metadata" => $this->metadata, "webhookUrl" => $this->webhook, "locale" => $this->locale); $payment->create($apiContext); $approvalUrl = $payment->getApprovalLink(); return (object) array('id' => $payment->getId(), 'url' => $approvalUrl, 'provider' => 'paypal'); }
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 pay(array $items = null, $invoiceNo = null) { if (!isset($invoiceNo)) { $invoiceNo = uniqid(); } if (isset($items) && !empty($items)) { $baseUrl = SYMPHONY_URL . '/extension/paypal/payment'; $payer = new Payer(); $payer->setPaymentMethod("paypal"); $itemList = new ItemList(); $subTotal = 0; $taxTotal = 0; $shipping = 0; foreach ($items as $key => $itemDetails) { $subTotal += $itemDetails['price']; if (isset($itemDetails['tax'])) { $taxTotal += $itemDetails['tax']; } $itemList->addItem($this->paypalItemFromArray($itemDetails)); } $details = new Details(); $details->setShipping($shipping)->setTax($taxTotal)->setSubtotal($subTotal); $amount = new Amount(); $amount->setCurrency($this->currency)->setTotal($subTotal + $taxTotal)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("JCI Malta Membership")->setInvoiceNumber($invoiceNo); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}?success=true")->setCancelUrl("{$baseUrl}?success=false"); $payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($this->apiContext); } catch (Exception $ex) { var_dump($request); var_dump($ex); die; return "error"; //log the error // echo("Error Creating Payment Using PayPal.", "Payment", null, $request, $ex); // exit(1); } $return = array('id' => $payment->getId(), 'link' => $payment->getApprovalLink()); return $return; } }
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]); }
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); } }
public function getLinkCheckOut($params = null) { if (!$params) { return false; } /*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"); $itemList = new ItemList(); // Item must be a array and has one or more item. if (!$params['items']) { return false; } $arrItem = []; foreach ($params['items'] as $key => $item) { $it = new Item(); $it->setName($item['name'])->setCurrency($params['currency'])->setQuantity($item['quantity'])->setPrice($item['price']); $arrItem[] = $it; } $itemList->setItems($arrItem); $amount = new Amount(); $amount->setCurrency($params['currency'])->setTotal($params['total_price']); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription($params['description']); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation. $redirectUrls = new RedirectUrls(); $baseUrl = $this->getBaseUrl(); $redirectUrls->setReturnUrl($baseUrl . $this->successUrl)->setCancelUrl($baseUrl . $this->cancelUrl); // ### 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([$transaction]); // ### Create Payment // Create a payment by calling the 'create' method // passing it a valid apiContext. try { $payment->create($this->config); } catch (PayPal\Exception\PPConnectionException $ex) { throw new \DataErrorException($ex->getData(), $ex->getMessage()); } // ### Get redirect url $redirectUrl = $payment->getApprovalLink(); return ['payment_id' => $payment->getId(), 'status' => $payment->getState(), 'redirect_url' => $redirectUrl, 'description' => $transaction->getDescription()]; }
/** * Create the Payment request and process * @return null|string The approval url to which the user has to be redirected */ public function createPayment() { $payer = new Payer(); $payer->setPaymentMethod("paypal"); $this->validateData(); if (!is_null($this->details)) { $this->getAmount()->setDetails($this->details); } $transaction = new Transaction(); $transaction->setAmount($this->getAmount())->setDescription($this->getDescription())->setInvoiceNumber($this->getInvoiceNumber()); if (count($this->itemList->getItems())) { $transaction->setItemList($this->itemList); } $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->getSuccessUrl(self::paymentMethod))->setCancelUrl($this->getCancelUrl(self::paymentMethod)); $payment = new Payment(); $payment->setIntent(self::ACTION)->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $payment->create($this->getApiContext($this->clientId, $this->clientSecret)); } catch (\Exception $ex) { $this->container->get('logger')->error($ex); return null; } $approvalUrl = $payment->getApprovalLink(); return $approvalUrl; }
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 }
function payment_redirect($cart = false, $approval = false, $order_exists = false) { global $order, $xtPrice; // auth $apiContext = $this->apiContext(); // set payment $payer = new Payer(); $payer->setPaymentMethod('paypal'); if ($this->code == 'paypalinstallment') { $payer->setExternalSelectedFundingInstrumentType('CREDIT'); } // set payer_info $payer_info = new PayerInfo(); // set items $item = array(); // set details $this->details = new Details(); // set amount $this->amount = new Amount(); // set ItemList $itemList = new ItemList(); // set redirect $redirectUrls = new RedirectUrls(); // set address $shipping_address = new ShippingAddress(); if ($cart === true) { $products = $_SESSION['cart']->get_products(); for ($i = 0, $n = sizeof($products); $i < $n; $i++) { $item[$i] = new Item(); $item[$i]->setName($this->encode_utf8($products[$i]['name']))->setCurrency($_SESSION['currency'])->setQuantity($products[$i]['quantity'])->setPrice($products[$i]['price'])->setSku($products[$i]['model'] != '' ? $products[$i]['model'] : $products[$i]['id']); $this->details->setSubtotal($this->details->getSubtotal() + $products[$i]['final_price']); } $total = $price = $_SESSION['cart']->show_total(); if ($_SESSION['customers_status']['customers_status_ot_discount_flag'] == 1 && $_SESSION['customers_status']['customers_status_ot_discount'] != '0.00') { if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) { $price = $total - $_SESSION['cart']->show_tax(false); } $this->details->setShippingDiscount($this->details->getShippingDiscount() + $xtPrice->xtcGetDC($price, $_SESSION['customers_status']['customers_status_ot_discount']) * -1); } $this->amount->setTotal($total + $this->details->getShippingDiscount()); if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1 && MODULE_SMALL_BUSINESS != 'true') { foreach ($_SESSION['cart']->tax as $tax) { $this->details->setTax($this->details->getTax() + $tax['value']); } $total = $this->calc_total(); $amount_total = $this->amount->getTotal(); if ((string) $amount_total != (string) $total) { $this->details->setTax($this->details->getTax() + ($amount_total - $total)); } } $shipping_cost = $this->get_config('MODULE_PAYMENT_' . strtoupper($this->code) . '_SHIPPING_COST'); if ((int) $shipping_cost > 0) { $i = count($item); $item[$i] = new Item(); $item[$i]->setName($this->encode_utf8(PAYPAL_EXP_VORL))->setCurrency($_SESSION['currency'])->setQuantity(1)->setPrice($shipping_cost); $this->amount->setTotal($this->amount->getTotal() + $shipping_cost); $this->details->setSubtotal($this->amount->getTotal()); } // set amount $this->amount->setCurrency($_SESSION['currency'])->setDetails($this->details); // set redirect $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link('callback/paypal/paypalcart.php', '', 'SSL')))->setCancelUrl($this->link_encoding(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'SSL'))); } else { $shipping_address->setRecipientName($this->encode_utf8($order->delivery['firstname'] . ' ' . $order->delivery['lastname']))->setLine1($this->encode_utf8($order->delivery['street_address']))->setCity($this->encode_utf8($order->delivery['city']))->setCountryCode($this->encode_utf8($order_exists === false ? $order->delivery['country']['iso_code_2'] : $order->delivery['country_iso_2']))->setPostalCode($this->encode_utf8($order->delivery['postcode']))->setState($this->encode_utf8($order->delivery['state'] != '' ? xtc_get_zone_code($order->delivery['country_id'], $order->delivery['zone_id'], $order->delivery['state']) : '')); if ($order->delivery['suburb'] != '') { $shipping_address->setLine2($this->encode_utf8($order->delivery['suburb'])); } $subtotal = 0; for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) { $item[$i] = new Item(); $item[$i]->setName($this->encode_utf8($order->products[$i]['name']))->setCurrency($order->info['currency'])->setQuantity($order->products[$i]['qty'])->setPrice($order->products[$i]['price'])->setSku($order->products[$i]['model'] != '' ? $order->products[$i]['model'] : $order->products[$i]['id']); $subtotal += $order->products[$i]['price'] * $order->products[$i]['qty']; } // set totals if ($order_exists === false) { if (!class_exists('order_total')) { require_once DIR_WS_CLASSES . 'order_total.php'; } $order_total_modules = new order_total(); $order_totals = $order_total_modules->process(); $this->get_totals($order_totals, true, $subtotal); } else { $this->get_totals($order->totals); } // set amount $this->amount->setCurrency($order->info['currency'])->setDetails($this->details); // set redirect if ($order_exists === false) { $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL')))->setCancelUrl($this->link_encoding(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code, 'SSL'))); } else { $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link('callback/paypal/' . $this->code . '.php', 'oID=' . $order->info['order_id'] . '&key=' . md5($order->customer['email_address']), 'SSL')))->setCancelUrl($this->link_encoding(xtc_href_link('callback/paypal/' . $this->code . '.php', 'payment_error=' . $this->code . '&oID=' . $order->info['order_id'] . '&key=' . md5($order->customer['email_address']), 'SSL'))); } if ($this->code == 'paypalinstallment') { $redirectUrls->setReturnUrl($this->link_encoding(xtc_href_link(FILENAME_CHECKOUT_CONFIRMATION, 'conditions=true', 'SSL'))); } } // set ItemList if ($this->get_config('PAYPAL_ADD_CART_DETAILS') == '0' || $this->check_discount() === true) { $item = array(); $item[0] = new Item(); $item[0]->setName($this->encode_utf8(MODULE_PAYMENT_PAYPAL_TEXT_ORDER))->setCurrency($_SESSION['currency'])->setQuantity(1)->setPrice($this->details->getSubtotal()); if ($cart === true) { $shipping_cost = $this->get_config('MODULE_PAYMENT_' . strtoupper($this->code) . '_SHIPPING_COST'); if ((int) $shipping_cost > 0) { $item[1] = new Item(); $item[1]->setName($this->encode_utf8(PAYPAL_EXP_VORL))->setCurrency($_SESSION['currency'])->setQuantity(1)->setPrice($shipping_cost); $this->amount->setTotal($this->amount->getTotal() + $shipping_cost); $this->details->setSubtotal($this->amount->getTotal()); } } } $itemList->setItems($item); // profile $address_override = false; $profile_id = $this->get_config('PAYPAL_' . strtoupper($this->code . '_' . $_SESSION['language_code']) . '_PROFILE'); if ($profile_id == '') { $profile_id = $this->get_config('PAYPAL_STANDARD_PROFILE'); } if ($profile_id != '') { if ($this->get_config(strtoupper($profile_id) . '_TIME') < time() - 3600 * 24) { $profile = $this->get_profile($profile_id); $sql_data_array = array(array('config_key' => strtoupper($profile_id) . '_TIME', 'config_value' => time()), array('config_key' => strtoupper($profile_id) . '_ADDRESS', 'config_value' => $profile[0]['input_fields']['address_override'])); $this->save_config($sql_data_array); $address_override = $profile[0]['input_fields']['address_override'] == '0' ? true : false; } else { $address_override = $this->get_config(strtoupper($profile_id) . '_ADDRESS') == '0' ? true : false; } } if ($cart === false && $approval === false && $address_override === false || $order_exists === true || $this->code == 'paypalinstallment') { $itemList->setShippingAddress($shipping_address); } if ($this->code == 'paypalinstallment') { // set payment address $payment_address = new Address(); $payment_address->setLine1($this->encode_utf8($order->billing['street_address']))->setCity($this->encode_utf8($order->billing['city']))->setState($this->encode_utf8($order->billing['state'] != '' ? xtc_get_zone_code($order->billing['country_id'], $order->billing['zone_id'], $order->billing['state']) : ''))->setPostalCode($this->encode_utf8($order->billing['postcode']))->setCountryCode($this->encode_utf8($order->billing['country']['iso_code_2'])); if ($order->billing['suburb'] != '') { $payment_address->setLine2($this->encode_utf8($order->billing['suburb'])); } $payer_info->setBillingAddress($payment_address)->setShippingAddress($shipping_address)->setEmail($this->encode_utf8($order->customer['email_address']))->setFirstName($this->encode_utf8($order->delivery['firstname']))->setLastName($this->encode_utf8($order->delivery['lastname'])); $payer->setPayerInfo($payer_info); } // set transaction $transaction = new Transaction(); $transaction->setAmount($this->amount)->setItemList($itemList)->setDescription($this->encode_utf8(STORE_NAME))->setInvoiceNumber(uniqid()); // set payment $payment = new Payment(); $payment->setIntent($this->transaction_type)->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction))->setCreateTime(time()); if (isset($profile_id) && $profile_id != '') { $payment->setExperienceProfileId($profile_id); } try { $payment->create($apiContext); $_SESSION['paypal']['paymentId'] = $payment->getId(); $approval_link = $payment->getApprovalLink(); if ($approval === false) { xtc_redirect($approval_link); } else { return $approval_link; } } catch (Exception $ex) { $this->LoggingManager->log(print_r($ex, true), 'DEBUG'); unset($_SESSION['paypal']); if ($cart === true) { xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'SSL')); } elseif ($this->code != 'paypalplus') { xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code, 'SSL')); } } }
public function paypalAction() { //Zend_Loader::loadFile('paypal_bootstrap.php', APPLICATION_PATH . "/../library/My/", true); require_once APPLICATION_PATH . "/../library/My/paypal_bootstrap.php"; $error = false; $approvalLink = null; $payer = new Payer(); $payer->setPaymentMethod("paypal"); $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $currentUser = $auth->getIdentity(); $userMapper = new Application_Model_UserMapper(); $db_adapter = $userMapper->getDbTable()->getAdapter(); $db = Zend_Db::factory('Mysqli', $db_adapter->getConfig()); $results = $userMapper->getShoppingCart($currentUser); $user = $userMapper->getDbTable()->find($currentUser->id)->current(); $currencyMapper = new Application_Model_CurrencyMapper(); $defaultCurrency = $currencyMapper->getDefaultCurrency(); $data = array('user_id' => $currentUser->id, 'state' => 'created', 'email' => $user->email); $db->insert('orders', $data); $lastOrderId = $db->lastInsertId('orders', 'id'); $items = array(); $subTotal = 0; foreach ($results as $i => $result) { $item = new Item(); $item->setName($result->name)->setCurrency($defaultCurrency->code)->setQuantity($result->quantity)->setSku($i + 1)->setPrice($result->price); //->setDescription($result->c_id); $db->insert('ordered_products', array('product_id' => $result->id, 'name' => $result->name, 'category_id' => $result->getCategoryId(), 'currency' => $defaultCurrency->code, 'price' => $result->price, 'quantity' => $result->quantity, 'order_id' => $lastOrderId)); $items[] = $item; $subTotal += $result->quantity * (double) number_format($result->price, 2); } $itemList = new ItemList(); $itemList->setItems($items); $shippingTax = 0; // $details = new Details(); $details->setShipping($shippingTax)->setTax(0)->setSubtotal($subTotal); $total = $shippingTax + $subTotal; $amount = new Amount(); $amount->setCurrency($defaultCurrency->code)->setTotal($total)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setCustom($lastOrderId)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $baseUrl = getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($baseUrl . '/users/exepaypal/?success=true'); $redirectUrls->setCancelUrl($baseUrl . '/users/exepaypal/?cancel=true'); $payment = new Payment(); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setRedirectUrls($redirectUrls); $payment->setTransactions(array($transaction)); try { $result = $payment->create($apiContext); } catch (Exception $ex) { $error = true; } $approvalLink = $payment->getApprovalLink(); } else { $error = true; } $response = array('error' => $error, 'approvalLink' => $approvalLink); //Send as JSON header("Content-Type: application/json", true); //Return JSON echo json_encode($response); //Stop Execution exit; }
public function teszt($amount, $description) { $apiContext = new \PayPal\Rest\ApiContext(new \PayPal\Auth\OAuthTokenCredential('AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS', 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL')); //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.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 }
$redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/ExecutePayment.php?success=true")->setCancelUrl("{$baseUrl}/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) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY 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(); // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='{$approvalUrl}' >{$approvalUrl}</a>", $request, $payment); return $payment;
public function pay_online() { if ($this->input->server('REQUEST_METHOD') === 'POST') { $data['title'] = "payment"; $username = $this->session->userdata('username'); $data['username'] = $username; // Get OAuthToken $apiContext = $this->getAccessToken(); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $orderID = $this->input->post('order_id[]'); if ($orderID == null) { return; } $itemArray = array(); $subTotalPrice = 0; $tax = 1; $shipping = 1; foreach ($orderID as $key) { // Verify order_id to make sure order data correct if (!$this->Pay_item_model->verifyOrder($key, $this->session->userdata('id'))) { $this->session->set_flashdata('msg', 'Order data is not correct. Please try again later'); $data['link'] = ''; if ($this->agent->is_mobile()) { $this->load->view('mobile/template/header', $data); $this->load->view('mobile/payment_view/payment_mobile', $data); } else { $this->load->view('template/header', $data); $this->load->view('payment_view/payment', $data); } return; } // Get item data $itemData = $this->Pay_item_model->getItem($key); $itemPrice = $itemData['price'] * $itemData['quantity']; $item1 = new Item(); $item1->setName($itemData['name'])->setCurrency('MYR')->setQuantity($itemData['quantity'])->setSku($itemData['id'])->setPrice($itemData['price']); $subTotalPrice += $itemPrice; array_push($itemArray, $item1); } $itemList = new ItemList(); $itemList->setItems($itemArray); $details = new Details(); $details->setShipping($shipping)->setTax($tax)->setSubtotal($subTotalPrice); $amount = new Amount(); $amount->setCurrency("MYR")->setTotal($subTotalPrice + $shipping + $tax)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("UTMBazaar online payment")->setInvoiceNumber(uniqid()); $baseUrl = base_url(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($baseUrl . "pay_item/execute_payment?success=true")->setCancelUrl($baseUrl . "pay_item/execute_payment?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) { $this->session->set_flashdata('msg', 'Something wrong now. Please try again later' . $subTotalPrice); $data['link'] = ''; if ($this->agent->is_mobile()) { $this->load->view('mobile/template/header', $data); $this->load->view('mobile/payment_view/payment_mobile', $data); } else { $this->load->view('template/header', $data); $this->load->view('payment_view/payment', $data); } return; } $approvalUrl = $payment->getApprovalLink(); $data['link'] = $approvalUrl; if ($this->agent->is_mobile()) { $this->load->view('mobile/template/header', $data); $this->load->view('mobile/payment_view/payment_mobile', $data); } else { $this->load->view('template/header', $data); $this->load->view('payment_view/payment', $data); } header("refresh:1;url=" . $approvalUrl); } else { redirect('home'); } }
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"); } }
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 pay($id) { // ### 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 $order = \Yii::createObject(Order::className())->findOne($id); $orderItems = $order->orderItem; $itemTmp = []; foreach ($orderItems as $orderItem) { $item = new Item(); $item->setName($orderItem->name)->setCurrency($this->currency)->setQuantity($orderItem->qty)->setPrice($orderItem->price); $itemTmp[] = $item; } $itemList = new ItemList(); $itemList->setItems($itemTmp); // ### Additional payment details // Use this optional field to set additional // payment information such as tax, shipping // charges etc. $details = new Details(); $total = $order->total_price - $order->shipping_fee - $order->payment_fee; $details->setShipping($order->shipping_fee)->setTax($order->payment_fee)->setSubtotal($total); // ### Amount // Lets you specify a payment amount. // You can also specify additional details // such as shipping, tax. $amount = new Amount(); $amount->setCurrency($this->currency)->setDetails($details)->setTotal($order->total_price); // ### 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($order->order_no); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation. $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl(Url::to(['/Payment/home/payment/index'], true))->setCancelUrl(Url::to(['/Payment/home/payment/index'], true)); // ### Payment // A Payment Resource; create one using // the above types and intent set to 'order' $payment = new Payment(); $payment->setIntent("order")->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($this->_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); var_dump($ex); exit; 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 // ResultPrinter::printResult("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment); return $approvalUrl; }
function cart_checkout() { $rarray = array(); $request = Slim::getInstance()->request(); $body = json_decode($request->getBody()); if (!empty($body->cart)) { $apiContext = new \PayPal\Rest\ApiContext(new \PayPal\Auth\OAuthTokenCredential(PAYPAL_CLIENT_ID, PAYPAL_SECRET)); $payer = new Payer(); $payer->setPaymentMethod("paypal"); // ### Itemized information // (Optional) Lets you specify item wise // information $items = array(); foreach ($body->cart as $temp) { $temp = (array) $temp; $item1 = new Item(); if ($temp['event'] == 1) { $item1->setName($temp['offer_title'] . ' : Event')->setCurrency('USD')->setQuantity($temp['quantity'])->setSku($temp['event_id'])->setPrice($temp['offer_price']); } else { $item1->setName($temp['offer_title'] . ' : ' . $temp['restaurant_title'])->setCurrency('USD')->setQuantity($temp['quantity'])->setSku($temp['offer_id'])->setPrice($temp['offer_price']); } $items[] = $item1; } /*$item2 = new Item(); $item2->setName('Granola bars') ->setCurrency('USD') ->setQuantity(5) ->setSku("321321") // Similar to `item_number` in Classic API ->setPrice(2);*/ $itemList = new ItemList(); $itemList->setItems($items); // ### Additional payment details // Use this optional field to set additional // payment information such as tax, shipping // charges etc. $details = new Details(); $details->setShipping(0)->setTax(0)->setSubtotal($body->total); // ### Amount // Lets you specify a payment amount. // You can also specify additional details // such as shipping, tax. $amount = new Amount(); $amount->setCurrency("USD")->setTotal($body->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)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); // ### Redirect urls // Set the urls that the buyer must be redirected to after // payment approval/ cancellation. $baseUrl = WEBSITEURL; $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($baseUrl . "payment_return?success=true")->setCancelUrl($baseUrl . "payment_return?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 (PayPal\Exception\PayPalConnectionException $ex) { /*echo $ex->getCode(); // Prints the Error Code echo $ex->getData(); // Prints the detailed error message die($ex);*/ print_r($ex); $rarray = array('type' => 'error'); print_r($rarray); exit; } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY //ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex); //echo $ex; $rarray = array('type' => 'error'); echo $rarray; exit; 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 //ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment); //echo $payment->id; //print_r($payment); //exit; $order_data = array(); $order_data['user_id'] = $body->user_id; $order_data['amount'] = $body->total; $order_data['payment_id'] = $payment->id; $order_data['is_paid'] = 'U'; $order_save = add(json_encode(array('save_data' => $order_data)), 'orders'); if ($order_save) { $order_save = (array) json_decode($order_save); foreach ($body->cart as $temp) { $temp = (array) $temp; $temp_details = array(); $temp_details['user_id'] = $body->user_id; $temp_details['offer_id'] = $temp['offer_id']; $temp_details['order_id'] = $order_save['id']; $temp_details['price'] = $temp['price']; $temp_details['offer_price'] = $temp['offer_price']; $temp_details['quantity'] = $temp['quantity']; $temp_details['resell'] = $temp['resell']; $temp_details['resell_id'] = $temp['resell_id']; $temp_details['event'] = $temp['event']; $temp_details['event_id'] = $temp['event_id']; $temp_details['event_price'] = $temp['event_price']; $temp_details['event_bid_id'] = $temp['event_bid_id']; if (isset($temp['typemem'])) { $temp_details['typemem'] = $temp['typemem']; } else { $temp_details['typemem'] = ''; } add(json_encode(array('save_data' => $temp_details)), 'order_details'); } } $rarray = array('type' => 'success', 'url' => $approvalUrl); } else { $rarray = array('type' => 'error'); } echo json_encode($rarray); exit; }
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; }