-
Notifications
You must be signed in to change notification settings - Fork 7
/
PaymentController.php
executable file
·656 lines (592 loc) · 19.5 KB
/
PaymentController.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
<?php
/**
* Veritrans VT Web Payment Controller
*
* @category Mage
* @package Mage_Veritrans_snap_PaymentController
* @author Kisman Hong (plihplih.com), Ismail Faruqi (@ifaruqi_jpn)
* This class is used for handle redirection after placing order.
* function redirectAction -> redirecting to Veritrans VT Web
* function responseAction -> when payment at Veritrans VT Web is completed or
* failed, the page will be redirected to this function,
* you must set this url in your Veritrans MAP merchant account.
* http://yoursite.com/snap/payment/notification
*/
require_once(Mage::getBaseDir('lib') . '/veritrans-php/Veritrans.php');
class Midtrans_Snap_PaymentController
extends Mage_Core_Controller_Front_Action {
/**
* @return Mage_Checkout_Model_Session
*/
protected function _getCheckout() {
return Mage::getSingleton('checkout/session');
}
// The redirect action is triggered when someone places an order,
// redirecting to Veritrans payment page.
public function redirectAction() {
$orderIncrementId = $this->_getCheckout()->getLastRealOrderId();
$order = Mage::getModel('sales/order')
->loadByIncrementId($orderIncrementId);
$sessionId = Mage::getSingleton('core/session');
/* send an order email when redirecting to payment page although payment
has not been completed. */
/*$order->setState(Mage::getStoreConfig('payment/snap/'),true,
'New order, waiting for payment.');
$order->sendNewOrderEmail();
$order->setEmailSent(true);*/
$payment_type = Mage::getStoreConfig('payment/snap/payment_types');
Veritrans_Config::$isProduction =
Mage::getStoreConfig('payment/snap/environment') == 'production'
? true : false;
Veritrans_Config::$serverKey =
Mage::getStoreConfig('payment/snap/server_key');
Veritrans_Config::$is3ds =
Mage::getStoreConfig('payment/snap/enable_3d_secure') == '1'
? true : false;
Veritrans_Config::$isSanitized = true;
Mage::log($mixpanel_key.Veritrans_Config::$isProduction,null,'snap.log',true);
$transaction_details = array();
$transaction_details['order_id'] = $orderIncrementId;
$order_billing_address = $order->getBillingAddress();
$billing_address = array();
$billing_address['first_name'] = $order_billing_address->getFirstname();
$billing_address['last_name'] = $order_billing_address->getLastname();
$billing_address['address'] = $order_billing_address->getStreet(1);
$billing_address['city'] = $order_billing_address->getCity();
$billing_address['postal_code'] = $order_billing_address->getPostcode();
$billing_address['country_code'] = $this->convert_country_code($order_billing_address->getCountry());
$billing_address['phone'] = $order_billing_address->getTelephone();
$order_shipping_address = $order->getShippingAddress();
$shipping_address = array();
$shipping_address['first_name'] = $order_shipping_address->getFirstname();
$shipping_address['last_name'] = $order_shipping_address->getLastname();
$shipping_address['address'] = $order_shipping_address->getStreet(1);
$shipping_address['city'] = $order_shipping_address->getCity();
$shipping_address['postal_code'] = $order_shipping_address->getPostcode();
$shipping_address['phone'] = $order_shipping_address->getTelephone();
$shipping_address['country_code'] =
$this->convert_country_code($order_shipping_address->getCountry());
$customer_details = array();
$customer_details['billing_address'] = $billing_address;
$customer_details['shipping_address'] = $shipping_address;
$customer_details['first_name'] = $order_billing_address
->getFirstname();
$customer_details['last_name'] = $order_billing_address
->getLastname();
$customer_details['email'] = $order_billing_address->getEmail();
$customer_details['phone'] = $order_billing_address
->getTelephone();
$items = $order->getAllItems();
$shipping_amount = $order->getShippingAmount();
$shipping_tax_amount = $order->getShippingTaxAmount();
$tax_amount = $order->getTaxAmount();
$item_details = array();
foreach ($items as $each) {
$item = array(
'id' => $each->getProductId(),
'price' => $each->getPrice(),
'quantity' => $each->getQtyToInvoice(),
'name' => $each->getName()
);
if ($item['quantity'] == 0) continue;
// error_log(print_r($each->getProductOptions(), true));
$item_details[] = $item;
}
$num_products = count($item_details);
unset($each);
if ($order->getDiscountAmount() != 0) {
$couponItem = array(
'id' => 'DISCOUNT',
'price' => $order->getDiscountAmount(),
'quantity' => 1,
'name' => 'DISCOUNT'
);
$item_details[] = $couponItem;
}
if ($shipping_amount > 0) {
$shipping_item = array(
'id' => 'SHIPPING',
'price' => $shipping_amount,
'quantity' => 1,
'name' => 'Shipping Cost'
);
$item_details[] =$shipping_item;
}
if ($shipping_tax_amount > 0) {
$shipping_tax_item = array(
'id' => 'SHIPPING_TAX',
'price' => $shipping_tax_amount,
'quantity' => 1,
'name' => 'Shipping Tax'
);
$item_details[] = $shipping_tax_item;
}
if ($tax_amount > 0) {
$tax_item = array(
'id' => 'TAX',
'price' => $tax_amount,
'quantity' => 1,
'name' => 'Tax'
);
$item_details[] = $tax_item;
}
// convert to IDR
$current_currency = Mage::app()->getStore()->getCurrentCurrencyCode();
if ($current_currency != 'IDR') {
$conversion_func = function ($non_idr_price) {
return $non_idr_price *
Mage::getStoreConfig('payment/snap/conversion_rate');
};
foreach ($item_details as &$item) {
$item['price'] =
intval(round(call_user_func($conversion_func, $item['price'])));
}
unset($item);
}
else {
foreach ($item_details as &$each) {
$each['price'] = (int) $each['price'];
}
unset($each);
}
$credit_card['secure'] = true;
$credit_card['save_card'] = true;
$payloads = array();
$payloads['transaction_details'] = $transaction_details;
$payloads['item_details'] = $item_details;
$payloads['customer_details'] = $customer_details;
if(Mage::getStoreConfig('payment/snap/oneclick') == 1){
$payloads['credit_card'] = $credit_card;
//$payloads['user_id'] = crypt($order_billing_address->getEmail(), $serverKey);
$payloads['user_id'] = hash('sha256' , $order_billing_address->getEmail());
}
$expire = explode(",", Mage::getStoreConfig('payment/snap/expiry'));
$expiry_unit = $expire[1];
$expiry_duration = (int)$expire[0];
error_log($expiry_unit . $expiry_duration);
if (!empty($expiry_unit) && !empty($expiry_duration)){
$time = time();
$payloads['expiry'] = array(
'start_time' => date("Y-m-d H:i:s O",$time),
'unit' => $expiry_unit,
'duration' => (int)$expiry_duration
);
}
$totalPrice = 0;
foreach ($item_details as $item) {
$totalPrice += $item['price'] * $item['quantity'];
}
Mage::log(json_encode($payloads),null,'snap.log',true);
try {
$redirUrl = Veritrans_Snap::getSnapToken($payloads);
//Mage::log('debug:'.print_r($payloads,true),null,'snap.log',true);
Mage::log('snap token from controller = '.$redirUrl,null,'snap.log',true);
$this->_getCheckout()->setToken($redirUrl);
$this->_getCheckout()->setEnv(Mage::getStoreConfig('payment/snap/environment'));
//$this->_redirectUrl(Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . 'snap/payment/open');
foreach( Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item ){
Mage::getSingleton('checkout/cart')->removeItem( $item->getId() )->save();
}
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl().'snap/payment/opensnap');
//remove item
}
catch (Exception $e) {
error_log($e->getMessage());
Mage::log('error:'.print_r($e->getMessage(),true),null,'snap.log',true);
}
}
public function opensnapAction(){
$template = 'snap/open.phtml';
//Get current layout state
$this->loadLayout();
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'snap',
array('template' => $template)
);
$this->getLayout()->getBlock('root')->setTemplate('page/1column.phtml');
$this->getLayout()->getBlock('content')->append($block);
$this->_initLayoutMessages('core/session');
$this->renderLayout();
}
// The response action is triggered when your gateway sends back a response
// after processing the customer's payment, we will not update to success
// because success is valid when notification (security reason)
public function responseAction() {
//var_dump($_POST); use for debugging value.
if($_GET['order_id']) {
$orderId = $_GET['order_id']; // Generally sent by gateway
$status = $_GET['status_code'];
if($status == '200' || $status == '201' && !is_null($orderId) && $orderId != '') {
// Redirected by Veritrans, if ok
Mage::getSingleton('checkout/session')->unsQuoteId();
Mage_Core_Controller_Varien_Action::_redirect(
'checkout/onepage/success', array('_secure'=>false));
}
else {
// There is a problem in the response we got
$this->cancelAction();
Mage_Core_Controller_Varien_Action::_redirect(
'checkout/onepage/failure', array('_secure'=>true));
}
}
else{
Mage_Core_Controller_Varien_Action::_redirect('');
}
}
// Response early with 200 OK status for Midtrans notification & handle HTTP GET
public function earlyResponse(){
if ( $_SERVER['REQUEST_METHOD'] == 'GET' ){
die('This endpoint should not be opened using browser (HTTP GET). This endpoint is for Midtrans notification URL (HTTP POST)');
exit();
}
ob_start();
$input_source = "php://input";
$raw_notification = json_decode(file_get_contents($input_source), true);
echo "Notification Received: \n";
print_r($raw_notification);
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();
}
// Veritrans will send notification of the payment status, this is only way we
// make sure that the payment is successed, if success send the item(s) to
// customer :p
public function notificationAction() {
//echo "hahaha";
error_log('payment notification');
Veritrans_Config::$isProduction =
Mage::getStoreConfig('payment/snap/environment') == 'production' ? true : false;
Veritrans_Config::$serverKey = Mage::getStoreConfig('payment/snap/server_key');
$this->earlyResponse();
$notif = new Veritrans_Notification();
Mage::log('get status result'.print_r($notif,true),null,'snap.log',true);
$order = Mage::getModel('sales/order');
$order->loadByIncrementId($notif->order_id);
$transaction = $notif->transaction_status;
$fraud = $notif->fraud_status;
$payment_type = $notif->payment_type;
if ($transaction == 'capture') {
if ($fraud == 'challenge') {
$order->setStatus(Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW);
}
else if ($fraud == 'accept') {
$invoice = $order->prepareInvoice()
->setTransactionId($order->getId())
->addComment('Payment successfully processed by Midtrans.')
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
$order->setStatus(Mage_Sales_Model_Order::STATE_PROCESSING);
$order->sendOrderUpdateEmail(true,
'Thank you, your payment is successfully processed.');
}
}
else if ($transaction == 'settlement') {
if($payment_type != 'credit_card'){
$invoice = $order->prepareInvoice()
->setTransactionId($order->getId())
->addComment('Payment successfully processed by Midtrans.')
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
$order->setStatus(Mage_Sales_Model_Order::STATE_PROCESSING);
$order->sendOrderUpdateEmail(true,
'Thank you, your payment is successfully processed.');
}
}
else if ($transaction == 'pending') {
$order->setStatus(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT);
$order->sendOrderUpdateEmail(true,
'Thank you, your payment is successfully processed.');
}
else if ($transaction == 'cancel' || $transaction == 'deny' || $transaction == 'expire') {
if ($order->canCancel()) {
$order->cancel();
$order->setStatus(Mage_Sales_Model_Order::STATE_CANCELED);
$order->setState(Mage_Sales_Model_Order::STATE_CANCELED,true, 'Gateway has Notif Failure Transaction.');
}
}
$order->save();
}
// The cancel action is triggered when an order is to be cancelled
public function cancelAction() {
if (Mage::getSingleton('checkout/session')->getLastRealOrderId()) {
$order = Mage::getModel('sales/order')->loadByIncrementId(
Mage::getSingleton('checkout/session')->getLastRealOrderId());
if($order->getId()) {
// Flag the order as 'cancelled' and save it
$order->cancel()->setState(Mage_Sales_Model_Order::STATE_CANCELED,
true, 'Gateway has declined the payment.')->save();
}
}
}
/**
* Convert 2 digits coundry code to 3 digit country code
*
* @param String $country_code Country code which will be converted
*/
public function convert_country_code( $country_code ) {
// 3 digits country codes
$cc_three = array(
'AF' => 'AFG',
'AX' => 'ALA',
'AL' => 'ALB',
'DZ' => 'DZA',
'AD' => 'AND',
'AO' => 'AGO',
'AI' => 'AIA',
'AQ' => 'ATA',
'AG' => 'ATG',
'AR' => 'ARG',
'AM' => 'ARM',
'AW' => 'ABW',
'AU' => 'AUS',
'AT' => 'AUT',
'AZ' => 'AZE',
'BS' => 'BHS',
'BH' => 'BHR',
'BD' => 'BGD',
'BB' => 'BRB',
'BY' => 'BLR',
'BE' => 'BEL',
'PW' => 'PLW',
'BZ' => 'BLZ',
'BJ' => 'BEN',
'BM' => 'BMU',
'BT' => 'BTN',
'BO' => 'BOL',
'BQ' => 'BES',
'BA' => 'BIH',
'BW' => 'BWA',
'BV' => 'BVT',
'BR' => 'BRA',
'IO' => 'IOT',
'VG' => 'VGB',
'BN' => 'BRN',
'BG' => 'BGR',
'BF' => 'BFA',
'BI' => 'BDI',
'KH' => 'KHM',
'CM' => 'CMR',
'CA' => 'CAN',
'CV' => 'CPV',
'KY' => 'CYM',
'CF' => 'CAF',
'TD' => 'TCD',
'CL' => 'CHL',
'CN' => 'CHN',
'CX' => 'CXR',
'CC' => 'CCK',
'CO' => 'COL',
'KM' => 'COM',
'CG' => 'COG',
'CD' => 'COD',
'CK' => 'COK',
'CR' => 'CRI',
'HR' => 'HRV',
'CU' => 'CUB',
'CW' => 'CUW',
'CY' => 'CYP',
'CZ' => 'CZE',
'DK' => 'DNK',
'DJ' => 'DJI',
'DM' => 'DMA',
'DO' => 'DOM',
'EC' => 'ECU',
'EG' => 'EGY',
'SV' => 'SLV',
'GQ' => 'GNQ',
'ER' => 'ERI',
'EE' => 'EST',
'ET' => 'ETH',
'FK' => 'FLK',
'FO' => 'FRO',
'FJ' => 'FJI',
'FI' => 'FIN',
'FR' => 'FRA',
'GF' => 'GUF',
'PF' => 'PYF',
'TF' => 'ATF',
'GA' => 'GAB',
'GM' => 'GMB',
'GE' => 'GEO',
'DE' => 'DEU',
'GH' => 'GHA',
'GI' => 'GIB',
'GR' => 'GRC',
'GL' => 'GRL',
'GD' => 'GRD',
'GP' => 'GLP',
'GT' => 'GTM',
'GG' => 'GGY',
'GN' => 'GIN',
'GW' => 'GNB',
'GY' => 'GUY',
'HT' => 'HTI',
'HM' => 'HMD',
'HN' => 'HND',
'HK' => 'HKG',
'HU' => 'HUN',
'IS' => 'ISL',
'IN' => 'IND',
'ID' => 'IDN',
'IR' => 'RIN',
'IQ' => 'IRQ',
'IE' => 'IRL',
'IM' => 'IMN',
'IL' => 'ISR',
'IT' => 'ITA',
'CI' => 'CIV',
'JM' => 'JAM',
'JP' => 'JPN',
'JE' => 'JEY',
'JO' => 'JOR',
'KZ' => 'KAZ',
'KE' => 'KEN',
'KI' => 'KIR',
'KW' => 'KWT',
'KG' => 'KGZ',
'LA' => 'LAO',
'LV' => 'LVA',
'LB' => 'LBN',
'LS' => 'LSO',
'LR' => 'LBR',
'LY' => 'LBY',
'LI' => 'LIE',
'LT' => 'LTU',
'LU' => 'LUX',
'MO' => 'MAC',
'MK' => 'MKD',
'MG' => 'MDG',
'MW' => 'MWI',
'MY' => 'MYS',
'MV' => 'MDV',
'ML' => 'MLI',
'MT' => 'MLT',
'MH' => 'MHL',
'MQ' => 'MTQ',
'MR' => 'MRT',
'MU' => 'MUS',
'YT' => 'MYT',
'MX' => 'MEX',
'FM' => 'FSM',
'MD' => 'MDA',
'MC' => 'MCO',
'MN' => 'MNG',
'ME' => 'MNE',
'MS' => 'MSR',
'MA' => 'MAR',
'MZ' => 'MOZ',
'MM' => 'MMR',
'NA' => 'NAM',
'NR' => 'NRU',
'NP' => 'NPL',
'NL' => 'NLD',
'AN' => 'ANT',
'NC' => 'NCL',
'NZ' => 'NZL',
'NI' => 'NIC',
'NE' => 'NER',
'NG' => 'NGA',
'NU' => 'NIU',
'NF' => 'NFK',
'KP' => 'MNP',
'NO' => 'NOR',
'OM' => 'OMN',
'PK' => 'PAK',
'PS' => 'PSE',
'PA' => 'PAN',
'PG' => 'PNG',
'PY' => 'PRY',
'PE' => 'PER',
'PH' => 'PHL',
'PN' => 'PCN',
'PL' => 'POL',
'PT' => 'PRT',
'QA' => 'QAT',
'RE' => 'REU',
'RO' => 'SHN',
'RU' => 'RUS',
'RW' => 'EWA',
'BL' => 'BLM',
'SH' => 'SHN',
'KN' => 'KNA',
'LC' => 'LCA',
'MF' => 'MAF',
'SX' => 'SXM',
'PM' => 'SPM',
'VC' => 'VCT',
'SM' => 'SMR',
'ST' => 'STP',
'SA' => 'SAU',
'SN' => 'SEN',
'RS' => 'SRB',
'SC' => 'SYC',
'SL' => 'SLE',
'SG' => 'SGP',
'SK' => 'SVK',
'SI' => 'SVN',
'SB' => 'SLB',
'SO' => 'SOM',
'ZA' => 'ZAF',
'GS' => 'SGS',
'KR' => 'KOR',
'SS' => 'SSD',
'ES' => 'ESP',
'LK' => 'LKA',
'SD' => 'SDN',
'SR' => 'SUR',
'SJ' => 'SJM',
'SZ' => 'SWZ',
'SE' => 'SWE',
'CH' => 'CHE',
'SY' => 'SYR',
'TW' => 'TWN',
'TJ' => 'TJK',
'TZ' => 'TZA',
'TH' => 'THA',
'TL' => 'TLS',
'TG' => 'TGO',
'TK' => 'TKL',
'TO' => 'TON',
'TT' => 'TTO',
'TN' => 'TUN',
'TR' => 'TUR',
'TM' => 'TKM',
'TC' => 'TCA',
'TV' => 'TUV',
'UG' => 'UGA',
'UA' => 'UKR',
'AE' => 'ARE',
'GB' => 'GBR',
'US' => 'USA',
'UY' => 'URY',
'UZ' => 'UZB',
'VU' => 'VUT',
'VA' => 'VAT',
'VE' => 'VEN',
'VN' => 'VNM',
'WF' => 'WLF',
'EH' => 'ESH',
'WS' => 'WSM',
'YE' => 'YEM',
'ZM' => 'ZMB',
'ZW' => 'ZWE'
);
// Check if country code exists
if( isset( $cc_three[ $country_code ] ) && $cc_three[ $country_code ] != '' ) {
$country_code = $cc_three[ $country_code ];
}
return $country_code;
}
}
?>