PaymentController.php 13.9 KB
Newer Older
1 2 3 4
<?php

namespace App\Controller;

5 6 7 8 9
use App\Entity\GlobalParameter;
use App\Entity\Payment;
use App\Entity\User;
use App\Security\LoginAuthenticator;
use App\Utils\PaymentUtils;
10
use Doctrine\ORM\EntityManagerInterface;
11 12 13
use Payum\Core\Payum;
use Payum\Core\Request\GetHumanStatus;
use Payum\Core\Request\Notify;
14 15 16
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18 19
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
20 21
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Translation\TranslatorInterface;
22 23

/**
24
 * Gestion des paiements avec Payum.
25 26 27 28 29 30 31 32
 */
class PaymentController extends AbstractController
{
    protected $em;
    protected $translator;
    protected $payum;
    protected $authenticator;
    protected $guardHandler;
33
    protected $paymentUtils;
34 35 36 37 38

    public function __construct(EntityManagerInterface $em,
                                TranslatorInterface $translator,
                                LoginAuthenticator $authenticator,
                                GuardAuthenticatorHandler $guardHandler,
39 40
                                Payum $payum,
                                PaymentUtils $paymentUtils)
41 42 43 44 45 46
    {
        $this->em = $em;
        $this->translator = $translator;
        $this->payum = $payum;
        $this->authenticator = $authenticator;
        $this->guardHandler = $guardHandler;
47
        $this->paymentUtils = $paymentUtils;
48 49 50
    }

    /**
51
     * Crée une instance de Payment, les tokens associés, et redirige vers la page de paiement.
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
     */
    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'],
77
                'operateur' => ['id'], ],
78 79 80 81 82
            ]);

        $jsondata = $serializer->serialize($data, 'json');

        // Prepare CB Payment
83 84
        if ('true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_PAYZEN)) {
            $gatewayName = 'payzen';
85
        } else {
86
            $this->addFlash(
87 88 89
            '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.')
          );
90 91

            return $this->redirectToRoute('index');
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        }

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

107 108
        if (Payment::TYPE_ADHESION == $type) {
            $payment->setTotalAmount($form->get('cotisation')->get('montant')->getData() * 100); // 1.23 EUR
109 110 111 112 113 114 115 116 117 118 119 120 121
            $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());
        }

122 123 124 125 126
        if (Payment::TYPE_PAIEMENT_RECURRENT_COTISATION_TAV == $type) {
            $payment->setRecurrenceAmount($form->get('montant')->getData() * 100);
            $payment->setIsRecurrent(true);
            $payment->setRecurrenceMonthsCount($form->get('nombreMois')->getData());
            $payment->setRecurrenceMonthDay($form->get('jourPrelevement')->getData());
Damien Moulard committed
127 128
        }

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        $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());
    }

Yvon committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    /* COMMENT LES FLUX SONT-ILS CREES SUITE A LA CREATION D'UN PAIEMENT PAYZEN ?
     *
     *
     *
     * CAS 1 : Paiement standard
     * Deux voies de signalement coexistent :
     *
     * Voie 1 : via la notification instantannée payzen.
     * Un paramètre appelé "URL de notification à la fin du paiement" est configuré dans le backoffice payzen et
     * est renseigné à payement/notify. Cette valeur est utilisée par payzen, sauf si la variable vads_url_check
     * est transmise, auquel cas c'est cette dernière valeur qui prime.
     * Ici, vads_url_check est transmise à la valeur payment/notify/{token}.
     * Remarque : son usage systématique n'est pas recommandé par Payzen.
     * L'URL est ainsi captée par NotifyController.php.
     *
     * Voie 2 : via la redirection du client.
     * Cette voie n'est pas garantie (si l'utilisateur ferme son navigateur assez tôt, il ne sera pas redirigé).
     * A vérifier : l'URL de redirection est la combinaison entre une configuration côté backoffice et
     * un complément que nous transmettons.
     * Lorsque la redirection a bien lieu, c'est donc le contrôleur doneAction de PaymentController.php qui est sollicité,
     * avec une requête au format payement/done/?payum_token={token}
     *
     * Remarquons dans ces deux stratégie la présence d'un token permettant l'authentification de l'agent Payzen et
     * la récupération de l'objet paiement préalablement enregistré en base.
     *
     *
     *
     * CAS 2 : Paiement récurrent
     *
     * Dans le cadre de notre implémentation, un paiement récurrent commence par un paiement initial (occurence n°0).
     * Pour cette occurence n°0, au niveau du mode de communication, on est sur un processus en apparence similaire au
     * CAS 1. Un examen minutieux de ce process m'a cependant permis de mettre en évidence des comportements que
     * je n'ai pas réussi à comprendre :
     * En ouvrant les vannes pour tester le déclenchement d'une création de flux à chaque notification rattachée
     * à un paiement récurrent, j'ai observé la génération de pas moins de 5 événements, opérant donc
     * un accroissement de solde de +750 mona au lieu de +150 mona !!!
     * - 2 événements via /payement/notify/{token}
     * - 3 événements après l'execution de la ligne $gateway->execute($status = new GetHumanStatus($token)); dans doneAction.
     *
     * Le fonctionnement du module Payum est sans doute très intelligent mais il est trop complexe à maitriser pour moi.
     * Il fait également appel à des mécanismes dont l'usage systématique est déconseillé par Payzen (utilisation de la variable
     * vads_url_check).
     *
     * Bref. De toute façon, la gestion des notifications successives d'un paiement récurrent ne peut pas être gérée
     * via les voies 1 ou 2 en l'état.
     * En effet la variable vads_url_check ne fonctionne pas en mode récurrent et Payzen nous notifie à l'aide
     * d'une requête post au format de l'"URL de notification à la création d'un abonnement" (mal nommé), configurée à payement/notify,
     * (mais on aurait pu mettre autre chose pour plus de clarté). Il faut donc créer un controlleur spécifique qui va traiter
     * cette notification sans disposer du token utilisé par les voies 1 ou 2.
     *
     * Voie 3 : le traitement de la requête se fait finalement simplement dans notifyRecurringPaymentAction sans utiliser
     * les mécanismes complexes de Payum.
     *
     * Yvon KERDONCUFF
     * 26/03/2024
     */

