Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

CreditController.php 17KB

3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. // on crédite le crédit du client
  210. $creditHistory = new CreditHistory;
  211. $creditHistory->id_user = $idUser;
  212. $creditHistory->id_user_action = $idUser;
  213. $creditHistory->id_producer = $idProducer;
  214. $creditHistory->type = CreditHistory::TYPE_CREDIT;
  215. $creditHistory->comment = null;
  216. $creditHistory->amount = $amount;
  217. $creditHistory->mean_payment = MeanPayment::CREDIT_CARD;
  218. $creditHistory->save();
  219. if(isset($order) && $order) {
  220. // paiement de la commande
  221. $order->saveCreditHistory(
  222. CreditHistory::TYPE_PAYMENT,
  223. $amount,
  224. $idProducer,
  225. $order->id_user,
  226. $order->id_user
  227. );
  228. // client : envoi d'un email de confirmation de paiement
  229. /*$paramsEmail = [
  230. 'from_email' => $producer->getEmailOpendistrib(),
  231. 'from_name' => $producer->name,
  232. 'to_email' => $user->email,
  233. 'to_name' => $user->getUsername(),
  234. 'subject' => '['.$producer->name.'] Confirmation de paiement',
  235. 'content_view_text' => '@common/mail/paymentOrderConfirm-text.php',
  236. 'content_view_html' => '@common/mail/paymentOrderConfirm-html.php',
  237. 'content_params' => [
  238. 'amount' => $amount,
  239. 'user' => $user,
  240. 'producer' => $producer,
  241. ]
  242. ] ;
  243. Mailjet::sendMail($paramsEmail);*/
  244. // producteur : mail de confirmation
  245. Mailjet::sendMail([
  246. 'from_email' => $producer->getEmailOpendistrib(),
  247. 'from_name' => $producer->name,
  248. 'to_email' => $contactProducer->email,
  249. 'to_name' => $contactProducer->name,
  250. 'subject' => '[' . $producer->name . '] Confirmation de commande',
  251. 'content_view_text' => '@common/mail/orderConfirmProducer-text.php',
  252. 'content_view_html' => '@common/mail/orderConfirmProducer-html.php',
  253. 'content_params' => [
  254. 'order' => $order,
  255. 'pointSale' => $pointSale,
  256. 'distribution' => $distribution,
  257. 'user' => $user,
  258. 'producer' => $producer
  259. ]
  260. ]);
  261. }
  262. else {
  263. // envoi d'un email de confirmation
  264. $userProducer = UserProducer::find()
  265. ->where([
  266. 'id_user' => $idUser,
  267. 'id_producer' => $idProducer
  268. ])
  269. ->one();
  270. Mailjet::sendMail([
  271. 'from_email' => $producer->getEmailOpendistrib(),
  272. 'from_name' => $producer->name,
  273. 'to_email' => $user->email,
  274. 'to_name' => $user->getUsername(),
  275. 'subject' => '['.$producer->name.'] Alimentation de votre crédit',
  276. 'content_view_text' => '@common/mail/creditConfirm-text.php',
  277. 'content_view_html' => '@common/mail/creditConfirm-html.php',
  278. 'content_params' => [
  279. 'user' => $user,
  280. 'userProducer' => $userProducer,
  281. 'producer' => $producer,
  282. 'amount' => $amount,
  283. ]
  284. ]);
  285. }
  286. break;
  287. case 'charge.failed':
  288. // client
  289. Mailjet::sendMail([
  290. 'from_email' => $producer->getEmailOpendistrib(),
  291. 'from_name' => $producer->name,
  292. 'to_email' => $user->email,
  293. 'to_name' => $user->getUsername(),
  294. 'subject' => '['.$producer->name.'] Erreur de paiement',
  295. 'content_view_text' => '@common/mail/paymentError-text.php',
  296. 'content_view_html' => '@common/mail/paymentError-html.php',
  297. 'content_params' => [
  298. 'amount' => $amount,
  299. 'user' => $user,
  300. 'producer' => $producer,
  301. ]
  302. ]);
  303. // producteur
  304. if(isset($order) && $order) {
  305. Mailjet::sendMail([
  306. 'from_email' => $producer->getEmailOpendistrib(),
  307. 'from_name' => $producer->name,
  308. 'to_email' => $contactProducer->email,
  309. 'to_name' => $contactProducer->name,
  310. 'subject' => '[' . $producer->name . '] Erreur de paiement',
  311. 'content_view_text' => '@common/mail/paymentErrorProducer-text.php',
  312. 'content_view_html' => '@common/mail/paymentErrorProducer-html.php',
  313. 'content_params' => [
  314. 'amount' => $amount,
  315. 'user' => $user,
  316. 'producer' => $producer,
  317. 'order' => $order,
  318. 'distribution' => $distribution
  319. ]
  320. ]);
  321. }
  322. break;
  323. // handle other event types
  324. default:
  325. echo 'Received unknown event type ' . $event->type;
  326. }
  327. http_response_code(200);
  328. die();
  329. }
  330. }