Commit c8a82722 by Yvon Kerdoncuff

Merge branch '4241-fix-online-payment' into 'develop'

4241 fix online payment

See merge request cooperatic/kohinos-tav!25
parents 0a7b3ecd 742fbf03
......@@ -229,6 +229,13 @@ services:
tags:
- { name: payum.gateway_factory_builder, factory: payzen }
app.payum.extension.payment_status:
class: App\EventListener\PaymentStatusExtension
public: true
autowire: true
tags:
- { name: payum.extension, all: true, prepend: false }
###### Configuration de l'admin ######
admin.block.dashboard:
......
......@@ -55,7 +55,11 @@ class CaptureAction implements ActionInterface, GatewayAwareInterface, GenericTo
// Notify url
if (empty($model['vads_url_check']) && $this->tokenFactory) {
// Custom action
$model['vads_url_check'] = $request->getToken()->getAfterUrl();
$notifyToken = $this->tokenFactory->createNotifyToken(
$request->getToken()->getGatewayName(),
$request->getToken()->getDetails()
);
$model['vads_url_check'] = $notifyToken->getTargetUrl();
}
}
......
......@@ -74,7 +74,7 @@ class AdhesionController extends AbstractController
$jsondata = $serializer->serialize($data, 'json');
// Redirect to payment page
return $this->forward('App\Controller\FluxController::preparePaymentAction', [
return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
'form' => $form,
'type' => Payment::TYPE_ADHESION,
'extra_data' => $jsondata,
......
......@@ -2,33 +2,20 @@
namespace App\Controller;
use App\Entity\AchatMonnaieAdherent;
use App\Entity\AchatMonnaiePrestataire;
use App\Entity\Adherent;
use App\Entity\CotisationAdherent;
use App\Entity\CotisationPrestataire;
use App\Entity\Don;
use App\Entity\Flux;
use App\Entity\Geoloc;
use App\Entity\GlobalParameter;
use App\Entity\Groupe;
use App\Entity\Payment;
use App\Entity\Prestataire;
use App\Entity\Siege;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\CurrencyEnum;
use App\Flux\FluxInterface;
use App\Security\LoginAuthenticator;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
use App\Utils\TAVCotisationUtils;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use Gamez\Symfony\Component\Serializer\Normalizer\UuidNormalizer;
use Payum\Core\Payum;
use Payum\Core\Request\GetHumanStatus;
use Payum\Core\Request\Notify;
use Sonata\Exporter\Handler;
use Sonata\Exporter\Source\DoctrineORMQuerySourceIterator;
use Sonata\Exporter\Writer\CsvWriter;
......@@ -45,9 +32,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Translation\TranslatorInterface;
......@@ -85,10 +70,6 @@ class FluxController extends AbstractController
protected $translator;
protected $eventDispatcher;
protected $session;
protected $payum;
protected $authenticator;
protected $guardHandler;
protected $userManager;
protected $templating;
protected $operationUtils;
protected $tokenGenerator;
......@@ -100,10 +81,6 @@ class FluxController extends AbstractController
TranslatorInterface $translator,
EventDispatcherInterface $eventDispatcher,
SessionInterface $session,
LoginAuthenticator $authenticator,
GuardAuthenticatorHandler $guardHandler,
UserManagerInterface $userManager,
Payum $payum,
Environment $templating,
OperationUtils $operationUtils,
TAVCotisationUtils $tavCotisationsUtils,
......@@ -116,10 +93,6 @@ class FluxController extends AbstractController
$this->translator = $translator;
$this->eventDispatcher = $eventDispatcher;
$this->session = $session;
$this->payum = $payum;
$this->authenticator = $authenticator;
$this->guardHandler = $guardHandler;
$this->userManager = $userManager;
$this->templating = $templating;
$this->operationUtils = $operationUtils;
$this->tokenGenerator = $tokenGenerator;
......@@ -346,374 +319,4 @@ class FluxController extends AbstractController
'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
]);
}
/**
* Crée une instance de Payment et redirige vers la page de paiement.
*/
public function preparePaymentAction(Form $form, $type, $extra_data = null)
{
// Enregistre les données du Flux en json, pour l'enregistrer une fois le paiement validé
$encoders = [new JsonEncoder()];
$normalizers = [new UuidNormalizer(), new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$toSerialize = Payment::TYPE_ADHESION == $type ? $form->get('cotisation')->getData() : $form->getData();
$data = $serializer->normalize(
$toSerialize,
null,
[AbstractNormalizer::ATTRIBUTES => [
'reference',
'moyen',
'montant',
'role',
'don' => [
'reference',
'moyen',
'montant',
'role',
'type',
'expediteur' => ['id'],
'destinataire' => ['id'],
'operateur' => ['id'],
],
'expediteur' => ['id'],
'destinataire' => ['id'],
'operateur' => ['id'],
],
]
);
$jsondata = $serializer->serialize($data, 'json');
// Prepare CB Payment
if ('true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_PAYZEN)) {
$gatewayName = 'payzen';
} else {
$this->addFlash(
'error',
$this->translator->trans('Une erreur est survenue due à la configuration du paiement dans l\'application. Il est pour l\'instant impossible de payer par CB, merci de contacter votre monnaie locale.')
);
return $this->redirectToRoute('index');
}
$storage = $this->payum->getStorage('App\Entity\Payment');
$payment = $storage->create();
$payment->setNumber(uniqid());
$payment->setCurrencyCode('978');
$payment->setDescription($type);
$payment->setFluxData($jsondata);
// Data to persist when payment is valid (other than Flux data)
if (null != $extra_data) {
$payment->setExtraData($extra_data);
}
if (Payment::TYPE_ADHESION == $type) {
$payment->setTotalAmount($form->get('cotisation')->get('montant')->getData() * 100); // 1.23 EUR
$payment->setClientId('Nouvel adhérent');
$payment->setClientEmail($form->get('user')->get('email')->getData());
} else {
// $payment->setTotalAmount($form->get('montant')->getData() * 100); // 1.23 EUR
if ($form->has('don') && $form->get('don')->getData()->getMontant() > 0) {
$payment->setTotalAmount(($form->get('montant')->getData() * 100) + ($form->get('don')->getData()->getMontant() * 100)); // 1.23 EUR
} else {
$payment->setTotalAmount($form->get('montant')->getData() * 100); // 1.23 EUR
}
$payment->setClientId($this->getUser()->getId());
$payment->setClientEmail($this->getUser()->getEmail());
}
$storage->update($payment);
$captureToken = $this->payum->getTokenFactory()->createCaptureToken(
$gatewayName,
$payment,
'payment_done' // the route to redirect after capture
);
return $this->redirect($captureToken->getTargetUrl());
}
/**
* Fonction de traitement du paiement, à appeler :
* - automatiquement lorsqu'un événement se produit sur le site de Paiement (notification)
* - au retour sur le site par l'utilisateur.
*
* @Route("/payment/done/", name="payment_done")
*/
public function doneAction(Request $request)
{
try {
$token = $this->payum->getHttpRequestVerifier()->verify($request);
} catch (\Exception $e) {
// Token expired
return $this->redirectToRoute('index');
}
$gateway = $this->payum->getGateway($token->getGatewayName());
// Execute Notify action
$gateway->execute(new Notify($token));
// Execute 'done' action according to payment status
$gateway->execute($status = new GetHumanStatus($token));
// Get payment
$payment = $status->getFirstModel();
// Check for actual payment status. If not null or new: payment has already been processed.
if (GetHumanStatus::STATUS_CAPTURED == $payment->getStatus() || GetHumanStatus::STATUS_AUTHORIZED == $payment->getStatus()) {
// Invalidate token
$this->payum->getHttpRequestVerifier()->invalidate($token);
$type = $payment->getDescription();
if (Payment::TYPE_ACHAT_MONNAIE_ADHERENT == $type || Payment::TYPE_ACHAT_MONNAIE_PRESTA == $type) {
$this->addFlash(
'success',
$this->translator->trans('Achat de monnaie locale numérique par Carte bancaire bien effectué !')
);
} elseif (Payment::TYPE_COTISATION_ADHERENT == $type || Payment::TYPE_COTISATION_PRESTA == $type) {
$this->addFlash(
'success',
$this->translator->trans('Cotisation bien reçue. Merci !')
);
} elseif (Payment::TYPE_ADHESION == $type) {
$this->addFlash(
'success',
$this->translator->trans('Votre adhésion a bien été prise en compte, bienvenue !')
);
// Connect new user
return $this->guardHandler
->authenticateUserAndHandleSuccess(
$this->em->getRepository(User::class)->findOneBy(['id' => $payment->getClientId()]),
$request,
$this->authenticator,
'main'
);
}
return $this->redirectToRoute('index');
} elseif (GetHumanStatus::STATUS_CANCELED == $payment->getStatus() ||
GetHumanStatus::STATUS_EXPIRED == $payment->getStatus() ||
GetHumanStatus::STATUS_FAILED == $payment->getStatus()) {
// Invalidate token
$this->payum->getHttpRequestVerifier()->invalidate($token);
$this->addFlash(
'error',
$this->translator->trans('La transaction a été annulée.')
);
return $this->redirectToRoute('index');
}
// We got here, payment hasn't been processed, we're in the notification process. Update payment status and go on.
$payment->setStatus($status->getValue());
// @TODO : decommenter cela
// $this->em->persist($payment);
// $this->em->flush();
$type = '';
// If payment succesful, persist serialized 'Flux' stored in payment
if (GetHumanStatus::STATUS_CAPTURED == $status->getValue() || GetHumanStatus::STATUS_AUTHORIZED == $status->getValue()) {
$serializer = $this->container->get('serializer');
$flux_array = json_decode($payment->getFluxData(), true);
$type = $payment->getDescription();
if (Payment::TYPE_ACHAT_MONNAIE_ADHERENT == $type) {
$flux = $serializer->deserialize(
$payment->getFluxData(),
AchatMonnaieAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Siege::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Adherent::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setReconverti(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_ADHERENT);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($dest);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
$this->addFlash(
'success',
$this->translator->trans('Votre achat de monnaie locale a bien été pris en compte !')
);
} elseif (Payment::TYPE_ACHAT_MONNAIE_PRESTA == $type) {
$flux = $serializer->deserialize(
$payment->getFluxData(),
AchatMonnaiePrestataire::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Siege::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Prestataire::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setReconverti(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_PRESTATAIRE);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($dest);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
$this->addFlash(
'success',
$this->translator->trans('Votre achat de monnaie locale a bien été pris en compte !')
);
} elseif (Payment::TYPE_COTISATION_ADHERENT == $type) {
$flux = $serializer->deserialize(
$payment->getFluxData(),
CotisationAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Adherent::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Prestataire::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setRecu(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_ADHERENT);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($exp);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
$this->addFlash(
'success',
$this->translator->trans('Votre cotisation a bien été prise en compte !')
);
} elseif (Payment::TYPE_COTISATION_PRESTA == $type) {
$flux = $serializer->deserialize(
$payment->getFluxData(),
CotisationPrestataire::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Prestataire::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Prestataire::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setRecu(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_PRESTATAIRE);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($exp);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
$this->addFlash(
'success',
$this->translator->trans('Votre cotisation a bien été prise en compte !')
);
} elseif (Payment::TYPE_ADHESION == $type) {
$new_adherent_data = json_decode($payment->getExtraData());
$adherent = new Adherent();
$user = $this->userManager->createUser();
$usergroup = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
$group = $this->em->getRepository(Groupe::class)->findOneBy(['id' => $new_adherent_data->groupe->id]);
$user->setEmail($new_adherent_data->user->email);
$user->setUsername($new_adherent_data->user->username);
$user->setFirstname($new_adherent_data->user->firstname);
$user->setLastname($new_adherent_data->user->lastname);
$user->setPlainPassword($new_adherent_data->user->plainPassword);
$user->setEnabled(true);
$user->addPossiblegroup($usergroup);
$user->addGroup($usergroup);
$user->setAdherent($adherent);
$adherent->setEcompte('0');
$adherent->setUser($user);
$adherent->setGroupe($group);
if (null == $adherent->getGeoloc()) {
$geoloc = new Geoloc();
$geoloc->setAdresse($new_adherent_data->geoloc->adresse);
$geoloc->setCpostal($new_adherent_data->geoloc->cpostal);
$geoloc->setVille($new_adherent_data->geoloc->ville);
$adherent->setGeoloc($geoloc);
}
$this->em->persist($adherent);
$this->em->flush();
// Create first cotisation
$flux = $serializer->deserialize(
$payment->getFluxData(),
CotisationAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$flux->setOperateur($user);
$flux->setExpediteur($adherent);
$flux->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
$flux->setRole('Adherent');
$flux->setRecu(true);
// Update payment with new user id, remove user data
$payment->setClientId($user->getId());
$payment->setExtraData('');
$this->em->persist($payment);
$this->addFlash(
'success',
$this->translator->trans('Votre adhésion a bien été prise en compte, bienvenue !')
);
// Connect new user
$this->guardHandler->authenticateUserAndHandleSuccess(
$this->em->getRepository(User::class)->findOneBy(['id' => $payment->getClientId()]),
$request,
$this->authenticator,
'main'
);
} else {
return new Response('', Response::HTTP_BAD_REQUEST);
}
$flux->setReference('CB ' . $payment->getNumber());
$this->operationUtils->executeOperations($flux);
} elseif (GetHumanStatus::STATUS_CANCELED == $payment->getStatus() ||
GetHumanStatus::STATUS_EXPIRED == $payment->getStatus() ||
GetHumanStatus::STATUS_FAILED == $payment->getStatus()) {
$this->addFlash(
'error',
$this->translator->trans('La transaction a été annulée.')
);
}
return $this->redirectToRoute('index');
}
}
<?php
namespace App\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Translation\TranslatorInterface;
use Payum\Core\Payum;
use Payum\Core\Request\Notify;
use Payum\Core\Request\GetHumanStatus;
use App\Entity\Flux;
use App\Entity\Payment;
use App\Entity\User;
use App\Entity\GlobalParameter;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use App\Security\LoginAuthenticator;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
/**
* Gestion des paiements avec Payum
*/
class PaymentController extends AbstractController
{
protected $em;
protected $translator;
protected $payum;
protected $authenticator;
protected $guardHandler;
public function __construct(EntityManagerInterface $em,
TranslatorInterface $translator,
LoginAuthenticator $authenticator,
GuardAuthenticatorHandler $guardHandler,
Payum $payum)
{
$this->em = $em;
$this->translator = $translator;
$this->payum = $payum;
$this->authenticator = $authenticator;
$this->guardHandler = $guardHandler;
}
/**
* Crée une instance de Payment, les tokens associés, et redirige vers la page de paiement
*/
public function preparePaymentAction(Form $form, $type, $extra_data = null)
{
// Enregistre les données du Flux en json, pour l'enregistrer une fois le paiement validé
$serializer = $this->container->get('serializer');
$toSerialize = Payment::TYPE_ADHESION == $type ? $form->get('cotisation')->getData() : $form->getData();
$data = $serializer->normalize($toSerialize,
null,
[AbstractNormalizer::ATTRIBUTES => [
'reference',
'moyen',
'montant',
'role',
'don' => [
'reference',
'moyen',
'montant',
'role',
'type',
'expediteur' => ['id'],
'destinataire' => ['id'],
'operateur' => ['id'],
],
'expediteur' => ['id'],
'destinataire' => ['id'],
'operateur' => ['id']]
]);
$jsondata = $serializer->serialize($data, 'json');
// Prepare CB Payment
if ($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_PAYZEN) === 'true') {
$gatewayName = 'payzen';
} else {
$this->addFlash(
'error',
$this->translator->trans('Une erreur est survenue due à la configuration du paiement dans l\'application. Il est pour l\'instant impossible de payer par CB, merci de contacter votre monnaie locale.')
);
return $this->redirectToRoute('index');
}
$storage = $this->payum->getStorage('App\Entity\Payment');
$payment = $storage->create();
$payment->setNumber(uniqid());
$payment->setCurrencyCode('978');
$payment->setDescription($type);
$payment->setFluxData($jsondata);
// Data to persist when payment is valid (other than Flux data)
if (null != $extra_data) {
$payment->setExtraData($extra_data);
}
if ($type == Payment::TYPE_ADHESION) {
$payment->setTotalAmount($form->get('cotisation')->get('montant')->getData()*100); // 1.23 EUR
$payment->setClientId('Nouvel adhérent');
$payment->setClientEmail($form->get('user')->get('email')->getData());
} else {
if ($form->has('don') && $form->get('don')->getData()->getMontant() > 0) {
$payment->setTotalAmount(($form->get('montant')->getData() * 100) + ($form->get('don')->getData()->getMontant() * 100)); // 1.23 EUR
} else {
$payment->setTotalAmount($form->get('montant')->getData() * 100); // 1.23 EUR
}
$payment->setClientId($this->getUser()->getId());
$payment->setClientEmail($this->getUser()->getEmail());
}
$storage->update($payment);
$captureToken = $this->payum->getTokenFactory()->createCaptureToken(
$gatewayName,
$payment,
'payment_done' // the route to redirect after capture
);
// Symfony creates URLs with http and not https -> replace
$targetUrl = preg_replace('/^http:/', 'https:', $captureToken->getTargetUrl());
$afterUrl = preg_replace('/^http:/', 'https:', $captureToken->getAfterUrl());
$captureToken->setTargetUrl($targetUrl);
$captureToken->setAfterUrl($afterUrl);
$this->em->persist($captureToken);
$this->em->flush();
return $this->redirect($captureToken->getTargetUrl());
}
/**
* Fonction de retour sur le site par l'utilisateur après paiement
*
* @Route("/payment/done/", name="payment_done")
*/
public function doneAction(Request $request)
{
try {
$token = $this->payum->getHttpRequestVerifier()->verify($request);
} catch (\Exception $e) {
// Token expired
return $this->redirectToRoute('index');
}
// Get payment
$gateway = $this->payum->getGateway($token->getGatewayName());
$gateway->execute($status = new GetHumanStatus($token));
$payment = $status->getFirstModel();
if ($payment->getStatus() == GetHumanStatus::STATUS_NEW) {
// No notification arrived at this point: execute Notify action
$gateway->execute(new Notify($token));
} else {
// Invalidate token
$this->payum->getHttpRequestVerifier()->invalidate($token);
}
// Set flash message according to payment status
if ($payment->getStatus() == GetHumanStatus::STATUS_CAPTURED || $payment->getStatus() == GetHumanStatus::STATUS_AUTHORIZED) {
$type = $payment->getDescription();
if (Payment::TYPE_ACHAT_MONNAIE_ADHERENT == $type || Payment::TYPE_ACHAT_MONNAIE_PRESTA == $type) {
$this->addFlash(
'success',
$this->translator->trans('Achat de monnaie locale bien effectué !')
);
} else if (Payment::TYPE_COTISATION_ADHERENT == $type || Payment::TYPE_COTISATION_PRESTA == $type) {
$this->addFlash(
'success',
$this->translator->trans('Cotisation bien reçue. Merci !')
);
} else if (Payment::TYPE_ADHESION == $type) {
$this->addFlash(
'success',
$this->translator->trans('Votre adhésion a bien été prise en compte, bienvenue !')
);
// Connect new user
return $this->guardHandler
->authenticateUserAndHandleSuccess(
$this->em->getRepository(User::class)->findOneBy(array('id' => $payment->getClientId())),
$request,
$this->authenticator,
'main'
);
} else if (Payment::TYPE_PAIEMENT_COTISATION_TAV == $type) {
$this->addFlash(
'success',
$this->translator->trans('Cotisation payée !')
);
}
} else if ($payment->getStatus() == GetHumanStatus::STATUS_CANCELED ||
$payment->getStatus() == GetHumanStatus::STATUS_EXPIRED ||
$payment->getStatus() == GetHumanStatus::STATUS_FAILED)
{
$this->addFlash(
'error',
$this->translator->trans('La transaction a été annulée.')
);
}
return $this->redirectToRoute('index');
}
}
......@@ -104,10 +104,10 @@ class UserAdherentController extends FluxController
if ($form->has('payOther') && $form->get('payOther')->isClicked()) {
return $this->redirectToRoute('achatMonnaieAConfirmerAdherent');
} elseif ($form->has('save') && $form->get('save')->isClicked()) {
return $this->preparePaymentAction(
$form,
Payment::TYPE_ACHAT_MONNAIE_ADHERENT
);
return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
'form' => $form,
'type' => Payment::TYPE_ACHAT_MONNAIE_ADHERENT
]);
} elseif ($form->has('saveHelloAsso') && $form->get('saveHelloAsso')->isClicked()) {
$url = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::HELLOASSO_URL_EMLC_ADHERENT);
......@@ -166,19 +166,25 @@ class UserAdherentController extends FluxController
$flux->setDon(null);
}
$this->em->persist($flux);
$this->operationUtils->executeOperations($flux);
// TODO redirect to paiement
return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
'form' => $form,
'type' => Payment::TYPE_PAIEMENT_COTISATION_TAV // TODO
]);
// $this->em->persist($flux);
// $this->operationUtils->executeOperations($flux);
// Apply cotisation rate, create new flux
$this->tavCotisationsUtils->applyTauxCotisation($flux);
// // Apply cotisation rate, create new flux
// $this->tavCotisationsUtils->applyTauxCotisation($flux);
$this->em->flush();
$this->addFlash(
'success',
$this->translator->trans('Cotisation payée ! [Paiement via Payzen temporairement désactivé]')
);
// $this->em->flush();
// $this->addFlash(
// 'success',
// $this->translator->trans('Cotisation payée ! [Paiement via Payzen temporairement désactivé]')
// );
return $this->redirectToRoute('index');
// return $this->redirectToRoute('index');
}
return $this->render('@kohinos/flux/transaction.html.twig', [
......
......@@ -135,7 +135,7 @@ class UserController extends AbstractController
return $this->redirect($url);
} elseif (MoyenEnum::MOYEN_CB == $cotisation->getMoyen()) {
// Redirect to payment page
return $this->forward('App\Controller\FluxController::preparePaymentAction', [
return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
'form' => $form,
'type' => $payment_type,
]);
......
......@@ -259,10 +259,11 @@ class UserPrestataireController extends FluxController
return $this->redirect($url);
} elseif ($form->get('save')->isClicked()) {
return $this->preparePaymentAction(
$form,
Payment::TYPE_ACHAT_MONNAIE_PRESTA
);
return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
'form' => $form,
'type' => Payment::TYPE_ACHAT_MONNAIE_PRESTA
]);
}
}
......
......@@ -17,6 +17,7 @@ class Payment extends BasePayment
const TYPE_COTISATION_ADHERENT = 'cotisation_adherent';
const TYPE_COTISATION_PRESTA = 'cotisation_presta';
const TYPE_ADHESION = 'adhesion';
const TYPE_PAIEMENT_COTISATION_TAV = 'paiement_cotisation_tav';
/**
* @var \Ramsey\Uuid\UuidInterface
......
<?php
namespace App\EventListener;
use Payum\Core\Extension\Context;
use Payum\Core\Extension\ExtensionInterface;
use Payum\Core\Model\PaymentInterface;
use Payum\Core\Request\Generic;
use Payum\Core\Request\GetHumanStatus;
use Payum\Core\Request\GetStatusInterface;
use Payum\Core\Bridge\Symfony\Event\ExecuteEvent;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Serializer\SerializerInterface;
use App\Events\MLCEvents;
use App\Events\FluxEvent;
use App\Entity\Flux;
use App\Entity\Payment;
use App\Entity\PaymentToken;
use App\Entity\Siege;
use App\Entity\User;
use App\Entity\Adherent;
use App\Entity\Prestataire;
use App\Entity\Geoloc;
use App\Entity\Groupe;
use App\Entity\Usergroup;
use App\Entity\AchatMonnaieAdherent;
use App\Entity\AchatMonnaiePrestataire;
use App\Entity\CotisationAdherent;
use App\Entity\CotisationPrestataire;
use App\Entity\Don;
use App\Utils\OperationUtils;
use App\Utils\TAVCotisationUtils;
class PaymentStatusExtension implements ExtensionInterface
{
private $em;
private $eventDispatcher;
private $serializer;
private $userManager;
private $operationUtils;
private $tavCotisationsUtils;
/**
* PaymentStatusExtension constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(
EntityManagerInterface $em,
EventDispatcherInterface $eventDispatcher,
SerializerInterface $serializer,
UserManagerInterface $userManager,
OperationUtils $operationUtils,
TAVCotisationUtils $tavCotisationsUtils
) {
$this->em = $em;
$this->eventDispatcher = $eventDispatcher;
$this->serializer = $serializer;
$this->userManager = $userManager;
$this->operationUtils = $operationUtils;
$this->tavCotisationsUtils = $tavCotisationsUtils;
}
/**
* Fired after a payum 'execute' to detect payment status changes after a notification
* {@inheritDoc}
*/
public function onPostExecute(Context $context)
{
$request = $context->getRequest();
if (false == $request instanceof Generic) {
return;
}
if ($request instanceof GetStatusInterface) {
return;
}
$payment = $request->getFirstModel();
if (false == $payment instanceof PaymentInterface) {
return;
}
try {
$token = $request->getToken();
} catch (\Exception $e) {
return;
}
// Get current & new status
$context->getGateway()->execute($status = new GetHumanStatus($payment));
$current_payment_status = $payment->getStatus();
// Payment can be captured if it hasn't been captured before
if ($current_payment_status !== GetHumanStatus::STATUS_CAPTURED
&& $current_payment_status != GetHumanStatus::STATUS_AUTHORIZED)
{
// If payment succesful, persist serialized 'Flux' stored in payment
if ($status->getValue() == GetHumanStatus::STATUS_CAPTURED
|| $status->getValue() == GetHumanStatus::STATUS_AUTHORIZED)
{
$flux_array = json_decode($payment->getFluxData(), true);
$type = $payment->getDescription();
if (Payment::TYPE_ACHAT_MONNAIE_ADHERENT == $type) {
$flux = $this->serializer->deserialize(
$payment->getFluxData(),
AchatMonnaieAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Siege::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Adherent::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setReconverti(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_ADHERENT);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($dest);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
} else if (Payment::TYPE_ACHAT_MONNAIE_PRESTA == $type) {
$flux = $this->serializer->deserialize(
$payment->getFluxData(),
AchatMonnaiePrestataire::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Siege::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Prestataire::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setReconverti(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_PRESTATAIRE);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($dest);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
} else if (Payment::TYPE_COTISATION_ADHERENT == $type) {
$flux = $this->serializer->deserialize(
$payment->getFluxData(),
CotisationAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Adherent::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Prestataire::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setRecu(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_ADHERENT);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($exp);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
} else if (Payment::TYPE_COTISATION_PRESTA == $type) {
$flux = $this->serializer->deserialize(
$payment->getFluxData(),
CotisationPrestataire::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Prestataire::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Prestataire::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setRecu(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_PRESTATAIRE);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($exp);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
} else if (Payment::TYPE_ADHESION == $type) {
$new_adherent_data = json_decode($payment->getExtraData());
$adherent = new Adherent();
$user = $this->userManager->createUser();
$usergroup = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
$group = $this->em->getRepository(Groupe::class)->findOneBy(array('id' => $new_adherent_data->groupe->id));
$user->setEmail($new_adherent_data->user->email);
$user->setUsername($new_adherent_data->user->username);
$user->setFirstname($new_adherent_data->user->firstname);
$user->setLastname($new_adherent_data->user->lastname);
$user->setPlainPassword($new_adherent_data->user->plainPassword);
$user->setEnabled(true);
$user->addPossiblegroup($usergroup);
$user->addGroup($usergroup);
$user->addRole('ROLE_ADHERENT');
$user->setAdherent($adherent);
$adherent->setEcompte('0');
$adherent->setUser($user);
$adherent->setGroupe($group);
if ($adherent->getGeoloc() == null) {
$geoloc = new Geoloc();
$geoloc->setAdresse($new_adherent_data->geoloc->adresse);
$geoloc->setCpostal($new_adherent_data->geoloc->cpostal);
$geoloc->setVille($new_adherent_data->geoloc->ville);
$adherent->setGeoloc($geoloc);
}
$this->em->persist($adherent);
$this->em->flush();
// Create first cotisation
$flux = $this->serializer->deserialize(
$payment->getFluxData(),
CotisationAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$flux->setOperateur($user);
$flux->setExpediteur($adherent);
$flux->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(array('mlc' => true)));
$flux->setRole('Adherent');
$flux->setRecu(true);
// Update payment with new user id, remove user data
$payment->setClientId($user->getId());
$payment->setExtraData('');
$this->em->persist($payment);
} else if (Payment::TYPE_PAIEMENT_COTISATION_TAV == $type) {
$flux = $this->serializer->deserialize(
$payment->getFluxData(),
AchatMonnaieAdherent::class,
'json',
['disable_type_enforcement' => true]
);
$exp = $this->em->getRepository(Siege::class)->find($flux_array['expediteur']);
$flux->setExpediteur($exp);
$dest = $this->em->getRepository(Adherent::class)->find($flux_array['destinataire']);
$flux->setDestinataire($dest);
$op = $this->em->getRepository(User::class)->find($flux_array['operateur']);
$flux->setOperateur($op);
$flux->setReconverti(true);
if (null != $flux->getDon()) {
$flux->getDon()->setType(Don::TYPE_DON_ADHERENT);
$flux->getDon()->setOperateur($op);
$flux->getDon()->setExpediteur($dest);
$flux->getDon()->setDestinataire($this->em->getRepository(Prestataire::class)->findOneBy(['mlc' => true]));
}
} else {
// Bad request
}
$this->em->persist($flux);
$this->operationUtils->executeOperations($flux);
if (Payment::TYPE_PAIEMENT_COTISATION_TAV == $type) {
// Apply cotisation rate, create new flux
$this->tavCotisationsUtils->applyTauxCotisation($flux);
}
// Invalidate (delete) notify token after payment is captured
$this->em->remove($token);
$this->em->flush();
}
}
// Update payment status with status received in payzen response
$payment->setStatus($status->getValue());
$this->em->persist($payment);
$this->em->flush();
}
/**
* {@inheritDoc}
*/
public function onPreExecute(Context $context)
{
}
/**
* {@inheritDoc}
*/
public function onExecute(Context $context)
{
}
}
......@@ -83,8 +83,8 @@ class TAVCotisationUtils
$fluxCotis->setReference("Prélèvement cotisation après paiement de " . $cotisationAmount . "€ et application du taux " . $cotisationTaux);
}
$fluxCotis->setOperateur($this->security->getUser());
$fluxCotis->setRole($this->security->getUser()->getGroups()[0]->__toString());
$fluxCotis->setOperateur($flux->getOperateur());
$fluxCotis->setRole($flux->getRole());
$fluxCotis->setMoyen(MoyenEnum::MOYEN_EMLC);
$this->em->persist($fluxCotis);
$this->operationUtils->executeOperations($fluxCotis);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment