✨ feat(WalletController): Ajoute la complétion du paiement du wallet.
📝 chore(WalletController): Crée le controller pour gérer les wallets. 🐛 fix(WalletController): Corrige la description de l'historique du wallet. ✨ feat(Stancer/Client): Ajoute la récupération du status du paiement.
This commit is contained in:
@@ -156,11 +156,12 @@ class WalletController extends AbstractController
|
||||
$wallet = $websiteFromDns->getCustomer()->getCustomerWallet();
|
||||
|
||||
|
||||
$t = new \DateTime();
|
||||
|
||||
$ch = new CustomerWalletHistory();
|
||||
$ch->setWallet($wallet);
|
||||
$ch->setOperation("credit");
|
||||
$ch->setDescrition("");
|
||||
$ch->setDescrition("cc-".$wallet->getCustomer()->getId()."_ww-".$websiteDns->getWebsite()->getId()."_".$t->getTimestamp());
|
||||
$ch->setEntryAt(new \DateTimeImmutable());
|
||||
$ch->setIsCompleted(false);
|
||||
$ch->setAmmount($content->amount);
|
||||
|
||||
116
src/Controller/WalletController.php
Normal file
116
src/Controller/WalletController.php
Normal file
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Entity\CustomerWalletHistory;
|
||||
use App\Entity\EsyWeb\Website;
|
||||
use App\Repository\CustomerWalletHistoryRepository;
|
||||
use App\Service\Stancer\Client;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Psr\Log\LoggerInterface; // Added for logging
|
||||
|
||||
class WalletController extends AbstractController
|
||||
{
|
||||
// Simplified route definition
|
||||
#[Route(path: '/wallet/complete', name: 'app_completed_payment', methods: ['GET'])]
|
||||
public function walletCompleted(
|
||||
Request $request,
|
||||
CustomerWalletHistoryRepository $customerWalletHistoryRepository, // Renamed for clarity
|
||||
Client $client,
|
||||
EntityManagerInterface $entityManager,
|
||||
// EventDispatcherInterface $eventDispatcher, // Removed if not used in current logic
|
||||
LoggerInterface $logger // Added logger for better debugging
|
||||
): Response {
|
||||
// 1. Validate ID existence and type
|
||||
$id = $request->query->get('id');
|
||||
if (empty($id) || !is_string($id)) {
|
||||
$logger->warning('Wallet completion request received without a valid ID.');
|
||||
// Return 400 Bad Request or empty JSON, depending on desired API behavior
|
||||
return new JsonResponse(['message' => 'Missing or invalid payment ID.'], Response::HTTP_BAD_REQUEST);
|
||||
}
|
||||
|
||||
// 2. Fetch Wallet History
|
||||
/** @var CustomerWalletHistory|null $ch */
|
||||
// Assuming 'descrition' is a typo for 'description' and is used as a unique identifier for the payment
|
||||
$ch = $customerWalletHistoryRepository->findOneBy(['descrition' => $id]);
|
||||
|
||||
if (!$ch) {
|
||||
$logger->error("CustomerWalletHistory not found for ID: {$id}");
|
||||
return new JsonResponse(['message' => 'Payment history not found.'], Response::HTTP_NOT_FOUND);
|
||||
}
|
||||
|
||||
if ($ch->isCompleted()) { // Check if already completed
|
||||
$logger->info("Payment ID: {$id} is already completed. Redirecting.");
|
||||
return $this->redirectToWebsite($ch->getDescrition(), $entityManager);
|
||||
}
|
||||
|
||||
// 3. Check Payment Status
|
||||
$paymentStatus = $client->payment($ch->getPaimentId());
|
||||
|
||||
// Use strict comparison
|
||||
if ($paymentStatus !== "to_capture") {
|
||||
$logger->info("Payment ID: {$id} has status: {$paymentStatus}. Expected: to_capture.");
|
||||
// If the payment isn't ready to capture, we just return
|
||||
return new JsonResponse(['message' => 'Payment status is not ready to capture.'], Response::HTTP_OK);
|
||||
}
|
||||
|
||||
// 4. Update Database in a Transaction
|
||||
try {
|
||||
$entityManager->getConnection()->beginTransaction();
|
||||
|
||||
$wallet = $ch->getWallet();
|
||||
$ammount = $ch->getAmmount();
|
||||
|
||||
// Set completion status
|
||||
$ch->setIsCompleted(true);
|
||||
|
||||
// Update wallet amount - ensure float type conversion
|
||||
$wallet->setAmmount($wallet->getAmmount() + floatval($ammount));
|
||||
|
||||
// Persist changes
|
||||
// Note: Since $ch and $wallet were fetched, they are managed, but explicit persist is safe.
|
||||
// $entityManager->persist($ch); // Not strictly needed if fetched entities are modified
|
||||
// $entityManager->persist($wallet); // Not strictly needed
|
||||
$entityManager->flush();
|
||||
|
||||
$entityManager->getConnection()->commit();
|
||||
|
||||
// 5. Fire Event (Optional: for decoupled tasks like sending email/invoicing)
|
||||
// $eventDispatcher->dispatch(new ResetPasswordConfirmEvent($ch), ResetPasswordConfirmEvent::NAME);
|
||||
$logger->info("Wallet updated successfully for ID: {$id}. Amount: {$ammount}.");
|
||||
|
||||
// 6. Redirect
|
||||
return $this->redirectToWebsite($ch->getDescrition(), $entityManager);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$entityManager->getConnection()->rollBack();
|
||||
$logger->error("Database transaction failed for ID: {$id}. Error: {$e->getMessage()}");
|
||||
// Return a server error response
|
||||
return new JsonResponse(['message' => 'An internal error occurred during wallet update.'], Response::HTTP_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to determine the redirect URL based on description.
|
||||
*/
|
||||
private function redirectToWebsite(string $description, EntityManagerInterface $entityManager): ?RedirectResponse
|
||||
{
|
||||
$parts = explode('_', $description);
|
||||
|
||||
|
||||
|
||||
$websiteId = explode('-', $parts[1]);
|
||||
|
||||
/** @var Website|null $w */
|
||||
$w = $entityManager->getRepository(Website::class)->find($websiteId[1]);
|
||||
return new RedirectResponse("https://".$w->getMainDns()."/api-internal/complete/wallet");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -69,9 +69,15 @@ class Client
|
||||
$payment->setCustomer(Customer::retrieve($customer->getStancerId()));
|
||||
$payment->setCurrency('eur');
|
||||
$url = ($_ENV['APP_ENV'] == "dev")?$_ENV['DEV_URL']:$this->requestStack->getCurrentRequest()->getSchemeAndHttpHost();
|
||||
$payment->setReturnUrl($url.$this->urlGenerator->generate('app_logout'));
|
||||
$payment->setReturnUrl($url.$this->urlGenerator->generate('app_completed_payment',['id'=>$ch->getDescrition()]));
|
||||
$payment->setAmount($ch->getAmmount()*100);
|
||||
|
||||
return $payment->send();
|
||||
}
|
||||
|
||||
public function payment(?string $getPaimentId)
|
||||
{
|
||||
$payment = Payment::retrieve($getPaimentId);
|
||||
return $payment->status->value;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user