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;
}
}
}
}