/** * @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()); }
/** * 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; }
/** * Creates a PayPal transaction object for given order * * @param OrderInterface $order * * @return Transaction */ protected function createTransaction(OrderInterface $order) : Transaction { $transaction = new Transaction(); $transaction->setAmount($this->createAmount($order)); $transaction->setItemList($this->createItemList($order)); $transaction->setDescription($order->getId()); return $transaction; }
/** * @param Amount $amount * @param ItemList $itemLists * @param string $invoiceNumber * @param string $description * * @return Transaction */ public static function createTransaction(Amount $amount, ItemList $itemLists, $invoiceNumber, $description) { $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setItemList($itemLists); $transaction->setInvoiceNumber($invoiceNumber); $transaction->setDescription($description); return $transaction; }
public static function createTransaction() { $transaction = new Transaction(); $transaction->setAmount(AmountTest::createAmount()); $transaction->setDescription(self::$description); $transaction->setItemList(ItemListTest::createItemList()); $transaction->setPayee(PayeeTest::createPayee()); $transaction->setRelatedResources(array(RelatedResourcesTest::createRelatedResources())); return $transaction; }
public static function createTransaction() { $transaction = new Transaction(); $transaction->setAmount(AmountTest::createAmount()); $transaction->setDescription(self::$description); $transaction->setInvoiceNumber(self::$invoiceNumber); $transaction->setCustom(self::$custom); $transaction->setSoftDescriptor(self::$softDescriptor); $transaction->setItemList(ItemListTest::createItemList()); $transaction->setPayee(PayeeTest::createPayee()); $transaction->setRelatedResources(array(RelatedResourcesTest::createRelatedResources())); return $transaction; }
/** * @return array array of PayPal\Api\Transaction */ protected function getTransactions() { $payPalItems = array(); $currency = $this->currency ? $this->currency : $this->context->getCurrency(); $payPalItem = new Item(); $payPalItem->setName($this->name); $payPalItem->setCurrency($currency); $payPalItem->setQuantity($this->quantity); $payPalItem->setPrice($this->price); $payPalItems[] = $payPalItem; $totalPrice = $this->quantity * $this->price; $itemLists = new ItemList(); $itemLists->setItems($payPalItems); $amount = new Amount(); $amount->setCurrency($currency); $amount->setTotal($totalPrice); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setItemList($itemLists); return array($transaction); }
/** * When you have configured the payment properly this will give you a URL that you can redirect your visitor to, * so that he can pay the desired amount. * * @param string $url_format * @return string */ public function get_payment_url($url_format) { if (!is_array($this->payment_provider_auth_config[self::PROVIDER_NAME]) || !isset($this->payment_provider_auth_config[self::PROVIDER_NAME]['clientid']) || !isset($this->payment_provider_auth_config[self::PROVIDER_NAME]['secret'])) { throw new \Exception('Auth Config for Provider ' . self::PROVIDER_NAME . ' is not set.', 1394795187); } $total_price = $this->order->get_total_price(); if ($total_price == 0) { throw new \Exception('Total price is 0. Provider ' . self::PROVIDER_NAME . ' does not support free payments.', 1394795478); } $api_context = new ApiContext(new OAuthTokenCredential($this->payment_provider_auth_config[self::PROVIDER_NAME]['clientid'], $this->payment_provider_auth_config[self::PROVIDER_NAME]['secret'])); $api_context->setConfig(array('mode' => 'sandbox', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => false)); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $amount = new Amount(); $amount->setCurrency("EUR"); $amount->setTotal($this->order->get_total_price()); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setDescription($this->order->get_reason()); $transaction->setItemList($this->getItemList()); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->get_success_url($url_format)); $redirectUrls->setCancelUrl($this->get_abort_url($url_format)); $payment = new \PayPal\Api\Payment(); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setRedirectUrls($redirectUrls); $payment->setTransactions(array($transaction)); $payment->create($api_context); $payment_url = ''; foreach ($payment->getLinks() as $link) { /** @var \PayPal\Api\Links $link */ if ($link->getRel() == 'approval_url') { $payment_url = $link->getHref(); } } return $payment_url; }
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; }
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()); } }
/** * Создаем платеж типа paypal * в случае успеха возвращает массив с ид-платежа, * токеном и редирект-урлом куда нужно направить пользователя для оплаты * * @param double $pay_sum * @param string $paymentInfo * @param string $sku - internal UNIT ID * * @return array | null */ public function payThroughPayPal($pay_sum, $paymentInfo, $sku = null) { set_time_limit(120); $payer = new Payer(); $payer->setPaymentMethod('paypal'); $amount = new Amount(); $amount->setCurrency('USD'); $amount->setTotal($pay_sum); $item1 = new Item(); $item1->setName($paymentInfo)->setCurrency('USD')->setQuantity(1)->setPrice($pay_sum); // Ид товара/услуги на вашей стороне if ($sku) { $item1->setSku($sku); } $itemList = new ItemList(); $itemList->setItems([$item1]); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setDescription('Payment to DirectLink'); $transaction->setItemList($itemList); $transaction->setNotifyUrl($this->config['url.notify_url']); //** $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl($this->config['url.return_url']); $redirect_urls->setCancelUrl($this->config['url.cancel_url']); $payment = new Payment(); $payment->setIntent('sale'); $payment->setPayer($payer); $payment->setTransactions([$transaction]); $payment->setRedirectUrls($redirect_urls); //$payment->setId('123456789'); //** $payment->create($this->_apiContext); //var_dump($payment); exit; $links = $payment->getLinks(); foreach ($links as $link) { if ($link->getMethod() == 'REDIRECT') { $redirect_to = $link->getHref(); $token = time() . "_" . rand(100, 999); $tmp = parse_url($redirect_to); if (isset($tmp['query'])) { parse_str($tmp['query'], $out); if (isset($out['token'])) { $token = $out['token']; } } $paymentId = $payment->getId(); // ++ DEBUG LOG $this->logging_queryes('paymentCreate_' . $paymentId . '.txt', $payment->toJSON()); // -- DEBUG LOG return ['paymentId' => $paymentId, 'token' => $token, 'redirect_to' => $redirect_to]; } } return null; }
/** * @param $data array form post data * @return string HTML to display */ function _prePayment($data) { $this->_autoload(); $order = $this->_getOrder($data['order_number']); //initialise application $app = JFactory::getApplication(); //get card input $data['cardtype'] = $app->input->getString("cardtype"); $data['cardnum'] = $app->input->getString("cardnum"); $month = $app->input->getString("month"); $year = $app->input->getString("year"); $card_exp = $month . '' . $year; $data['cardexp'] = $card_exp; $data['cardcvv'] = $app->input->getString("cardcvv"); $data['cardnum_last4'] = substr($app->input->getString("cardnum"), -4); //initialise payment $apiContext = new ApiContext(new OAuthTokenCredential($this->api_clientId, $this->api_clientSecret)); $apiContext->setConfig(array('mode' => $this->api_mode)); // echo'<pre>';print_r($apiContext);die; $card = new CreditCard(); $card->setType($data['cardtype']); $card->setNumber($data['cardnum']); $card->setExpireMonth($month); $card->setExpireYear($year); $card->setFirstName($data['firstname']); $card->setLastName($data['lastname']); $card->setCvv2($data['cardcvv']); $fi = new FundingInstrument(); $fi->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card")->setFundingInstruments(array($fi)); if (!empty($data['email'])) { $payerInfo = new PayerInfo(); $payerInfo->setFirstName($data['firstname']); $payerInfo->setLastName($data['lastname']); $payerInfo->setEmail($data['email']); $payer->setPayerInfo($payerInfo); } $amount = new Amount(); $amount->setCurrency($this->currency); $amount->setTotal($data['total']); $item1 = new Item(); $item1->setName($data['order_number'])->setDescription($data['order_number'])->setCurrency($this->currency)->setQuantity(1)->setTax(0)->setPrice($data['total']); $itemList = new ItemList(); $itemList->setItems(array($item1)); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setItemList($itemList); $transaction->setDescription($data['order_number']); $payment = new Payment(); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setTransactions(array($transaction)); $request = clone $payment; try { $payment->create($apiContext); } catch (PayPal\Exception\PayPalConnectionException $ex) { $error = json_decode($ex->getData()); $error_html = '<h2>' . $error->name . '</h2><br>'; foreach ($error->details as $r) { $error_html .= '- ' . $r->field . ' - ' . $r->issue . '<br>'; } $app->enqueueMessage($error_html, 'error'); $app->redirect('index.php?option=com_bookpro&view=formpayment&order_id=' . $order->id . '&' . JSession::getFormToken() . '=1'); return; } catch (Exception $ex) { die($ex); } $ack = $payment->getState(); if ($ack == 'approved' || $ack == 'completed') { $order->pay_status = "SUCCESS"; $order->order_status = "CONFIRMED"; $order->tx_id = $payment->getId(); $order->store(); } else { JLog::addLogger(array('text_file' => 'paypal.txt', 'text_file_path' => 'logs', 'text_file_no_php' => 1, 'text_entry_format' => '{DATE} {TIME} {MESSAGE}'), JLog::ALERT); JLog::add('Transaction: ' . json_encode($payment) . '\\nOrder: ' . $order->order_number . ' Status: ' . $ack, JLog::ALERT, 'com_bookpro'); $order->pay_status = "PENDING"; $order->tx_id = $transaction_id; $order->store(); } $app = JFactory::getApplication(); $app->redirect('index.php?option=com_bookpro&controller=payment&task=postpayment&method=' . $this->_element . '&order_number=' . $order->order_number); return; }
public function createTransaction(Amount $amount, $paymentDesc, ItemList $itemList = null) { // ###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)->setDescription($paymentDesc); if (isset($itemList)) { $transaction->setItemList($itemList); } return $transaction; }
public function createPayment($addressee, $order) { // Order Totals $subTotal = $order->total; $shippingCharges = $order->shipping; $tax = $order->tax; $grandTotal = $order->grandTotal; // Get Context $context = $this->getApiContext(); // Payer $payer = new Payer(); $payer->setPaymentMethod('paypal'); // Cart Items $itemList = $this->generateItemsList($order); // Shipping Address if ($this->properties->isSendAddress()) { $shippingAddress = $this->generateShippingAddress($addressee, $cart); $itemList->setShippingAddress($shippingAddress); } // Details $details = new Details(); $details->setSubtotal($subTotal); $details->setShipping($shippingCharges); $details->setTax($tax); // Amount $amount = new Amount(); $amount->setCurrency($this->properties->getCurrency()); $amount->setTotal($grandTotal); $amount->setDetails($details); // Transaction $transaction = new Transaction(); $transaction->setAmount($amount); if (isset($order->description)) { $transaction->setDescription($order->description); } $transaction->setItemList($itemList); // Status URLs $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($this->successUrl); $redirectUrls->setCancelUrl($this->failureUrl); // Payment $payment = new Payment(); $payment->setRedirectUrls($redirectUrls); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setTransactions([$transaction]); $payment->create($context); return $payment; }
public function pay() { // BEGINNING OF PAYMENT CHECK if (empty($_COOKIE)) { echo json_encode(array("error" => true, "description" => "Non hai effettuato l'accesso a reSeed. Effettua l'accesso e riprova.", "errorCode" => "ACCESS_DENIED", "parameters" => array())); return; } if (!isset($_COOKIE['cart'])) { echo json_encode(array("error" => true, "description" => "Non hai inserito alcun articolo nel carrello.", "errorCode" => "EMPTY_CART_ERROR", "parameters" => array())); return; } $userID = $_COOKIE['username']; if (!$userID) { echo json_encode(array("error" => true, "description" => "Non hai effettuato l'accesso a reSeed. Effettua l'accesso e riprova.", "errorCode" => "ACCESS_DENIED", "parameters" => array())); return; } $cart = json_decode($_COOKIE['cart'], true); $cartItems = $cart['items']; $cartOptions = $cart['options']; if (!array_key_exists('paymentMediaChosen', $cartOptions)) { echo json_encode(array("error" => true, "description" => "Non hai selezionato un mezzo di pagamento.", "errorCode" => "MISSING_PAYMENT_MEDIA", "parameters" => array())); return; } if ($this->debugMode) { print "UTENTE: " . $userID; } if ($this->debugMode) { print "<br/>WHOLE CART:"; print_r($cart); } if ($this->debugMode) { print "<br/>ITEMS:"; print_r($cartItems); } if ($this->debugMode) { print "<br/>OPTIONS:"; print_r($cartOptions); } // Prendi i corsi a cui è già iscritto l'utente $userCourses = array(); foreach ($this->payment_model->get_courses($userID) as $course) { $userCourses[$course['courseID']] = $course; } if ($this->debugMode) { print "<br/>USER'S COURSES"; print_r($userCourses); } // Prendi tutti i corsi disponibili $allCourses = []; foreach ($this->courses_model->get_all() as $course) { $allCourses[$course['courseID']] = $course; } $totalItems = array(); $total = 0; foreach ($cartItems as $item) { $courseID = $item['courseID']; $courseInfo = $allCourses[$courseID]; $alreadySubscribed = array_key_exists($courseID, $userCourses); // Evita di far pagare corsi che l'utente ha già acquistato $wantCourse = !$alreadySubscribed && $item['payCourse'] == "1"; // Check se l'utente ha acquistato la simulazione $wantSimulation = $item['paySimulation'] == "1"; if (!$alreadySubscribed && !$wantCourse && $wantSimulation) { if ($this->debugMode) { print "ERRORE: non puoi comprare solo la simulazione."; } echo json_encode(array("error" => true, "description" => "Non è possibile acquistare soltanto la simulazione per un corso. Seleziona anche il corso e riprova.", "errorCode" => "INVALID_CHOICE", "parameters" => array("paySimulation"))); return; } // Non dare per buone le somme che arrivano dai cookie. Ricalcola. if ($wantCourse) { $coursePrice = $courseInfo['price']; if ($this->debugMode) { print "<br/>Costo di " . $courseID . ": " . $coursePrice; } $totalItems[] = array('item' => $courseID, 'itemType' => 'course', 'price' => $coursePrice, 'description' => "Il corso di " . $courseInfo['name'] . " a reSeed"); $total += $coursePrice; } // Se l'utente ha pagato anche la simulazione, vediamo qual è il suo prezzo if ($wantSimulation) { $simulationPrice = $courseInfo['simulationPrice']; if ($this->debugMode) { print "<br/>Costo della simulazione di " . $courseID . ": " . $simulationPrice; } if ($simulationPrice) { $totalItems[] = array('item' => $courseID . "-simulation", 'itemType' => 'simulation', 'price' => $simulationPrice, 'description' => "La simulazione del corso di " . $courseInfo['name'] . " a reSeed"); $total += $simulationPrice; } } } if ($this->debugMode) { print "<br/>PREZZO FINALE (PRE-SCONTI): " . $total; } $seedOnDiscount = 0; // Prendi l'eventuale seedon che l'utente ha specificato e controlla che // i) ce l'abbia davvero // ii) sia ancora valido (non usato && non scaduto) if (array_key_exists('seedOnChosen', $cartOptions) && $cartOptions['seedOnChosen'] !== "-1") { // Prendi il seedon scelto $seedonChosen = $cartOptions['seedOnChosen']; if ($this->debugMode) { print_r("<br/>L'utente " . $userID . " ha scelto il seedon con ID=" . $cartOptions['seedOnChosen']); } // Prendi tutti i seedon dell'utente $userSeedons = []; foreach ($this->seedon_model->get_seedon_not_used($userID) as $seedon) { // Considera solo seedon che non sono scaduti if ($seedon['endingDate'] > $this->time->get_timestamp()) { $userSeedons[$seedon['seedonID']] = $seedon; } } if ($this->debugMode) { print "<br/>Seedon dell'utente: "; print_r($userSeedons); } if ($this->debugMode) { print_r(array_key_exists($seedonChosen, $userSeedons)); } if (array_key_exists($seedonChosen, $userSeedons)) { $seedonInfo = $userSeedons[$seedonChosen]; if ($seedonInfo['tag'] === "DISCOUNT") { $seedOnDiscount = $seedonInfo['data']; } } } if ($this->debugMode) { print "<br/>SCONTO SEEDON FINALE: " . $seedOnDiscount; } // Considera gli sconti lifetime dell'utente $lifetimeDiscount = 0; foreach ($this->user_achievements_rewards_model->get_achievements_and_rewards_obtained($userID, "REWARD", "DISCOUNT") as $discount) { $lifetimeDiscount += $discount['data']; } if ($this->debugMode) { print "<br/>SCONTO LIFETIME FINALE: " . $lifetimeDiscount; } $totalDiscount = $seedOnDiscount + $lifetimeDiscount; $total = $total - $total * $totalDiscount; foreach ($totalItems as $key => $item) { // print("<br/>Il prezzo prima: " . $item['price']); $item['price'] = $item['price'] - $item['price'] * $totalDiscount; $totalItems[$key] = $item; // print("<br/>Il prezzo dopo: " . $item['price']); } // Considera se l'utente ha scelto le rate mensili if (array_key_exists('paymentCycleChosen', $cartOptions)) { $paymentCycleChosen = $cartOptions['paymentCycleChosen']; if ($paymentCycleChosen === "monthly") { if ($this->debugMode) { print "<br/>PAGANDO A RATE IL TOTALE " . $total . " DIVENTA " . $total / 3; } $total /= 3; foreach ($totalItems as $key => $item) { $item['price'] /= 3; $totalItems[$key] = $item; } } } if ($this->debugMode) { print "<br/>PREZZO FINALE: " . $total; } // END OF PAYMENT CHECK $paymentChoice = $cartOptions['paymentMediaChosen']; if ($paymentChoice === "wireTransfer") { // Salva sul DB la richiesta di pagamento $paymentID = "WT-" . $this->randomString(); $this->paypal_history_model->add($paymentID, $userID, $_COOKIE['cart'], "", $this->time->get_timestamp(), "created"); // Aggiungiamo la pre-iscrizione al DB (se necessario) foreach ($cartItems as $item) { $courseID = $item['courseID']; $payment = $this->payment_model->get_payment($userID, $courseID); if (empty($payment)) { $this->payment_model->add($userID, $courseID); } } sleep(3); echo json_encode(array("error" => false, "url" => "index.php/Paypal/payment_successful?paymentId=" . $paymentID . "&PayerID=" . $userID)); return; } else { if ($paymentChoice === "cash") { $paymentID = "CASH-" . $this->randomString(); $this->paypal_history_model->add($paymentID, $userID, $_COOKIE['cart'], "", $this->time->get_timestamp(), "created"); // Aggiungiamo la pre-iscrizione al DB (se necessario) foreach ($cartItems as $item) { $courseID = $item['courseID']; $payment = $this->payment_model->get_payment($userID, $courseID); if (empty($payment)) { $this->payment_model->add($userID, $courseID); } } sleep(3); echo json_encode(array("error" => false, "url" => "index.php/Paypal/payment_successful?paymentId=" . $paymentID . "&PayerID=" . $userID)); return; } else { if ($paymentChoice === "creditCard") { $userInfo = $this->userinfo_model->get($userID); $payer = new Payer(); $payerInfo = new PayerInfo(); if (array_key_exists('name', $userInfo)) { $payerInfo->setFirstName($userInfo['name']); } if (array_key_exists('surname', $userInfo)) { $payerInfo->setLastName($userInfo['surname']); } if (array_key_exists('birthdate', $userInfo)) { $payerInfo->setBirthDate($userInfo['birthdate']); } $payerInfo->setPayerId($userID); $payer->setPayerInfo($payerInfo); $payer->setPaymentMethod('paypal'); $amount = new Amount(); $amount->setCurrency('EUR'); $amount->setTotal($total); $transaction = new Transaction(); $transaction->setAmount($amount); $itemList = new ItemList(); foreach ($totalItems as $cartItem) { $item = new Item(); $item->setName($cartItem['item']); $item->setDescription($cartItem['description']); $item->setQuantity(1); $item->setCurrency("EUR"); $item->setPrice($cartItem['price']); $itemList->addItem($item); } $transaction->setItemList($itemList); $payment = new Payment(); $payment->setIntent('sale'); $payment->setPayer($payer); $payment->setTransactions(array($transaction)); // Set redirects URLs $redirectUrls = new RedirectUrls(); $baseUrl = "https://www.reseed.it/index.php/"; $redirectUrls->setReturnUrl($baseUrl . "Paypal/payment_successful")->setCancelUrl($baseUrl . "Paypal/payment_cancelled"); $payment->setRedirectUrls($redirectUrls); try { // Prendiamo i docenti di tutti i corsi $all_teachers = array(); foreach ($this->course_teachers_model->get_all_teachers() as $course_teacher) { $all_teachers[$course_teacher['courseID']] = $course_teacher['teacherID']; } // Vediamo quali sono i docenti coinvolti dal pagamento dell'utente $course_teachers = array(); foreach ($cartItems as $cartItem) { if ($cartItem['payCourse'] == "1" || $cartItem['paySimulation'] == "1") { $teacher = $all_teachers[$cartItem['courseID']]; if (!array_key_exists($teacher, $course_teachers)) { $course_teachers[] = $teacher; } } } $teacher = null; if (count($course_teachers) == 1) { $teacher = $course_teachers[0]; } $apiContext = $this->get_credentials($teacher); // print("USING CREDENTIALS: "); // print_r($apiContext); $response = $payment->create($apiContext); // Salva sul DB il successo $this->paypal_history_model->add($response->getId(), $userID, json_encode($payment->toJSON()), json_encode($response->toJSON()), $this->time->get_timestamp(), $response->getState()); } catch (\PayPal\Exception\PayPalConnectionException $ex) { echo json_encode(array("error" => true, "description" => "Errore durante la connessione a Paypal. Riprova più tardi. Dettagli errore: " . $ex->getData(), "errorCode" => "PAYPAL_ERROR", "parameters" => array(""))); return; } // Aggiungiamo la pre-iscrizione al DB (se necessario) foreach ($cartItems as $item) { $courseID = $item['courseID']; $payment = $this->payment_model->get_payment($userID, $courseID); if (empty($payment)) { $this->payment_model->add($userID, $courseID); } } echo json_encode(array("error" => false, "url" => $response->getApprovalLink())); return; } } } }
/** * Create payment for curretn quote * * @param WebProfile $webProfile * @param Mage_Sales_Model_Quote $quote * @return boolean */ public function createPayment($webProfile, $quote, $taxFailure = false) { $payer = new Payer(); $payer->setPaymentMethod("paypal"); $itemList = $this->buildItemList($quote, $taxFailure); $shippingAddress = $this->buildShippingAddress($quote); if ($shippingAddress) { $itemList->setShippingAddress($shippingAddress); } $amount = $this->buildAmount($quote); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setItemList($itemList); $baseUrl = Mage::getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($baseUrl . 'paypalplus/index/success')->setCancelUrl(Mage::helper('checkout/url')->getCheckoutUrl()); $payment = new Payment(); $payment->setIntent("sale")->setExperienceProfileId($webProfile->getId())->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); try { $response = $payment->create($this->_apiContext); Mage::getSingleton('customer/session')->setPayPalPaymentId($response->getId()); Mage::getSingleton('customer/session')->setPayPalPaymentPatched(null); } catch (PayPal\Exception\PayPalConnectionException $ex) { if (!$taxFailure) { return $this->createPayment($webProfile, $quote, true); } Mage::helper('iways_paypalplus')->handleException($ex); return false; } catch (Exception $e) { Mage::logException($e); return false; } return $response; }
private function createPayment($details) { $payment = new Payment(); $payer = new Payer(); $payer->payment_method = "paypal"; $amount = new Amount(); $amount->currency = $details['PAYMENTREQUEST_CURRENCYCODE']; $amount->total = $details['PAYMENTREQUEST_AMT']; $transaction = new Transaction(); $transaction->amount = $amount; $transaction->description = $details['PAYMENTREQUEST_DESCRIPTION']; $itemList = new ItemList(); foreach ($details['PAYMENTREQUEST_ITEMS'] as $itemInfo) { $item = new Item(); $item->setQuantity($itemInfo['quantity']); $item->setName($itemInfo['name']); $item->setDescription($itemInfo['description']); $item->setPrice($itemInfo['price']); $item->setCategory($itemInfo['category']); $item->setCurrency($itemInfo['currency']); $item->setTax($itemInfo['tax']); $item->setSku($itemInfo['sku']); $itemList->addItem($item); } $addressInfo = $details['PAYMENTREQUEST_SHIPPING_ADDRESS']; $shippingAddress = new ShippingAddress(); $shippingAddress->setRecipientName($addressInfo['recipient_name']); $shippingAddress->setLine1($addressInfo['line1']); $shippingAddress->setPostalCode($addressInfo['postal_code']); $shippingAddress->setCity($addressInfo['city']); $shippingAddress->setCountryCode($addressInfo['country_code']); $itemList->setShippingAddress($shippingAddress); $transaction->setItemList($itemList); $redirectUrls = new RedirectUrls(); $redirectUrls->return_url = $details['RETURN_URL']; $redirectUrls->cancel_url = $details['CANCEL_URL']; $payment->intent = "sale"; $payment->payer = $payer; $payment->redirect_urls = $redirectUrls; $payment->transactions = [$transaction]; if (false == isset($details['response']) && false == isset($details['response']['state']) && isset($payment->payer->payment_method) && 'paypal' == $payment->payer->payment_method) { $paymentResponse = $payment->create($this->api); $details->replace(['response' => $paymentResponse->toArray()]); foreach ($paymentResponse->links as $link) { if ($link->rel == 'approval_url') { $details->replace(['approval_url' => $link->href]); } } } }
public function store(Request $request) { //stores a new order for confirmation $result = false; $msg = ""; $info = $request->all(); //return dd($request->all()); //return var_dump( $info ); if (Auth::check()) { if (User::profileComplete(Auth::user())) { $paypal_conf = config('paypal'); $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret'])); $this->_api_context->setConfig($paypal_conf['settings']); $fabric = Fabric::find($info["fabric"]); $user = Auth::user(); $order = new Order(); if ($fabric->stock >= $info["totalAmount"] && $info["totalAmount"] > 0) { //create new order with from the given data. $order->user_id = $user->id; $order->fabric_id = $fabric->id; $order->fabric_name = $fabric->name; $order->amount = $info["totalAmount"]; $weight = $info["totalAmount"] / 5 * (2.5 * 1.2); $order->shipping = $weight; $order->type_sample = $info["type-sample"]; $order->carrier = $info["carrier"]; $order->sub_total = $fabric->priceYard * $info["totalAmount"]; $order->total = $order->sub_total + $order->shipping; $order->status = "not-confirmed"; $fabric->stock -= $order->amount; $result = true; $dataMail["subTotal"] = $order->sub_total; $dataMail["shipping"] = $order->shipping; $dataMail["carrier"] = $order->carrier; $dataMail["type-sample"] = $order->type_sample; $dataMail["total"] = $order->total; $dataMail["fabric-name"] = $fabric->name; $dataMail["name"] = $user->name; $dataMail["city"] = $user->city; $dataMail["country"] = $user->country; $dataMail["zp"] = $user->zp_code; $dataMail["address"] = $user->address; $dataMail["email"] = $user->email; $dataMail["totalAmount"] = $order->amount; // paypal logic starts here $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item = new Item(); $item->setName($order->fabric_name . $order->created_at); $item->setCurrency('USD'); $item->setQuantity($order->amount); $item->setPrice($fabric->priceYard); $itemCarrier = new Item(); $itemCarrier->setName("Shipping Price"); $itemCarrier->setCurrency('USD'); $itemCarrier->setQuantity(1); $itemCarrier->setPrice($weight); // add item to list $item_list = new ItemList(); $item_list->setItems([$itemCarrier, $item]); $amount = new Amount(); $amount->setCurrency('USD'); $amount->setTotal($order->sub_total + $weight); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setItemList($item_list); $transaction->setDescription('New Fabric Order'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(url('successPay/orders')); $redirect_urls->setCancelUrl(url("cancelPay/orders")); $payment = new Payment(); $payment->setIntent('Sale'); $payment->setPayer($payer); $payment->setRedirectUrls($redirect_urls); $payment->setTransactions(array($transaction)); try { PPHttpConfig::$DEFAULT_CURL_OPTS[CURLOPT_SSLVERSION] = 4; $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); echo '<pre>'; print_r(json_decode($pce->getData())); exit; 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 $paypal_data = ['paypal_payment_id' => $payment->getId(), "fabric" => $fabric, "order" => $order, "data_mail" => $dataMail, "paypal_context" => $this->_api_context]; Session::put("paypal_data", $paypal_data); $order_data = ["msg" => "Error: could not connect to paypal", "result" => false]; if (isset($redirect_url)) { // redirect to paypal return redirect($redirect_url); } else { return redirect('/fabrics')->with('order_data', $order_data); } } else { $msg = "Error: The order value exceeds the stock or its 0"; $result = false; } } else { $msg = "Error: To use this option you need to fill your profile first"; $result = false; } } else { $msg = "Error: You need to create an account first"; } $order_data = ["msg" => $msg, "result" => $result]; return redirect("/fabrics")->with("order_data", $order_data); }
/** * Create a payment using the buyer's paypal * account as the funding instrument. Your app * will have to redirect the buyer to the paypal * website, obtain their consent to the payment * and subsequently execute the payment using * the execute API call. * * @param string $total payment amount in DDD.DD format * @param string $currency 3 letter ISO currency code such as 'USD' * @param string $paymentDesc A description about the payment * @param string $returnUrl The url to which the buyer must be redirected * to on successful completion of payment * @param string $cancelUrl The url to which the buyer must be redirected * to if the payment is cancelled * @return \PayPal\Api\Payment */ function makePaymentUsingPayPal($total, $currency, $paymentDesc, $returnUrl, $cancelUrl) { $payer = new Payer(); $payer->setPaymentMethod("paypal"); // Specify the payment amount. $amount = new Amount(); $amount->setCurrency($currency); $amount->setTotal($total); // ###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 $item = new Item(); $item->setQuantity(1); $item->setName($paymentDesc); $item->setPrice($total); $item->setCurrency("USD"); $itemList = new ItemList(); $itemList->setItems(array($item)); $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setItemList($itemList); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($returnUrl); $redirectUrls->setCancelUrl($cancelUrl); $payment = new Payment(); $payment->setRedirectUrls($redirectUrls); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setTransactions(array($transaction)); $payment->create($this->getApiContext()); return $payment; }
/** * [makePaymentUsingPayPal description] * @param [type] $order [description] * @param [type] $currency [description] * @param [type] $returnUrl [description] * @param [type] $cancelUrl [description] * @return [type] [description] */ function makePaymentUsingPayPal($order, $currency, $returnUrl, $cancelUrl) { $payer = new Payer(); $payer->setPaymentMethod("paypal"); // $payee = new Payee(); // $payee->setEmail((string)$order['email_paypal']); // Specify the payment amount. $item = new Item(); $item->setQuantity((string) $order['quantity']); $item->setName($order['description']); $item->setPrice((string) $order['input_price']); $item->setCurrency($currency); $item->setSku($order['item_number']); $array_item[] = $item; if (isset($order['price_ship'])) { $item_ship = new Item(); $item_ship->setQuantity('1'); $item_ship->setName('shipping'); $item_ship->setPrice((string) $order['price_ship']); $item_ship->setCurrency($currency); $item_ship->setSku('shipping'); $array_item[] = $item_ship; } $item_list = new ItemList(); $item_list->setItems($array_item); $amount = new Amount(); $amount->setCurrency($currency); $amount->setTotal((string) $order['total']); //$amount->setTax() // ###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); $transaction->setDescription($order['description']); $transaction->setItemList($item_list); // $transaction->setPayee($payee); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($returnUrl); $redirectUrls->setCancelUrl($cancelUrl); $payment = new Payment(); $payment->setRedirectUrls($redirectUrls); $payment->setIntent("sale"); $payment->setPayer($payer); $payment->setTransactions(array($transaction)); $payment->create($this->getApiContext()); return $payment; }
public function setPaypalTransaction($amount, $descr, $invoiceNumber, $itemList) { $transaction = new Transaction(); $transaction->setAmount($amount); $transaction->setDescription($descr); $transaction->setInvoiceNumber($invoiceNumber); $transaction->setItemList($itemList); return $transaction; }