public function testSerializeDeserialize() { $p1 = $this->payerInfo; $p2 = new PayerInfo(); $p2->fromJson($p1->toJson()); $this->assertEquals($p1, $p2); }
public function postPayment() { $name = 'Transaction'; $mmnumber = Input::get('number'); $amounttosend = Input::get('amount'); $currency = Input::get('currency'); $type = Input::get('target'); //destination/receipient's payment Provider $cno = Input::get('cardnumber'); $charges = new PlatformCharges($amounttosend, $currency, $type); $desc = $charges->getReceiverType($type); Session::set('destProvider', $type); Session::set('destination', $mmnumber); if ($type == 'pp') { return Redirect::route('dashboard')->with('alertError', 'You need to select different payment provider for sender and receiver'); } $payer = new Payer(); $payer->setPaymentMethod('paypal'); // Valid Values: ["credit_card", "bank", "paypal", "pay_upon_invoice", "carrier"] //TODO:: try to deduce the receiver type (email or number) and set the payerinfo data correctly for consistency $payerInfo = new PayerInfo(); $payerInfo->setFirstName($mmnumber); //used to represent the receiver name/number/email $payerInfo->setLastName('Paypal to ' . $desc); //used to pass the transaction type in the request $payer->setPayerInfo($payerInfo); $item_1 = new Item(); $item_1->setName('Money Transfer')->setDescription("Send money to a {$desc} User")->setCurrency('USD')->setQuantity(1)->setPrice($charges->getDueAmount('pp', $type)); // unit price) // add item to list $item_list = new ItemList(); $item_list->setItems(array($item_1)); $amount = new Amount(); $amount->setCurrency('USD')->setTotal($charges->getDueAmount('pp', $type)); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Send money To a Mobile Money User'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(URL::route('payment-status'))->setCancelUrl(URL::route('payment-status')); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction)); try { $payment->create($this->_api_context); foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } // add payment ID to session Session::put('paypal_payment_id', $payment->getId()); if (isset($redirect_url)) { // redirect to paypal return Redirect::away($redirect_url); } return "Error!!!!"; } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); return Redirect::route('dashboard')->with('alertError', 'Connection error. $err_data'); exit; } else { return Redirect::route('dashboard')->with('alertError', 'Connection error occured. Please try again later. ' . $ex->getMessage()); // die('Some error occurred, sorry for the inconvenience. Our team has been notified to correct this error.'); } } catch (Exception $ex) { return Redirect::route('dashboard')->with('alertError', 'Error! ' . $ex->getMessage()); } }
/** * @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; }
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 createBillingAgreement($planId, $shippingAddress, $billingAddress, $productName, $cartSummary, $cardDetails, $apiContext) { $billingPlanDefaultValues = $this->getBillingPlanDefaultValues(); $billingAgreement = new Agreement(); $billingAgreement->setName('Billing Agreement For ' . $productName); $billingAgreement->setDescription($cartSummary->paymentPlanTitle); $startDate = new Zend_Date(); $startDate->addDay($billingPlanDefaultValues->startDateInterval); $billingAgreement->setStartDate($startDate->get(Zend_Date::ISO_8601)); $payerInfo = new PayerInfo(); $payerInfo->setFirstName($billingAddress->firstname); $payerInfo->setLastName($billingAddress->lastname); $payerInfo->setEmail($billingAddress->emailAddress); /* Fields not supported yet */ //$payerInfo->setEmail($cart->address->billing['billing_email']); //$payerInfo->setPhone($cart->address->billing['billing_contactNo']); /* Get a MALFORMED_REQUEST error when using this field */ //$payerInfo->setCountryCode($cart->address->billing['billing_countryCode']); $cardName = $cardDetails->cardName; $cardNumber = $cardDetails->cardNumber; $cardType = strtolower($cardDetails->cardType); $cardExpiryMonth = $cardDetails->cardExpiryMonth; $cardExpiryYear = $cardDetails->cardExpiryYear; $cardSecurityCode = $cardDetails->cardSecurityCode; $nameParser = new Om_Model_Name(); $name = $nameParser->parse_name($cardName); $card = new CreditCard(); $card->setType($cardType); $card->setNumber($cardNumber); $card->setExpireMonth($cardExpiryMonth); $card->setExpireYear($cardExpiryYear); $card->setCvv2($cardSecurityCode); $card->setFirstName($name['fname']); $card->setLastName($name['lname']); $fundingInstrument = new FundingInstrument(); $fundingInstrument->setCreditCard($card); $payer = new Payer(); $payer->setPaymentMethod("credit_card"); $payer->setFundingInstruments(array($fundingInstrument)); $payer->setPayerInfo($payerInfo); $billingAgreement->setPayer($payer); $shippingAddressPayPal = new Address(); $shippingAddressPayPal->setLine1($shippingAddress->addressLine1); $shippingAddressPayPal->setLine2($shippingAddress->addressLine2 . ' ' . $shippingAddress->addressLine3); $shippingAddressPayPal->setCity($shippingAddress->city); $shippingAddressPayPal->setCountryCode($shippingAddress->getCountry()->code); $shippingAddressPayPal->setPostalCode($shippingAddress->postcode); $shippingAddressPayPal->setState($shippingAddress->county); $shippingAddressPayPal->setPhone($shippingAddress->contactNumber); $billingAgreement->setShippingAddress($shippingAddressPayPal); $plan = new Plan(); $plan->setId($planId); $billingAgreement->setPlan($plan); return $billingAgreement->create($apiContext); }
/** * @depends testSerializationDeserialization * @param PayerInfo $obj */ public function testGetters($obj) { $this->assertEquals($obj->getEmail(), "TestSample"); $this->assertEquals($obj->getExternalRememberMeId(), "TestSample"); $this->assertEquals($obj->getAccountNumber(), "TestSample"); $this->assertEquals($obj->getSalutation(), "TestSample"); $this->assertEquals($obj->getFirstName(), "TestSample"); $this->assertEquals($obj->getMiddleName(), "TestSample"); $this->assertEquals($obj->getLastName(), "TestSample"); $this->assertEquals($obj->getSuffix(), "TestSample"); $this->assertEquals($obj->getPayerId(), "TestSample"); $this->assertEquals($obj->getPhone(), "TestSample"); $this->assertEquals($obj->getPhoneType(), "TestSample"); $this->assertEquals($obj->getBirthDate(), "TestSample"); $this->assertEquals($obj->getTaxId(), "TestSample"); $this->assertEquals($obj->getTaxIdType(), "TestSample"); $this->assertEquals($obj->getCountryCode(), "TestSample"); $this->assertEquals($obj->getBillingAddress(), AddressTest::getObject()); $this->assertEquals($obj->getShippingAddress(), ShippingAddressTest::getObject()); }
public function payWithPaypal() { //purchase parameters $mmnumber = Input::get('number'); $apikey = Input::get('apikey'); $amounttosend = Input::get('amount'); $currency = Input::get('currency'); $item = Input::get('item_name'); $cancel_url = Input::get('cancel_url'); $confirm_url = Input::get('confirm_url'); // $cno = Input::get('cardnumber'); $developers = Developer::where('dev_key', '=', $apikey)->where('dev_status', '=', 1)->limit(1)->get(); if ($developers != null) { foreach ($developers as $developer) { $mmnumber = $developer->dev_email . ' | ' . $developer->dev_number . ' | ' . $developer->dev_username; $type = $developer->dev_paymentprovider; // echo $mmnumber; // echo '<BR/>'.$type; } } else { Redirect::away($cancel_url); } $charges = new PlatformCharges($amounttosend, $currency, $type); // $desc = $charges->getReceiverType($type); Session::set('destProvider', $type); Session::set('destination', $mmnumber); $payer = new Payer(); $payer->setPaymentMethod('paypal'); // Valid Values: ["credit_card", "bank", "paypal", "pay_upon_invoice", "carrier"] //TODO:: try to deduce the receiver type (email or number) and set the payerinfo data correctly for consistency $payerInfo = new PayerInfo(); $payerInfo->setFirstName($mmnumber); //used to represent the receiver name/number/email $payerInfo->setLastName('Item: '); //used to pass the transaction type in the request $payer->setPayerInfo($payerInfo); $item_1 = new Item(); $item_1->setName('Item purchase')->setDescription("Purchase made for {$item}")->setCurrency('USD')->setQuantity(1)->setPrice($charges->getDueAmount('pp', $type)); // unit price // add item to list $item_list = new ItemList(); $item_list->setItems(array($item_1)); $amount = new Amount(); $amount->setCurrency('USD')->setTotal($charges->getDueAmount('pp', $type)); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($item_list)->setDescription('Payment for $item'); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(URL::route('api/merchantapi/paypalconfirm'))->setCancelUrl(URL::route('api/merchantapi/paypalcancel')); $payment = new Payment(); $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirect_urls)->setTransactions(array($transaction)); try { $payment->create($this->_api_context); foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } // var_dump($payment->getLinks()); // var_dump($redirect_url); // add payment ID to session Session::put('paypal_payment_id', $payment->getId()); header('Location: ' . $redirect_url); exit; // return isset($redirect_url)?Redirect::away($redirect_url): "Error!!Paypal Checkout error"; } catch (\PayPal\Exception\PPConnectionException $ex) { if (\Config::get('app.debug')) { echo "Exception: " . $ex->getMessage() . PHP_EOL; $err_data = json_decode($ex->getData(), true); return Redirect::route($cancel_url)->with('alertError', 'Connection error. $err_data'); exit; } else { return Redirect::route($cancel_url)->with('alertError', 'Connection error occured. Please try again later. ' . $ex->getMessage()); // die('Some error occurred, sorry for the inconvenience. Our team has been notified to correct this error.'); } } catch (Exception $ex) { return Redirect::route($cancel_url)->with('alertError', 'Error! ' . $ex->getMessage()); } }
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; } } } }
/** * Build PayerInfo for Payer * * @param $quote * @return PayerInfo */ protected function buildPayerInfo($quote) { $payerInfo = new PayerInfo(); $address = $quote->getBillingAddress(); if ($address->getFirstname()) { $payerInfo->setFirstName($address->getFirstname()); } if ($address->getMiddlename()) { $payerInfo->setMiddleName($address->getMiddlename()); } if ($address->getLastname()) { $payerInfo->setLastName($address->getLastname()); } $billingAddress = $this->buildBillingAddress($quote); if ($billingAddress) { $payerInfo->setBillingAddress($billingAddress); } return $payerInfo; }