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

namespace App\Controller;

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

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

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

    /**
53
     * Crée une instance de Payment, les tokens associés, et redirige vers la page de paiement.
54 55 56 57 58 59
     */
    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();
Yvon Kerdoncuff committed
60 61
        $data = $serializer->normalize(
            $toSerialize,
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
            null,
            [AbstractNormalizer::ATTRIBUTES => [
                'reference',
                'moyen',
                'montant',
                'role',
                'don' => [
                    'reference',
                    'moyen',
                    'montant',
                    'role',
                    'type',
                    'expediteur' => ['id'],
                    'destinataire' => ['id'],
                    'operateur' => ['id'],
                ],
                'expediteur' => ['id'],
                'destinataire' => ['id'],
80
                'operateur' => ['id'], ],
Yvon Kerdoncuff committed
81 82
            ]
        );
83 84 85 86

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

        // Prepare CB Payment
87 88
        if ('true' === $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_PAYZEN)) {
            $gatewayName = 'payzen';
89
        } else {
90
            $this->addFlash(
Yvon Kerdoncuff committed
91 92 93
                '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.')
            );
94 95

            return $this->redirectToRoute('index');
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        }

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

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

126 127 128 129 130
        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
131 132
        }

133 134 135
        $storage->update($payment);

        $captureToken = $this->payum->getTokenFactory()->createCaptureToken(
Yvon Kerdoncuff committed
136 137 138
            $gatewayName,
            $payment,
            'payment_done' // the route to redirect after capture
139 140 141 142 143 144 145 146 147 148 149 150
        );

        // 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();

Yvon Kerdoncuff committed
151
        return $this->redirect($captureToken->getTargetUrl());
152 153
    }

Yvon committed
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.
     *
207 208 209
     * Pour d'autres problèmes avec Payum, voir aussi les commentaires liés à
     * l'utilisation de GetHumanStatus::STATUS_AUTHORIZED.
     *
Yvon committed
210 211 212 213
     * Yvon KERDONCUFF
     * 26/03/2024
     */

214
    /**
215 216 217 218 219
     * 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.
     *
220
     * @param Request $request
221
     *
222
     * @return Response
Yvon committed
223
     * @Route("/payment/notify", name="notify_recurring_payment")
224 225 226
     */
    public function notifyRecurringPaymentAction(Request $request)
    {
227 228
        $vads_cust_email = $request->request->get('vads_cust_email');
        //Look for recurring payments from this client.
229 230 231 232 233
        $recurringPayments = $this->em->getRepository(Payment::class)->findBy([
            'isRecurrent' => true,
            'clientEmail' => $vads_cust_email,
        ]);

234 235 236
        if (!$recurringPayments) {
            //return error
            return new Response('No recurring payments with email ' . $vads_cust_email, 405);
237 238
        }

239 240 241 242 243 244
        $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.
245 246 247 248 249
            if (
                $payment->getDetails()
                && array_key_exists('vads_identifier', $payment->getDetails())
                && $payment->getDetails()['vads_identifier'] == $vads_identifier
            ) {
250
                // Payum GetHumanStatus constants don't match Payzen vads_trans_status here
251
                // e.g. GetHumanStatus::STATUS_AUTHORIZED does not match 'authorised' value sent by Payzen
252
                if (in_array($new_status, ['captured', 'authorised', GetHumanStatus::STATUS_CAPTURED, GetHumanStatus::STATUS_AUTHORIZED])) {
253 254 255
                    $this->paymentUtils->handlePayzenNotificationCore($payment);
                    $this->em->flush();
                }
256 257
                //for debug purpose, display vads_trans_status in payzen backoffice
                return new Response('Recurring payment occurence taken into account. vads_trans_status = ' . $new_status, 200);
258
            }
259
        }
260 261
        //return error
        return new Response('No recurring payments with vads_identifier ' . $vads_identifier, 405);
262 263
    }

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

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

283
        if (GetHumanStatus::STATUS_NEW == $payment->getStatus()) {
284
            $gateway->execute(new Notify($token));
285
        } else {
286
            $this->payum->getHttpRequestVerifier()->invalidate($token);
287 288 289
        }

        // Set flash message according to payment status
290 291 292 293 294 295 296 297 298
        /* WARNING : THIS PIECE OF CODE IS USING INAPPROPRIATE GetHumanStatus::STATUS_AUTHORIZED :
         *
         * This is (another) issue here with Payum.
         * current_payment_status will never match STATUS_AUTHORIZED
         * on the opposite, we have no chance to detect 'authorised' value here
         * because Payzen vads_trans_status is written 'authorised' and not 'authorized'
         *
         * @see comment above notifyRecurringPaymentAction for more Payum weird stuff
        */
299
        if (in_array($payment->getStatus(), ['captured', 'authorised', GetHumanStatus::STATUS_CAPTURED, GetHumanStatus::STATUS_AUTHORIZED])) {
300
            $type = $payment->getDescription();
301

302 303
            if (Payment::TYPE_ACHAT_MONNAIE_ADHERENT == $type || Payment::TYPE_ACHAT_MONNAIE_PRESTA == $type) {
                $this->addFlash(
Yvon Kerdoncuff committed
304 305 306
                    'success',
                    $this->translator->trans('Achat de monnaie locale bien effectué !')
                );
307 308
            } elseif (Payment::TYPE_COTISATION_ADHERENT == $type || Payment::TYPE_COTISATION_PRESTA == $type) {
                $this->addFlash(
Yvon Kerdoncuff committed
309 310 311
                    'success',
                    $this->translator->trans('Cotisation bien reçue. Merci !')
                );
312 313
            } elseif (Payment::TYPE_ADHESION == $type) {
                $this->addFlash(
Yvon Kerdoncuff committed
314 315 316
                    'success',
                    $this->translator->trans('Votre adhésion a bien été prise en compte, bienvenue !')
                );
317

318 319
                // Connect new user
                return $this->guardHandler
Yvon Kerdoncuff committed
320 321 322 323 324 325
                ->authenticateUserAndHandleSuccess(
                    $this->em->getRepository(User::class)->findOneBy(['id' => $payment->getClientId()]),
                    $request,
                    $this->authenticator,
                    'main'
                );
326 327
            } elseif (Payment::TYPE_PAIEMENT_COTISATION_TAV == $type || Payment::TYPE_PAIEMENT_RECURRENT_COTISATION_TAV) {
                $this->addFlash(
Yvon Kerdoncuff committed
328 329 330
                    'success',
                    $this->translator->trans('Cotisation payée !')
                );
331
            }
Yvon Kerdoncuff committed
332 333
        } elseif (
            GetHumanStatus::STATUS_CANCELED == $payment->getStatus() ||
334
                    GetHumanStatus::STATUS_EXPIRED == $payment->getStatus() ||
Yvon Kerdoncuff committed
335 336
                    GetHumanStatus::STATUS_FAILED == $payment->getStatus()
        ) {
337
            $this->addFlash(
Yvon Kerdoncuff committed
338 339 340
                'error',
                $this->translator->trans('La transaction a été annulée.')
            );
341
        }
342 343 344 345

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