207
    /**
208 209 210 211 212
     * Collects payzen recurring payment payment occurence in place of default payum system.
     *
     * Payum default controler is not able to catch URL recurring payment notifications
     * because payzen actual used URL has shape /payment/notify instead of /payment/notify/token.
     *
213
     * @param Request $request
214
     *
215
     * @return Response
Yvon committed
216
     * @Route("/payment/notify", name="notify_recurring_payment")
217 218 219
     */
    public function notifyRecurringPaymentAction(Request $request)
    {
220 221
        $vads_cust_email = $request->request->get('vads_cust_email');
        //Look for recurring payments from this client.
222 223 224 225 226
        $recurringPayments = $this->em->getRepository(Payment::class)->findBy([
            'isRecurrent' => true,
            'clientEmail' => $vads_cust_email,
        ]);

227 228 229
        if (!$recurringPayments) {
            //return error
            return new Response('No recurring payments with email ' . $vads_cust_email, 405);
230 231
        }

232 233 234 235 236 237
        $vads_identifier = $request->request->get('vads_identifier');
        $vads_trans_status = $request->request->get('vads_trans_status');
        $new_status = strtolower($vads_trans_status);

        foreach ($recurringPayments as $payment) {
            //Just look for one valid payment.
238 239 240 241 242
            if (
                $payment->getDetails()
                && array_key_exists('vads_identifier', $payment->getDetails())
                && $payment->getDetails()['vads_identifier'] == $vads_identifier
            ) {
243 244 245 246 247 248 249 250 251
                if (
                    GetHumanStatus::STATUS_CAPTURED == $new_status
                    || GetHumanStatus::STATUS_AUTHORIZED == $new_status
                ) {
                    $this->paymentUtils->handlePayzenNotificationCore($payment);
                    $this->em->flush();
                }

                return new Response('Recurring payment occurence taken into account.', 200);
252
            }
253
        }
254 255
        //return error
        return new Response('No recurring payments with vads_identifier ' . $vads_identifier, 405);
256 257
    }

258
    /**
Yvon committed
259
     * Ce contrôleur est sollicité lorsque Payzen renvoie le cotisant sur l'URL de retour,
260
     *
261 262 263 264 265
     * @Route("/payment/done/", name="payment_done")
     */
    public function doneAction(Request $request)
    {
        try {
266
            $token = $this->payum->getHttpRequestVerifier()->verify($request);
267
        } catch (\Exception  $e) {
268 269
            // Token expired
            return $this->redirectToRoute('index');
270 271 272 273 274 275 276
        }

        // Get payment
        $gateway = $this->payum->getGateway($token->getGatewayName());
        $gateway->execute($status = new GetHumanStatus($token));
        $payment = $status->getFirstModel();

277
        if (GetHumanStatus::STATUS_NEW == $payment->getStatus()) {
278
            $gateway->execute(new Notify($token));
279
        } else {
280
            $this->payum->getHttpRequestVerifier()->invalidate($token);
281 282 283
        }

        // Set flash message according to payment status
284 285
        if (GetHumanStatus::STATUS_CAPTURED == $payment->getStatus() || GetHumanStatus::STATUS_AUTHORIZED == $payment->getStatus()) {
            $type = $payment->getDescription();
286

287 288
            if (Payment::TYPE_ACHAT_MONNAIE_ADHERENT == $type || Payment::TYPE_ACHAT_MONNAIE_PRESTA == $type) {
                $this->addFlash(
289 290 291
              'success',
              $this->translator->trans('Achat de monnaie locale bien effectué !')
            );
292 293
            } elseif (Payment::TYPE_COTISATION_ADHERENT == $type || Payment::TYPE_COTISATION_PRESTA == $type) {
                $this->addFlash(
294 295 296
              'success',
              $this->translator->trans('Cotisation bien reçue. Merci !')
            );
297 298
            } elseif (Payment::TYPE_ADHESION == $type) {
                $this->addFlash(
299 300 301 302
              'success',
              $this->translator->trans('Votre adhésion a bien été prise en compte, bienvenue !')
            );

303 304
                // Connect new user
                return $this->guardHandler
305
              ->authenticateUserAndHandleSuccess(
306
                $this->em->getRepository(User::class)->findOneBy(['id' => $payment->getClientId()]),
307 308 309 310
                $request,
                $this->authenticator,
                'main'
            );
311 312
            } elseif (Payment::TYPE_PAIEMENT_COTISATION_TAV == $type || Payment::TYPE_PAIEMENT_RECURRENT_COTISATION_TAV) {
                $this->addFlash(
313 314 315
              'success',
              $this->translator->trans('Cotisation payée !')
            );
316 317 318 319 320
            }
        } elseif (GetHumanStatus::STATUS_CANCELED == $payment->getStatus() ||
                    GetHumanStatus::STATUS_EXPIRED == $payment->getStatus() ||
                    GetHumanStatus::STATUS_FAILED == $payment->getStatus()) {
            $this->addFlash(
321 322 323
            'error',
            $this->translator->trans('La transaction a été annulée.')
          );
324
        }
325 326 327 328

        return $this->redirectToRoute('index');
    }
}