-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqentaceecheckout.php
1964 lines (1674 loc) · 65.4 KB
/
qentaceecheckout.php
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Shop System Plugins
* - Terms of use can be found under
* https://guides.qenta.com/shop_plugins:info
* - License can be found under:
* https://github.com/qenta-cee/virtuemart3-qcp/blob/master/LICENSE
*/
defined('_JEXEC') or die('Restricted access');
/* resources:
* http://www.spiralscripts.co.uk/Joomla-Tips/custom-plugin-fields-in-virtuemart-2-2.html
* http://docs.joomla.org/Developers
* order-states: select * from jom_virtuemart_orderstates;
*/
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . realpath(dirname(__FILE__)) . '/library');
if (!class_exists('vmPSPlugin')) {
require(JPATH_VM_PLUGINS . DIRECTORY_SEPARATOR . 'vmpsplugin.php');
}
require_once 'autoload.php';
class plgVmPaymentqentaceecheckout extends vmPSPlugin
{
public static $_this = false;
protected static $WINDOW_NAME = 'QentaCEECheckoutFrame';
protected static $PLUGIN_NAME = 'VirtueMart2_CheckoutPage';
protected static $PLUGIN_VERSION = '2.0.0';
protected $_method;
protected $_order;
const QCP_CUSTOMER_ID_DEMO = 'D200001';
const QCP_SHOP_ID_DEMO = '';
const QCP_SECRET_DEMO = 'B8AKTPWBRMNBV455FG6M2DANE99WU2';
const QCP_BACKEND_PASSWORD_DEMO = 'jcv45z';
const QCP_CUSTOMER_ID_TEST = 'D200411';
const QCP_SHOP_ID_TEST = '';
const QCP_SECRET_TEST = 'CHCSH7UGHVVX2P7EHDHSY4T2S4CGYK4QBE4M5YUUG2ND5BEZWNRZW5EJYVJQ';
const QCP_BACKEND_PASSWORD_TEST = '2g4f9q2m';
const QCP_CUSTOMER_ID_TEST3D = 'D200411';
const QCP_SHOP_ID_TEST3D = '3D';
const QCP_SECRET_TEST3D = 'DP4TMTPQQWFJW34647RM798E9A5X7E8ATP462Z4VGZK53YEJ3JWXS98B9P4F';
const QCP_BACKEND_PASSWORD_TEST3D = '2g4f9q2m';
const QCP_SERVICE_PROVIDER_PAYOLUTION = 'payolution';
const INVOICE_INSTALLMENT_MIN_AGE = 18;
public function __construct(& $subject, $config)
{
parent::__construct($subject, $config);
$this->_loggable = true;
$this->_debug = true;
$this->tableFields = array_keys($this->getTableSQLFields());
$this->_tablepkey = 'id';
$this->_tableId = 'id';
$logosFieldName = $this->_psType . '_logos';
$this->$logosFieldName = array();
$this->tellMerchantIfConfigurationIsValidate();
$varsToPush = $this->getVarsToPush();
$varsToPush['max_retries'] = array(-1, 'int');
unset($varsToPush['support_email']);
unset($varsToPush['support_replyto']);
unset($varsToPush['support_message']);
$this->setConfigParameterable($this->_configTableFieldName, $varsToPush);
$this->sendSupportRequest();
}
/**
* Validates configuration by initiating a transaction with the given parameters and displays the determined state
*/
private function tellMerchantIfConfigurationIsValidate()
{
$data = vRequest::getPost(FILTER_SANITIZE_STRING);
if (!isset($data['params'])) {
return;
}
//TODO dirty hack... an improvement is strongly encouraged...
$check_configuration = $data['params']['support_message'];
if ($check_configuration === '1') {
$client = new QentaCEE\QPay\FrontendClient(array(
'CUSTOMER_ID' => trim($data['params']['customer_id'] ? $data['params']['customer_id'] : ' '),
'SHOP_ID' => $data['params']['shop_id'],
'SECRET' => trim($data['params']['secret'] ? $data['params']['secret'] : ' '),
'LANGUAGE' => $this->_getLanguage()
));
$returnUrl = JROUTE::_(JURI::root());
$consumerData = new QentaCEE\Stdlib\ConsumerData();
$consumerData->setUserAgent($_SERVER['HTTP_USER_AGENT'])
->setIpAddress($_SERVER['REMOTE_ADDR']);
$client->setAmount(0.01)
->setCurrency('EUR')
->setPaymentType(QentaCEE\QPay\PaymentType::CCARD)
->setOrderDescription('Config Test')
->setSuccessUrl($returnUrl)
->setCancelUrl($returnUrl)
->setFailureUrl($returnUrl)
->setConfirmUrl($returnUrl)
->setServiceUrl($data['params']['service_url'] ? $data['params']['service_url'] : ' ')
->setImageUrl($data['params']['image_url'] ? $data['params']['image_url'] : ' ')
->setConsumerData($consumerData);
$response = $client->initiate();
if ($response->hasFailed()) {
$responseArray = $response->getResponse();
vmError($responseArray['message']);
} else {
vmAdminInfo(vmText::_('VMPAYMENT_QENTACEECHECKOUT_CHECK_CONFIGURATION_OK'));
}
}
}
/**
* Sends a support request including shop and plugin configuration
*/
private function sendSupportRequest()
{
$data = vRequest::getPost(FILTER_SANITIZE_STRING);
$support_email = $data['params']['support_email'];
if (strlen($support_email) > 0) {
$support_replyto = $data['params']['support_replyto'];
$support_message = $data['params']['support_message'];
unset($data['params']['secret']);
unset($data['params']['support_email']);
unset($data['params']['support_replyto']);
unset($data['params']['support_message']);
$support_message .= sprintf("\tVirtueMart version: %s\n", VmConfig::getInstalledVersion());
$support_message .= sprintf("\tPlugin: %s %s\n", self::$PLUGIN_NAME, self::$PLUGIN_VERSION);
foreach ($data['params'] as $key => $value) {
$support_message .= sprintf("\t%s: %s\n", $key, $value);
}
$mailer = JFactory::getMailer();
$mailer->addRecipient($support_email);
if (strlen($support_replyto) > 0) {
$mailer->addReplyTo($support_replyto);
}
$mailer->setSubject(vmText::_('VMPAYMENT_QENTACEECHECKOUT_SUPPORT_REQUEST'));
$mailer->setBody($support_message);
if ($mailer->Send()) {
vmAdminInfo(vmText::_('VMPAYMENT_QENTACEECHECKOUT_SUPPORT_SEND_OK'));
}
}
}
public function getVmPluginCreateTableSQL()
{
return $this->createTableSQL('Payment Qenta Table');
}
/**
* @return string
*/
public function getTableSQLFields()
{
$SQLfields = array(
'id' => 'int(11) UNSIGNED NOT NULL AUTO_INCREMENT',
'virtuemart_order_id' => 'int(1) UNSIGNED',
'order_number' => 'char(64)',
'virtuemart_paymentmethod_id' => 'mediumint(1) UNSIGNED',
'payment_name' => 'varchar(5000)',
'payment_order_total' => 'decimal(15,5) NOT NULL',
'payment_currency' => 'smallint(1)',
// qenta specific data
'qenta_order_number' => 'varchar(50)',
'qenta_gateway_ref' => 'varchar(50)',
'qenta_response_raw' => 'text');
return $SQLfields;
}
/**
* User completed checkout, start payment
* return: may be redirect is done by the payment plugin (eg: paypal)
* if payment plugin echos a form, false = nothing happen, true= echo form ,
* 1 = cart should be emptied, 0 cart should not be emptied
*
* @param VirtueMartCart $cart
* @param $order
* @return bool|null
*/
public function plgVmConfirmedOrder($cart, $order)
{
if (!($method = $this->getVmPluginMethod($order['details']['BT']->virtuemart_paymentmethod_id))) {
return null; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($method->payment_element)) {
return false;
}
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'orders.php');
}
$this->_setMethod($method);
$this->_setOrder($order);
$redirectUrl = $this->_initiatePayment($cart);
if (!$redirectUrl) {
$msg = vmText::_('VMPAYMENT_QENTACEECHECKOUT_INITIATE_PAYMENT_ERROR');
$app = JFactory::getApplication();
$app->redirect(JRoute::_('index.php?option=com_virtuemart&view=cart&Itemid=' . vRequest::getInt('Itemid') . '&lang=' . vRequest::getCmd('lang', ''), false), $msg);
}
$dbValues = array();
$dbValues['virtuemart_order_id'] = $order['details']['BT']->virtuemart_order_id;
$dbValues['order_number'] = $order['details']['BT']->order_number;
$dbValues['virtuemart_paymentmethod_id'] = $cart->virtuemart_paymentmethod_id;
$dbValues['payment_name'] = parent::renderPluginName($method);
$dbValues['payment_order_total'] = $this->_getAmount($order);
$dbValues['payment_currency'] = $this->_getOrderCurrency();
$this->storePSPluginInternalData($dbValues);
if ($this->_useIFrame()) {
$html = sprintf('<iframe src="%s" width="100%%" height="900" name="%s" border="0" frameborder="0"></iframe>',
$redirectUrl,
$this->_getWindowName());
// don't delete the cart, don't send email and don't redirect
$cart->_confirmDone = false;
$cart->_dataValidated = false;
$cart->setCartIntoSession();
JFactory::getApplication()->input->set('html', $html);
} else {
header('Location: ' . $redirectUrl);
exit;
}
}
/**
* We are returning to the shop, returnUrl
*
* @param $html HTML string which couly be modified
* @param $paymentResponse response text to be printed
* @return bool|null|string
*/
public function plgVmOnPaymentResponseReceived(&$html, &$paymentResponse)
{
if (!class_exists('VirtueMartCart')) {
require(JPATH_VM_SITE . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'cart.php');
}
if (!class_exists('shopFunctionsF')) {
require(JPATH_VM_SITE . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'shopfunctionsf.php');
}
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'orders.php');
}
$input = new JInput;
// do iframe breakout
if ($input->get('iframebreakout') == 'true') {
print $this->renderByLayout('breakoutiframe', array(
'returnUrl' => JROUTE::_(JURI::root() .
'index.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived')
));
die;
}
$order_number = $input->get('vmOrderNumber');
$virtuemart_paymentmethod_id = $input->get('vmPaymentMethodId');
if (!($method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
return null; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($method->payment_element)) {
return null;
}
if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number))) {
$mainframe = JFactory::getApplication();
$mainframe->redirect(JRoute::_('index.php/cart'), $input->get('cosumerMessage', '', 'STRING'));
}
if (!($paymentTable = $this->getDataByOrderId($virtuemart_order_id))) {
return '';
}
$this->_setMethod($method);
$order = new VirtueMartModelOrders();
$order = $order->getOrder($virtuemart_order_id);
$this->_setOrder($order);
$this->logInfo(__FUNCTION__ . print_r($_POST, true), 'message');
$return = QentaCEE\QPay\ReturnFactory::getInstance($_POST, $this->_getSecret($method));
if (!$return->validate()) {
$paymentResponse = JText::_('VMPAYMENT_QENTACEECHECKOUT_INVALID_RESPONSE');
$mainframe = JFactory::getApplication();
$mainframe->redirect(JRoute::_('index.php/cart'), JText::_($paymentResponse));
}
$paymentState = $input->get('paymentState');
if ($paymentState == QentaCEE\QPay\ReturnFactory::STATE_PENDING ||
$paymentState == QentaCEE\QPay\ReturnFactory::STATE_SUCCESS
) {
$cart = VirtueMartCart::getCart();
$cart->emptyCart();
}
// C ... completed
// X ... cancelled
// R ... refunded
// S ... shipped
if (in_array($order['details']['BT']->order_status, array('C', 'X', 'R', 'S'))) {
$this->logInfo(__FUNCTION__ . ' Can\'t change order state, as the order has already a final state', 'message');
return true;
}
if ($paymentState == QentaCEE\QPay\ReturnFactory::STATE_PENDING) {
$modelOrder = VmModel::getModel('orders');
$order = array();
$order['order_status'] = $this->_getStatusPending();
$order['comments'] = JText::sprintf('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_STATUS_PENDING', $order_number);
$order['customer_notified'] = 0;
$modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true);
$paymentResponse = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_PENDING');
return true;
}
if ($paymentState == QentaCEE\QPay\ReturnFactory::STATE_FAILURE) {
$modelOrder = VmModel::getModel('orders');
$order = array();
$order['order_status'] = $this->_getStatusFailed();
$order['comments'] = JText::sprintf('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_STATUS_FAILED', $order_number, $return->getErrors()->getMessage());
$order['customer_notified'] = 0;
if ($this->_getMethod()->keep_unsuccessful_orders) {
$modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true);
} else {
$modelOrder->remove(array($virtuemart_order_id));
}
$paymentResponse = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_FAILED');
$mainframe = JFactory::getApplication();
$mainframe->redirect(JRoute::_('index.php/cart'), JText::_($paymentResponse));
}
// C ... completed
if ($order['details']['BT']->order_status == 'C') {
$paymentResponse = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_CONFIRMED');
}
$session = JFactory::getSession();
$data = $session->get('QENTACEECHECKOUT', 0, 'vm');
if (!empty($data)) {
$sessionQenta = unserialize($data);
$sessionQenta->consentInvoice = 'off';
$sessionQenta->consentInvoiceB2B = 'off';
$sessionQenta->consentInstallment = 'off';
$session->set('QENTACEECHECKOUT', serialize($sessionQenta), 'vm');
}
return true;
}
/**
* Payment notification received, server to server request, confirmUrl
*
* @return mixed Null when this method was not selected, otherwise the true or false
*
*/
public function plgVmOnPaymentNotification()
{
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'orders.php');
}
$input = new JInput;
$order_number = $input->get('vmOrderNumber');
$virtuemart_paymentmethod_id = $input->get('vmPaymentMethodId');
if (!($method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
$this->logInfo(__FUNCTION__ . ' Can\'t get payment type', 'message');
return null; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($method->payment_element)) {
return null;
}
if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number))) {
$this->logInfo(__FUNCTION__ . ' Can\'t get VirtueMart order id', 'message');
return null;
}
if (!($paymentTable = $this->getDataByOrderId($virtuemart_order_id))) {
$this->logInfo('getDataByOrderId payment not found: exit ', 'ERROR');
return null;
}
$this->_setMethod($method);
$order = VirtueMartModelOrders::getOrder($virtuemart_order_id);
$this->_setOrder($order);
// C ... completed
// X ... cancelled
// R ... refunded
// S ... shipped
if (in_array($order['details']['BT']->order_status, array('C', 'X', 'R', 'S'))) {
$this->logInfo(__FUNCTION__ . ' Can\'t change order state, as the order has already a final state', 'message');
return null;
}
$dbValues = array();
$dbValues['virtuemart_order_id'] = $virtuemart_order_id;
$dbValues['order_number'] = $order_number;
$dbValues['virtuemart_paymentmethod_id'] = $virtuemart_paymentmethod_id;
$dbValues['qenta_order_number'] = $input->get('orderNumber');
$dbValues['payment_name'] = parent::renderPluginName($method);
$dbValues['payment_order_total'] = $this->_getAmount($order);
$dbValues['payment_currency'] = $this->_getOrderCurrency();
$dbValues['qenta_gateway_ref'] = $input->get('gatewayReferenceNumber');
$dbValues['qenta_response_raw'] = serialize($_POST);
$this->storePSPluginInternalData($dbValues, 'virtuemart_order_id', false);
$modelOrder = VmModel::getModel('orders');
$order = array();
$order['customer_notified'] = 1;
$this->logInfo(__FUNCTION__ . print_r($_POST, true), 'message');
$message = null;
try {
$return = QentaCEE\QPay\ReturnFactory::getInstance($_POST, $this->_getSecret($method));
if (!$return->validate()) {
$order['order_status'] = $this->_getStatusFailed();
$message = $order['comments'] = JText::_('VMPAYMENT_QENTACEECHECKOUT_INVALID_RESPONSE');
}
$order['order_status'] = $method->status_pending;
$paymentState = $input->get('paymentState');
switch ($paymentState) {
case QentaCEE\QPay\ReturnFactory::STATE_SUCCESS:
$order['order_status'] = $this->_getStatusSuccess();
$order['comments'] = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_CONFIRMED');
break;
case QentaCEE\QPay\ReturnFactory::STATE_PENDING:
$order['order_status'] = $this->_getStatusPending();
$order['comments'] = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_PENDING');
break;
case QentaCEE\QPay\ReturnFactory::STATE_CANCEL:
$order['order_status'] = $this->_getStatusCancel();
$order['comments'] = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_CANCELLED');
break;
case QentaCEE\QPay\ReturnFactory::STATE_FAILURE:
$order['order_status'] = $this->_getStatusFailed();
$order['comments'] = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_FAILED');
break;
default:
break;
}
} catch (Exception $e) {
$this->logInfo(__FUNCTION__ . $e->getMessage(), 'error');
$order['order_status'] = $this->_getStatusFailed();
$order['comments'] = JText::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_FAILED');
$message = $e->getMessage();
}
if (!$this->_getMethod()->keep_unsuccessful_orders && ($order['order_status'] == $this->_getStatusFailed() || $order['order_status'] == $this->_getStatusCancel())) {
$modelOrder->remove(array($virtuemart_order_id));
} else {
$modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true);
}
echo QentaCEE\QPay\ReturnFactory::generateConfirmResponseString($message, true);
}
/**
* cancelUrl
* From the payment page, the user has cancelled the order. The order previousy created is deleted.
* The cart is not emptied, so the user can reorder if necessary.
*
*/
public function plgVmOnUserPaymentCancel()
{
if (!class_exists('VirtueMartCart')) {
require(JPATH_VM_SITE . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'cart.php');
}
if (!class_exists('shopFunctionsF')) {
require(JPATH_VM_SITE . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'shopfunctionsf.php');
}
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'orders.php');
}
$input = new JInput;
// do iframe breakout
if ($input->get('iframebreakout') == 'true') {
print $this->renderByLayout('breakoutiframe', array(
'returnUrl' => JROUTE::_(JURI::root() .
'index.php?option=com_virtuemart&view=pluginresponse&task=pluginUserPaymentCancel')
));
die;
}
$order_number = $input->get('vmOrderNumber');
$virtuemart_paymentmethod_id = $input->get('vmPaymentMethodId');
if (!($method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
return null; // Another method was selected, do nothing
}
if (empty($order_number) ||
!$this->selectedThisElement($method->payment_element)
) {
return null;
}
if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number))) {
return null;
}
if (!($paymentTable = $this->getDataByOrderId($virtuemart_order_id))) {
return '';
}
$this->_setMethod($method);
$order = VirtueMartModelOrders::getOrder($virtuemart_order_id);
$this->_setOrder($order);
VmInfo(Jtext::_('VMPAYMENT_QENTACEECHECKOUT_PAYMENT_CANCELLED'));
$this->handlePaymentUserCancel($virtuemart_order_id);
return true;
}
/**
* This is for adding the input data of the payment method to the cart, after selecting
*
* @param VirtueMartCart $cart
* @param $msg
* @return null if payment not selected; true if card infos are correct; string containing the errors id cc is not valid
*/
public function plgVmOnSelectCheckPayment(VirtueMartCart $cart, &$msg)
{
if (!$this->selectedThisByMethodId($cart->virtuemart_paymentmethod_id)) {
return null; // Another method was selected, do nothing
}
$method = $this->getVmPluginMethod($cart->virtuemart_paymentmethod_id);
$this->_setMethod($method);
$input = new JInput;
$paymenttype = $input->get('qenta_paymenttype');
$birthDay = $input->get('qcp_day');
$birthMonth = $input->get('qcp_month');
$birthYear = $input->get('qcp_year');
$consentInvoice = 'off';
$consentInvoiceB2B = 'off';
$consentInstallment = 'off';
switch ($paymenttype) {
case 'invoice':
$consentInvoice = $input->get('consent_invoice');
break;
case 'invoiceb2b':
$consentInvoiceB2B = $input->get('consent_invoiceb2b');
break;
case 'installment':
$consentInstallment = $input->get('consent_installment');
break;
}
$found = !strlen($paymenttype);
foreach ($this->_getEnabledPaymentTypes() as $m) {
if (strtolower($m['value']) == $paymenttype) {
$found = true;
break;
}
}
$session = JFactory::getSession();
$sessionQenta = new stdClass();
$sessionQenta->paymenttype = $paymenttype;
$sessionQenta->consentInvoice = $consentInvoice;
$sessionQenta->consentInvoiceB2B = $consentInvoiceB2B;
$sessionQenta->consentInstallment = $consentInstallment;
$sessionQenta->birthDay = $birthDay;
$sessionQenta->birthMonth = $birthMonth;
$sessionQenta->birthYear = $birthYear;
$session->set('QENTACEECHECKOUT', serialize($sessionQenta), 'vm');
if (!$found) {
$msg .= JText::_('VMPAYMENT_QENTACEECHECKOUT_ERROR_PAYMENTTYPE');
return false;
}
return true;
}
/**
* This is for checking the input data of the payment method within the checkout
*
* @param VirtueMartCart $cart
* @return null if payment not selected; true if card infos are correct;
*/
public function plgVmOnCheckoutCheckDataPayment(VirtueMartCart $cart)
{
$data = vRequest::getPost();
if(array_key_exists('qenta_paymenttype', $data)) {
$this->changePaymentTypeAjax($data);
}
if (!$this->selectedThisByMethodId($cart->virtuemart_paymentmethod_id)) {
return null; // Another method was selected, do nothing
}
$method = $this->getVmPluginMethod($cart->virtuemart_paymentmethod_id);
$this->_setMethod($method);
$session = JFactory::getSession();
$data = $session->get('QENTACEECHECKOUT', 0, 'vm');
if (empty($data))
return false;
$sessionQenta = unserialize($data);
$found = !strlen($sessionQenta->paymenttype);
foreach ($this->_getEnabledPaymentTypes() as $m) {
if (strtolower($m['value']) == $sessionQenta->paymenttype) {
$found = true;
break;
}
}
return $found;
}
/**
* Calculate the price (value, tax_id) of the selected method
*
* @param VirtueMartCart $cart
* @param array $cart_prices
* @param $cart_prices_name
* @return bool|null
*/
public function plgVmonSelectedCalculatePricePayment(VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name)
{
return $this->onSelectedCalculatePrice($cart, $cart_prices, $cart_prices_name);
}
/**
* Display stored payment data for an order
*
* @see components/com_virtuemart/helpers/vmPaymentPlugin::plgVmOnShowOrderPaymentBE()
*/
public function plgVmOnShowOrderBEPayment($virtuemart_order_id, $payment_method_id)
{
if (!$this->selectedThisByMethodId($payment_method_id)) {
return null; // Another method was selected, do nothing
}
if (!($paymentTable = $this->getDataByOrderId($virtuemart_order_id))) {
return null;
}
$data = unserialize($paymentTable->qenta_response_raw);
$blacklist = array('vmOrderNumber', 'vmPaymentMethodId', 'responseFingerprint', 'responseFingerprintOrder');
$html = '<table class="adminlist">' . "\n";
$html .= $this->getHtmlHeaderBE();
$html .= $this->getHtmlRowBE('QENTACEECHECKOUT_NAME', $paymentTable->payment_name);
foreach ($data as $key => $value) {
if (in_array($key, $blacklist))
continue;
$html .= str_replace("QENTACEECHECKOUT_", "", $this->getHtmlRowBE("QENTACEECHECKOUT_$key", $value));
}
$html .= '</table>' . "\n";
return $html;
}
/**
* plgVmDisplayListFEPayment
* This event is fired to display the plugin methods in the cart (edit shipment/payment) for example
*
* @param VirtueMartCart $cart Cart object
* @param integer $selected ID of the method selected
* @param string $htmlIn HTML
* @return boolean True on success, false on failures, null when this plugin was not selected.
*
* @author Valerie Isaksen
*/
public function plgVmDisplayListFEPayment(VirtueMartCart $cart, $selected = 0, &$htmlIn)
{
return $this->displayListFE($cart, $selected, $htmlIn);
}
/**
* This method is fired when showing when priting an Order
* It displays the the payment method-specific data.
* XXX never invoked by virtuemart
*
* @param integer $order_number The order number
* @param integer $method_id method used for this order
* @return mixed Null when for payment methods that were not selected, text (HTML) otherwise
* @author Valerie Isaksen
*/
public function plgVmonShowOrderPrintPayment($order_number, $method_id)
{
$html = $this->onShowOrderPrint($order_number, $method_id);
return $html;
}
/**
* Create the table for this plugin if it does not yet exist.
* This functions checks if the called plugin is active one.
* When yes it is calling the standard method to create the tables
*
* @author QENTA Payment CEE
*
*/
public function plgVmOnStoreInstallPaymentPluginTable($jplugin_id)
{
return $this->onStoreInstallPluginTable($jplugin_id);
}
public function plgVmDeclarePluginParamsPayment($name, $id, &$data)
{
return $this->declarePluginParams('payment', $name, $id, $data);
}
public function plgVmSetOnTablePluginParamsPayment($name, $id, &$table)
{
return $this->setOnTablePluginParams($name, $id, $table);
}
public function plgVmDeclarePluginParamsPaymentVM3(&$data)
{
return $this->declarePluginParams('payment', $data);
}
######################################################################
# PROTECTED METHODS #
######################################################################
/**
* Check if the payment conditions are fulfilled for this payment method
* If false, payment method is not selectable
* Always return true in our case, because we are managing many paymenttypes with this plugin
*
* @param $cart cart
* @param $method
* @param $cart_prices
* @return true: if the conditions are fulfilled, false otherwise
*
*/
protected function checkConditions($cart, $method, $cart_prices)
{
return true;
}
/**
* Render the enabled paymenttypes
*
* @param $plugin
* @param $selectedPlugin
* @param $pluginSalesPrice
* @return string
*/
protected function getPluginHtml($plugin, $selectedPlugin, $pluginSalesPrice)
{
$this->_setMethod($plugin);
$pluginmethod_id = $this->_idName;
$session = JFactory::getSession();
$data = $session->get('QENTACEECHECKOUT', 0, 'vm');
if (empty($data) || $selectedPlugin != $plugin->$pluginmethod_id ) {
$paymenttype_selected = null;
$birthDay = '0';
$birthMonth = '0';
$birthYear = '0';
} else {
$sessionQenta = unserialize($data);
$paymenttype_selected = $sessionQenta->paymenttype;
$birthDay = $sessionQenta->birthDay;
$birthMonth = $sessionQenta->birthMonth;
$birthYear = $sessionQenta->birthYear;
}
$ratepay = "";
if (((int)$this->_getMethod()->paymenttype_invoice == 1 && $this->_getInvoiceFinancialInstitution() == "ratepay") ||
((int)$this->_getMethod()->paymenttype_installment == 1 && $this->_getInstallmentFinancialInstitution() == "ratepay")) {
$customer_id = $this->_getCustomerId();
if (isset($_SESSION['qcp-consumerDeviceId'])) {
$consumerDeviceId = $_SESSION['qcp-consumerDeviceId'];
} else {
$timestamp = microtime();
$consumerDeviceId = md5( $customer_id . "_" . $timestamp );
$_SESSION['qcp-consumerDeviceId'] = $consumerDeviceId;
}
$ratepay = '<script language="JavaScript">var di = {t:"' . $consumerDeviceId . '",v:"WDWL",l:"Checkout"};</script>';
$ratepay .= '<script type="text/javascript" src="//d.ratepay.com/' . $consumerDeviceId . '/di.js"></script>';
$ratepay .= '<noscript><link rel="stylesheet" type="text/css" href="//d.ratepay.com/di.css?t=' . $consumerDeviceId . '&v=WDWL&l=Checkout"></noscript>';
$ratepay .= '<object type="application/x-shockwave-flash" data="//d.ratepay.com/WDWL/c.swf" width="0" height="0"><param name="movie" value="//d.ratepay.com/WDWL/c.swf" /><param name="flashvars" value="t=' . $consumerDeviceId . '&v=WDWL"/><param name="AllowScriptAccess" value="always"/></object>';
}
$html = $this->renderByLayout('displaypayment', array(
'paymenttypes' => $this->_getEnabledPaymentTypes(),
'paymentmethod_id' => $plugin->$pluginmethod_id,
'paymenttype_selected' => $paymenttype_selected,
'birth_day' => $birthDay,
'birth_month' => $birthMonth,
'birth_year' => $birthYear,
'ratepay_script' => $ratepay
));
return $html;
}
/**
* Initiate Payment
*
* @param VirtueMartCart $cart
* @return string Url to be redirected
* @throws Exception
*/
protected function _initiatePayment($cart)
{
try {
$order = $this->_getOrder();
$client = new QentaCEE\QPay\FrontendClient(array(
'CUSTOMER_ID' => $this->_getCustomerId(),
'SHOP_ID' => $this->_getShopId(),
'SECRET' => $this->_getSecret(),
'LANGUAGE' => $this->_getLanguage()
));
$session = JFactory::getSession();
$data = $session->get('QENTACEECHECKOUT', null, 'vm');
$sessionQenta = unserialize($data);
/**
* If only one payment plugin is published, then selection of payment methods within QPay checkout page
* is not possible. Thus a default has to be used.
*/
if(!$sessionQenta->paymenttype) {
$sessionQenta->paymenttype = 'SELECT';
}
$paymentType = strtoupper($sessionQenta->paymenttype);
if ($paymentType == QentaCEE\QPay\PaymentType::INVOICE . 'B2B') {
$paymentType = QentaCEE\QPay\PaymentType::INVOICE;
}
// consumer data (IP and User agent) are mandatory!
$consumerData = new QentaCEE\Stdlib\ConsumerData();
$consumerData->setUserAgent($_SERVER['HTTP_USER_AGENT'])
->setIpAddress($_SERVER['REMOTE_ADDR']);
if ($this->_sendShippingInformation()
|| ($paymentType == QentaCEE\QPay\PaymentType::INVOICE && $this->_getMethod()->invoice_provider != 'payolution')
|| ($paymentType == QentaCEE\QPay\PaymentType::INSTALLMENT && $this->_getMethod()->installment_provider != 'payolution')
) {
$this->_setConsumerShippingInformation($consumerData);
}
if ($this->_sendBillingInformation() || in_array($paymentType, array(QentaCEE\QPay\PaymentType::INVOICE, QentaCEE\QPay\PaymentType::INSTALLMENT))) {
$this->_setConsumerBillingInformation($consumerData);
}
if ($this->_sendBasketInformation()
|| ($paymentType == QentaCEE\QPay\PaymentType::INVOICE && $this->_getMethod()->invoice_provider != 'payolution')
|| ($paymentType == QentaCEE\QPay\PaymentType::INSTALLMENT && $this->_getMethod()->installment_provider != 'payolution')
) {
$client->setBasket($this->_generateBasketInformation($cart));
}
$returnUrl = JROUTE::_(JURI::root() .
'index.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived' .
'&iframebreakout=' . ($this->_useIFrame() ? 'true' : 'false') .
'&Itemid=' . JFactory::getApplication()->input->getInt('Itemid'));
$cancelURL = JROUTE::_(JURI::root() .
'index.php?option=com_virtuemart&view=pluginresponse&task=pluginUserPaymentCancel' .
'&iframebreakout=' . ($this->_useIFrame() ? 'true' : 'false') .
'&Itemid=' . JFactory::getApplication()->input->getInt('Itemid')
);
$confirmUrl = JROUTE::_(JURI::root() . 'index.php?option=com_virtuemart&view=pluginresponse&task=pluginnotification&tmpl=component');
$version = QentaCEE\QPay\FrontendClient::generatePluginVersion(
$this->_getVendor(),
VmConfig::getInstalledVersion(),
self::$PLUGIN_NAME,
self::$PLUGIN_VERSION);
$client->setAmount($this->_getAmount())
->setCurrency($this->_getOrderCurrency())
->setPaymentType($paymentType)
->setOrderDescription($this->_getOrderDescription())
->setPluginVersion($version)
->setSuccessUrl($returnUrl)
->setPendingUrl($returnUrl)
->setCancelUrl($cancelURL)
->setFailureUrl($returnUrl)
->setConfirmUrl($confirmUrl)
->setServiceUrl($this->_getServiceUrl())
->setImageUrl($this->_getImageUrl())
->setBackgroundColor($this->_getBackgroundColor())
->setConsumerData($consumerData)
->setDisplayText($this->_getDisplayText())
->setCustomerStatement($this->_getCustomerStatement($paymentType, $this->_getMethod()->shopname))
->setDuplicateRequestCheck($this->_getDuplicateRequestCheck())
->setMaxRetries($this->_getMaxRetries())
->setAutoDeposit($this->_getAutoDeposit($paymentType))
->setWindowName($this->_getWindowName());
if ( isset( $_SESSION['qcp-consumerDeviceId'] ) ){
$client->consumerDeviceId = $_SESSION['qcp-consumerDeviceId'];
unset( $_SESSION['qcp-consumerDeviceId'] );
}
if ($paymentType == QentaCEE\QPay\PaymentType::MASTERPASS) {
$client->setShippingProfile('NO_SHIPPING');
}
if ($paymentType == QentaCEE\QPay\PaymentType::IDL) {
if (isset($_POST['financialInstitution_idl'])) {
$client->setFinancialInstitution($_POST['financialInstitution_idl']);
} else {
$client->setFinancialInstitution($sessionQenta->additional["financialInstitution_idl"]);
}
} else if ($paymentType == QentaCEE\QPay\PaymentType::EPS) {
if (isset($_POST['financialInstitution_eps'])) {
$client->setFinancialInstitution($_POST['financialInstitution_eps']);
} else {
$client->setFinancialInstitution($sessionQenta->additional["financialInstitution_eps"]);
}
}
if (array_key_exists('ST', $order['details'])) {
$client->createConsumerMerchantCrmId($order['details']['ST']->email);
}
else {
$client->createConsumerMerchantCrmId($order['details']['BT']->email);
}
if ($this->_sendConfirmationEmail()) {
$client->setConfirmMail($this->_getConfirmMail());
}
$client->vmOrderNumber = $order['details']['BT']->order_number;
$client->vmPaymentMethodId = $order['details']['BT']->virtuemart_paymentmethod_id;
$response = $client->initiate();
if ($response->hasFailed()) {
vmError(JText::_("Response failed! Error: {$response->getError()->getMessage()}"));
//throw new \Exception("Response failed! Error: {$response->getError()->getMessage()}", 500);
}
} catch (Exception $e) {
$sErrorMessage = "Initialization failed with exception: {$e->getMessage()}";
throw($e);
}
return $response->getRedirectUrl();
}
/**