|
- <?php
-
- /**
- * Copyright distrib (2018)
- *
- * contact@opendistrib.net
- *
- * Ce logiciel est un programme informatique servant à aider les producteurs
- * à distribuer leur production en circuits courts.
- *
- * Ce logiciel est régi par la licence CeCILL soumise au droit français et
- * respectant les principes de diffusion des logiciels libres. Vous pouvez
- * utiliser, modifier et/ou redistribuer ce programme sous les conditions
- * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
- * sur le site "http://www.cecill.info".
- *
- * En contrepartie de l'accessibilité au code source et des droits de copie,
- * de modification et de redistribution accordés par cette licence, il n'est
- * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
- * seule une responsabilité restreinte pèse sur l'auteur du programme, le
- * titulaire des droits patrimoniaux et les concédants successifs.
- *
- * A cet égard l'attention de l'utilisateur est attirée sur les risques
- * associés au chargement, à l'utilisation, à la modification et/ou au
- * développement et à la reproduction du logiciel par l'utilisateur étant
- * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
- * manipuler et qui le réserve donc à des développeurs et des professionnels
- * avertis possédant des connaissances informatiques approfondies. Les
- * utilisateurs sont donc invités à charger et tester l'adéquation du
- * logiciel à leurs besoins dans des conditions permettant d'assurer la
- * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
- * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
- *
- * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
- * pris connaissance de la licence CeCILL, et que vous en avez accepté les
- * termes.
- */
-
- namespace producer\controllers;
-
- use common\helpers\GlobalParam;
- use common\helpers\Mailjet;
- use common\helpers\MeanPayment;
- use common\logic\User\CreditHistory\CreditHistory;
- use common\logic\User\CreditHistory\CreditHistorySearch;
- use common\logic\User\User\User;
- use common\logic\User\UserProducer\UserProducer;
- use producer\models\CreditForm;
- use yii\filters\VerbFilter;
-
- class CreditController extends ProducerBaseController
- {
- /**
- * @inheritdoc
- */
- public function behaviors()
- {
- return [
- 'verbs' => [
- 'class' => VerbFilter::className(),
- 'actions' => [
- 'stripe-verification' => ['post'],
- ],
- ]
- ];
- }
-
- public function actions()
- {
- return [
- 'captcha' => [
- 'class' => 'yii\captcha\CaptchaAction',
- 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
- ],
- ];
- }
-
- public function beforeAction($action)
- {
- $this->enableCsrfValidation = false;
- return parent::beforeAction($action);
- }
-
- /**
- * Affiche l'historique du crédit client.
- */
- public function actionHistory(string $returnPayment = '')
- {
- $producer = $this->getProducer();
- if (\Yii::$app->user->isGuest) {
- return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
- }
-
- $searchModel = new CreditHistorySearch();
- $searchModel->id_user = GlobalParam::getCurrentUserId();
- $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
- $userProducer = $this->getLogic()->getUserProducerContainer()->getRepository()->getOne(GlobalParam::getCurrentUser(), $producer);
-
- if (strlen($returnPayment)) {
- if ($returnPayment == 'success') {
- $this->setFlash('success', "Paiement accepté : votre compte vient d'être crédité.");
- }
- if ($returnPayment == 'cancel') {
- $this->setFlash('error', 'Paiement annulé.');
- }
- }
-
- return $this->render('history', [
- 'searchModel' => $searchModel,
- 'dataProvider' => $dataProvider,
- 'creditUser' => $userProducer->credit
- ]);
- }
-
- public function actionAdd()
- {
- $producer = $this->getProducer();
- if (\Yii::$app->user->isGuest) {
- return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
- }
-
- if ($producer->online_payment || $producer->option_stripe_mode_test) {
-
- $creditForm = new CreditForm;
-
- if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
- $user = GlobalParam::getCurrentUser();
-
- \Stripe\Stripe::setApiKey(
- $this->getLogic()->getProducerContainer()->getSolver()->getPrivateKeyApiStripe($producer)
- );
-
- $checkout_session = \Stripe\Checkout\Session::create([
- 'line_items' => [
- [
- 'price_data' => [
- 'currency' => 'eur',
- 'product_data' => [
- 'name' => 'Alimentation crédit',
- ],
- 'unit_amount' => (float) $creditForm->amount * 100,
- ],
- 'quantity' => 1,
- ]
- ],
- 'payment_method_types' => ['card'],
- 'mode' => 'payment',
- 'customer_email' => $user->email,
- 'client_reference_id' => $user->id,
- 'payment_intent_data' => [
- 'metadata' => [
- 'user_id' => $user->id,
- 'producer_id' => $producer->id
- ],
- ],
- 'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
- [
- 'credit/history',
- 'returnPayment' => 'success'
- ]
- ),
- 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
- [
- 'credit/history',
- 'returnPayment' => 'cancel'
- ]
- ),
- ]);
-
- header("HTTP/1.1 303 See Other");
- header("Location: " . $checkout_session->url);
- die();
- }
-
- return $this->render('add', [
- 'creditForm' => $creditForm
- ]);
- } else {
- throw new \yii\base\UserException('Cette option est désactivée chez ce producteur.');
- }
- }
-
- public function actionStripeVerification()
- {
- $creditHistoryBuilder = $this->getLogic()->getCreditHistoryContainer()->getBuilder();
- $producerSolver = $this->getLogic()->getProducerContainer()->getSolver();
- $userSolver = $this->getLogic()->getUserContainer()->getSolver();
- $producer = $this->getProducer();
- $contactProducer = $producer->getMainContact();
-
- $payload = @file_get_contents('php://input');
- $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
-
- try {
- $event = \Stripe\Webhook::constructEvent(
- $payload,
- $sig_header,
- $producerSolver->getPrivateKeyEndpointStripe($producer)
- );
- } catch (\UnexpectedValueException $e) {
- // Invalid payload
- http_response_code(400);
- exit();
- } catch (\Stripe\Exception\SignatureVerificationException $e) {
- // Invalid signature
- http_response_code(400);
- exit();
- }
-
- $paymentIntent = $event->data->object;
- $paymentIntentMetadata = $paymentIntent->metadata;
- $amount = $paymentIntent->amount / 100;
- $idUser = $paymentIntentMetadata->user_id;
- $user = $this->getLogic()->getUserContainer()->getRepository()->getOneById($paymentIntentMetadata->user_id);
- $idProducer = $paymentIntentMetadata->producer_id;
-
- if (isset($paymentIntentMetadata->order_id)) {
- $order = $this->getLogic()->getOrderContainer()->getRepository()->getOneById($paymentIntentMetadata->order_id);
- $pointSale = $this->getLogic()->getPointSaleContainer()->getRepostory()->getOneById($order->id_point_sale);
- $distribution = $this->getLogic()->getDistributionContainer()->getRepository()->getOneById($order->id_distribution);
- }
-
- // Handle the event
- switch ($event->type) {
- case 'charge.succeeded':
-
- $creditHistoryExist = CreditHistory::searchOne([
- 'id_user' => $idUser,
- 'amount' => $amount,
- ], [
- 'conditions' => [
- 'date > DATE_SUB(NOW(), INTERVAL 1 MINUTE)'
- ]
- ]);
-
- if (!$creditHistoryExist) {
-
- $creditHistoryBuilder->create(
- CreditHistory::TYPE_CREDIT,
- $amount,
- $producer,
- $user,
- $user,
- MeanPayment::CREDIT_CARD
- );
-
- if (isset($order) && $order) {
-
- $creditHistoryBuilder->create(
- CreditHistory::TYPE_PAYMENT,
- $amount,
- $producer,
- $user,
- $user,
- MeanPayment::CREDIT,
- $order
- );
-
- // client : envoi d'un email de confirmation de paiement
- $paramsEmail = [
- 'from_email' => $producerSolver->getEmailOpendistrib($producer),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $userSolver->getUsername($user),
- 'subject' => '[' . $producer->name . '] Confirmation de paiement',
- 'content_view_text' => '@common/mail/paymentOrderConfirm-text.php',
- 'content_view_html' => '@common/mail/paymentOrderConfirm-html.php',
- 'content_params' => [
- 'amount' => $amount,
- 'user' => $user,
- 'producer' => $producer,
- ]
- ];
- //Mailjet::sendMail($paramsEmail);
-
- // producteur : mail de confirmation
- Mailjet::sendMail([
- 'from_email' => $producerSolver->getEmailOpendistrib($producer),
- 'from_name' => $producer->name,
- 'to_email' => $contactProducer->email,
- 'to_name' => $contactProducer->name,
- 'subject' => '[' . $producer->name . '] Confirmation de commande',
- 'content_view_text' => '@common/mail/orderConfirmProducer-text.php',
- 'content_view_html' => '@common/mail/orderConfirmProducer-html.php',
- 'content_params' => [
- 'order' => $order,
- 'pointSale' => $pointSale,
- 'distribution' => $distribution,
- 'user' => $user,
- 'producer' => $producer
- ]
- ]);
- } else {
- $userProducer = $this->getLogic()->getUserProducerContainer()->getRepository()->getOne($user, $producer);
-
- Mailjet::sendMail([
- 'from_email' => $producerSolver->getEmailOpendistrib($producer),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $userSolver->getUsername($user),
- 'subject' => '[' . $producer->name . '] Alimentation de votre crédit',
- 'content_view_text' => '@common/mail/creditConfirm-text.php',
- 'content_view_html' => '@common/mail/creditConfirm-html.php',
- 'content_params' => [
- 'user' => $user,
- 'userProducer' => $userProducer,
- 'producer' => $producer,
- 'amount' => $amount,
- ]
- ]);
- }
- }
-
- break;
-
- case 'charge.failed':
-
- // client
- Mailjet::sendMail([
- 'from_email' => $producerSolver->getEmailOpendistrib($producer),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $userSolver->getUsername($user),
- 'subject' => '[' . $producer->name . '] Erreur de paiement',
- 'content_view_text' => '@common/mail/paymentError-text.php',
- 'content_view_html' => '@common/mail/paymentError-html.php',
- 'content_params' => [
- 'amount' => $amount,
- 'user' => $user,
- 'producer' => $producer,
- ]
- ]);
-
- // producteur
- if (isset($order) && $order) {
- Mailjet::sendMail([
- 'from_email' => $producerSolver->getEmailOpendistrib($producer),
- 'from_name' => $producer->name,
- 'to_email' => $contactProducer->email,
- 'to_name' => $contactProducer->name,
- 'subject' => '[' . $producer->name . '] Erreur de paiement',
- 'content_view_text' => '@common/mail/paymentErrorProducer-text.php',
- 'content_view_html' => '@common/mail/paymentErrorProducer-html.php',
- 'content_params' => [
- 'amount' => $amount,
- 'user' => $user,
- 'producer' => $producer,
- 'order' => $order,
- 'distribution' => $distribution
- ]
- ]);
- }
-
- break;
-
- // handle other event types
- default:
- echo 'Received unknown event type ' . $event->type;
- }
-
- http_response_code(200);
- die();
- }
- }
|