You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CreditController.php 15KB

3 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace producer\controllers;
  38. use common\helpers\GlobalParam;
  39. use common\helpers\Mailjet;
  40. use common\helpers\MeanPayment;
  41. use common\logic\User\CreditHistory\Model\CreditHistory;
  42. use common\logic\User\CreditHistory\Model\CreditHistorySearch;
  43. use producer\models\CreditForm;
  44. use yii\filters\VerbFilter;
  45. class CreditController extends ProducerBaseController
  46. {
  47. /**
  48. * @inheritdoc
  49. */
  50. public function behaviors()
  51. {
  52. return [
  53. 'verbs' => [
  54. 'class' => VerbFilter::className(),
  55. 'actions' => [
  56. 'stripe-verification' => ['post'],
  57. ],
  58. ]
  59. ];
  60. }
  61. public function actions()
  62. {
  63. return [
  64. 'captcha' => [
  65. 'class' => 'yii\captcha\CaptchaAction',
  66. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  67. ],
  68. ];
  69. }
  70. public function beforeAction($action)
  71. {
  72. $this->enableCsrfValidation = false;
  73. return parent::beforeAction($action);
  74. }
  75. /**
  76. * Affiche l'historique du crédit client.
  77. */
  78. public function actionHistory(string $returnPayment = '')
  79. {
  80. $producer = $this->getProducerCurrent();
  81. if (\Yii::$app->user->isGuest) {
  82. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  83. }
  84. $searchModel = new CreditHistorySearch();
  85. $searchModel->id_user = GlobalParam::getCurrentUserId();
  86. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  87. $userProducer = $this->getUserProducerManager()->findOneUserProducer(GlobalParam::getCurrentUser(), $producer);
  88. if (strlen($returnPayment)) {
  89. if ($returnPayment == 'success') {
  90. $this->setFlash('success', "Paiement accepté : votre compte vient d'être crédité.");
  91. }
  92. if ($returnPayment == 'cancel') {
  93. $this->setFlash('error', 'Paiement annulé.');
  94. }
  95. }
  96. return $this->render('history', [
  97. 'searchModel' => $searchModel,
  98. 'dataProvider' => $dataProvider,
  99. 'creditUser' => $userProducer->credit
  100. ]);
  101. }
  102. public function actionAdd()
  103. {
  104. $producer = $this->getProducerCurrent();
  105. if (\Yii::$app->user->isGuest) {
  106. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  107. }
  108. if ($producer->online_payment || $producer->option_stripe_mode_test) {
  109. $creditForm = new CreditForm;
  110. if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
  111. $user = GlobalParam::getCurrentUser();
  112. \Stripe\Stripe::setApiKey(
  113. $this->getProducerManager()->getPrivateKeyApiStripe($producer)
  114. );
  115. $checkout_session = \Stripe\Checkout\Session::create([
  116. 'line_items' => [
  117. [
  118. 'price_data' => [
  119. 'currency' => 'eur',
  120. 'product_data' => [
  121. 'name' => 'Alimentation crédit',
  122. ],
  123. 'unit_amount' => (float) $creditForm->amount * 100,
  124. ],
  125. 'quantity' => 1,
  126. ]
  127. ],
  128. 'payment_method_types' => ['card'],
  129. 'mode' => 'payment',
  130. 'customer_email' => $user->email,
  131. 'client_reference_id' => $user->id,
  132. 'payment_intent_data' => [
  133. 'metadata' => [
  134. 'user_id' => $user->id,
  135. 'producer_id' => $producer->id
  136. ],
  137. ],
  138. 'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  139. [
  140. 'credit/history',
  141. 'returnPayment' => 'success'
  142. ]
  143. ),
  144. 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  145. [
  146. 'credit/history',
  147. 'returnPayment' => 'cancel'
  148. ]
  149. ),
  150. ]);
  151. header("HTTP/1.1 303 See Other");
  152. header("Location: " . $checkout_session->url);
  153. die();
  154. }
  155. return $this->render('add', [
  156. 'creditForm' => $creditForm
  157. ]);
  158. } else {
  159. throw new \yii\base\UserException('Cette option est désactivée chez ce producteur.');
  160. }
  161. }
  162. public function actionStripeVerification()
  163. {
  164. $creditHistoryManager = $this->getCreditHistoryManager();
  165. $producerManager = $this->getProducerManager();
  166. $userManager = $this->getUserManager();
  167. $producer = $this->getProducerCurrent();
  168. $contactProducer = $producerManager->getMainContact($producer);
  169. $payload = @file_get_contents('php://input');
  170. $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
  171. try {
  172. $event = \Stripe\Webhook::constructEvent(
  173. $payload,
  174. $sig_header,
  175. $producerManager->getPrivateKeyEndpointStripe($producer)
  176. );
  177. } catch (\UnexpectedValueException $e) {
  178. // Invalid payload
  179. http_response_code(400);
  180. exit();
  181. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  182. // Invalid signature
  183. http_response_code(400);
  184. exit();
  185. }
  186. $paymentIntent = $event->data->object;
  187. $paymentIntentMetadata = $paymentIntent->metadata;
  188. $amount = $paymentIntent->amount / 100;
  189. $idUser = $paymentIntentMetadata->user_id;
  190. $user = $userManager->findOneUserById($paymentIntentMetadata->user_id);
  191. $idProducer = $paymentIntentMetadata->producer_id;
  192. if (isset($paymentIntentMetadata->order_id)) {
  193. $order = $this->getOrderManager()->findOneOrderById($paymentIntentMetadata->order_id);
  194. $pointSale = $this->getPointSaleManager()->findOnePointSaleById($order->id_point_sale);
  195. $distribution = $this->getDistributionManager()->findOneDistributionById($order->id_distribution);
  196. }
  197. // Handle the event
  198. switch ($event->type) {
  199. case 'charge.succeeded':
  200. $creditHistoryExist = CreditHistory::searchOne([
  201. 'id_user' => $idUser,
  202. 'amount' => $amount,
  203. ], [
  204. 'conditions' => [
  205. 'date > DATE_SUB(NOW(), INTERVAL 1 MINUTE)'
  206. ]
  207. ]);
  208. if (!$creditHistoryExist) {
  209. $creditHistoryManager->createCreditHistory(
  210. CreditHistory::TYPE_CREDIT,
  211. $amount,
  212. $producer,
  213. $user,
  214. $user,
  215. MeanPayment::CREDIT_CARD
  216. );
  217. if (isset($order) && $order) {
  218. $creditHistoryManager->createCreditHistory(
  219. CreditHistory::TYPE_PAYMENT,
  220. $amount,
  221. $producer,
  222. $user,
  223. $user,
  224. MeanPayment::CREDIT,
  225. $order
  226. );
  227. // client : envoi d'un email de confirmation de paiement
  228. $paramsEmail = [
  229. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  230. 'from_name' => $producer->name,
  231. 'to_email' => $user->email,
  232. 'to_name' => $userManager->getUsername($user),
  233. 'subject' => '[' . $producer->name . '] Confirmation de paiement',
  234. 'content_view_text' => '@common/mail/paymentOrderConfirm-text.php',
  235. 'content_view_html' => '@common/mail/paymentOrderConfirm-html.php',
  236. 'content_params' => [
  237. 'amount' => $amount,
  238. 'user' => $user,
  239. 'producer' => $producer,
  240. ]
  241. ];
  242. //Mailjet::sendMail($paramsEmail);
  243. // producteur : mail de confirmation
  244. Mailjet::sendMail([
  245. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  246. 'from_name' => $producer->name,
  247. 'to_email' => $contactProducer->email,
  248. 'to_name' => $contactProducer->name,
  249. 'subject' => '[' . $producer->name . '] Confirmation de commande',
  250. 'content_view_text' => '@common/mail/orderConfirmProducer-text.php',
  251. 'content_view_html' => '@common/mail/orderConfirmProducer-html.php',
  252. 'content_params' => [
  253. 'order' => $order,
  254. 'pointSale' => $pointSale,
  255. 'distribution' => $distribution,
  256. 'user' => $user,
  257. 'producer' => $producer
  258. ]
  259. ]);
  260. } else {
  261. $userProducer = $this->getUserProducerManager()->findOneUserProducer($user, $producer);
  262. Mailjet::sendMail([
  263. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  264. 'from_name' => $producer->name,
  265. 'to_email' => $user->email,
  266. 'to_name' => $userManager->getUsername($user),
  267. 'subject' => '[' . $producer->name . '] Alimentation de votre crédit',
  268. 'content_view_text' => '@common/mail/creditConfirm-text.php',
  269. 'content_view_html' => '@common/mail/creditConfirm-html.php',
  270. 'content_params' => [
  271. 'user' => $user,
  272. 'userProducer' => $userProducer,
  273. 'producer' => $producer,
  274. 'amount' => $amount,
  275. ]
  276. ]);
  277. }
  278. }
  279. break;
  280. case 'charge.failed':
  281. // client
  282. Mailjet::sendMail([
  283. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  284. 'from_name' => $producer->name,
  285. 'to_email' => $user->email,
  286. 'to_name' => $userManager->getUsername($user),
  287. 'subject' => '[' . $producer->name . '] Erreur de paiement',
  288. 'content_view_text' => '@common/mail/paymentError-text.php',
  289. 'content_view_html' => '@common/mail/paymentError-html.php',
  290. 'content_params' => [
  291. 'amount' => $amount,
  292. 'user' => $user,
  293. 'producer' => $producer,
  294. ]
  295. ]);
  296. // producteur
  297. if (isset($order) && $order) {
  298. Mailjet::sendMail([
  299. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  300. 'from_name' => $producer->name,
  301. 'to_email' => $contactProducer->email,
  302. 'to_name' => $contactProducer->name,
  303. 'subject' => '[' . $producer->name . '] Erreur de paiement',
  304. 'content_view_text' => '@common/mail/paymentErrorProducer-text.php',
  305. 'content_view_html' => '@common/mail/paymentErrorProducer-html.php',
  306. 'content_params' => [
  307. 'amount' => $amount,
  308. 'user' => $user,
  309. 'producer' => $producer,
  310. 'order' => $order,
  311. 'distribution' => $distribution
  312. ]
  313. ]);
  314. }
  315. break;
  316. // handle other event types
  317. default:
  318. echo 'Received unknown event type ' . $event->type;
  319. }
  320. http_response_code(200);
  321. die();
  322. }
  323. }