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 18KB

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