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 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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\Mailjet;
  39. use common\helpers\MeanPayment;
  40. use common\logic\User\CreditHistory\CreditHistoryModel;
  41. use common\logic\User\User\UserModel;
  42. use common\logic\User\UserProducer\UserProducerModel;
  43. use common\models\CreditHistorySearch;
  44. use common\models\Distribution;
  45. use common\models\Order;
  46. use common\models\PointSale;
  47. use producer\models\CreditForm;
  48. use yii\filters\VerbFilter;
  49. class CreditController extends ProducerBaseController
  50. {
  51. /**
  52. * @inheritdoc
  53. */
  54. public function behaviors()
  55. {
  56. return [
  57. 'verbs' => [
  58. 'class' => VerbFilter::className(),
  59. 'actions' => [
  60. 'stripe-verification' => ['post'],
  61. ],
  62. ]
  63. ];
  64. }
  65. public function actions()
  66. {
  67. return [
  68. 'captcha' => [
  69. 'class' => 'yii\captcha\CaptchaAction',
  70. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  71. ],
  72. ];
  73. }
  74. public function beforeAction($action)
  75. {
  76. $this->enableCsrfValidation = false;
  77. return parent::beforeAction($action);
  78. }
  79. /**
  80. * Affiche l'historique du crédit client.
  81. *
  82. */
  83. public function actionHistory($returnPayment = '')
  84. {
  85. $producer = $this->getProducer();
  86. if(\Yii::$app->user->isGuest) {
  87. return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
  88. }
  89. $searchModel = new CreditHistorySearch();
  90. $searchModel->id_user = UserModel::getCurrentId();
  91. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  92. $userProducer = UserProducerModel::searchOne([
  93. 'id_producer' => $producer->id,
  94. 'id_user' => UserModel::getCurrentId()
  95. ]);
  96. if (strlen($returnPayment)) {
  97. if ($returnPayment == 'success') {
  98. \Yii::$app->getSession()->setFlash('success', "Paiement accepté : votre compte vient d'être crédité.");
  99. }
  100. if ($returnPayment == 'cancel') {
  101. \Yii::$app->getSession()->setFlash('error', 'Paiement annulé.');
  102. }
  103. }
  104. return $this->render('history', [
  105. 'searchModel' => $searchModel,
  106. 'dataProvider' => $dataProvider,
  107. 'creditUser' => $userProducer->credit
  108. ]);
  109. }
  110. public function actionAdd()
  111. {
  112. $producer = $this->getProducer();
  113. if(\Yii::$app->user->isGuest) {
  114. return $this->redirect(\Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/producer','id' => $producer->id])) ;
  115. }
  116. if ($producer->online_payment || $producer->option_stripe_mode_test) {
  117. $creditForm = new CreditForm;
  118. if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
  119. $user = UserModel::getCurrent();
  120. \Stripe\Stripe::setApiKey(
  121. $producer->getPrivateKeyApiStripe()
  122. );
  123. $checkout_session = \Stripe\Checkout\Session::create([
  124. 'line_items' => [
  125. [
  126. 'price_data' => [
  127. 'currency' => 'eur',
  128. 'product_data' => [
  129. 'name' => 'Alimentation crédit',
  130. ],
  131. 'unit_amount' => (float)$creditForm->amount * 100,
  132. ],
  133. 'quantity' => 1,
  134. ]
  135. ],
  136. 'payment_method_types' => ['card'],
  137. 'mode' => 'payment',
  138. 'customer_email' => $user->email,
  139. 'client_reference_id' => $user->id,
  140. 'payment_intent_data' => [
  141. 'metadata' => [
  142. 'user_id' => $user->id,
  143. 'producer_id' => $producer->id
  144. ],
  145. ],
  146. 'success_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
  147. [
  148. 'credit/history',
  149. 'returnPayment' => 'success'
  150. ]
  151. ),
  152. 'cancel_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(
  153. [
  154. 'credit/history',
  155. 'returnPayment' => 'cancel'
  156. ]
  157. ),
  158. ]);
  159. header("HTTP/1.1 303 See Other");
  160. header("Location: " . $checkout_session->url);
  161. die();
  162. }
  163. return $this->render('add', [
  164. 'creditForm' => $creditForm
  165. ]);
  166. } else {
  167. throw new \yii\base\UserException('Cette option est désactivée chez ce producteur.');
  168. }
  169. }
  170. public function actionStripeVerification()
  171. {
  172. $creditHistoryBuilder = $this->getLogic()->getCreditHistoryContainer()->getBuilder();
  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 = UserModel::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 = CreditHistoryModel::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 CreditHistoryModel();
  220. $creditHistory->id_user = $idUser;
  221. $creditHistory->id_user_action = $idUser;
  222. $creditHistory->id_producer = $idProducer;
  223. $creditHistory->type = CreditHistoryModel::TYPE_CREDIT;
  224. $creditHistory->comment = null;
  225. $creditHistory->amount = $amount;
  226. $creditHistory->mean_payment = MeanPayment::CREDIT_CARD;
  227. $creditHistoryBuilder->save($creditHistory);
  228. if (isset($order) && $order) {
  229. // paiement de la commande
  230. $order->saveCreditHistory(
  231. CreditHistoryModel::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 = UserProducerModel::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. }