Retorno automático do PagSeguro atualizando errado

09/05/2019

0

Olá,
Eu sou da galera do front-end, mas fui me arriscar a editar um arquivo .php e tive problemas, busco ajuda..

Meu site vende planos, originalmente é o plano com pagamento mensal e o plano com pagamento anual. O Site já vem integrado PagSeguro, com histórico de pagamento, tudo funciona!
Porém, fui inventar de alterar o pagamento anual para semestral e adicionar pagamento trimestral. Ficando: mensal, trimestral e semestral.
Consegui toda a parte do pagamento, cobra o valor que eu quero, atualiza a conta após a compra ser aprovada, etc..

O problema: Se eu escolher pagamento trimestral ou semestral, serão adicionados apenas 30 dias na conta do usuário. em vez de 90 ou 180.
Se poderem me ajudar ficarei extremamente grato.

o código:
public function complete(){
		if(isset($_POST['notificationCode']) && isset($_POST['notificationType'])){
			$code = (isset($_POST['notificationCode']) && trim($_POST['notificationCode']) !== "" ?
	            trim($_POST['notificationCode']) : null);
	        $type = (isset($_POST['notificationType']) && trim($_POST['notificationType']) !== "" ?
	            trim($_POST['notificationType']) : null);

	        if ($code && $type) {

	            $notificationType = new PagSeguroNotificationType($type);
	            $strType = $notificationType->getTypeFromValue();

	            switch ($strType) {

	                case 'TRANSACTION':
	                    $credentials = PagSeguroConfig::getAccountCredentials();

				        try {
				            $transaction = PagSeguroNotificationService::checkTransaction($credentials, $code);
				            $ids = $transaction->getItems()[0]->getId();
				            $reference = $transaction->getReference();
				            $uid = (int)str_replace("REF", "", $reference);
							$package = $this->model->get("*", $this->tb_packages, "ids = '".$ids."'  AND status = 1");
							
							$amount_monthly = $package->price_monthly;
							$amount_tri = $package->price_tri*3;
							$amount_annually = $package->price_annually*12;
							$plan = 1;
							if($amount_tri == $transaction->getGrossAmount()){
								$plan = 2;
							}
							elseif($amount_annually == $transaction->getGrossAmount()){
								$plan = 3;
							}

							$paymentId = get('paymentId');
							$PayerID = get('PayerID');
							$transaction_id = $transaction->getCode();

							$checkPaid = $this->model->get("*", $this->tb_payment_history, "transaction_id = '".$transaction_id."'");

							if(!empty($package) && empty($checkPaid) && $transaction->getStatus()->getValue() == 3){
								$data = array(
									'ids' => ids(),
									'uid' => $uid,
									'package' => $package->id,
									'type' => 'pagseguro_charge',
									'transaction_id' => $transaction_id,
									'amount' => $transaction->getGrossAmount(),
									'plan' => $plan,
									'status' => 1,
									'created' => NOW
								);
								$this->db->insert($this->tb_payment_history, $data);
								$this->update_package($package, $plan, $uid);

								echo "Sucesss";
							}else{
								die("Invalid notification parameters. Please try to again.");
							}
				        } catch (PagSeguroServiceException $e) {
				            die($e->getMessage());
				        }
	                    break;

	                default:
	                    die("Invalid notification parameters. Please try to again.");

	            }
	        } else {
	            die("Invalid notification parameters. Please try to again.");
	        }
		}else{
			//redirect(cn("dashboard"));
		}
	}

    public function update_package($package_new, $plan, $uid){
		$user = $this->model->get("*", $this->tb_users, "id = '".$uid."'");
		if(!empty($user)){
			$package_old = $this->model->get("*", $this->tb_packages, "id = '".$user->package."'");
			$package_id = $package_new->id;

			$new_days  = 30;
			if($plan == 2){
				$new_days  = 90;
			}
			if($plan == 3){
				$new_days  = 180;
			}

			if(!empty($package_old)){
				if(strtotime(NOW) < strtotime($user->expiration_date)){
					$date_now = date("Y-m-d", strtotime(NOW));
					$date_expiration = date("Y-m-d", strtotime($user->expiration_date));
					$diff = abs(strtotime($date_expiration) - strtotime($date_now));
					$left_days = floor($diff/86400);
					if($plan == 2){
						$new_days  = 90;
						$day_added = round(($package_old->price_tri/$package_new->price_tri)*$left_days);
					}if($plan == 3){
						$new_days  = 180;
						$day_added = round(($package_old->price_annually/$package_new->price_annually)*$left_days);
					}
					else{
						$new_days  = 30;
						$day_added = round(($package_old->price_monthly/$package_new->price_monthly)*$left_days);
					}
					

					$total_day = $new_days + $day_added;
					$expiration_date = date('Y-m-d', strtotime(NOW." +".$total_day." days"));
				}else{
					$expiration_date = date('Y-m-d', strtotime(NOW." +".$new_days." days"));
				}
			}else{
				$expiration_date = date('Y-m-d', strtotime(NOW." +".$new_days." days"));
			}

			$data = array(
				"package"      => $package_id,
				"expiration_date" => $expiration_date
			);

			$this->db->update($this->tb_users, $data, "id = '".$uid."'");
		}
	}

	public function process(){
		$ids  = segment(4);
		$plan  = segment(5);
		$package = $this->model->get("*", $this->tb_packages, "ids = '".$ids."'  AND status = 1");
		$user = $this->model->get("*", $this->tb_users, "id = '".session("uid")."' AND status = 1");

		if(!empty($package) && !empty($user)){
			$amount = $package->price_monthly;
			if($plan == 2){
				$amount = $package->price_tri*3;
			}
			if($plan == 3){
				$amount = $package->price_annually*6;
			}

			// Instantiate a new payment request
	        $paymentRequest = new PagSeguroPaymentRequest();

	        // Set the currency
	        $paymentRequest->setCurrency("BRL");

	        // Add an item for this payment request
	        $paymentRequest->addItem($package->ids, $package->name, 1, number_format($amount,2));

	        // Set a reference code for this payment request. It is useful to identify this payment
	        // in future notifications.
	        $paymentRequest->setReference("REF".session("uid"));

	        // Set your customer information.
	        $paymentRequest->setSender(
	            $user->fullname." customer",
	            $user->email
	        );

	        // Set the url used by PagSeguro to redirect user after checkout process ends
	        $paymentRequest->setRedirectUrl(cn("payment/pagseguro/complete"));

	        // Another way to set checkout parameters
	        $paymentRequest->addParameter('notificationURL', cn("payment/pagseguro/complete"));
	        $paymentRequest->addIndexedParameter('itemId', $package->ids, 3);
	        $paymentRequest->addIndexedParameter('itemDescription', $package->name, 3);
	        $paymentRequest->addIndexedParameter('itemQuantity', '1', 3);
	        $paymentRequest->addIndexedParameter('itemAmount', number_format($amount,2), 3);
Pedro Buck

Pedro Buck

Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar