|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371 |
- <?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\models\CreditHistory;
- use common\models\Distribution;
- use common\models\Order;
- use common\models\PointSale;
- use common\models\UserProducer;
- use producer\models\CreditForm;
- use common\models\User;
- use Stripe\PaymentIntent;
- 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($returnPayment = '')
- {
- $producer = $this->getProducer();
-
- if(\Yii::$app->user->isGuest) {
- return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
- }
-
- $searchModel = new CreditHistorySearch();
- $searchModel->id_user = User::getCurrentId();
- $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
-
- $userProducer = UserProducer::searchOne([
- 'id_producer' => $producer->id,
- 'id_user' => User::getCurrentId()
- ]);
-
- if (strlen($returnPayment)) {
- if ($returnPayment == 'success') {
- Yii::$app->getSession()->setFlash('success', "Paiement accepté : votre compte vient d'être crédité.");
- }
- if ($returnPayment == 'cancel') {
- Yii::$app->getSession()->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(Yii::$app->urlManagerFrontend->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 = User::getCurrent();
-
- \Stripe\Stripe::setApiKey(
- $producer->getPrivateKeyApiStripe()
- );
-
- $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' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
- [
- 'credit/history',
- 'returnPayment' => 'success'
- ]
- ),
- 'cancel_url' => \Yii::$app->urlManagerProducer->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()
- {
- $producer = $this->getProducer();
- $contactProducer = $producer->getMainContact();
-
- $payload = @file_get_contents('php://input');
- $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
- $event = null;
-
- try {
- $event = \Stripe\Webhook::constructEvent(
- $payload,
- $sig_header,
- $producer->getPrivateKeyEndpointStripe()
- );
- } 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 = User::findOne($paymentIntentMetadata->user_id);
- $idProducer = $paymentIntentMetadata->producer_id;
-
- if(isset($paymentIntentMetadata->order_id)) {
- $order = Order::searchOne([
- 'id' => $paymentIntentMetadata->order_id
- ]);
- $pointSale = PointSale::searchOne(['id' => $order->id_point_sale]);
- $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
- }
-
- // Handle the event
- switch ($event->type) {
- case 'charge.succeeded':
-
- // on crédite le crédit du client
- $creditHistory = new CreditHistory;
- $creditHistory->id_user = $idUser;
- $creditHistory->id_user_action = $idUser;
- $creditHistory->id_producer = $idProducer;
- $creditHistory->type = CreditHistory::TYPE_CREDIT;
- $creditHistory->comment = null;
- $creditHistory->amount = $amount;
- $creditHistory->mean_payment = MeanPayment::CREDIT_CARD;
- $creditHistory->save();
-
- if(isset($order) && $order) {
- // paiement de la commande
- $order->saveCreditHistory(
- CreditHistory::TYPE_PAYMENT,
- $amount,
- $idProducer,
- $order->id_user,
- $order->id_user
- );
-
- // client : envoi d'un email de confirmation de paiement
- /*$paramsEmail = [
- 'from_email' => $producer->getEmailOpendistrib(),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $user->getUsername(),
- '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' => $producer->getEmailOpendistrib(),
- '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 {
- // envoi d'un email de confirmation
- $userProducer = UserProducer::find()
- ->where([
- 'id_user' => $idUser,
- 'id_producer' => $idProducer
- ])
- ->one();
-
- Mailjet::sendMail([
- 'from_email' => $producer->getEmailOpendistrib(),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $user->getUsername(),
- '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' => $producer->getEmailOpendistrib(),
- 'from_name' => $producer->name,
- 'to_email' => $user->email,
- 'to_name' => $user->getUsername(),
- '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' => $producer->getEmailOpendistrib(),
- '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();
- }
-
- }
|