This repository was archived by the owner on Aug 18, 2023. It is now read-only.
forked from payutc/casper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
630 lines (519 loc) · 21.9 KB
/
Copy pathindex.php
File metadata and controls
630 lines (519 loc) · 21.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Slim
require 'vendor/autoload.php';
use \Payutc\Casper\Config;
use \Payutc\Casper\JsonClientFactory;
use \Payutc\Casper\JsonClientMiddleware;
// Load configuration
require "config.inc.php";
Config::initFromArray($_CONFIG);
// Settings for cookies
$sessionPath = parse_url(Config::get("casper_url"), PHP_URL_PATH);
session_set_cookie_params(0, $sessionPath);
session_start();
// Slim initialization
$app = new \Slim\Slim(Config::get('slim_config'));
// This middleware loads all our json clients
$app->add(new JsonClientMiddleware);
// A few helpers to handle amounts in cents
function format_amount($val) {
return number_format($val/100, 2, ',', ' ');
}
function parse_user_amount($val) {
$amount = str_replace(',','.', $val);
return $amount*100;
}
// --- Coeur de casper
// Page principale
$app->get('/', function() use($app) {
$app->render('header.php', array(
"title" => Config::get("title"),
"loggedin" => true
));
// The array that will be sent to the template
$pageData = array();
$pageData["canReload"] = false;
$pageData["canReloadPapercut"] = false;
$pageData["canReloadEvent"] = false;
$pageData["cannotReloadMessage"] = "PayIcam ferme ! Transfert des soldes des étudiants Icam Lille vers la nouvelle solution en cours.";
try {
// $reloadInfo = JsonClientFactory::getInstance()->getClient("RELOAD")->info();
$pageData["maxReload"] = 0;
$pageData["minReload"] = 0;
}
catch(\JsonClient\JsonException $e){
$pageData["canReload"] = false;
$pageData["cannotReloadMessage"] = $e->getMessage();
}
$pageData["isBlocked"] = false;
// $pageData["isBlocked"] = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->isBlockedMe();
// $resultat = JsonClientFactory::getInstance()->getClient("RELOADPAPERCUT")->getSoldePaperCut();
// $pageData["reloadsPapercut"] = json_decode($resultat, 1);
$account = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->historique();
$pageData["cannotReloadEventMessage"] = false;
if ($account->credit < 1000) {
$pageData["cannotReloadEventMessage"] = "On ne peut recharger que par tranches d'au moins 10 euros. Rechargez votre solde PayIcam.";
} else if ($account->credit_event > 24000) {
$pageData["cannotReloadEventMessage"] = "On ne peut recharger plus de 250 euros sur le solde event.";
}
$pageData["historique"] = $account->historique;
$pageData["historique_event"] = $account->historique_event;
$env = $app->environment();
$pageData["userDetails"] = array(
"firstname" => $env["user_data"]->firstname,
"lastname" => $env["user_data"]->lastname,
"credit" => $account->credit,
"credit_event" => $account->credit_event,
"credit_ecocup" => $account->credit_ecocup,
"credit_ecocup_soiree" => $account->credit_ecocup_soiree,
);
$app->render('main.php', $pageData);
$app->render('footer.php');
})->name('home');
// Blocage du compte
$app->get('/block', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
try {
JsonClientFactory::getInstance()->getClient("MYACCOUNT")->setSelfBlock(array(
"blocage" => 1
));
}
catch(\JsonClient\JsonException $e){
$app->flash('block_erreur', $e->getMessage());
$app->getLog()->error("Block failed: ".$e->getMessage());
}
$app->response()->redirect($app->urlFor('home'));
});
// Déblocage du compte
$app->get('/unblock', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
try {
JsonClientFactory::getInstance()->getClient("MYACCOUNT")->setSelfBlock(array(
"blocage" => 0
));
}
catch(\JsonClient\JsonException $e){
$app->flash('block_erreur', $e->getMessage());
$app->getLog()->error("Unblock failed: ".$e->getMessage());
}
$app->response()->redirect($app->urlFor('home'));
});
// Autocomplete du virement
$app->get('/ajax', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
if(!empty($_GET["q"])) {
$search = JsonClientFactory::getInstance()->getClient("RELOAD")->userAutocomplete(array(
"queryString" => $_GET["q"]
));
echo json_encode($search);
}
});
// Départ vers le rechargement
$app->post('/reload', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
if(empty($_POST["montant"])) {
$app->flash('error_reload', "Saisissez un montant");
$app->response()->redirect($app->urlFor('home'));
}
$amount = parse_user_amount($_POST['montant']);
try {
$reloadUrl = JsonClientFactory::getInstance()->getClient("RELOAD")->reload(array(
"amount" => $amount,
"callbackUrl" => Config::get("casper_url")
));
// $app->flash('indice_gala', "Dumbledore aurait été très fier de toi ! c’est pourquoi je n’utiliserai que ces dernières paroles : Harryy !! De l’eau.");
$app->redirect($reloadUrl);
}
catch(\JsonClient\JsonException $e){
$app->flash('reload_erreur', $e->getMessage());
$app->flash('reload_value', $amount/100);
$app->getLog()->error("Reload failed: ".$e->getMessage());
$app->response()->redirect($app->urlFor('home'));
}
});
$app->post('/reload_event', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
if (!Config::get("canReloadEvent")) {
return $app->response()->redirect($app->urlFor('home'));
}
if(empty($_POST["amount"])) {
$app->flash('reload_event_erreur', "Saisissez un montant");
$app->response()->redirect($app->urlFor('home'));
}
$status = JsonClientFactory::getInstance()->getClient("RELOADEVENT")->getStatus();
$account = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->historique();
$account->credit;
$amount = $_POST['amount'];
if($amount < 0) {
$app->flash('reload_event_erreur', "Tu ne peux pas faire un virement négatif (bien essayé)");
} else if($amount == 0) {
$app->flash('reload_event_erreur', "Pas de montant saisi");
} else if($account->credit < $amount) {
$app->flash('reload_event_erreur', "Tu n'as pas assez d'argent pour réaliser ce virement");
} else {
// Connect the application if required
if(empty($status->application)){
$app->getLog()->debug("No app logged in for WEBSALECONFIRM, calling loginApp");
try {
JsonClientFactory::getInstance()->getClient("RELOADEVENT")->loginApp(array(
"key" => Config::get("application_key")
));
} catch (\JsonClient\JsonException $e) {
$app->getLog()->error("Application login error for RELOADEVENT: ".$e->getMessage());
throw $e;
}
}
try {
$resultat = JsonClientFactory::getInstance()->getClient("RELOADEVENT")->reloadPayIcam(array(
"amount" => $amount*1
));
if ($resultat == $amount)
$app->flash('reload_event_ok', 'Le virement de '.format_amount($resultat).' € a réussi.');
else {
$app->flash('reload_event_erreur', "Quelque chose de louche s'est passé.".$resultat);
}
} catch(\JsonClient\JsonException $e) {
echo $e->getMessage();
$app->flash('reload_event_erreur', $e->getMessage());
$app->flash('reload_event_value', abs($amount/100));
}
}
$app->response()->redirect($app->urlFor('home'));
});
// Virement à un ami
$app->post('/virement', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
// Récupèration du montant en cents
$montant = parse_user_amount($_POST['montant']);
try {
$virement = JsonClientFactory::getInstance()->getClient("TRANSFER")->transfer(array(
"amount" => $montant,
"userID" => $_POST['userId'],
"message" => $_POST['message']
));
$sender = $app->environment()['user_data'];
$receiver_email = JsonClientFactory::getInstance()->getClient("TRANSFER")->getUserEmail(array("usr_id" => $_POST['userId']));
$mail = new PHPMailer;
$mailer_config = Config::get('PHPMailer');
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = $mailer_config['Host']; // Specify main and backup SMTP servers
$mail->SMTPAuth = $mailer_config['SMTPAuth']; // Enable SMTP authentication
$mail->Username = $mailer_config['Username']; // SMTP username
$mail->Password = $mailer_config['Password']; // SMTP password
$mail->SMTPSecure = $mailer_config['SMTPSecure']; // Enable TLS encryption, `ssl` also accepted
$mail->Port = $mailer_config['Port']; // TCP port to connect to
$mail->Encoding = 'base64';
$mail->CharSet = 'UTF-8';
$mail->setFrom('noreply.payicam@gmail.com', 'No Reply PayIcam');
$mail->addAddress($receiver_email);
$mail->isHTML(true);
$subject = 'Virement reçu de la part de '.$sender->firstname . ' ' . $sender->lastname;
$message = empty($_POST['message']) ? '' : 'Son message : ' . $_POST['message'];
$mail->Subject = $subject;
$mail->Body = '<html>
<head>
<meta charset="utf-8">
<title>'.$subject.'</title>
</head>
<body>
<h1>'.$subject.'</h1>
<p>Tu as reçu ' . format_amount($montant) . '€ de la part de ' . $sender->firstname . ' ' . $sender->lastname . '</p>
<p>' . $message . '</p>
<p>A bientôt,</p>
<p><em>PayIcam</em></p>
</body>
</html>
';
$mail->AltBody = $subject."\n".
'Tu as reçu ' . format_amount($montant) . '€ de la part de ' . $sender->firstname . ' ' . $sender->lastname ."\n".
$message .
'A bientôt,'."\n".
"PayIcam";
if(!$mail->send()) {
$app->flash('virement_ok', 'Le virement de '.format_amount($montant).' € a réussi. Le mail automatique a toutefois échoué... Prévenez votre ami tout seul, et signalez nous le bug :)');
}
$app->flash('virement_ok', 'Le virement de '.format_amount($montant).' € a réussi.');
}
catch(\JsonClient\JsonException $e){
$app->flash('virement_erreur', $e->getMessage());
}
// Retour vers la page d'accueil
$app->response()->redirect($app->urlFor('home'));
});
// --- Enregistrement
// Affichage de la charte
$app->get('/register', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
$app->render('header.php', array(
"title" => Config::get("title"),
"loggedin" => true
));
$app->render('register.php', array("form" => true));
$app->render('footer.php');
})->name('register');
// Enregistrement après validation de la charte
$app->post('/register', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
try {
// Appel serveur
$result = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->register();
// Si ok, go vers la page d'accueil de payicam
$app->redirect("../");
// $app->redirect($app->urlFor('home'));
}
catch(\JsonClient\JsonException $e){
// Si on a une erreur on l'affiche
$app->flash('register_erreur', $e->getMessage());
// On n'a pas réussi à s'enregistrer, retour vers la charte
$app->redirect($app->urlFor('register'));
}
});
// --- Websale confirmation gateway
// Initial access
$app->get('/validation', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
// If no transaction data, go home
if(empty($_GET['tra_id']) || empty($_GET['token'])){
$app->getLog()->error("No transaction data recieved");
$app->redirect($app->urlFor('home'));
}
// Get environment
$env = $app->environment();
// Get data the transaction data
try {
$transactionData = JsonClientFactory::getInstance()->getClient("WEBSALECONFIRM")->getTransactionInfo(array(
'tra_id' => $_GET['tra_id'],
'token' => $_GET['token']
));
// If this transaction is not waiting
if($transactionData->status != 'W'){
throw new \Exception("Cette transaction n'est pas en attente.");
}
}
catch(\Exception $e){
$app->getLog()->error("Cannot get transaction ".$_GET['tra_id']." with token ".$_GET['token'].": ".$e->getMessage());
$app->render('header.php', array("title" => Config::get("title", "payutc"), "loggedin" => false));
$app->render('error.php', array('login_erreur' => "Impossible de récupérer la transaction"));
$app->render('footer.php');
$app->stop();
}
$app->render('header.php', array(
"title" => Config::get("title"),
"loggedin" => $env["loggedin"]
));
$products = array();
foreach($transactionData->products as $product) {
$products[$product->id] = $product;
}
if($env["loggedin"]){
$account = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->historique();
$canReload = true;
$maxReload = 10000-$account->credit;
$minReload = 1000;
$cannotReloadMessage = "";
try {
$reloadInfo = JsonClientFactory::getInstance()->getClient("RELOAD")->info();
$maxReload = $reloadInfo->max_reload;
$minReload = $reloadInfo->min;
}
catch(\JsonClient\JsonException $e){
$canReload = false;
$cannotReloadMessage = $e->getMessage();
}
$app->render('websale_payutc.php', array(
"purchases" => $transactionData->purchases,
"products" => $products,
"total" => $transactionData->total,
"solde" => $account->credit,
"maxReload" => $maxReload,
"minReload" => $minReload,
"canReload" => $canReload,
"cannotReloadMessage" => $cannotReloadMessage,
"fundation" => $transactionData->fun_name,
"firstname" => $env['user_data']->firstname,
"logoutUrl" => $app->urlFor('logout')."?tra_id=".$_GET['tra_id']."&token=".$_GET['token']
));
}
else {
$app->render('websale.php', array(
"purchases" => $transactionData->purchases,
"products" => $products,
"total" => $transactionData->total,
"fundation" => $transactionData->fun_name,
"tra_id" => $_GET['tra_id'],
"token" => $_GET['token']
));
}
$app->render('footer.php');
});
// Submit of payment form
$app->post('/validation', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
// If no transaction data, go home
if(empty($_POST['tra_id']) || empty($_POST['token']) || empty($_POST['method'])){
$app->getLog()->error("No transaction data recieved");
$app->redirect($app->urlFor('home'));
}
// Get environment
$env = $app->environment();
// Get data the transaction data
try {
if($_POST['method'] == "direct"){
if(empty($_POST['cgu'])){
throw new \Exception("Vous devez accepter les CGU de PayIcam pour continuer");
}
$nextUrl = JsonClientFactory::getInstance()->getClient("WEBSALECONFIRM")->doTransaction(array(
'tra_id' => $_POST['tra_id'],
'token' => $_POST['token'],
'montant_reload' => 0
));
}
else if($_POST['method'] == "payutc" && $env["loggedin"]){
$montant = !empty($_POST['montant']) ? parse_user_amount($_POST['montant']) : 0;
$nextUrl = JsonClientFactory::getInstance()->getClient("WEBSALECONFIRM")->doTransaction(array(
'tra_id' => $_POST['tra_id'],
'token' => $_POST['token'],
'montant_reload' => $montant
));
}
else {
throw new \Exception("Méthode de paiement non reconnue");
}
}
catch(\Exception $e){
$app->getLog()->error("Cannot do transaction ".$_POST['tra_id']." with token ".$_POST['token'].": ".$e->getType(). " - ".$e->getMessage());
$app->render('header.php', array("title" => Config::get("title", "payutc"), "loggedin" => false));
$app->render('error.php', array('login_erreur' => "Impossible de valider la transaction"));
$app->render('footer.php');
$app->stop();
}
$app->redirect($nextUrl);
});
// Return from payline
$app->get('/validationReturn', function() use ($app) {
$app->flash('fermeture', 'PayIcam ferme.');
header('Location: /casper');
die();
// Get data the transaction data
try {
// If no token, fail
if(empty($_GET['token'])){
$app->getLog()->error("No token recieved");
throw new \Exception("No token received");
}
$nextUrl = JsonClientFactory::getInstance()->getClient("WEBSALECONFIRM")->notificationPayline(array(
'token_payline' => $_GET['token']
));
}
catch(\Exception $e){
$app->getLog()->error("Cannot do notification with token ".$_GET['token'].": ".$e->getMessage());
$app->render('header.php', array("title" => Config::get("title", "payutc"), "loggedin" => false));
$app->render('error.php', array('login_erreur' => "Impossible de notifier la transaction"));
$app->render('footer.php');
$app->stop();
}
$app->redirect($nextUrl);
});
// --- CAS
$app->get('/login', function() use ($app) {
// Si pas de ticket, c'est une invitation à se connecter
if(empty($_GET["ticket"])) {
$app->getLog()->debug("No CAS ticket, unsetting cookies and redirecting to CAS");
// On jette les cookies actuels
JsonClientFactory::getInstance()->destroyCookie();
// If we have transaction parameters, save them
if(!empty($_GET['tra_id']) && !empty($_GET['token'])){
$app->getLog()->debug("Setting login redirect URL to validation");
$_SESSION['login_redirect'] = "validation?tra_id=".$_GET['tra_id']."&token=".$_GET['token'];
}
// Redirection vers le CAS
$app->redirect(JsonClientFactory::getInstance()->getClient("MYACCOUNT")->getCasUrl()."login?service=".Config::get("casper_url").'login');
} else {
// Connexion au serveur avec le ticket CAS
try {
$app->getLog()->debug("Trying loginCas");
$result = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->loginCas(array(
"ticket" => $_GET["ticket"],
"service" => Config::get("casper_url").'login'
));
} catch (\JsonClient\JsonException $e) {
// Si l'utilisateur n'existe pas, go inscription
if($e->getType() == "Payutc\Exception\UserNotFound"){
// On doit garder le cookie car le serveur garde le login de son côté
JsonClientFactory::getInstance()->setCookie(JsonClientFactory::getInstance()->getClient("MYACCOUNT")->cookie);
// Redirection vers la charte
$app->redirect($app->urlFor('register'));
}
$app->getLog()->warn("Error with CAS ticket ".$_GET["ticket"].": ".$e->getMessage());
// Affichage d'une page avec juste l'erreur
$app->render('header.php', array("title" => Config::get("title", "payutc"), "loggedin"=>false));
$app->render('error.php', array('login_erreur' => 'Erreur de login CAS<br /><a href="'.$app->urlFor('login').'">Réessayer</a>'));
$app->render('footer.php');
$app->stop();
}
// On stocke le cookie
JsonClientFactory::getInstance()->setCookie(JsonClientFactory::getInstance()->getClient("MYACCOUNT")->cookie);
// Go vers la page d'accueil
if(!empty($_SESSION['login_redirect'])){
$url = $_SESSION['login_redirect'];
unset($_SESSION['login_redirect']);
$app->getLog()->debug("Redirect after login: $url");
$app->redirect($url);
}
else {
$app->redirect($app->urlFor('home'));
}
}
})->name('login');
$app->get('/logout', function() use ($app) {
// On clot la session avec le serveur
try {
JsonClientFactory::getInstance()->getClient("MYACCOUNT")->logout();
}
catch (\JsonClient\JsonException $e){
// No worries, we'll just continue
}
// Throw our cookies away
JsonClientFactory::getInstance()->destroyCookie();
$logoutUrl = JsonClientFactory::getInstance()->getClient("MYACCOUNT")->getCasUrl()."/logout";
// If we have transaction parameters, save them
if(!empty($_GET['tra_id']) && !empty($_GET['token'])){
$app->getLog()->debug("Setting logout redirect URL to validation");
$logoutUrl .= "?url=".urlencode(Config::get("casper_url")."validation?tra_id=".$_GET['tra_id']."&token=".$_GET['token']);
}
// Logout from CAS
$app->redirect($logoutUrl);
})->name('logout');
// Affichage de la charte (Pour le lien CGU du paiement en ligne)
$app->get('/cgu', function() use ($app) {
$app->render('header.php', array(
"title" => Config::get("title"),
"loggedin" => false
));
$app->render('register.php', array("form" => false));
$app->render('footer.php');
})->name('cgu');
$app->run();