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.

364 satır
15KB

  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\CreditHistory;
  42. use common\logic\User\CreditHistory\CreditHistorySearch;
  43. use common\logic\User\User\User;
  44. use common\logic\User\UserProducer\UserProducer;
  45. use producer\models\CreditForm;
  46. use yii\filters\VerbFilter;
  47. class CreditController extends ProducerBaseController
  48. {
  49. /**
  50. * @inheritdoc
  51. */
  52. public function behaviors()
  53. {
  54. return [
  55. 'verbs' => [
  56. 'class' => VerbFilter::className(),
  57. 'actions' => [
  58. 'stripe-verification' => ['post'],
  59. ],
  60. ]
  61. ];
  62. }
  63. public function actions()
  64. {
  65. return [
  66. 'captcha' => [
  67. 'class' => 'yii\captcha\CaptchaAction',
  68. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  69. ],
  70. ];
  71. }
  72. public function beforeAction($action)
  73. {
  74. $this->enableCsrfValidation = false;
  75. return parent::beforeAction($action);
  76. }
  77. /**
  78. * Affiche l'historique du crédit client.
  79. */
  80. public function actionHistory(string $returnPayment = '')
  81. {
  82. $producer = $this->getProducer();
  83. if (\Yii::$app->user->isGuest) {
  84. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  85. }
  86. $searchModel = new CreditHistorySearch();
  87. $searchModel->id_user = GlobalParam::getCurrentUserId();
  88. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  89. $userProducer = $this->getUserProducerManager()->findOneUserProducer(GlobalParam::getCurrentUser(), $producer);
  90. if (strlen($returnPayment)) {
  91. if ($returnPayment == 'success') {
  92. $this->setFlash('success', "Paiement accepté : votre compte vient d'être crédité.");
  93. }
  94. if ($returnPayment == 'cancel') {
  95. $this->setFlash('error', 'Paiement annulé.');
  96. }
  97. }
  98. return $this->render('history', [
  99. 'searchModel' => $searchModel,
  100. 'dataProvider' => $dataProvider,
  101. 'creditUser' => $userProducer->credit
  102. ]);
  103. }
  104. public function actionAdd()
  105. {
  106. $producer = $this->getProducer();
  107. if (\Yii::$app->user->isGuest) {
  108. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  109. }
  110. if ($producer->online_payment || $producer->option_stripe_mode_test) {
  111. $creditForm = new CreditForm;
  112. if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
  113. $user = GlobalParam::getCurrentUser();
  114. \Stripe\Stripe::setApiKey(
  115. $this->getProducerManager()->getPrivateKeyApiStripe($producer)
  116. );
  117. $checkout_session = \Stripe\Checkout\Session::create([
  118. 'line_items' => [
  119. [
  120. 'price_data' => [
  121. 'currency' => 'eur',
  122. 'product_data' => [
  123. 'name' => 'Alimentation crédit',
  124. ],
  125. 'unit_amount' => (float) $creditForm->amount * 100,
  126. ],
  127. 'quantity' => 1,
  128. ]
  129. ],
  130. 'payment_method_types' => ['card'],
  131. 'mode' => 'payment',
  132. 'customer_email' => $user->email,
  133. 'client_reference_id' => $user->id,
  134. 'payment_intent_data' => [
  135. 'metadata' => [
  136. 'user_id' => $user->id,
  137. 'producer_id' => $producer->id
  138. ],
  139. ],
  140. 'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  141. [
  142. 'credit/history',
  143. 'returnPayment' => 'success'
  144. ]
  145. ),
  146. 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  147. [
  148. 'credit/history',
  149. 'returnPayment' => 'cancel'
  150. ]
  151. ),
  152. ]);
  153. header("HTTP/1.1 303 See Other");
  154. header("Location: " . $checkout_session->url);
  155. die();
  156. }
  157. return $this->render('add', [
  158. 'creditForm' => $creditForm
  159. ]);
  160. } else {
  161. throw new \yii\base\UserException('Cette option est désactivée chez ce producteur.');
  162. }
  163. }
  164. public function actionStripeVerification()
  165. {
  166. $creditHistoryManager = $this->getCreditHistoryManager();
  167. $producerManager = $this->getProducerManager();
  168. $userManager = $this->getUserManager();
  169. $producer = $this->getProducer();
  170. $contactProducer = $producerManager->getMainContact($producer);
  171. $payload = @file_get_contents('php://input');
  172. $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
  173. try {
  174. $event = \Stripe\Webhook::constructEvent(
  175. $payload,
  176. $sig_header,
  177. $producerManager->getPrivateKeyEndpointStripe($producer)
  178. );
  179. } catch (\UnexpectedValueException $e) {
  180. // Invalid payload
  181. http_response_code(400);
  182. exit();
  183. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  184. // Invalid signature
  185. http_response_code(400);
  186. exit();
  187. }
  188. $paymentIntent = $event->data->object;
  189. $paymentIntentMetadata = $paymentIntent->metadata;
  190. $amount = $paymentIntent->amount / 100;
  191. $idUser = $paymentIntentMetadata->user_id;
  192. $user = $userManager->findOneUserById($paymentIntentMetadata->user_id);
  193. $idProducer = $paymentIntentMetadata->producer_id;
  194. if (isset($paymentIntentMetadata->order_id)) {
  195. $order = $this->getOrderManager()->findOneOrderById($paymentIntentMetadata->order_id);
  196. $pointSale = $this->getPointSaleManager()->findOnePointSaleById($order->id_point_sale);
  197. $distribution = $this->getDistributionManager()->findOneDistributionById($order->id_distribution);
  198. }
  199. // Handle the event
  200. switch ($event->type) {
  201. case 'charge.succeeded':
  202. $creditHistoryExist = CreditHistory::searchOne([
  203. 'id_user' => $idUser,
  204. 'amount' => $amount,
  205. ], [
  206. 'conditions' => [
  207. 'date > DATE_SUB(NOW(), INTERVAL 1 MINUTE)'
  208. ]
  209. ]);
  210. if (!$creditHistoryExist) {
  211. $creditHistoryManager->createCreditHistory(
  212. CreditHistory::TYPE_CREDIT,
  213. $amount,
  214. $producer,
  215. $user,
  216. $user,
  217. MeanPayment::CREDIT_CARD
  218. );
  219. if (isset($order) && $order) {
  220. $creditHistoryManager->createCreditHistory(
  221. CreditHistory::TYPE_PAYMENT,
  222. $amount,
  223. $producer,
  224. $user,
  225. $user,
  226. MeanPayment::CREDIT,
  227. $order
  228. );
  229. // client : envoi d'un email de confirmation de paiement
  230. $paramsEmail = [
  231. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  232. 'from_name' => $producer->name,
  233. 'to_email' => $user->email,
  234. 'to_name' => $userManager->getUsername($user),
  235. 'subject' => '[' . $producer->name . '] Confirmation de paiement',
  236. 'content_view_text' => '@common/mail/paymentOrderConfirm-text.php',
  237. 'content_view_html' => '@common/mail/paymentOrderConfirm-html.php',
  238. 'content_params' => [
  239. 'amount' => $amount,
  240. 'user' => $user,
  241. 'producer' => $producer,
  242. ]
  243. ];
  244. //Mailjet::sendMail($paramsEmail);
  245. // producteur : mail de confirmation
  246. Mailjet::sendMail([
  247. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  248. 'from_name' => $producer->name,
  249. 'to_email' => $contactProducer->email,
  250. 'to_name' => $contactProducer->name,
  251. 'subject' => '[' . $producer->name . '] Confirmation de commande',
  252. 'content_view_text' => '@common/mail/orderConfirmProducer-text.php',
  253. 'content_view_html' => '@common/mail/orderConfirmProducer-html.php',
  254. 'content_params' => [
  255. 'order' => $order,
  256. 'pointSale' => $pointSale,
  257. 'distribution' => $distribution,
  258. 'user' => $user,
  259. 'producer' => $producer
  260. ]
  261. ]);
  262. } else {
  263. $userProducer = $this->getUserProducerManager()->findOneUserProducer($user, $producer);
  264. Mailjet::sendMail([
  265. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  266. 'from_name' => $producer->name,
  267. 'to_email' => $user->email,
  268. 'to_name' => $userManager->getUsername($user),
  269. 'subject' => '[' . $producer->name . '] Alimentation de votre crédit',
  270. 'content_view_text' => '@common/mail/creditConfirm-text.php',
  271. 'content_view_html' => '@common/mail/creditConfirm-html.php',
  272. 'content_params' => [
  273. 'user' => $user,
  274. 'userProducer' => $userProducer,
  275. 'producer' => $producer,
  276. 'amount' => $amount,
  277. ]
  278. ]);
  279. }
  280. }
  281. break;
  282. case 'charge.failed':
  283. // client
  284. Mailjet::sendMail([
  285. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  286. 'from_name' => $producer->name,
  287. 'to_email' => $user->email,
  288. 'to_name' => $userManager->getUsername($user),
  289. 'subject' => '[' . $producer->name . '] Erreur de paiement',
  290. 'content_view_text' => '@common/mail/paymentError-text.php',
  291. 'content_view_html' => '@common/mail/paymentError-html.php',
  292. 'content_params' => [
  293. 'amount' => $amount,
  294. 'user' => $user,
  295. 'producer' => $producer,
  296. ]
  297. ]);
  298. // producteur
  299. if (isset($order) && $order) {
  300. Mailjet::sendMail([
  301. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  302. 'from_name' => $producer->name,
  303. 'to_email' => $contactProducer->email,
  304. 'to_name' => $contactProducer->name,
  305. 'subject' => '[' . $producer->name . '] Erreur de paiement',
  306. 'content_view_text' => '@common/mail/paymentErrorProducer-text.php',
  307. 'content_view_html' => '@common/mail/paymentErrorProducer-html.php',
  308. 'content_params' => [
  309. 'amount' => $amount,
  310. 'user' => $user,
  311. 'producer' => $producer,
  312. 'order' => $order,
  313. 'distribution' => $distribution
  314. ]
  315. ]);
  316. }
  317. break;
  318. // handle other event types
  319. default:
  320. echo 'Received unknown event type ' . $event->type;
  321. }
  322. http_response_code(200);
  323. die();
  324. }
  325. }