Payair_gate - Version 4.0.0.23

Version Notes

All issues fixed.

Download this release

Release Info

Developer vikas
Extension Payair_gate
Version 4.0.0.23
Comparing to
See all releases


Version 4.0.0.23

Files changed (27) hide show
  1. app/code/community/Payair/Gate/Block/Paycheckout.php +18 -0
  2. app/code/community/Payair/Gate/Block/Paymentjs.php +22 -0
  3. app/code/community/Payair/Gate/Block/Payproduct.php +50 -0
  4. app/code/community/Payair/Gate/Helper/Data.php +76 -0
  5. app/code/community/Payair/Gate/Model/Checkout.php +328 -0
  6. app/code/community/Payair/Gate/Model/Display.php +13 -0
  7. app/code/community/Payair/Gate/Model/Environment.php +14 -0
  8. app/code/community/Payair/Gate/Model/Observer.php +37 -0
  9. app/code/community/Payair/Gate/Model/Order/Api.php +113 -0
  10. app/code/community/Payair/Gate/Model/Order/Api/V2.php +10 -0
  11. app/code/community/Payair/Gate/Model/Payair.php +93 -0
  12. app/code/community/Payair/Gate/Model/RestConnect_Model_Oauth_Client.php +228 -0
  13. app/code/community/Payair/Gate/controllers/IndexController.php +1617 -0
  14. app/code/community/Payair/Gate/etc/config.xml +63 -0
  15. app/code/community/Payair/Gate/etc/system.xml +114 -0
  16. app/design/frontend/default/default/layout/payair.xml +33 -0
  17. app/design/frontend/default/default/template/gate/button.phtml +31 -0
  18. app/design/frontend/default/default/template/gate/checkout.phtml +231 -0
  19. app/design/frontend/default/default/template/gate/product.phtml +49 -0
  20. app/etc/modules/Payair_Adminhtml.xml +9 -0
  21. app/etc/modules/Payair_Gate.xml +12 -0
  22. media/payair/android_video_thumb_small.png +0 -0
  23. media/payair/express_checkout_banner_v3.png +0 -0
  24. media/payair/express_checkout_bg_383.png +0 -0
  25. package.xml +18 -0
  26. skin/frontend/default/default/css/payair.css +69 -0
  27. skin/frontend/default/default/js/payair/payaircheckout.js +54 -0
app/code/community/Payair/Gate/Block/Paycheckout.php ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ Created By : PayAir Team
4
+ Funnction : Payair_Gate_Block_Paycheckout Class to extend the Mage_Core_Block_Template, prepare layout and return html for payair checkout
5
+ */
6
+
7
+ class Payair_Gate_Block_Paycheckout extends Mage_Core_Block_Template {
8
+
9
+ protected function _toHtml() {
10
+ $html = parent::_toHtml();
11
+
12
+ return $html;
13
+ }
14
+
15
+ protected function _prepareLayout() {
16
+ return parent::_prepareLayout();
17
+ }
18
+ }
app/code/community/Payair/Gate/Block/Paymentjs.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ Created By : PayAir Team
4
+ Funnction : Payair_Gate_Block_Paymentjs Class to extend the Mage_Core_Block_Template, return checkout javascript for payair checkout
5
+ */
6
+
7
+ class Payair_Gate_Block_Paymentjs extends Mage_Core_Block_Template
8
+ {
9
+ /**
10
+ * Function return the checkout javascript
11
+ */
12
+
13
+ protected function _toHtml() {
14
+ $js = '<script type="text/javascript" src="'.$this->getSkinUrl("js/payair/payaircheckout.js").'"></script>';
15
+
16
+ return $js;
17
+ }
18
+
19
+ protected function _prepareLayout() {
20
+ return parent::_prepareLayout();
21
+ }
22
+ }
app/code/community/Payair/Gate/Block/Payproduct.php ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magentocommerce.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magentocommerce.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Adminhtml
23
+ * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ class Payair_Gate_Block_Payproduct extends Mage_Core_Block_Template
28
+ {
29
+ protected function _toHtml()
30
+ {
31
+ $html = parent::_toHtml();
32
+ return $html;
33
+ }
34
+
35
+ protected function _prepareLayout()
36
+ {
37
+ return parent::_prepareLayout();
38
+ }
39
+
40
+ public function chooseTemplate()
41
+ {
42
+ $method_display_type = Mage::getStoreConfig('payment/gate/display_method');
43
+ if ($method_display_type == 'banner') {
44
+ $this->setTemplate($this->getBannerTemplate());
45
+ } elseif ($method_display_type == 'button') {
46
+ $this->setTemplate($this->getButtonTemplate());
47
+ }
48
+ }
49
+
50
+ }
app/code/community/Payair/Gate/Helper/Data.php ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ Created By : PayAir Team
4
+ Funnction : Payair_Gate_Helper_Data Class to extend the Mage_Core_Helper_Abstract, to to check if the remote image is ready to load in the dom
5
+ */
6
+
7
+ class Payair_Gate_Helper_Data extends Mage_Core_Helper_Abstract
8
+ {
9
+ /**
10
+ * Function to check if the remote image is ready to load in the dom
11
+ */
12
+
13
+ public function is_remote_image_ready($image_url) {
14
+ $ch = curl_init($image_url);
15
+ curl_setopt($ch, CURLOPT_NOBODY, true);
16
+ curl_exec($ch);
17
+ $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
18
+
19
+ // $retcode > 400 -> not found, $retcode = 200 -> found.
20
+
21
+ if ($retcode > 400) {
22
+ return false;
23
+ } elseif ($retcode == 200) {
24
+ return true;
25
+ }
26
+ curl_close($ch);
27
+ }
28
+
29
+ public function getEnvironmentJavascript($page_type='') {
30
+ $payair_env_type = Mage::getStoreConfig('payment/gate/environment');
31
+ if ($payair_env_type == 'development') {
32
+ if($page_type == "checkout") {
33
+ $payair_script = 'https://test.payair.com/embed/js/checkout.js';
34
+ }else{
35
+ $payair_script = 'https://test.payair.com/embed/js/product.js';
36
+ }
37
+ } elseif ($payair_env_type == 'production') {
38
+ if($page_type == "checkout") {
39
+ $payair_script = 'https://payair.com/ms/js/checkout.js';
40
+ }else{
41
+ $payair_script = 'https://payair.com/ms/js/product.js';
42
+ }
43
+ } elseif ($payair_env_type == 'qa') {
44
+ $payair_script = 'https://qa.payair.com/embed/js/checkout.js';
45
+ } else {
46
+ $payair_script = 'https://test.payair.com/embed/js/mobileshopper_dev.js';
47
+ }
48
+
49
+ return $payair_script;
50
+ }
51
+
52
+ public function getBannerImages($type = 'background') {
53
+ $payair_checkout_img_url = 'http://payairus.net/images/ecommerce/express_checkout_banner_v3.png';
54
+ $android_small_thumb_url = 'https://www.payair.com/img/android_video_thumb_small.png';
55
+
56
+ if ($this->is_remote_image_ready($payair_checkout_img_url)) {
57
+ $payair_checkout_img = $payair_checkout_img_url;
58
+ } else {
59
+ // Load from the client library
60
+ $payair_checkout_img = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL) . 'media/payair/express_checkout_banner_v3.png';
61
+ }
62
+
63
+ if ($this->is_remote_image_ready($android_small_thumb_url)) {
64
+ $payair_android_small_img = $android_small_thumb_url;
65
+ } else {
66
+ // Load from the client library
67
+ $payair_android_small_img = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL) . 'media/payair/android_video_thumb_small.png';
68
+ }
69
+ if($type == 'background') {
70
+ return $payair_checkout_img;
71
+ } else if($type == 'video') {
72
+ return $payair_android_small_img;
73
+ }
74
+ }
75
+ }
76
+ ?>
app/code/community/Payair/Gate/Model/Checkout.php ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Payair_Gate_Model_Checkout extends Mage_Payment_Model_Method_Abstract {
4
+
5
+ protected $_code = 'gate';
6
+
7
+ /**
8
+ * Availability options
9
+ */
10
+ protected $_isGateway = false;
11
+ protected $_canOrder = false;
12
+ protected $_canAuthorize = false;
13
+ protected $_canCapture = false;
14
+ protected $_canCapturePartial = false;
15
+ protected $_canRefund = false;
16
+ protected $_canRefundInvoicePartial = false;
17
+ protected $_canVoid = false;
18
+ protected $_canUseInternal = false;
19
+ protected $_canUseCheckout = true;
20
+ protected $_canReviewPayment = true;
21
+ protected $_canUseForMultishipping = true;
22
+ protected $_canCancelInvoice = false;
23
+
24
+
25
+ public function authorize(Varien_Object $payment, $amount) {
26
+ $payment->setAdditionalInformation('payment_type', $this->getConfigData('payment_action'));
27
+ return $this;
28
+ }
29
+
30
+ public function capture(Varien_Object $payment, $amount) {
31
+ parent::capture($payment, $amount);
32
+ $data = $payment->getData();
33
+
34
+ if(strlen($data['last_trans_id']) == 7) {
35
+ $data['last_trans_id'] = "0".$data['last_trans_id'];
36
+ }
37
+
38
+ $string = 'clear' .
39
+ "\t" .number_format( $amount ,2 , '','').
40
+ "\t" . $this->getConfig('gate_marchantref') .
41
+ "\t" . $payment->getOrder()->getEntityId() .
42
+ "\t" . str_pad($data['last_trans_id'], 8, "0", STR_PAD_LEFT).
43
+ "\t";
44
+
45
+ $request = 'request_type=clear' .
46
+ '&amount=' .number_format( $amount ,2 , '','').
47
+ '&merchant_reference=' . $this->getConfig('gate_marchantref') .
48
+ '&customer_refno=' . $payment->getOrder()->getEntityId() .
49
+ '&payair_reference=' . str_pad($data['last_trans_id'], 8, "0", STR_PAD_LEFT) .
50
+ '&date=' . date("Ymd") .
51
+ '&mac=' . $this->mac($string);
52
+
53
+ $result = $this->sendRequest($request);
54
+
55
+ /**
56
+ *Create Reciept Call
57
+ */
58
+
59
+ $all_items = $payment->getOrder()->getAllItems();
60
+
61
+ $i = 0;
62
+ $total_tax = '';
63
+ $cart_items = '';
64
+ $cart_items_serial = '';
65
+
66
+ foreach ($all_items as $item) {
67
+ if ($item->getParentItemId()) {
68
+ continue;
69
+ }
70
+ $options = $item->getProductOptions();
71
+ if ($item->getProductType() == 'configurable'){
72
+ $options['options'] = $options['attributes_info'];
73
+ }
74
+
75
+ $j = 1;
76
+ $attr = '';
77
+ if (count(@$options['options']) > 0){
78
+ foreach ($options['options'] as $key => $o) {
79
+ $attr[] = $o['value'] ;
80
+ }
81
+ $attr = join('/', $attr);
82
+ }
83
+
84
+ $tax = $item->getTaxPercent();
85
+ $total_tax += $item->getTaxAmount();
86
+
87
+ $taxRate = $tax / 100;
88
+ $tax_amount = $item->getPrice() * $taxRate;
89
+
90
+ $productPriceInclTax = $item->getPrice() + $tax_amount;
91
+ $cart_items .= '&post' . $i .'='.
92
+ 'price=' . number_format($productPriceInclTax, 2, '', '') .
93
+ ($attr != null?';extra=' . $attr :'') .
94
+ ';name=' . urlencode($item->getName()) .
95
+ ';vat=' . (int)number_format($tax_amount, 2, '', '') ;
96
+
97
+
98
+ $cart_items_serial .= number_format($productPriceInclTax, 2, '', '') .
99
+ ($attr != null?"\t". $attr :'').
100
+ "\t". $item->getName() .
101
+ "\t" . (int)number_format($tax_amount, 2, '', '')."\t" ;
102
+
103
+ $i++;
104
+ }
105
+ $cart_items .= '&post' . $i .'='.
106
+ 'price=' . (int)number_format($payment->getOrder()->getShippingAmount(), 2, '', '') .
107
+ ';name=' . 'Shipping' .
108
+ ';vat=' . 0 ;
109
+
110
+
111
+ $cart_items_serial .= (int)number_format($payment->getOrder()->getShippingAmount(), 2, '', '') .
112
+ "\t". 'Shipping' .
113
+ "\t" . 0 ."\t" ;
114
+
115
+
116
+ $string = 'create_receipt' .
117
+ "\t" . $this->getConfig('gate_marchantref') .
118
+ "\t" . $payment->getOrder()->getEntityId() .
119
+ "\t" . str_pad($data['last_trans_id'], 8, "0", STR_PAD_LEFT) .
120
+ "\t" . $this->getConfig('gate_final_info_top') .
121
+ "\t" . $this->getConfig('gate_final_info_bottom') .
122
+ "\t" . $payment->getOrder()->getCustomerEmail() .
123
+ "\t" . number_format( $amount ,2 , '','') .
124
+ "\t" . number_format($total_tax , 2, '', '') .
125
+ "\t" . ($i + 1) ."\t".
126
+ $cart_items_serial ;
127
+
128
+ $request = 'request_type=create_receipt' .
129
+ '&merchant_reference=' . $this->getConfig('gate_marchantref') .
130
+ '&customer_refno=' . $payment->getOrder()->getEntityId() .
131
+ '&payair_reference=' . str_pad($data['last_trans_id'], 8, "0", STR_PAD_LEFT) .
132
+ '&top_information=' . $this->getConfig('gate_final_info_top') .
133
+ '&bottom_information=' . $this->getConfig('gate_final_info_bottom') .
134
+ '&user_email=' . $payment->getOrder()->getCustomerEmail() .
135
+ '&amount=' . number_format( $amount ,2 , '','') .
136
+ '&total_vat=' . number_format($total_tax , 2, '', '') .
137
+ '&no_of_items=' . ($i + 1) .
138
+ $cart_items .
139
+ '&mac=' . $this->mac($string);
140
+
141
+ $result = $this->sendRequest($request);
142
+
143
+ if(!preg_match('!status=OK!is', $result)){
144
+ $error = Mage::helper('paygate')->__('Error in create reciept');
145
+
146
+ if ($error !== false) {
147
+ Mage::throwException($error);
148
+ }
149
+ }
150
+
151
+ $payment->setForcedState(Mage_Sales_Model_Order_Invoice::STATE_PAID);
152
+
153
+ $payment->setStatus(self::STATUS_APPROVED);
154
+
155
+ return $this;
156
+ }
157
+
158
+ public function cancel(Varien_Object $payment) {
159
+ parent::cancel($payment);
160
+
161
+ return $this;
162
+ }
163
+
164
+ public function refund(Varien_Object $payment, $amount) {
165
+ parent::refund($payment, $amount);
166
+ $data = $payment->getData();
167
+
168
+ $string = 'credit'."\t".
169
+ number_format($data['amount_paid'], 2, '', '')."\t".
170
+ Mage::getStoreConfig('payment/gate/gate_marchantref')."\t".
171
+ $data['increment_id']."\t".
172
+ str_pad(str_ireplace('-capture', '', $data['refund_transaction_id']), 8, "0", STR_PAD_LEFT)."\t";
173
+
174
+ $url = 'https://test.payair.com:10000/merchant_ri/';
175
+ $data = 'request_type=credit' .
176
+ '&amount='.number_format($data['amount_paid'], 2, '', '').
177
+ '&merchant_reference='.Mage::getStoreConfig('payment/gate/gate_marchantref').
178
+ '&customer_refno='.$data['increment_id'].
179
+ '&payair_reference='.str_pad(str_ireplace('-capture', '', $data['refund_transaction_id']), 8, "0", STR_PAD_LEFT).
180
+ '&mac='.$this->mac($string);
181
+
182
+ //open connection
183
+ $ch = curl_init();
184
+
185
+ //set the url, number of POST vars, POST data
186
+ curl_setopt($ch, CURLOPT_URL, $url);
187
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
188
+ curl_setopt($ch, CURLOPT_POST, 1);
189
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
190
+
191
+ //execute post
192
+ $result = curl_exec($ch);
193
+
194
+ //close connection
195
+ curl_close($ch);
196
+
197
+ if (preg_match('!error!is', $result)) {
198
+ $error = Mage::helper('paygate')->__('Error in refunding the payment');
199
+ if ($error !== false) {
200
+ Mage::throwException($error);
201
+ }
202
+ }
203
+
204
+ $data = $payment->getData();
205
+ $all_items = $payment->getOrder()->getAllItems();
206
+
207
+
208
+ $i = 0;
209
+ $i = 0;
210
+ foreach ($all_items as $item) {
211
+
212
+ if ($item->getParentItemId()) {
213
+ continue;
214
+ }
215
+
216
+ $options = $item->getProductOptions();
217
+
218
+ $j = 1;
219
+ $attr = '';
220
+ foreach ($options['options'] as $key => $o) {
221
+ $attr[] = $o['value'] ;
222
+ }
223
+ $attr = join('/', $attr);
224
+
225
+ $tax = $item->getTaxPercent();
226
+ $total_tax += $item->getTaxAmount();
227
+
228
+
229
+ $taxRate = $tax / 100;
230
+ $tax_amount = $item->getPrice() * $taxRate;
231
+ if ($tax_amount > 0) {
232
+ $tax_amount = (int)number_format($tax_amount, 2, '', '');
233
+ }
234
+ if ($total_tax > 0) {
235
+ $total_tax = (int)number_format($total_tax, 2, '', '');
236
+ }
237
+ $productPriceInclTax = $item->getPrice() + $tax_amount;
238
+
239
+ $cart_items .= '&post' . $i .'='.
240
+ 'price=' . number_format($productPriceInclTax, 2, '', '') .
241
+ ($attr != null?';extra=' . $attr :'') .
242
+ ';name=' . urlencode($item->getName()) .
243
+ ';vat=' . $tax_amount ;
244
+
245
+
246
+ $cart_items_serial .= number_format($productPriceInclTax, 2, '', '') .
247
+ ($attr != null?"\t". $attr :'').
248
+ "\t". $item->getName() .
249
+ "\t" . $tax_amount."\t" ;
250
+
251
+ $i++;
252
+ }
253
+
254
+ $cart_items .= '&post' . $i .'='.
255
+ 'price=' . (int)number_format($payment->getOrder()->getShippingAmount(), 2, '', '') .
256
+ ';name=' . 'Shipping' .
257
+ ';vat=' . 0 ;
258
+
259
+
260
+ $cart_items_serial .= (int)number_format($payment->getOrder()->getShippingAmount(), 2, '', '') .
261
+ "\t". 'Shipping' .
262
+ "\t" . 0 ."\t" ;
263
+
264
+ $string = 'create_receipt' .
265
+ "\t" . $this->getConfig('gate_marchantref') .
266
+ "\t" . $payment->getOrder()->getEntityId() .
267
+ "\t" . str_pad(str_ireplace("-capture",'',$data['last_trans_id']), 8, "0", STR_PAD_LEFT) .
268
+ "\t" . $this->getConfig('gate_refund_info_top') .
269
+ "\t" . $this->getConfig('gate_refund_info_bottom') .
270
+ "\t" . $payment->getOrder()->getCustomerEmail() .
271
+ "\t" . "-".number_format( $amount ,2 , '','') .
272
+ "\t" . $total_tax.
273
+ "\t" . ($i + 1) ."\t".
274
+ $cart_items_serial ;
275
+
276
+ $request = 'request_type=create_receipt' .
277
+ '&merchant_reference=' . $this->getConfig('gate_marchantref') .
278
+ '&customer_refno=' . $payment->getOrder()->getEntityId() .
279
+ '&payair_reference=' . str_pad(str_ireplace("-capture",'',$data['last_trans_id']), 8, "0", STR_PAD_LEFT) .
280
+ '&top_information=' . $this->getConfig('gate_refund_info_top') .
281
+ '&bottom_information=' . $this->getConfig('gate_refund_info_bottom') .
282
+ '&user_email=' . $payment->getOrder()->getCustomerEmail() .
283
+ '&amount=' . "-".number_format( $amount ,2 , '','') .
284
+ '&total_vat=' . $total_tax .
285
+ '&no_of_items=' . ($i + 1) .
286
+ $cart_items .
287
+ '&mac=' . $this->mac($string);
288
+
289
+ $result = $this->sendRequest($request);
290
+
291
+ return $this;
292
+ }
293
+
294
+ public function mac($string) {
295
+ $hash = $string . Mage::getStoreConfig('payment/gate/gate_secret');
296
+
297
+ return hash('sha256', $hash);
298
+ }
299
+
300
+ protected function getConfig($item){
301
+ return Mage::getStoreConfig('payment/gate/'.$item);
302
+ }
303
+
304
+ protected function sendRequest($data){
305
+ //open connection
306
+ $ch = curl_init();
307
+
308
+ $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
309
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
310
+
311
+ //set the url, number of POST vars, POST data
312
+ curl_setopt($ch, CURLOPT_URL, $this->getConfig('gate_merchant_url'));
313
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
314
+ curl_setopt($ch, CURLOPT_POST, 1);
315
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
316
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
317
+
318
+ //execute post
319
+ $result = curl_exec($ch);
320
+
321
+ //close connection
322
+ curl_close($ch);
323
+
324
+ return $result;
325
+ }
326
+ }
327
+
328
+ ?>
app/code/community/Payair/Gate/Model/Display.php ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Payair_Gate_Model_Display {
3
+
4
+ public function toOptionArray()
5
+ {
6
+
7
+ return array(
8
+ array('value' => '0', 'label' => '-- Select Display Method --'),
9
+ array('value' => 'banner', 'label' => 'Banner'),
10
+ array('value' => 'button', 'label' => 'Button'),
11
+ );
12
+ }
13
+ }
app/code/community/Payair/Gate/Model/Environment.php ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Payair_Gate_Model_Environment {
3
+
4
+ public function toOptionArray()
5
+ {
6
+
7
+ return array(
8
+ array('value' => '0', 'label' => '-- Select Enviornment --'),
9
+ array('value' => 'development', 'label' => 'Development'),
10
+ array('value' => 'production', 'label' => 'Production'),
11
+ array('value' => 'qa', 'label' => 'QA'),
12
+ );
13
+ }
14
+ }
app/code/community/Payair/Gate/Model/Observer.php ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ Created By : PayAir Team
4
+ Funnction : Payair_Gate_Model_Observer Class to extend the Mage_Core_Model_Abstract, a checkout observer
5
+ */
6
+
7
+ class Payair_Gate_Model_Observer extends Mage_Core_Model_Abstract {
8
+
9
+ public function createInvoiceAndCapturePayment($observer) {
10
+ try {
11
+ $shipment = $observer->getEvent()->getShipment();
12
+ $order = $shipment->getOrder();
13
+
14
+ if (!$order->canInvoice()) {
15
+ return $this;
16
+ }
17
+
18
+ $transactionSave = Mage::getModel('core/resource_transaction');
19
+
20
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
21
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
22
+ $invoice->register();
23
+
24
+
25
+ $transactionSave = Mage::getModel('core/resource_transaction')
26
+ ->addObject($invoice)
27
+ ->addObject($invoice->getOrder());
28
+
29
+ $transactionSave->save();
30
+
31
+ // Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The invoice has been created.'));
32
+ } catch(Exception $e) {
33
+ die($e->getMessage());
34
+ }
35
+ }
36
+ }
37
+ ?>
app/code/community/Payair/Gate/Model/Order/Api.php ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ * To change this template, choose Tools | Templates
5
+ * and open the template in the editor.
6
+ */
7
+
8
+ class Payair_Gate_Model_Order_Api extends Mage_Sales_Model_Order_Api {
9
+
10
+ public function cancel($orderIncrementId) {
11
+ if ($order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId)) {
12
+
13
+ try {
14
+ $response = $this->callRefundAction($order);
15
+
16
+ if ($response != 'A0') {
17
+ //$this->_getSession()->addError('Order Cancellation Failed, because refunding of amount failed. Payair Error : ' . $response);
18
+ $order->setState($order->getState(), $order->getState(), "Order Cancellation Failed, because refunding of amount failed. Payair Error: " . $response);
19
+ $order->save();
20
+ } else {
21
+
22
+ $order->cancel()
23
+ ->save();
24
+ $this->_getSession()->addSuccess(
25
+ $this->__('The order has been cancelled.')
26
+ );
27
+ // $this->_getSession()->addSuccess('Amount has been successfully refunded by Payair');
28
+ $order->setState(Mage_Sales_Model_Order::STATE_CANCELED, Mage_Sales_Model_Order::STATE_CANCELED, "Amount has been successfully refunded by Payair");
29
+ $order->save();
30
+ }
31
+ } catch (Mage_Core_Exception $e) {
32
+ // $this->_getSession()->addError($e->getMessage());
33
+ } catch (Exception $e) {
34
+ // $this->_getSession()->addError($this->__('The order has not been cancelled.'));
35
+ // Mage::logException($e);
36
+ }
37
+
38
+ }
39
+
40
+ return true; //$response;
41
+ }
42
+
43
+ public function callRefundAction($order) {
44
+ //Mage::log('Method Module called : Payair_Adminhtml_Sales_OrderController :: callRefundAction() ');
45
+ try {
46
+ $storeid = $order->getStoreId(); // FROM STORE ID for purchase store
47
+
48
+ $merchant_reference = $this->getConfig('gate_marchantref', $storeid);
49
+
50
+ $customer_refno = $order->getIncrementId(); // FROM ORDER ID
51
+ $amount = $this->getFormattedPrice($order->getBaseGrandTotal()); // getting integer value for BaseGrandTotal
52
+ $payair_reference = $order->getPayment()->getLastTransId(); // FROM TRANSACTION ID
53
+
54
+ $string = 'credit' . "\t" . $amount . "\t" . $merchant_reference . "\t" . $customer_refno . "\t" . $payair_reference . "\t";
55
+
56
+ $mac = $this->mac($string, $storeid);
57
+ $data = 'request_type=credit&amount=' . $amount . '&merchant_reference=' . $merchant_reference . '&customer_refno=' . $customer_refno . '&payair_reference=' . $payair_reference . '&mac=' . $mac;
58
+ $response = $this->sendRequest($data, $storeid);
59
+ $responseArry = explode('&', $response);
60
+ $tempArryStatus = explode('=', $responseArry[0]);
61
+ $tempArryMac = explode('=', $responseArry[4]);
62
+ $payairStatus = $tempArryStatus[1];
63
+ $payairMac = $tempArryMac[1];
64
+ /* Cross refer MAC match disbled till further notice */
65
+ /* if($payairMac != $mac )
66
+ {
67
+ return 'Wrong MAC';
68
+ }else{
69
+ return $payairStatus;
70
+ } */
71
+ return $payairStatus;
72
+
73
+ } catch (Exception $e) {
74
+ // Mage::logException($e);
75
+ }
76
+ }
77
+
78
+ public function sendRequest($data, $storeid) {
79
+ Mage::log("\nRefund Request: \n" . print_r($data, TRUE), null, 'refund_log.txt');
80
+ //open connection
81
+ $ch = curl_init();
82
+
83
+ $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
84
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
85
+ //set the url, number of POST vars, POST data
86
+ curl_setopt($ch, CURLOPT_URL, $this->getConfig('gate_merchant_url', $storeid));
87
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
88
+ curl_setopt($ch, CURLOPT_POST, 1);
89
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
90
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
91
+ //execute post
92
+ $result = curl_exec($ch);
93
+ Mage::log("\nRefund Response: \n" . print_r($result, TRUE), null, 'refund_log.txt');
94
+ //close connection
95
+ curl_close($ch);
96
+ return $result;
97
+ }
98
+
99
+ public function mac($string, $storeid) {
100
+ $hash = $string . $this->getConfig('gate_secret', $storeid);
101
+ return hash('sha256', $hash);
102
+ }
103
+
104
+ public function getConfig($item, $storeid) {
105
+ return Mage::getStoreConfig('payment/gate/' . $item, $storeid);
106
+ }
107
+
108
+ public function getFormattedPrice($realPrice) {
109
+ $formattedPrice = number_format(Mage::helper('core')->currency($realPrice, false, false), 2, '.', '');
110
+ return ($formattedPrice) ? $formattedPrice * 100 : 0;
111
+ }
112
+
113
+ }
app/code/community/Payair/Gate/Model/Order/Api/V2.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ * To change this template, choose Tools | Templates
5
+ * and open the template in the editor.
6
+ */
7
+ class Payair_Gate_Model_Order_Api_V2 extends Payair_Gate_Model_Order_Api
8
+ {
9
+
10
+ }
app/code/community/Payair/Gate/Model/Payair.php ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ Created By : PayAir Team
4
+ Funnction : Payair_Gate_Model_Observer Class to extend the Mage_Core_Model_Abstract, a checkout observer
5
+ */
6
+
7
+ class Payair_Gate_Model_Payair extends Mage_Api_Model_Resource_Abstract {
8
+
9
+ /**
10
+ * Retrieve regions list
11
+ *
12
+ * @param string $country
13
+ * @return array
14
+ */
15
+ public function getRegionId($country, $name)
16
+ {
17
+ try {
18
+ $country = Mage::getModel('directory/country')->loadByCode($country);
19
+ } catch (Mage_Core_Exception $e) {
20
+ $this->_fault('country_not_exists', $e->getMessage());
21
+ }
22
+
23
+ if (!$country->getId()) {
24
+ $this->_fault('country_not_exists');
25
+ }
26
+
27
+ $result = array();
28
+ foreach ($country->getRegions() as $region) {
29
+ if ( strtolower($region->getName()) == strtolower($name)) {
30
+ return $region->getRegionId();
31
+ }
32
+ }
33
+
34
+ return 1;
35
+ }
36
+
37
+ /**
38
+ * Get allowed product tax classes by rule id
39
+ *
40
+ * @param int $ruleId
41
+ * @return array
42
+ */
43
+ private function createCustomer($user) {
44
+
45
+ $customer = Mage::getModel('customer/customer');
46
+ $customer->website_id = Mage::getModel('core/store')->load( $this->getStoreId() )->getWebsiteId();
47
+ $customer->setStore(Mage::getModel('core/store')->load( $this->getStoreId() ));
48
+ $customer->loadByEmail((string)$user->email);
49
+ if (!$customer->getId()) {
50
+ $pass = uniqid();
51
+ $customer->setEmail($user->email);
52
+ $customer->setFirstname($user->firstName);
53
+ $customer->setLastname($user->lastName);
54
+ $customer->setPassword($pass);
55
+ $customer->sendNewAccountEmail();
56
+ $customer->setConfirmation(null);
57
+ $customer->save();
58
+ }
59
+
60
+ $customAddress = Mage::getModel("customer/address");
61
+ $customAddress->setCustomerId($customer->getId());
62
+ if ($defaultShippingId = $customer->getDefaultShipping()) {
63
+ $customAddress->load($defaultShippingId);
64
+ } elseif ($defaultBillingId = $customer->getDefaultBilling()) {
65
+ $customAddress->load($defaultBillingId);
66
+ }
67
+ try {
68
+ $customAddress->firstname = $user->firstName;
69
+ $customAddress->lastname = $user->lastName;
70
+ $customAddress->country_id = $user->country; //Country code here
71
+ /* NOTE: If country is USA, please set up $address->region also */
72
+ if($user->country == 'US') {
73
+ $customAddress->region_id = Mage::getModel('gate/payair')->getRegionId('US', $user->state);
74
+ }
75
+ $customAddress->street = $user->address1;
76
+ $customAddress->postcode = $user->zip;
77
+ $customAddress->city = $user->city;
78
+ $customAddress->telephone = $user->phoneNr;
79
+ $customAddress->fax = "";
80
+ $customAddress->company = "";
81
+ $customAddress->save();
82
+
83
+ $customAddress->setCustomerId($customer->getId())
84
+ ->setIsDefaultBilling(1)
85
+ ->setIsDefaultShipping(1)
86
+ ->setSaveInAddressBook(1);
87
+ $customAddress->save();
88
+ } catch (Exception $ex) {}
89
+
90
+ return $customer;
91
+ }
92
+ }
93
+ ?>
app/code/community/Payair/Gate/Model/RestConnect_Model_Oauth_Client.php ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ *
4
+ * @author Darko Goleš <darko.goles@inchoo.net>
5
+ * @package Inchoo
6
+ * @subpackage RestConnect
7
+ */
8
+ class Inchoo_RestConnect_Model_Oauth_Client extends Mage_Core_Model_Abstract
9
+ {
10
+ private $_callbackUrl;
11
+ private $_siteUrl;
12
+ private $_consumerKey;
13
+ private $_consumerSecret;
14
+ private $_requestTokenUrl;
15
+ private $_accessTokenUrl;
16
+ private $_consumer;
17
+ private $_authorizeUrl;
18
+ private $_userAuthorizationUrl;
19
+ private $_authorized_token;
20
+ const OAUTH_STATE_NO_TOKEN = 0;
21
+ const OAUTH_STATE_REQUEST_TOKEN = 1;
22
+ const OAUTH_STATE_ACCESS_TOKEN = 2;
23
+ const OAUTH_STATE_ERROR = 3;
24
+ public function init($config)
25
+ {
26
+ $this->setOAuthConfig($config);
27
+ return $this;
28
+ }
29
+ public function setAuthorizedToken($token)
30
+ {
31
+ $this->_authorized_token = $token;
32
+ }
33
+ public function getAuthorizedToken()
34
+ {
35
+ if ($this->_authorized_token) {
36
+ return $this->_authorized_token;
37
+ }
38
+ return false;
39
+ }
40
+ public function reset()
41
+ {
42
+ return $this->resetSessionParams();
43
+ }
44
+ public function authenticate()
45
+ {
46
+ $state = $this->getOAuthState();
47
+ $consumer = $this->_getOAuthConsumer();
48
+ try {
49
+ switch ($state) {
50
+ case self::OAUTH_STATE_NO_TOKEN:
51
+ $requestToken = $this->getRequestToken();
52
+ $this->setOAuthState(self::OAUTH_STATE_REQUEST_TOKEN);
53
+ $consumer->redirect();
54
+ return self::OAUTH_STATE_REQUEST_TOKEN;
55
+ break;
56
+ case self::OAUTH_STATE_REQUEST_TOKEN:
57
+ $accessToken = $this->getAccessToken($this->getRequestToken());
58
+ $this->setAuthorizedToken($accessToken);
59
+ $this->setOAuthState(self::OAUTH_STATE_ACCESS_TOKEN);
60
+ return self::OAUTH_STATE_ACCESS_TOKEN;
61
+ break;
62
+ case self::OAUTH_STATE_ACCESS_TOKEN:
63
+ return self::OAUTH_STATE_ACCESS_TOKEN;
64
+ default:
65
+ $this->resetSessionParams();
66
+ return self::OAUTH_STATE_NO_TOKEN;
67
+ return;
68
+ break;
69
+ }
70
+ } catch (Zend_Oauth_Exception $e) {
71
+ $this->resetSessionParams();
72
+ Mage::logException($e);
73
+ } catch (Exception $e) {
74
+ Mage::logException($e);
75
+ }
76
+ return self::OAUTH_STATE_NO_TOKEN;
77
+ }
78
+ private function resetSessionParams()
79
+ {
80
+ $this->getSession()->unsetData('o_auth_state');
81
+ $this->getSession()->unsetData('request_token');
82
+ $this->getSession()->unsetData('o_auth_config');
83
+ $this->getSession()->unsetData('access_token');
84
+ return $this;
85
+ }
86
+ public function getRequestToken()
87
+ {
88
+ $token = $this->_getRequestTokenFromSession();
89
+ if ($token && $token instanceof Zend_Oauth_Token_Request) {
90
+ return $token;
91
+ }
92
+ $token = $this->_getRequestTokenFromServer();
93
+ if ($token && $token instanceof Zend_Oauth_Token_Request) {
94
+ $this->_saveRequestTokenInSession($token);
95
+ return $token;
96
+ }
97
+ return false;
98
+ }
99
+ public function getAccessToken($requestToken)
100
+ {
101
+ $token = $this->_getAccessTokenFromSession();
102
+ if ($token && $token instanceof Zend_Oauth_Token_Access) {
103
+ return $token;
104
+ }
105
+ $token = $this->_getAcessTokenFromServer($requestToken);
106
+ if ($token && $token instanceof Zend_Oauth_Token_Access) {
107
+ $this->_saveAccessTokenInSesion($token);
108
+ return $token;
109
+ }
110
+ }
111
+ private function _getAcessTokenFromServer($requestToken)
112
+ {
113
+ if ($requestToken && $requestToken instanceof Zend_Oauth_Token_Request) {
114
+ $accToken = $this->_getOAuthConsumer()->getAccessToken(
115
+ $_GET,
116
+ $requestToken
117
+ );
118
+ }
119
+ if ($accToken && $accToken instanceof Zend_Oauth_Token_Access) {
120
+ return $accToken;
121
+ }
122
+ return false;
123
+ }
124
+ private function _saveAccessTokenInSesion($accessToken)
125
+ {
126
+ $this->getSession()->setAccessToken(serialize($accessToken));
127
+ }
128
+ private function _getAccessTokenFromSession()
129
+ {
130
+ $accessToken = unserialize($this->getSession()->getAcessToken());
131
+ if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
132
+ return $accessToken;
133
+ }
134
+ return false;
135
+ }
136
+ private function _getRequestTokenFromServer()
137
+ {
138
+ $token = $this->_getOAuthConsumer()->getRequestToken();
139
+ return $token;
140
+ }
141
+ private function _saveRequestTokenInSession(Zend_Oauth_Token_Request $requestToken)
142
+ {
143
+ $this->getSession()->setRequestToken(serialize($requestToken));
144
+ }
145
+ private function _getRequestTokenFromSession()
146
+ {
147
+ $requestToken = unserialize($this->getSession()->getRequestToken());
148
+ if ($requestToken && $requestToken instanceof Zend_Oauth_Token_Request) {
149
+ return $requestToken;
150
+ }
151
+ return false;
152
+ }
153
+ public function getSession()
154
+ {
155
+ return Mage::getSingleton('core/session');
156
+ }
157
+ public function getOAuthToken()
158
+ {
159
+ return $this->getRequest()->getParam('oauth_token', false);
160
+ }
161
+ public function getRequest()
162
+ {
163
+ return Mage::app()->getRequest();
164
+ }
165
+ private function _getOAuthConsumer()
166
+ {
167
+ if ($consumer = $this->_consumer) {
168
+ if ($consumer instanceof Zend_Oauth_Consumer) {
169
+ return $this->_consumer;
170
+ }
171
+ }
172
+ $this->_consumer = new Zend_Oauth_Consumer($this->getOAuthConfig());
173
+ return $this->_consumer;
174
+ }
175
+ private function getOAuthConfig()
176
+ {
177
+ $config = array(
178
+ 'callbackUrl' => $this->_callbackUrl,
179
+ 'siteUrl' => $this->_siteUrl,
180
+ 'consumerKey' => $this->_consumerKey,
181
+ 'consumerSecret' => $this->_consumerSecret,
182
+ 'requestTokenUrl' => $this->_requestTokenUrl,
183
+ 'accessTokenUrl' => $this->_accessTokenUrl,
184
+ );
185
+ if ($this->_authorizeUrl && $this->_authorizeUrl != '') {
186
+ $config['authorizeUrl'] = $this->_authorizeUrl;
187
+ }
188
+ if ($this->_userAuthorizationUrl && $this->_userAuthorizationUrl != '') {
189
+ $config['userAuthorizationUrl'] = $this->_userAuthorizationUrl;
190
+ }
191
+ return $config;
192
+ }
193
+ private function setOAuthConfig($config)
194
+ {
195
+ $this->getSession()->setOAuthConfig(serialize($config));
196
+ foreach ($config as $key => $val) {
197
+ $_key = '_' . $key;
198
+ $this->$_key = $val;
199
+ }
200
+ }
201
+ public function getConfigFromSession()
202
+ {
203
+ $config = unserialize($this->getSession()->getOAuthConfig());
204
+ if ($config && is_array($config)) {
205
+ return $config;
206
+ }
207
+ return false;
208
+ }
209
+ private function setOAuthState($state)
210
+ {
211
+ $this->getSession()->setOAuthState($state);
212
+ }
213
+ public function getOAuthState()
214
+ {
215
+ $state = $this->getSession()->getOAuthState();
216
+ if ($state == null) {
217
+ return self::OAUTH_STATE_NO_TOKEN;
218
+ }
219
+ $paramOAuthToken = $this->getOAuthToken();
220
+ if ($paramOAuthToken == false && $state == self::OAUTH_STATE_REQUEST_TOKEN) {
221
+ $this->resetSessionParams();
222
+ return self::OAUTH_STATE_NO_TOKEN;
223
+ }
224
+ return $state;
225
+ }
226
+ }
227
+
228
+ ?>
app/code/community/Payair/Gate/controllers/IndexController.php ADDED
@@ -0,0 +1,1617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* ===================================================
3
+ * @description: PayAir Callback controller
4
+ * ==================================================
5
+ */
6
+
7
+ class Payair_Gate_IndexController extends Mage_Core_Controller_Front_Action {
8
+
9
+ private $log_file = 'log.txt';
10
+ private $vatPercent = 0;
11
+ public $request = '';
12
+ private $headers = array();
13
+ private $tax = 0;
14
+ private $data_file_extension = '.txt';
15
+
16
+ /**
17
+ * Initialize controller
18
+ */
19
+
20
+ public function indexAction() {
21
+ echo "We are in index function";
22
+ $this->request = $this->getServiceRequest();
23
+ exit;
24
+ }
25
+
26
+ /**
27
+ * The function which take control over the web service request
28
+ */
29
+ public function itemAction() {
30
+ $suggested_items = array(); // Suggested Item Array
31
+ $this->request = $this->getServiceRequest(); // JSON request from Payair server
32
+ $this->setStoreId(); // Set Store Id
33
+ $customer = $this->createCustomer( $this->request->user );
34
+
35
+ $product_id = $this->request->reference; // Product Id
36
+ $product_obj = $this->loadProduct( $product_id ); // Load Product by Product Id
37
+ $this->setVatPercent( $customer, $product_obj );
38
+ $item = array(
39
+ "name" => $this->limitStringLenght( $product_obj->name, 254 ),
40
+ "amount" => $this->getFormattedPrice($product_obj->price),
41
+ "vat" => $this->getFormattedPrice( $this->getVatAmount( $product_obj->price, $this->getVatPercent() ) ),
42
+ "quantity" => "1",
43
+ "description" => $this->limitStringLenght( $product_obj->short_description, 254 ),
44
+ "sku" => $this->limitStringLenght( $product_obj->sku, 63 ),
45
+ "vatPercent" => $this->getVatPercent(),//$this->getFormattedPrice($this->getVatPercent()),
46
+ "imageUrl" => $this->limitStringLenght((string) Mage::Helper('catalog/image')->init($product_obj,'image'), 1023),
47
+ "url" => $this->limitStringLenght( $product_obj->getProductUrl(), 1023 ),
48
+ "longDescription" => $this->limitStringLenght( $product_obj->description, 1499 ),
49
+ "currency" => $this->getCurrencyISONumber(),
50
+ "sortOrder" => "1",
51
+ "discounts" => array(),
52
+ "customValues" => $this->setCustomValue( $product_id ),
53
+ "attributes" => $this->getAttributes($product_obj)
54
+ );
55
+
56
+ $related_products_id_array = $product_obj->getRelatedProductIds(); // Get Related Products
57
+ if ( count($related_products_id_array) > 0 ) {
58
+ foreach ( $related_products_id_array as $related_product_id ) {
59
+ $related_product = $this->loadProduct($related_product_id); // Load related Product by Product Id
60
+ $suggested_items[] = array(
61
+ "name" => $related_product->name,
62
+ "amount" => $this->getFormattedPrice($related_product->price),
63
+ "vat" => 0,
64
+ "quantity" => "1",
65
+ "description" => $related_product->short_description,
66
+ "sku" => $related_product->sku,
67
+ "vatPercent" => 0,
68
+ "imageUrl" => (string) Mage::Helper('catalog/image')->init($related_product,'image'),
69
+ "url" => $related_product->getProductUrl(),
70
+ "longDescription" => $related_product->description,
71
+ "currency" => $this->getCurrencyISONumber(),
72
+ "sortOrder" => "1"
73
+ );
74
+ }
75
+ }
76
+
77
+ $response_array = array(
78
+ "statusCode" => "SUCCESS",
79
+ "message" => "operation successful",
80
+ "item" => $item,
81
+ "suggestedItems" => $suggested_items
82
+ );
83
+ $response_json = json_encode($response_array);
84
+ Mage::log("\n GetItem Response IS: \n" . print_r($response_json, true), null, $this->log_file);
85
+ echo $response_json;
86
+ }
87
+
88
+ /**
89
+ * The function which take control over the web service request for Cart sync
90
+ */
91
+ public function syncAction() {
92
+
93
+ $this->request = $this->getServiceRequest(); // JSON request from Payair server
94
+ $this->setStoreId(); // Set Store Id
95
+ $customer = $this->createCustomer($this->request->user);
96
+ $item = array();
97
+ $products = $this->getRequestCollection('cart'); // get product data for request array
98
+
99
+ if ( is_array( $products) && count( $products > 0 ) ) {
100
+ foreach ( $products as $product ) {
101
+ $product_id = $this->getCustomNameValue($product['customValues'], 'reference');
102
+ $product_obj = $this->loadProduct($product_id); // Load Product by Product Id
103
+ $product_quantity = $product['quantity'];
104
+ $this->setVatPercent( $customer, $product_obj );
105
+ $product_price = ( $product['amount']/100 );
106
+ $product_vat = $this->getFormattedPrice( ( $this->getVatAmount( $product_price, $this->getVatPercent() ) ) * $product_quantity );
107
+
108
+ $options = $product_obj->getOptions();
109
+ $cartOptions = array();
110
+ $configCartOptions = array();
111
+ foreach ($options as $option) {
112
+ $optionData = $option->getData();
113
+ $optionValues = Mage::helper('core')->decorateArray($option->getValues());
114
+
115
+ $type = $option->getData('type');
116
+ $optionValuesArray = array();
117
+
118
+ if ( $type == 'field' || $type == 'area' ) {
119
+ $optionValuesArray[$option->getData('default_title')] = $option->getData('option_id');
120
+ } else {
121
+ foreach ( $optionValues as $optionValue ) {
122
+ $optionValueData = $optionValue->getData();
123
+ $optionValuesArray[$optionValueData['default_title']] = $optionValueData['option_type_id'];
124
+ }
125
+ }
126
+
127
+ foreach ( $product['attributes'] as $attribute ) {
128
+ if ( $attribute['name'] == $optionData['default_title'] ) {
129
+ $selectedAttributes = array();
130
+ $selectedAttributesValue = array();
131
+ foreach ( $attribute['attributeValues'] as $attributeValue ) {
132
+ if ( $attributeValue['chosen']) {
133
+ $selectedAttributes[] = $optionValuesArray[$attributeValue ['value']];
134
+ if ( $type == 'field' || $type == 'area' ) {
135
+ $selectedAttributesValue[] = $attributeValue ['value'];
136
+ }
137
+ }
138
+ }
139
+ if ( $type == 'field' || $type == 'area' ) {
140
+ $cartOptions[$optionData['option_id']] = $selectedAttributesValue[0];
141
+ } else {
142
+ $cartOptions[$optionData['option_id']] = count($selectedAttributes) == 1 ? $selectedAttributes[0] : $selectedAttributes;
143
+ }
144
+ }
145
+ }
146
+ }
147
+ // Add configurable product to the cart
148
+ if ( $product_obj->getTypeId() == 'configurable' ) {
149
+ $configAttributesOptions = $product_obj->getTypeInstance(true)->getConfigurableAttributesAsArray($product_obj);
150
+
151
+ foreach ( $configAttributesOptions as $configAttributesOption ) {
152
+ $attribute_code = $configAttributesOption['attribute_code'];
153
+ $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attribute_code);
154
+ $optionValuesArray = array();
155
+ foreach ( $product['attributes'] as $attribute ) {
156
+ if( $attribute['name'] == $attribute_details->getData('store_label') ) {
157
+ foreach ( $configAttributesOption['values'] as $value ) {
158
+ $optionValuesArray[$value['default_label']] = $value['value_index'];
159
+ $selectedAttributes = array();
160
+ foreach ( $attribute['attributeValues'] as $attributeValue ) {
161
+ if ( $attributeValue['chosen']) {
162
+ $selectedAttributes[] = $optionValuesArray[$attributeValue ['value']];
163
+ }
164
+ }
165
+ }
166
+ $configCartOptions[$attribute_details->getData('attribute_id')] = count($selectedAttributes) == 1 ? $selectedAttributes[0] : $selectedAttributes;
167
+ }
168
+ }
169
+ }
170
+ }
171
+
172
+ $item[] = array(
173
+ "name" => $this->limitStringLenght( $product['name'], 254),
174
+ "amount" => $product['amount'],
175
+ "vat" => $product_vat,
176
+ "quantity" => $product['quantity'],
177
+ "description" => $this->limitStringLenght( $product['description'], 254),
178
+ "sku" => $this->limitStringLenght( $product['sku'], 63 ),
179
+ "vatPercent" => $this->getVatPercent(),//$this->getFormattedPrice($this->getVatPercent()),
180
+ "imageUrl" => $this->limitStringLenght( $product['imageUrl'], 1023 ),
181
+ "url" => $this->limitStringLenght( $product['url'], 1023 ),
182
+ "longDescription" => $this->limitStringLenght( $product['longDescription'], 1499 ),
183
+ "currency" => $product['currency'],
184
+ "discounts" => array(),
185
+ "customValues" => $product['customValues'],
186
+ "attributes" => $this->getAttributes($product_obj, NULL, $cartOptions ),
187
+ "sortOrder" => $product['sortOrder'],
188
+ "type" => $product['type']
189
+ );
190
+
191
+ $option = array();
192
+ if ( count($cartOptions ) > 0) {
193
+ $option['product'] = (string) $product_id;
194
+ $option['qty'] = $product_quantity;
195
+ $option['options'] = $cartOptions;
196
+ if ( is_array($configCartOptions) && count($configCartOptions) ) { //if config proudct attributes exists
197
+ $option['super_attribute'] = $configCartOptions;
198
+ }
199
+ $option_request = new Varien_Object();
200
+ $option_request->setData($option);
201
+ try {
202
+ Mage::getSingleton('checkout/cart')->addProduct($product_obj, $option_request);
203
+ } catch (Exception $ex) {}
204
+ } else {
205
+ $option['product'] = (string) $product_id;
206
+ $option['qty'] = $product_quantity;
207
+ $option_request = new Varien_Object();
208
+ $option_request->setData($option);
209
+ try {
210
+ Mage::getSingleton('checkout/cart')->addProduct($product_obj, $option_request);
211
+ } catch (Exception $ex) {}
212
+ }
213
+ }
214
+ }
215
+
216
+ $quoteObj = Mage::getSingleton('checkout/cart')->getQuote();
217
+ $address = $quoteObj->getShippingAddress();
218
+ $quoteObj->assignCustomer($customer); //sets shipping/billing address
219
+ $customerAddressId = $this->getCustomerAddress()->getId();
220
+ $customerAddress = Mage::getModel('customer/address')->load($customerAddressId);
221
+
222
+ $address->importCustomerAddress($customerAddress)->setSaveInAddressBook(0);
223
+ $address->implodeStreetAddress();
224
+ $quoteObj->getShippingAddress()->setCollectShippingRates(true)->collectShippingRates();
225
+ $available_shipping_methods = $quoteObj->getShippingAddress()->getShippingRatesCollection();
226
+ if ( is_array( $this->getRequestCollection('chosenDeliveryMethod') ) && count ( $this->getRequestCollection('chosenDeliveryMethod') > 0 ) ) {
227
+ $chosenDeliveryMethod = $this->getRequestCollection('chosenDeliveryMethod'); // get chosen delivery method data from payair request array
228
+ } else {
229
+ $chosenDeliveryMethod = '';
230
+ $chosenDeliveryMethodName = '';
231
+ }
232
+
233
+ if ( is_array( $chosenDeliveryMethod ) && ( count( $chosenDeliveryMethod ) > 0 ) ) {
234
+ $chosenDeliveryMethodId = $chosenDeliveryMethod['customIdentifier'];
235
+ $chosenDeliveryMethodName = $chosenDeliveryMethod['name'];
236
+
237
+ /*Load the Shipping Rate Model by its ID*/
238
+ $salesQuoteRate = Mage::getModel('sales/quote_address_rate')->load($chosenDeliveryMethodId);
239
+ if ($salesQuoteRate) {
240
+ $_mcode = $salesQuoteRate->getCode();
241
+ $_shp_price = $salesQuoteRate->getPrice();
242
+ }
243
+ } elseif ( count ( $available_shipping_methods ) == 1 ) {
244
+ foreach( $available_shipping_methods as $_method ) {
245
+ $_mcode = $_method->getData('code');
246
+ $_shp_price = $_method->getData('price');
247
+ }
248
+ } elseif ( count ( $available_shipping_methods ) > 1 ) {
249
+ foreach( $available_shipping_methods as $_method ) {
250
+ $_mcode = NULL;
251
+ $_shp_price = 0;
252
+ }
253
+ }
254
+
255
+ $storeObj = $quoteObj->getStore()->load($this->getStoreId());
256
+ $quoteObj->setStore($storeObj);
257
+ $QuoteItems = $quoteObj->getAllItems();
258
+
259
+ $quoteObj->getShippingAddress()->setShippingMethod((string) $_mcode)->setCollectShippingRates(true);
260
+ $quoteObj->collectTotals();
261
+ $quoteObj->reserveOrderId();
262
+ $quoteObj->save();
263
+
264
+ $address = $quoteObj->getShippingAddress();
265
+
266
+ $quotePaymentObj = $quoteObj->getPayment(); // Get payment object
267
+ $quotePaymentObj->setMethod('gate');
268
+ $quoteObj->setPayment($quotePaymentObj); // Set Payair payment method
269
+
270
+ $rates_collection = Mage::getModel('sales/quote_address_rate')->getCollection()->setAddressFilter($address->getId());
271
+ $rates = array();
272
+ foreach ( $rates_collection as $rate ){
273
+ if ( !$rate->isDeleted() && $rate->getCarrierInstance() && Mage::getStoreConfig('carriers/'.$rate->getCarrier().'/active', $this->getStoreId())) {
274
+ if ( !isset( $rates[$rate->getCarrier()] ) ) {
275
+ $rates[$rate->getCarrier()] = array();
276
+ }
277
+ $rates[$rate->getCarrier()] = $rate->getData();
278
+ }
279
+ }
280
+
281
+ $subTotal = Mage::getSingleton('checkout/cart')->getQuote()->getSubtotal();
282
+ $grandTotal = ( Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal() ) ; // total amount of the products
283
+ $totalVat = $grandTotal - ($subTotal + $_shp_price); // total vat of the product
284
+
285
+ $deliveryMethods = $this->getDeliveryMethods( $rates, $chosenDeliveryMethodName ); // get delivery methods array
286
+
287
+ // Create cart respone to the mobile app
288
+ $response_array = array(
289
+ "statusCode" => "SUCCESS",
290
+ "message" => "operation successful",
291
+ "cart" => $item,
292
+ "deliveryMethods" => $deliveryMethods,
293
+ "totalAmount" => $this->getFormattedPrice($grandTotal),
294
+ "totalVat" => $this->getFormattedPrice($totalVat)
295
+ );
296
+ $response_json = json_encode($response_array);
297
+ Mage::log("\n response JSON methods in INDEX CONTROLLER SYNC ACTION: \n" . print_r($response_json, true), null, 'log.txt');
298
+ echo $response_json;
299
+
300
+
301
+ }
302
+ /**
303
+ * To pre varify the cart price and amount.
304
+ */
305
+ public function preverifyAction() {
306
+
307
+ $this->request = $this->getServiceRequest(); // JSON request from Payair server
308
+ $this->setStoreId(); // Set Store Id
309
+
310
+ $customer = $this->createCustomer($this->request->user);
311
+ $orderReference = $this->request->orderReference;
312
+ $payairReference = $this->request->payairReference;
313
+ $totalAmount = $this->request->totalAmount;
314
+ $totalVat = $this->request->totalVat;
315
+ $deliveryMethods = $this->getRequestCollection('chosenDeliveryMethod'); // get delivery methods for request array
316
+
317
+ $method_id = $deliveryMethods['customIdentifier']; // get method id
318
+
319
+ if ( empty( $method_id ) ) {
320
+ // Get the very first shipping method ID
321
+ $method_id = $this->getDefaultShippingMethodId($this->getStoreId());
322
+ }
323
+
324
+ $salesQuoteRate = Mage::getModel('sales/quote_address_rate')->load( (int) $method_id);
325
+
326
+ if ( $salesQuoteRate ) {
327
+ $_mcode = $salesQuoteRate->getCode();
328
+ }
329
+
330
+ Mage::getSingleton('checkout/cart')->truncate();
331
+
332
+ $products = $this->getRequestCollection('cart'); // get product data for request array
333
+
334
+ if( is_array( $products) && count( $products > 0 ) ) {
335
+ foreach ( $products as $product ) {
336
+ $product_id = $this->getCustomNameValue($product['customValues'], 'reference');
337
+ $product_obj = $this->loadProduct($product_id); // Load Product by Product Id
338
+ $product_quantity = $product['quantity'];
339
+
340
+ $options = $product_obj->getOptions();
341
+ $cartOptions = array();
342
+ $ConfigCartOptions = array();
343
+ foreach ( $options as $option ) {
344
+ $optionData = $option->getData();
345
+ $optionValues = Mage::helper('core')->decorateArray($option->getValues());
346
+
347
+ $type = $option->getData('type');
348
+ $optionValuesArray = array();
349
+
350
+ if ( $type == 'field' || $type == 'area' ) {
351
+ $optionValuesArray[$option->getData('default_title')] = $option->getData('option_id');
352
+ } else {
353
+ foreach ( $optionValues as $optionValue ) {
354
+ $optionValueData = $optionValue->getData();
355
+
356
+ $optionValuesArray[$optionValueData['default_title']] = $optionValueData['option_type_id'];
357
+ }
358
+ }
359
+
360
+ foreach ( $product['attributes'] as $attribute ) {
361
+ if ( $attribute['name'] == $optionData['default_title'] ) {
362
+ $selectedAttributes = array();
363
+ $selectedAttributesValue = array();
364
+ foreach ( $attribute['attributeValues'] as $attributeValue ) {
365
+ if ( $attributeValue['chosen']) {
366
+ $selectedAttributes[] = $optionValuesArray[$attributeValue ['value']];
367
+ if ( $type == 'field' || $type == 'area' ) {
368
+ $selectedAttributesValue[] = $attributeValue ['value'];
369
+ }
370
+
371
+ }
372
+ }
373
+ if ( $type == 'field' || $type == 'area' ) {
374
+ $cartOptions[$optionData['option_id']] = $selectedAttributesValue[0];
375
+ } else {
376
+ $cartOptions[$optionData['option_id']] = count($selectedAttributes) == 1 ? $selectedAttributes[0] : $selectedAttributes;
377
+ }
378
+ }
379
+ }
380
+ }
381
+ // Add configurable product to the cart
382
+ if ( $product_obj->getTypeId() == 'configurable' ) {
383
+ $configAttributesOptions = $product_obj->getTypeInstance(true)->getConfigurableAttributesAsArray($product_obj);
384
+
385
+ foreach ( $configAttributesOptions as $configAttributesOption ) {
386
+ $attribute_code = $configAttributesOption['attribute_code'];
387
+ $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attribute_code);
388
+ $optionValuesArray = array();
389
+ foreach ( $product['attributes'] as $attribute ) {
390
+ if( $attribute['name'] == $attribute_details->getData('store_label') ) {
391
+ foreach ( $configAttributesOption['values'] as $value ) {
392
+ $optionValuesArray[$value['default_label']] = $value['value_index'];
393
+ $selectedAttributes = array();
394
+ foreach( $attribute['attributeValues'] as $attributeValue ) {
395
+ if( $attributeValue['chosen']) {
396
+ $selectedAttributes[] = $optionValuesArray[$attributeValue ['value']];
397
+ }
398
+ }
399
+ }
400
+ $configCartOptions[$attribute_details->getData('attribute_id')] = count($selectedAttributes) == 1 ? $selectedAttributes[0] : $selectedAttributes;
401
+ }
402
+ }
403
+ }
404
+ }
405
+ isset( $configCartOptions ) ? $configCartOptions : $configCartOptions = NULL;
406
+ $option = array();
407
+ if ( count($cartOptions) > 0 ) {
408
+ $option['product'] = (string) $product_id;
409
+ $option['qty'] = $product_quantity;
410
+ $option['options'] = $cartOptions;
411
+ if ( is_array($configCartOptions) && count($configCartOptions) ) { //if config proudct attributes exists
412
+ $option['super_attribute'] = $configCartOptions;
413
+ }
414
+ $option_request = new Varien_Object();
415
+ $option_request->setData($option);
416
+ try {
417
+ Mage::getSingleton('checkout/cart')->addProduct($product_obj, $option_request);
418
+ } catch (Exception $ex) {}
419
+ } else {
420
+ $option['product'] = (string) $product_id;
421
+ $option['qty'] = $product_quantity;
422
+ $option_request = new Varien_Object();
423
+ $option_request->setData($option);
424
+ try {
425
+ Mage::getSingleton('checkout/cart')->addProduct($product_obj, $option_request);
426
+ } catch (Exception $ex) {}
427
+ }
428
+ }
429
+ }
430
+ $quoteObj = Mage::getSingleton('checkout/cart')->getQuote();
431
+
432
+ $quoteObj->assignCustomer($customer); //sets shipping/billing address
433
+
434
+ $storeObj = $quoteObj->getStore()->load($this->getStoreId());
435
+ $quoteObj->setStore($storeObj);
436
+ $QuoteItems = $quoteObj->getAllItems();
437
+
438
+ $quoteObj->getShippingAddress()->setShippingMethod((string) $_mcode)->setCollectShippingRates(true);
439
+ $quoteObj->collectTotals();
440
+ $quoteObj->reserveOrderId();
441
+ $quoteObj->save();
442
+
443
+ $quotePaymentObj = $quoteObj->getPayment();
444
+ $quotePaymentObj->setMethod('gate');
445
+ $quotePaymentObj->setTransactionId(uniqid());
446
+ $quoteObj->setPayment($quotePaymentObj);
447
+
448
+ $convertQuoteObj = Mage::getSingleton('sales/convert_quote');
449
+ $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
450
+ $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
451
+ $orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
452
+ $orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
453
+ $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
454
+ $orderObj->setShipping($customer->getShippingRelatedInfo());
455
+
456
+ foreach ( $QuoteItems as $item ) {
457
+ $orderItem = $convertQuoteObj->itemToOrderItem($item);
458
+ if ( $item->getParentItem() ) {
459
+ $orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
460
+ }
461
+ $orderObj->addItem($orderItem);
462
+ Mage::getSingleton('cataloginventory/stock')->registerItemSale($orderItem);
463
+ }
464
+
465
+ $orderObj->setCanShipPartiallyItem(false);
466
+ $orderObj->getPayment()->setTransactionId(str_pad((int)$this->request->payairReference, 8, "0", STR_PAD_LEFT));
467
+ $orderObj->place();
468
+ $orderId = $orderObj->getIncrementId();
469
+ $orderObj->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, "Payair has set the order status to Pending as the order is awaiting authorization.");
470
+ $orderObj->save();
471
+ $transaction = Mage::getModel('sales/order_payment_transaction');
472
+ $transaction->setOrderPaymentObject($orderObj->getPayment());
473
+ $transaction->setOrder($orderObj);
474
+ $transaction->setTxnType(Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER);
475
+ $transaction->save();
476
+
477
+ // Create cart respone to the mobile app
478
+ $response_array = array(
479
+ "statusCode" => "SUCCESS",
480
+ "message" => "operation successful",
481
+ "orderReference" => $orderId,
482
+ "payairReference" => $payairReference,
483
+ "cart" => $products,
484
+ "chosenDeliveryMethod" => $deliveryMethods,
485
+ "totalAmount" => $totalAmount,
486
+ "totalVat" => $totalVat
487
+ );
488
+
489
+ $response_json = json_encode($response_array);
490
+ Mage::log("\n response JSON methods in INDEX CONTROLLER preverify ACTION: \n" . print_r($response_json, true), null, 'log.txt');
491
+ echo $response_json;
492
+
493
+ }
494
+
495
+ /**
496
+ * To get the final payment confirmation.
497
+ */
498
+ public function resultAction() {
499
+
500
+ $this->request = $this->getServiceRequest(); // JSON request from Payair server
501
+ $orderReference = $this->request->orderReference;
502
+ $payairReference = $this->request->payairReference;
503
+ $transactionStatus = $this->request->transactionStatus;
504
+ $transactionStatusMessage = $this->request->transactionStatusMessage;
505
+ $payairExternalReference = $this->request->payairExternalReference;
506
+ $this->setStoreId();
507
+ //$totalAmount = $this->request->totalAmount;
508
+ //$totalVat = $this->request->totalVat;
509
+ $products = $this->getRequestCollection('cart'); // get product data for request array
510
+ $customValueArr = array();
511
+ if( is_array( $products) && count( $products > 0 ) ) {
512
+ foreach($products as $product) {
513
+ if( !empty ( $product['customValues'] ) ) {
514
+ $customValueArr = $product['customValues'];
515
+ }
516
+ }
517
+ }
518
+
519
+ $file_ref_name = $this->getCustomNameValue($customValueArr, 'fileRefNo'); // get the file name
520
+ $deliveryMethods = $this->getRequestCollection('chosenDeliveryMethod'); // get delivery methods for request array
521
+
522
+ if ( $transactionStatus == 1 ) {
523
+ if ( !empty ( $file_ref_name ) ) {
524
+ $fileContentArr = json_decode($this->getFileContent($file_ref_name),true);
525
+ $fileContentArr['paystatus'] = 'success';
526
+ $this->writeDataInFile($fileContentArr, $file_ref_name, 'w');
527
+ //$payair_reference = $array['payair_reference'];
528
+ }
529
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderReference);
530
+ $order->sendNewOrderEmail();
531
+ $order_status = $this->getConfig('gate_order_status', $this->getStoreId()); //get the order status from the admin config
532
+
533
+ $this->setOrderState( $order, $order_status );
534
+
535
+ if ( !empty ( $file_ref_name ) ) {
536
+ $this->deleteFile( $file_ref_name ); //delete the temp file in the log
537
+ }
538
+
539
+ $sanp_view = Mage::getStoreConfig('payment/gate/gate_snap_view', $this->getStoreId());
540
+
541
+ if ( $sanp_view == 1 ) {
542
+ $merchant_ref = Mage::getStoreConfig('payment/gate/gate_marchantref', $this->getStoreId());
543
+ $this->completedOrderNotification($merchant_ref);
544
+ }
545
+ } else {
546
+ //load your order by order_id
547
+ $order = Mage::getModel('sales/order')->load($orderReference);
548
+ $order->setState( Mage_Sales_Model_Order::STATE_CANCELED ); //Order cancel status
549
+ $order->save();
550
+ }
551
+
552
+ $receipt_msg_top = Mage::getStoreConfig('payment/gate/gate_order_info_top', $this->getStoreId());
553
+ $receipt_msg_bottom = Mage::getStoreConfig('payment/gate/gate_order_info_bottom', $this->getStoreId());
554
+
555
+ $response_array = array(
556
+ "statusCode" => "SUCCESS",
557
+ "message" => "operation successful",
558
+ "transactionStatus" => $transactionStatus,
559
+ "transactionStatusMessage" => $transactionStatusMessage,
560
+ "payairExternalReference" => $payairExternalReference,
561
+ "orderReference" => $orderReference,
562
+ "receiptMsgTop" => $receipt_msg_top,
563
+ "receiptMsgBottom" => $receipt_msg_bottom,
564
+ "payairReference" => $payairReference,
565
+ "cart" => $products,
566
+ "chosenDeliveryMethods" => $deliveryMethods
567
+ );
568
+
569
+ $response_json = json_encode($response_array);
570
+ Mage::log("\n response JSON methods in INDEX CONTROLLER result ACTION: \n" . print_r($response_json, true), null, 'log.txt');
571
+ echo $response_json;
572
+ }
573
+
574
+ /**
575
+ * The function used to get the ajax request.
576
+ * @return null
577
+ */
578
+ public function payStatusAction () {
579
+ $file_name = $this->getRequest()->getParam('link');
580
+ $pay_status = $this->readData($file_name, 'paystatus');
581
+ if ( $pay_status != 'running' ) {
582
+ Mage::getSingleton('checkout/cart')->truncate();
583
+ Mage::getSingleton('checkout/session')->clear();
584
+ }
585
+
586
+ echo $this->readData($file_name, 'paystatus');
587
+ }
588
+
589
+ /**
590
+ * The function used to write the data in the temporary file.
591
+ * @return null
592
+ */
593
+
594
+ public function writeDataInFile( $data, $data_file, $file_mode = 'a' ) {
595
+ $tmp_file_name = $data_file . $this->data_file_extension;
596
+ $file_location = $this->getFilePath() . $tmp_file_name;
597
+ @chmod($file_location,0777);
598
+ $handle = fopen($file_location, $file_mode);
599
+ if ($handle) {
600
+ @fwrite($handle, json_encode($data));
601
+ @fclose($handle);
602
+ } else {
603
+ Mage::log('Unable to write the data in the file "'.$file_location. '". No such file or direcrory found');
604
+ }
605
+ }
606
+
607
+ /**
608
+ * The function used to read the dataFile saved from the cart action.
609
+ * @return Array
610
+ */
611
+
612
+ public function readData( $file, $key = NULL ) {
613
+ $tmp_file_path = $this->getFilePath();
614
+ $_fileToImportLocal = $tmp_file_path.DS.$file . $this->data_file_extension;
615
+ $flocal = new Varien_Io_File();
616
+ $fp = $flocal->Open(array('path' => $tmp_file_path),'w+',0777);
617
+ if ($fp) {
618
+ $str = $flocal->read($_fileToImportLocal);
619
+ $data_array = json_decode($str,true);
620
+ if (@array_key_exists($key,$data_array)) {
621
+ $data = $data_array[$key];
622
+ return $data;
623
+ } else {
624
+ return null;
625
+ }
626
+ } else {
627
+ Mage::log('Unable to open the file "'.$_fileToImportLocal. '". No such file or direcrory found');
628
+ }
629
+ }
630
+
631
+ /**
632
+ * The function used to delete temporary file.
633
+ * @return null
634
+ */
635
+
636
+ public function deleteFile( $file_name ) {
637
+ $tmp_file_name = $file_name . $this->data_file_extension;
638
+ $file_location = $this->getFilePath() . $tmp_file_name;
639
+ try {
640
+ unlink( $file_location );
641
+ } catch ( Exception $e ) {
642
+ echo 'Caught exception: '. $e->getMessage();
643
+ }
644
+ }
645
+
646
+ /**
647
+ * The function used to get the temporary data file path.
648
+ * @return String
649
+ */
650
+
651
+ public function getFilePath() {
652
+ $base_dir = Mage::getBaseDir();
653
+ $tmp_file_dir = $base_dir.DS.'var/log/';
654
+
655
+ return $tmp_file_dir;
656
+ }
657
+
658
+ private function getFileContent( $file_name ) {
659
+ $tmp_file_path = $this->getFilePath();
660
+ $_fileToImportLocal = $tmp_file_path.DS.$file_name . $this->data_file_extension;
661
+ $flocal = new Varien_Io_File();
662
+ $fp = $flocal->Open( array ( 'path' => $tmp_file_path ),'w+',0777 );
663
+ return ($fp) ? $flocal->read($_fileToImportLocal) : '';
664
+ }
665
+
666
+ /**
667
+ * handle JSON request from the payair server
668
+ *
669
+ * @param
670
+ * @return request array
671
+ */
672
+ private function getServiceRequest() {
673
+ $json = file_get_contents('php://input');
674
+ $json = utf8_encode($json);
675
+ Mage::log("\n Request JSON is : \n" . print_r($json, true), null, $this->log_file);
676
+ return json_decode($json);
677
+ }
678
+
679
+ /**
680
+ * The function Return the first method ID
681
+ * @param $store_id
682
+ * @return Integer
683
+ */
684
+
685
+ public function getDefaultShippingMethodId($store_id) {
686
+ $rates_collection = Mage::getModel('sales/quote_address_rate')->getCollection();
687
+ $rates = array();
688
+ foreach ($rates_collection as $rate) {
689
+ if ( !$rate->isDeleted() && $rate->getCarrierInstance() && Mage::getStoreConfig('carriers/'.$rate->getCarrier().'/active', $store_id)) {
690
+ if (!isset($rates[$rate->getCarrier()])) {
691
+ $rates[$rate->getCarrier()] = array();
692
+ }
693
+ $rates[$rate->getCarrier()] = $rate;
694
+ }
695
+ }
696
+ $keys = @array_keys($rates);
697
+ $method = $rates[$keys[0]];
698
+ // Return the first method ID
699
+ return $method->getRateId();
700
+ }
701
+
702
+ /**
703
+ * The function encode the string.
704
+ * @return string
705
+ */
706
+ public function encodeString ( $string ) {
707
+ return urlencode(trim($string));
708
+ }
709
+
710
+ /**
711
+ * The function generates MAC.
712
+ *
713
+ * @return String
714
+ */
715
+
716
+ protected function mac($string, $storeId) {
717
+ $hash = $string . $this->getConfig('gate_secret', $storeId);
718
+
719
+ return hash('sha256', $hash);
720
+ }
721
+
722
+ /**
723
+ * The function returns the configuration object.
724
+ *
725
+ * @return String
726
+ */
727
+ protected function getConfig($item, $storeId) {
728
+ return Mage::getStoreConfig('payment/gate/' . $item, $storeId);
729
+ }
730
+
731
+ /**
732
+ * The function returns the request path .
733
+ *
734
+ * @return String
735
+ */
736
+ public function getRequestPath() {
737
+ $merchantAccountRef = $this->getConfig('gate_marchantref', $this->getStoreId());
738
+ return "/rest/merchant/".$merchantAccountRef."/checkout";
739
+
740
+ }
741
+
742
+ private function stringMac ($string) {
743
+ return hash('sha256', $string);
744
+ }
745
+
746
+ /**
747
+ * The function returns the authorization.
748
+ *
749
+ * @param $date, $timestamp
750
+ * @return String
751
+ */
752
+ function getAuthorization($data,$timestamp) {
753
+ $secretKey = $this->getConfig('gate_secret', $this->getStoreId());
754
+ $merchantAccountRef = $this->getConfig('gate_marchantref', $this->getStoreId());
755
+ $stringToSign = ( $timestamp) . $data . $this->getRequestPath() . $secretKey;
756
+ $signature = hash_hmac('sha256', $stringToSign, $secretKey,false );
757
+
758
+ $authorization = "PAA" . " " . base64_encode( $merchantAccountRef . ':' . $signature );
759
+ return $authorization;
760
+ }
761
+
762
+ /**
763
+ * The function returns the header.
764
+ *
765
+ * @param String $data
766
+ * @return String $header
767
+ */
768
+ function getHeaders($data) {
769
+ $timestamp = time() * 1000;
770
+ $headers = array();
771
+ $headers[] = 'Content-Type: application/json';
772
+ $headers[] = 'X-TIMESTAMP: ' . $timestamp;
773
+ $headers[] = 'X-WEBSERVICEVERSION: 4.1';
774
+ $headers[] = 'Authorization: ' . $this->getAuthorization($data,$timestamp);
775
+ return $headers;
776
+ }
777
+
778
+ /**
779
+ * The function POST the data through the curl.
780
+ *
781
+ * @param String $data
782
+ * @return result
783
+ */
784
+
785
+ function sendRequest($data) {
786
+
787
+ $headers = $this->getHeaders($data);
788
+
789
+ $environment = $this->getConfig('environment', $this->getStoreId());
790
+ $merchantAccountRef = $this->getConfig('gate_marchantref', $this->getStoreId());
791
+
792
+ if ( $environment == 'production' ) {
793
+ $address = 'payair.com';
794
+ } else {
795
+ $address = 'test.payair.com';
796
+ }
797
+
798
+ $httpfile = "/rest/merchant/".$merchantAccountRef."/checkout";
799
+ $port = 443;
800
+ $ssl = "ssl://";
801
+
802
+ $fp = fsockopen( $ssl.$address, $port , $errno, $errstr, 30 );
803
+ if (!$fp) {
804
+ echo "$errstr ($errno)<br />\n";
805
+ } else {
806
+ $out = "POST $httpfile HTTP/1.1\r\n";
807
+ $out .= "Host: $address\r\n";
808
+
809
+ foreach ($headers as $header) {
810
+ $out .= "$header\r\n";
811
+ }
812
+
813
+ $out .= "Content-Length: ".strlen($data)."\r\n";
814
+ $out .= "Connection: Close\r\n\r\n";
815
+ $out .= $data;
816
+
817
+ fwrite($fp, $out);
818
+ $reuslt = "";
819
+ while (!feof($fp)) {
820
+ @$result .= fgets($fp, 1024);
821
+ }
822
+ fclose($fp);
823
+ }
824
+ return $result;
825
+ }
826
+
827
+ /**
828
+ * To create QR code at shopping cart page.
829
+ */
830
+
831
+ public function cartAction() {
832
+
833
+ $this->setStoreId();
834
+ $data_file_name = uniqid();
835
+ $item_array = array();
836
+ $items_in_cart = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
837
+
838
+ if ( count($items_in_cart) == 0 ) {
839
+ echo "There are no items in the cart";
840
+ exit;
841
+ }
842
+
843
+ $countryCode = Mage::getStoreConfig('general/country/default', $this->getStoreId());
844
+ Mage::getSingleton('checkout/cart')->getQuote()->getShippingAddress()
845
+ ->setCountryId($countryCode)
846
+ ->setCity('')
847
+ ->setPostcode('')
848
+ ->setRegionId('')
849
+ ->setRegion('')
850
+ ->setCollectShippingRates(true);
851
+ Mage::getSingleton('checkout/cart')->getQuote()->save();
852
+ Mage::getSingleton('checkout/cart')->init();
853
+ Mage::getSingleton('checkout/cart')->save();
854
+
855
+ foreach ( $items_in_cart as $item ) {
856
+ $product_obj = $this->loadProduct($item->getProductId()); // Load Product by Product Id
857
+ // Get product options (for custom and configurable products)
858
+ $options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
859
+ if ( empty( $options['options'] ) ) {
860
+ $options['options'] = NULL;
861
+ }
862
+ $cartOptionArr = array();
863
+ if ( is_array ( $options['options'] ) && count( $options['options'] ) > 0 ) {
864
+ foreach ( $options['options'] as $option ) {
865
+ $cartOptionArr[ $option['option_id'] ] = $option['option_value'];
866
+ }
867
+ }
868
+ $item_array[] = array(
869
+ "name" => $this->limitStringLenght( $product_obj->name, 254 ),
870
+ "amount" => $this->getFormattedPrice($product_obj->price),
871
+ "vat" => $this->getFormattedPrice( $this->getVatAmount( $product_obj->price, $this->getVatPercent() ) ),
872
+ "quantity" => $item->getQty(),
873
+ "description" => $this->limitStringLenght( $product_obj->short_description, 254 ),
874
+ "sku" => $this->limitStringLenght( $product_obj->sku, 63 ),
875
+ "vatPercent" => $this->getFormattedPrice($this->getVatPercent()),
876
+ "imageUrl" => $this->limitStringLenght((string) Mage::Helper('catalog/image')->init($product_obj,'image'),1023),
877
+ "url" => $this->limitStringLenght( $product_obj->getProductUrl(), 1023),
878
+ "longDescription" => $this->limitStringLenght( $product_obj->description, 1499 ),
879
+ "currency" => $this->getCurrencyISONumber(),
880
+ "sortOrder" => "1",
881
+ "discounts" => array(),
882
+ "customValues" => $this->setCustomValue( $item->getProductId(), $data_file_name ),//$this->setCustomValue('reference', $item->getProductId()),
883
+ "attributes" => $this->getAttributes($product_obj, $cartOptionArr)
884
+ );
885
+
886
+ }
887
+
888
+ $grandTotal = Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal() ; // total amount of the products
889
+ $subTotal = Mage::getSingleton('checkout/cart')->getQuote()->getSubtotal();
890
+ $totalVat = $grandTotal - $subTotal;
891
+
892
+ $data_array = array(
893
+ "currency" => $this->getCurrencyISONumber(),
894
+ "totalAmount" => $this->getFormattedPrice($grandTotal),
895
+ "totalVat" => $totalVat,
896
+ "cart" => $item_array
897
+ );
898
+
899
+ $transaction_status = array( 'paystatus' => 'running');
900
+ // Write the data to the temporay file @dataFile
901
+ $this->writeDataInFile( $transaction_status, $data_file_name );
902
+
903
+ $data = json_encode($data_array);
904
+ Mage::log("\n response JSON methods in INDEX CONTROLLER Cart ACTION: \n" . print_r($data, true), null, 'log.txt');
905
+
906
+ // Post Checkout request on Merchant URL
907
+ $result = $this->sendRequest($data);
908
+
909
+ $response = explode('{', $result);
910
+ $data = array();
911
+ if ( is_array($response) ) {
912
+ foreach ( $response as $key => $value ) {
913
+ $res = explode('"', $value);
914
+ if (isset($res[1])) { $res[1]; } else { $res[1] = NULL;}
915
+ if (isset($res[3])) { $res[3]; } else { $res[3] = NULL;}
916
+ if (isset($res[5])) { $res[5]; } else { $res[5] = NULL;}
917
+ if (isset($res[7])) { $res[7]; } else { $res[7] = NULL;}
918
+ if (isset($res[11])) { $res[11]; } else { $res[11] = NULL;}
919
+ if (isset($res[13])) { $res[13]; } else { $res[13] = NULL;}
920
+ $data[$res[1]] = $res[3];
921
+ $data[$res[5]] = $res[7];
922
+ $data[$res[11]] = $res[13];
923
+ }
924
+ }
925
+
926
+ $cartResponseArr = array();
927
+ if ( $data['statusMessage'] != 'Your request was processed successfully' ) {
928
+ $cartResponseArr['file'] = $data_file_name;
929
+ $cartResponseArr['text'] = $data['statusMessage'];
930
+ echo json_encode($cartResponseArr);
931
+ } else {
932
+ // Check if the QR data was set in the string
933
+ if ( stripos($result, 'qrData') !== false && $data['qrData'] !='' ) {
934
+ $cartResponseArr['file'] = $data_file_name;
935
+ $cartResponseArr['text'] = $data['qrData'];
936
+ echo json_encode($cartResponseArr);
937
+ } else {
938
+ // Something went wrong
939
+ //echo 'Error. Can not get QR code. Please contact admin';
940
+ $cartResponseArr['text'] = 'Error. Can not get QR code. Please contact admin';
941
+ $cartResponseArr['file'] = $data_file_name;
942
+ echo json_encode($cartResponseArr);
943
+ }
944
+ }
945
+ exit;
946
+ }
947
+
948
+
949
+ /**
950
+ * Get value of the Custom Array
951
+ *
952
+ * @param $customArrays, $identifier
953
+ * @return Custom Value
954
+ */
955
+ private function getCustomNameValue ($customArrays, $identifier) {
956
+ foreach ($customArrays as $id => $customArray) {
957
+ if ( in_array( $identifier, $customArray ) ) {
958
+ return $customArrays[$id]['value'];
959
+ }
960
+ }
961
+
962
+ return '';
963
+ }
964
+
965
+
966
+ /**
967
+ * Set store id
968
+ *
969
+ * @param int $store id
970
+ * @return int $store id
971
+ */
972
+ private function setStoreId ( $storeId = NULL) {
973
+ if ( empty($storeId) ) {
974
+ $this->store_id = Mage::app()->getStore()->getStoreId();
975
+ } else {
976
+ $this->store_id = $storeId;
977
+ }
978
+ }
979
+
980
+ /**
981
+ * Get store id
982
+ *
983
+ * @return int $store id
984
+ */
985
+ private function getStoreId() {
986
+ return $this->store_id;
987
+ }
988
+
989
+ /**
990
+ * Load product from
991
+ *
992
+ * @param $product_id
993
+ * @return Product Object
994
+ */
995
+ private function loadProduct ( $product_id ) {
996
+ $product = Mage::getModel('catalog/product')->setStoreId( $this->getStoreId() );
997
+ $product->load( (string) $product_id);
998
+ return $product;
999
+ }
1000
+
1001
+ /**
1002
+ * Get Currency ISO number based upon currency code
1003
+ *
1004
+ * @return int $ISONumber
1005
+ */
1006
+ private function getCurrencyISONumber () {
1007
+ $currency_code = Mage::app()->getStore($this->getStoreId())->getCurrentCurrencyCode();
1008
+ switch ( $currency_code ) {
1009
+ case 'SWE' :
1010
+ $ISONumber = 752;
1011
+ break;
1012
+ case 'USD' :
1013
+ default:
1014
+ $ISONumber = 840;
1015
+ }
1016
+
1017
+ return $ISONumber;
1018
+ }
1019
+ /**
1020
+ * Get allowed product tax classes by rule id
1021
+ *
1022
+ * @param int $ruleId
1023
+ * @return array
1024
+ */
1025
+ private function createCustomer($user) {
1026
+
1027
+ $customer = Mage::getModel('customer/customer');
1028
+ $customer->website_id = Mage::getModel('core/store')->load( $this->getStoreId() )->getWebsiteId();
1029
+ $customer->setStore(Mage::getModel('core/store')->load( $this->getStoreId() ));
1030
+ $customer->loadByEmail((string)$user->email);
1031
+ if (!$customer->getId()) {
1032
+ $pass = uniqid();
1033
+ $customer->setEmail($user->email);
1034
+ $customer->setFirstname($user->firstName);
1035
+ $customer->setLastname($user->lastName);
1036
+ $customer->setPassword($pass);
1037
+ $customer->sendNewAccountEmail();
1038
+ $customer->setConfirmation(null);
1039
+ $customer->save();
1040
+ }
1041
+
1042
+ $customAddress = Mage::getModel("customer/address");
1043
+ $this->setCustomerAddress($customAddress);
1044
+
1045
+ $customAddress->setCustomerId($customer->getId());
1046
+ if ($defaultShippingId = $customer->getDefaultShipping()) {
1047
+ $customAddress->load($defaultShippingId);
1048
+ } elseif ($defaultBillingId = $customer->getDefaultBilling()) {
1049
+ $customAddress->load($defaultBillingId);
1050
+ }
1051
+ try {
1052
+ $customAddress->firstname = $user->firstName;
1053
+ $customAddress->lastname = $user->lastName;
1054
+ $customAddress->country_id = $user->country; //Country code here
1055
+ /* NOTE: If country is USA, please set up $address->region also */
1056
+ if($user->country == 'US') {
1057
+ $customAddress->region_id = Mage::getModel('gate/payair')->getRegionId('US', $user->state);
1058
+ }
1059
+ $customAddress->street = $user->address1;
1060
+ $customAddress->postcode = $user->zip;
1061
+ $customAddress->city = $user->city;
1062
+ $customAddress->telephone = $user->phoneNr;
1063
+ $customAddress->fax = "";
1064
+ $customAddress->company = "";
1065
+ $customAddress->save();
1066
+
1067
+ $customAddress->setCustomerId($customer->getId())
1068
+ ->setIsDefaultBilling(1)
1069
+ ->setIsDefaultShipping(1)
1070
+ ->setSaveInAddressBook(1);
1071
+ $customAddress->save();
1072
+
1073
+ } catch (Exception $ex) {}
1074
+
1075
+ return $customer;
1076
+ }
1077
+
1078
+ /**
1079
+ * Set Customer addres
1080
+ *
1081
+ * @param Obj $customAddress
1082
+ */
1083
+ private function setCustomerAddress ($customAddress) {
1084
+ $this->customAddress = $customAddress;
1085
+ }
1086
+
1087
+ /**
1088
+ * get Customer addres
1089
+ *
1090
+ * @return customAddress
1091
+ */
1092
+ private function getCustomerAddress() {
1093
+ return $this->customAddress;
1094
+ }
1095
+
1096
+ /**
1097
+ * The function returns the customer tax class id .
1098
+ * @param $customer
1099
+ * @return int
1100
+ */
1101
+ private function getCustomerTaxClassId ( $customer ) {
1102
+ $class_id = Mage::getModel('customer/group')->getTaxClassId( $customer->getData('group_id') );
1103
+ return $class_id;
1104
+ }
1105
+
1106
+ /**
1107
+ * The function returns the tax rate.
1108
+ * @param $customer, $product_obj
1109
+ * @return Float
1110
+ */
1111
+ private function setVatPercent($customer, $product_obj) {
1112
+ $calculator = Mage::getSingleton('tax/calculation');
1113
+ $request = $calculator->getRateRequest(
1114
+ $customer->getDefaultShippingAddress(),
1115
+ $customer->getDefaultBillingAddress(),
1116
+ $this->getCustomerTaxClassId($customer),
1117
+ Mage::getModel('core/store')->load($this->getStoreId())
1118
+ );
1119
+ $tax = 0;
1120
+
1121
+ if ( $product_obj->getTaxClassId() == 0 ) {
1122
+ $this->vatPercent = $tax;
1123
+ } else {
1124
+ $request->setProductClassId($product_obj->getTaxClassId());
1125
+ $rate = $calculator->getRate($request);
1126
+ $applied_rates = $calculator->getAppliedRates($request);
1127
+
1128
+ foreach ($applied_rates as $t) {
1129
+ $tax = $tax + $t['percent'];
1130
+ }
1131
+ $this->vatPercent = $tax;
1132
+ }
1133
+
1134
+ return $this;
1135
+ }
1136
+
1137
+ /**
1138
+ * Get Vat Percentage
1139
+ *
1140
+ * @return VatPercent
1141
+ */
1142
+ private function getVatPercent () {
1143
+
1144
+ return $this->vatPercent;
1145
+ }
1146
+
1147
+ /**
1148
+ * Get vat amount
1149
+ *
1150
+ * @param $price, $taxRate
1151
+ * @return customAddress
1152
+ */
1153
+ private function getVatAmount ($price, $taxRate) {
1154
+ return $price * ( $taxRate / 100 );
1155
+ }
1156
+
1157
+ /**
1158
+ * Set Custom Value
1159
+ *
1160
+ * @param $name, $value
1161
+ * @return Array
1162
+ */
1163
+ private function setCustomValue ( $product_id, $data_file_name = NULL ) {
1164
+ if( empty($data_file_name) || $data_file_name == NULL ) {
1165
+ $customValueArr = array(
1166
+ array( 'name' => 'reference', 'value' => $product_id )
1167
+ );
1168
+ } else {
1169
+ $customValueArr = array(
1170
+ array( 'name' => 'reference', 'value' => $product_id ),
1171
+ array( 'name' => 'fileRefNo','value' => $data_file_name )
1172
+ );
1173
+ }
1174
+ return $customValueArr ;
1175
+ }
1176
+
1177
+ /**
1178
+ * get attribute name
1179
+ *
1180
+ * @param $product_obj
1181
+ * @return attribute array
1182
+ */
1183
+ public function getAttributes ($product_obj, $cartOptionArr = array(), $syncCartOptionArr = array() ) {
1184
+
1185
+ switch ( $product_obj->getTypeId() ) {
1186
+ case 'simple':
1187
+ $attributes = $this->getSimpleProductAttributes($product_obj, $cartOptionArr, $syncCartOptionArr);
1188
+ break;
1189
+ case 'configurable':
1190
+ $attributes = $this->getConfigurableProductAttributes($product_obj);
1191
+ break;
1192
+ default:
1193
+ $attributes = array();
1194
+ break;
1195
+
1196
+ }
1197
+
1198
+ return $attributes;
1199
+ }
1200
+
1201
+ /**
1202
+ * get simple product attributes
1203
+ *
1204
+ * @param $product_obj
1205
+ * @return attribute array
1206
+ */
1207
+ private function getSimpleProductAttributes ($product_obj, $cartOptionArr = array(), $syncCartOptionArr = array()) {
1208
+
1209
+ $options = Mage::helper('core')->decorateArray($product_obj->getOptions());
1210
+ if ( is_array($options) && count($options) > 0 ) {
1211
+ $attributes = array();
1212
+ $total_options = count($options);
1213
+ $i = 1;
1214
+ foreach ($options as $option) {
1215
+ $optionData = $option->getData();
1216
+
1217
+ switch ( strtolower(trim($optionData['type'])) ) {
1218
+ case 'drop_down':
1219
+ case 'radio':
1220
+ $optionType = "RADIO";
1221
+ break;
1222
+ case 'checkbox':
1223
+ $optionType = "CHECKBOX";
1224
+ break;
1225
+ case 'field':
1226
+ case 'area':
1227
+ default:
1228
+ $optionType = "INPUT";
1229
+ break;
1230
+ }
1231
+
1232
+ $sort_order = ($total_options - $optionData['sort_order']) + 1; //calulate sort order in reverse to magento
1233
+ if( $sort_order <= 0 ) {
1234
+ $sort_order = $last_order - 1;
1235
+ }
1236
+
1237
+ $attributes[] = array(
1238
+ "type" => $optionType,
1239
+ "mandatory" => $optionData['is_require'] ? true : false,
1240
+ "name" => $optionData['default_title'],
1241
+ "attributeValues" => $this->getAttributeValues($option, $product_obj, $cartOptionArr, $syncCartOptionArr),
1242
+ "customIdentifier" => $optionData['option_id'],
1243
+ "sortOrder" => ( $sort_order >= 0 ) ? $sort_order : 1
1244
+ );
1245
+ $last_order = $sort_order;
1246
+ }
1247
+ }
1248
+ return !empty($attributes) ? $attributes : array();
1249
+ }
1250
+
1251
+ /**
1252
+ * get simple product attributes value
1253
+ *
1254
+ * @param option $product_obj
1255
+ * @return attribute value array
1256
+ */
1257
+ private function getAttributeValues ($option, $product_obj, $cartOptionArr = array(), $syncCartOptionArr = array() ) {
1258
+ $optionValues = Mage::helper('core')->decorateArray($option->getValues());
1259
+ $total_options = count($optionValues);
1260
+ $attributeValues = array();
1261
+ $type = $option->getData('type');
1262
+
1263
+ // If items are selected in cart
1264
+ $cartOptionValueArr = array();
1265
+ $option->getData('option_id');
1266
+ if ( is_array ($cartOptionArr) && count($cartOptionArr) > 0 ) {
1267
+ $cartOptionValue = $cartOptionArr[$option->getData('option_id')];
1268
+ $cartOptionValueArr = explode(',', $cartOptionValue);
1269
+
1270
+ } elseif ( is_array ($syncCartOptionArr) && count($syncCartOptionArr) > 0 ) {
1271
+ $cartOptionValue = $syncCartOptionArr[$option->getData('option_id')];
1272
+ if ( is_array ( $cartOptionValue ) && count ( $cartOptionValue ) > 1 ) {
1273
+ $cartOptionValueArr = $cartOptionValue;
1274
+ } else {
1275
+ $cartOptionValueArr[] = $cartOptionValue;
1276
+ }
1277
+
1278
+ }
1279
+ if ( $type == 'field' || $type == 'area' ) {
1280
+ $cartOptionValueArr = array_filter($cartOptionValueArr);
1281
+ $sort_order = ($total_options - $option->getData('sort_order')) + 1; //calulate sort order in reverse to magento
1282
+
1283
+ $attributeValues[] = array(
1284
+ "value" => !empty($cartOptionValueArr) ? $cartOptionValueArr[0] : " ",
1285
+ "chosen" => true,
1286
+ "amount" => $this->getFormattedPrice($option->getData('default_price')),
1287
+ "vat" => $this->getFormattedPrice( $this->getVatAmount( $option->getData('default_price'), $this->getVatPercent() ) ),
1288
+ "overrideImageUrl" => false,
1289
+ "customIdentifier" => $option->getData('option_id'),
1290
+ "sortOrder" => ( $sort_order >= 0 ) ? $sort_order : 1
1291
+ );
1292
+ } else {
1293
+ $last_order = 0;
1294
+ foreach ( $optionValues as $optionValue ) {
1295
+ $optionValueData = $optionValue->getData();
1296
+ $sort_order = ($total_options - $optionValueData['sort_order']) + 1; //calulate sort order in reverse to magento
1297
+ if ( $sort_order <= 0 ) {
1298
+ $sort_order = $last_order - 1;
1299
+ }
1300
+
1301
+ $attributeValues[] = array(
1302
+ "value" => $optionValueData['default_title'],
1303
+ "chosen" => ( in_array($optionValueData['option_type_id'], $cartOptionValueArr) ) ? true : false,
1304
+ "amount" => $this->getFormattedPrice($optionValueData['default_price']),
1305
+ "vat" => $this->getFormattedPrice( $this->getVatAmount( $optionValueData['default_price'], $this->getVatPercent() ) ),
1306
+ "overrideImageUrl" => false,
1307
+ "customIdentifier" => $optionValueData['option_type_id'],
1308
+ "sortOrder" => ( $sort_order >= 0 ) ? $sort_order : 1
1309
+ );
1310
+ $last_order = $sort_order;
1311
+ }
1312
+ }
1313
+ return !empty($attributeValues) ? $attributeValues : '';
1314
+ }
1315
+
1316
+ /**
1317
+ * get Configurable product attributes
1318
+ *
1319
+ * @param $product_obj
1320
+ * @return attribute array
1321
+ */
1322
+ private function getConfigurableProductAttributes ($product_obj) {
1323
+
1324
+ $attributes = array();
1325
+ $productConfigAttributeOptions = $product_obj->getTypeInstance(true)->getConfigurableAttributesAsArray($product_obj);
1326
+
1327
+ if ( is_array($productConfigAttributeOptions) && count($productConfigAttributeOptions) > 0 ) {
1328
+ foreach ($productConfigAttributeOptions as $productConfigAttribute) {
1329
+ $attribute_code = $productConfigAttribute['attribute_code'];
1330
+ $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attribute_code);
1331
+
1332
+ switch ( strtolower(trim($attribute_details->getData('frontend_input'))) ) {
1333
+ case 'select':
1334
+ case 'radio':
1335
+ $optionType = "RADIO";
1336
+ break;
1337
+ case 'checkbox':
1338
+ $optionType = "CHECKBOX";
1339
+ break;
1340
+ case 'field':
1341
+ case 'area':
1342
+ default:
1343
+ $optionType = "INPUT";
1344
+ break;
1345
+ }
1346
+
1347
+ $attributes[] = array(
1348
+ "type" => $optionType,
1349
+ "mandatory" => $attribute_details->getData('is_require') ? true : false,
1350
+ "name" => $attribute_details->getData('store_label'),
1351
+ "attributeValues" => $this->getCofigAttributeValues($productConfigAttribute['values'], $product_obj),
1352
+ "customIdentifier" => $attribute_details->getData('attribute_id'),
1353
+ "sortOrder" => ( $attribute_details->getData('sort_order') > 0 ) ? $attribute_details->getData('sort_order') : 1
1354
+ );
1355
+ }
1356
+ }
1357
+ $simpleOptions = Mage::helper('core')->decorateArray($product_obj->getOptions());
1358
+ if ( is_array($simpleOptions) && count($simpleOptions) > 0 ) {
1359
+ $sortOrder = 0;
1360
+ foreach ($simpleOptions as $option) {
1361
+
1362
+ $sortOrder ++;
1363
+ $optionData = $option->getData();
1364
+
1365
+ switch ( strtolower(trim($optionData['type'])) ) {
1366
+ case 'drop_down':
1367
+ case 'radio':
1368
+ $optionType = "RADIO";
1369
+ break;
1370
+ case 'checkbox':
1371
+ $optionType = "CHECKBOX";
1372
+ break;
1373
+ case 'field':
1374
+ case 'area':
1375
+ default:
1376
+ $optionType = "INPUT";
1377
+ break;
1378
+ }
1379
+
1380
+ $attributes[] = array(
1381
+ "type" => $optionType,
1382
+ "mandatory" => $optionData['is_require'] ? true : false,
1383
+ "name" => $optionData['default_title'],
1384
+ "attributeValues" => $this->getAttributeValues($option, $product_obj),
1385
+ "customIdentifier" => $optionData['option_id'],
1386
+ "sortOrder" => $sortOrder
1387
+ );
1388
+ }
1389
+ }
1390
+ return !empty($attributes) ? $attributes : array();
1391
+ }
1392
+
1393
+ /**
1394
+ * get cofig product attributes value
1395
+ *
1396
+ * @param $productConfigValues $product_obj
1397
+ * @return attribute value array
1398
+ */
1399
+ private function getCofigAttributeValues ($productConfigValues, $product_obj) {
1400
+
1401
+ $sortOrder = 1;
1402
+ $attributeValues = array();
1403
+
1404
+ foreach ( $productConfigValues as $value ) {
1405
+ $attributeValues[] = array(
1406
+ "value" => $value['default_label'],
1407
+ "chosen" => false,
1408
+ "amount" => $this->getFormattedPrice($value['pricing_value']),
1409
+ "vat" => $this->getFormattedPrice( $this->getVatAmount( $value['pricing_value'], $this->getVatPercent() ) ),
1410
+ "overrideImageUrl" => false,
1411
+ "customIdentifier" => $value['value_index'],
1412
+ "sortOrder" => $sortOrder
1413
+ );
1414
+ $sortOrder++;
1415
+ }
1416
+
1417
+ return !empty($attributeValues) ? $attributeValues : '';
1418
+ }
1419
+
1420
+ /**
1421
+ * The function returns the formatted price according to the currency.
1422
+ * @return float
1423
+ */
1424
+
1425
+ private function getFormattedPrice ( $realPrice ) {
1426
+ $formattedPrice = number_format(Mage::helper('core')->currency($realPrice, false, false), 2, '.', '');
1427
+
1428
+ return ($formattedPrice) ? $formattedPrice * 100: 0;
1429
+ }
1430
+
1431
+ public function prd ($d) {
1432
+ echo "<pre>";print_r($d);exit;
1433
+ }
1434
+
1435
+ public function pr ($d) {
1436
+ echo "<pre>";print_r($d);
1437
+ }
1438
+
1439
+ /**
1440
+ * get request collection
1441
+ *
1442
+ * @param $identifier
1443
+ * @return array
1444
+ */
1445
+ private function getRequestCollection ( $identifier ) {
1446
+ $requestCollection = json_decode(json_encode($this->request),true);
1447
+ return (isset($requestCollection[$identifier])) ? $requestCollection[$identifier] : NULL;
1448
+
1449
+ }
1450
+
1451
+
1452
+ /**
1453
+ * The function used to get methods of shipping.
1454
+ * @return Array
1455
+ */
1456
+ private function getDeliveryMethods ( $methods, $chosenDeliveryMethodName = NULL ) {
1457
+
1458
+ $deliveryMethodArray = array();
1459
+ $total_methods = count($methods);
1460
+ if ( is_array($methods) && count($methods) > 0 ) {
1461
+ foreach ( $methods as $method ) {
1462
+ $default_method_sort_order = Mage::getStoreConfig('carriers/'.$method['carrier'].'/sort_order');
1463
+ if ( $default_method_sort_order == 0 || empty( $default_method_sort_order ) ) {
1464
+ $order = 1;
1465
+ } else {
1466
+ $order = $default_method_sort_order;
1467
+ }
1468
+
1469
+ if ($total_methods == 1 && $chosenDeliveryMethodName == NULL) {
1470
+ $chosen = true;
1471
+ } elseif ( $chosenDeliveryMethodName != NULL) {
1472
+ $chosen = ( trim( $chosenDeliveryMethodName ) == trim( $method['carrier_title'] ) ) ? true : false;
1473
+ } else {
1474
+ $chosen = false;
1475
+ }
1476
+ $sort_order = ( $total_methods - $order ) + 1;
1477
+
1478
+ $deliveryMethodArray[] = array(
1479
+ "name" => $method['carrier_title'], //$method['carrier']
1480
+ "description" => $method['carrier_title'],
1481
+ "amount" => $this->getFormattedPrice($method['price']),
1482
+ "vatPercent" => 0,
1483
+ "type" => "OTHER",
1484
+ "vat" => 0,
1485
+ "customIdentifier" => $method['rate_id'],
1486
+ "chosen" => $chosen,
1487
+ "sortOrder" => ( $sort_order > 0 ) ? $sort_order : 1
1488
+ );
1489
+ $order++;
1490
+ }
1491
+
1492
+ }
1493
+ return $deliveryMethodArray;
1494
+ }
1495
+
1496
+ /**
1497
+ * The function used to get base url of the store.
1498
+ * @return url
1499
+ */
1500
+ private function getBaseUrl ( $store_id ) {
1501
+ $url = Mage::app()->getStore($store_id)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
1502
+ return $url;
1503
+ }
1504
+
1505
+ /*
1506
+ * Notify cloud server that a completed transaction is present for specified merchant
1507
+ *
1508
+ * @param int $merchantReference
1509
+ */
1510
+ public function completedOrderNotification( $merchantReference ) {
1511
+ //open connection
1512
+ $ch = curl_init();
1513
+ curl_setopt($ch, CURLOPT_URL, "http://54.243.60.205/notify.php?merchantReference=$merchantReference");
1514
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1515
+ curl_exec($ch);
1516
+ curl_close($ch);
1517
+ }
1518
+
1519
+ /*
1520
+ * Set order message in the order detail page
1521
+ *
1522
+ * @param string $order_status
1523
+ * @return string $msg
1524
+ */
1525
+ private function setOrderMessage( $order_status ) {
1526
+ switch ($order_status) {
1527
+ case 'pending' :
1528
+ $order_msg = 'Payair has set the order status to Pending as the order is awaiting authorization.';
1529
+ break;
1530
+ case 'processing' :
1531
+ $order_msg = 'Payair has set the status to Processing. Please INVOICE or SHIP the order to clear this transaction.';
1532
+ break;
1533
+ case 'canceled' :
1534
+ $order_msg = 'The order has been Canceled.';
1535
+ break;
1536
+ case 'holded' :
1537
+ $order_msg = 'Some data needs to be verified, therefore this order has been placed On Hold.';
1538
+ break;
1539
+ default :
1540
+ $order_msg = '';
1541
+ }
1542
+
1543
+ return $order_msg;
1544
+ }
1545
+
1546
+ /*
1547
+ * Set state of the order
1548
+ *
1549
+ * @param string $order,$order_status
1550
+ * @return NULL
1551
+ */
1552
+ private function setOrderState ( $order, $order_status ) {
1553
+
1554
+ switch ( $order_status ) {
1555
+ case 'processing':
1556
+ case 'holded':
1557
+ case 'canceled':
1558
+ $order_message = $this->setOrderMessage($order_status);
1559
+ $order->setState( $order_status, $order_status, $order_message, true );
1560
+ $order->setStatus($order_status);
1561
+ $order->save();
1562
+ break;
1563
+
1564
+ case 'pending' :
1565
+ $order_message = $this->setOrderMessage($order_status);
1566
+ $order->setState( Mage_Sales_Model_Order::STATE_NEW, Mage_Sales_Model_Order::STATE_NEW, $order_message, true);
1567
+ $order->setStatus("pending");
1568
+ $order->save();
1569
+ break;
1570
+
1571
+ case 'complete' :
1572
+ case 'closed' :
1573
+ try {
1574
+ if ( Mage::helper('core')->isModuleEnabled('Webkul_Marketplacepartner') ) {
1575
+ Mage::getModel('marketplacepartner/Productsales')->getProductSalesCalculation($order);
1576
+ }
1577
+ if ( !$order->canInvoice() ) {
1578
+ Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
1579
+ }
1580
+ $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
1581
+ if ( !$invoice->getTotalQty() ) {
1582
+ Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
1583
+ }
1584
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
1585
+ $invoice->register();
1586
+ $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
1587
+ $transactionSave->save();
1588
+
1589
+ if( $order->canShip() ) {
1590
+ $itemQty = $order->getItemsCollection()->count();
1591
+ $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);
1592
+ $shipment = new Mage_Sales_Model_Order_Shipment_Api();
1593
+ $shipmentId = $shipment->create( $order->getIncrementId() );
1594
+ $order->setState( 'complete', 'complete', 'Payair has Completed and Shipped Order automatically ', true);
1595
+ $order->addStatusHistoryComment('Payair has Completed and Shipped Order automatically.', false);
1596
+
1597
+ }
1598
+
1599
+ } catch (Mage_Core_Exception $e) {
1600
+
1601
+ }
1602
+ break;
1603
+ default :
1604
+ $order->setState( $order_status, $order_status, "No status seleted", true );
1605
+ $order->save();
1606
+ }
1607
+ }
1608
+
1609
+ private function limitStringLenght ( $string, $length ) {
1610
+ $str_strip = strip_tags($string);
1611
+ $str = substr( $str_strip, 0, $length );
1612
+ return $str ;
1613
+ }
1614
+ }
1615
+
1616
+
1617
+ ?>
app/code/community/Payair/Gate/etc/config.xml ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Payair_Gate>
5
+ <version>0.0.1</version>
6
+ </Payair_Gate>
7
+ </modules>
8
+ <frontend>
9
+ <routers>
10
+ <gate>
11
+ <use>standard</use>
12
+ <args>
13
+ <module>Payair_Gate</module>
14
+ <frontName>payaircallback</frontName>
15
+ </args>
16
+ </gate>
17
+ </routers>
18
+ <layout>
19
+ <updates>
20
+ <gate>
21
+ <file>payair.xml</file>
22
+ </gate>
23
+ </updates>
24
+ </layout>
25
+ <translate>
26
+ <modules>
27
+ <Payair_Gate>
28
+ <files>
29
+ <default>Payair_Gate.csv</default>
30
+ </files>
31
+ </Payair_Gate>
32
+ </modules>
33
+ </translate>
34
+ </frontend>
35
+ <global>
36
+ <models>
37
+ <gate>
38
+ <class>Payair_Gate_Model</class>
39
+ </gate>
40
+ </models>
41
+ <helpers>
42
+ <gate>
43
+ <class>Payair_Gate_Helper</class>
44
+ </gate>
45
+ </helpers>
46
+ <blocks>
47
+ <gate>
48
+ <class>Payair_Gate_Block</class>
49
+ </gate>
50
+ </blocks>
51
+ </global>
52
+ <default>
53
+ <payment>
54
+ <gate>
55
+ <active>1</active>
56
+ <model>gate/checkout</model>
57
+ <title>Payair</title>
58
+ <order_status>1</order_status>
59
+ <payment_action>authorize</payment_action>
60
+ </gate>
61
+ </payment>
62
+ </default>
63
+ </config>
app/code/community/Payair/Gate/etc/system.xml ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <sections>
4
+ <payment translate="label" module="payment">
5
+ <groups>
6
+ <gate translate="label" module="gate">
7
+ <label>Payair</label>
8
+ <frontend_type>text</frontend_type>
9
+ <sort_order>103</sort_order>
10
+ <show_in_default>1</show_in_default>
11
+ <show_in_website>1</show_in_website>
12
+ <show_in_store>1</show_in_store>
13
+
14
+ <fields>
15
+ <active translate="label">
16
+ <label>Enabled</label>
17
+ <frontend_type>select</frontend_type>
18
+ <source_model>adminhtml/system_config_source_yesno</source_model>
19
+ <sort_order>1</sort_order>
20
+ <show_in_default>1</show_in_default>
21
+ <show_in_website>1</show_in_website>
22
+ <show_in_store>1</show_in_store>
23
+ </active>
24
+ <display_method translate="label">
25
+ <label>Display Method</label>
26
+ <frontend_type>select</frontend_type>
27
+ <source_model>gate/display</source_model>
28
+ <sort_order>2</sort_order>
29
+ <show_in_default>1</show_in_default>
30
+ <show_in_website>1</show_in_website>
31
+ <show_in_store>1</show_in_store>
32
+ </display_method>
33
+ <environment translate="label">
34
+ <label>Environment</label>
35
+ <frontend_type>select</frontend_type>
36
+ <source_model>gate/environment</source_model>
37
+ <sort_order>3</sort_order>
38
+ <show_in_default>1</show_in_default>
39
+ <show_in_website>1</show_in_website>
40
+ <show_in_store>1</show_in_store>
41
+ </environment>
42
+ <gate_marchantref translate="label">
43
+ <label>Merchant Reference</label>
44
+ <frontend_type>text</frontend_type>
45
+ <sort_order>5</sort_order>
46
+ <show_in_default>1</show_in_default>
47
+ <show_in_website>1</show_in_website>
48
+ <show_in_store>1</show_in_store>
49
+ </gate_marchantref>
50
+ <gate_secret translate="label">
51
+ <label>Secret Key</label>
52
+ <frontend_type>text</frontend_type>
53
+ <sort_order>6</sort_order>
54
+ <show_in_default>1</show_in_default>
55
+ <show_in_website>1</show_in_website>
56
+ <show_in_store>1</show_in_store>
57
+ </gate_secret>
58
+ <gate_order_status translate="label">
59
+ <label>New Order Status</label>
60
+ <frontend_type>select</frontend_type>
61
+ <source_model>adminhtml/system_config_source_order_status</source_model>
62
+ <sort_order>7</sort_order>
63
+ <show_in_default>1</show_in_default>
64
+ <show_in_website>1</show_in_website>
65
+ <show_in_store>0</show_in_store>
66
+ </gate_order_status>
67
+ <gate_snap_view translate="label">
68
+ <label>Enable SnapView</label>
69
+ <frontend_type>select</frontend_type>
70
+ <source_model>adminhtml/system_config_source_yesno</source_model>
71
+ <sort_order>8</sort_order>
72
+ <show_in_default>1</show_in_default>
73
+ <show_in_website>1</show_in_website>
74
+ <show_in_store>1</show_in_store>
75
+ </gate_snap_view>
76
+ <gate_org_no translate="label">
77
+ <label>Organization Number</label>
78
+ <frontend_type>text</frontend_type>
79
+ <sort_order>9</sort_order>
80
+ <show_in_default>1</show_in_default>
81
+ <show_in_website>1</show_in_website>
82
+ <show_in_store>1</show_in_store>
83
+ </gate_org_no>
84
+ <gate_receipt_logo translate="label">
85
+ <label>Receipt Logo</label>
86
+ <comment>(example: https://www.payair.com/logo.jpg)</comment>
87
+ <frontend_type>text</frontend_type>
88
+ <sort_order>10</sort_order>
89
+ <show_in_default>1</show_in_default>
90
+ <show_in_website>1</show_in_website>
91
+ <show_in_store>1</show_in_store>
92
+ </gate_receipt_logo>
93
+ <gate_order_info_top translate="label">
94
+ <label>Top Message</label>
95
+ <frontend_type>text</frontend_type>
96
+ <sort_order>11</sort_order>
97
+ <show_in_default>1</show_in_default>
98
+ <show_in_website>1</show_in_website>
99
+ <show_in_store>1</show_in_store>
100
+ </gate_order_info_top>
101
+ <gate_order_info_bottom translate="label">
102
+ <label>Bottom Message</label>
103
+ <frontend_type>text</frontend_type>
104
+ <sort_order>12</sort_order>
105
+ <show_in_default>1</show_in_default>
106
+ <show_in_website>1</show_in_website>
107
+ <show_in_store>1</show_in_store>
108
+ </gate_order_info_bottom>
109
+ </fields>
110
+ </gate>
111
+ </groups>
112
+ </payment>
113
+ </sections>
114
+ </config>
app/design/frontend/default/default/layout/payair.xml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <layout version="0.1.0">
3
+ <default translate="label" module="page">
4
+ <reference name="head">
5
+ <action method="addCss"><stylesheet>css/payair.css</stylesheet></action>
6
+ </reference>
7
+ </default>
8
+ <catalog_product_view translate="label">
9
+ <reference name="content">
10
+ <block type="gate/payproduct" name="payair.gate.payproduct" before="-">
11
+ <action method="setBannerTemplate"><value>gate/product.phtml</value></action>
12
+ <action method="chooseTemplate"/>
13
+ </block>
14
+ </reference>
15
+
16
+ <reference name="product.info.addtocart">
17
+ <block type="gate/payproduct" name="payair.gate.paybutton">
18
+ <action method="setButtonTemplate"><value>gate/button.phtml</value></action>
19
+ <action method="chooseTemplate"/>
20
+ </block>
21
+ </reference>
22
+ </catalog_product_view>
23
+
24
+ <checkout_onepage_index translate="label">
25
+ <reference name="content">
26
+ <block type="gate/paycheckout" name="payair.gate.paycheckout" before="-" template="gate/checkout.phtml"/>
27
+ </reference>
28
+ <reference name="content">
29
+ <block type="gate/paymentjs" name="payair.gate.paymentjs" />
30
+ </reference>
31
+ </checkout_onepage_index>
32
+
33
+ </layout>
app/design/frontend/default/default/template/gate/button.phtml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ $is_payair_active = Mage::getStoreConfig('payment/gate/active');
3
+ $is_inlocation_installed = Mage::helper('core')->isModuleEnabled('Payair_Inlocationdelivery');
4
+ $is_payair_inlocation_active = Mage::getStoreConfig('carriers/inlocation/active');
5
+
6
+ if (!$is_inlocation_installed) $is_payair_inlocation_active = 0;
7
+
8
+ if ($is_payair_active) {
9
+ $product = Mage::registry('current_product');
10
+ // Load helper
11
+ $payair_script = Mage::helper('gate')->getEnvironmentJavascript();
12
+
13
+ $button_js = '<script src="'.$payair_script.'?merchantreference='.Mage::getStoreConfig('payment/gate/gate_marchantref').'&articleID='.$product->getId().'&product_name='.urlencode($product->getName()).'&product_price='.number_format($product->getPrice(),2,'.','').'&product_currency='.Mage::app()->getStore()->getCurrentCurrencyCode().'" type="text/javascript" charset="latin1" id="Payair_QR"></script>';
14
+
15
+ if ($is_payair_inlocation_active) {
16
+ $button_html = '<br />
17
+ <span style="display:none;">'.$button_js.'</span>
18
+ <div id="render_dialog_form" class="render-dialog-form-button">
19
+ <img onmouseover="this.style.opacity = 0.75;" onmouseout="this.style.opacity = 1;" src="https://test.payair.com/embed/img/payair_button.png">
20
+ </div>';
21
+ } else {
22
+ $button_html = '<br/>
23
+ <div class="render-dialog-form-button">
24
+ <!-- Button code start -->
25
+ <span style="display:block;">'.$button_js.'</span>
26
+ </div>';
27
+ }
28
+ echo $button_html;
29
+ }
30
+
31
+ ?>
app/design/frontend/default/default/template/gate/checkout.phtml ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ // Check the status
3
+ $is_payair_active = Mage::getStoreConfig('payment/gate/active');
4
+ $is_inlocation_installed = Mage::helper('core')->isModuleEnabled('Payair_Inlocationdelivery');
5
+ $is_payair_inlocation_active = Mage::getStoreConfig('carriers/inlocation/active');
6
+
7
+ if (!$is_inlocation_installed) $is_payair_inlocation_active = 0;
8
+
9
+ if ($is_payair_active) {
10
+ $payair_script = Mage::helper('gate')->getEnvironmentJavascript('checkout');
11
+ $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
12
+
13
+ if (count($items) == 0){
14
+ return "";
15
+ }
16
+
17
+ /*
18
+ * Check SnapView API to determine if the Store is OPEN or CLOSED to allow Payair to be ACTIVE -- Version 1.1
19
+ * Get Merchant Reference from Payair Payment Method and Store ID
20
+ */
21
+
22
+ $store_id = Mage::app()->getStore()->getStoreId();
23
+ $snap_view = Mage::getStoreConfig('payment/gate/gate_snap_view', $store_id);
24
+ if ( $snap_view == 1 ) {
25
+ $merchant_ref = Mage::getStoreConfig('payment/gate/gate_marchantref', $store_id);
26
+ $action = 'snapview';
27
+ $cmd = 'is_open';
28
+ $url = 'http://api.payairus.com';
29
+ $params = '?action='.$action.'&mref='.$merchant_ref.'&store_id='.$store_id.'&cmd='.$cmd;
30
+ $result = json_decode(file_get_contents($url.$params));
31
+
32
+ //Test printout of the request url and result from the API.
33
+ /*if($_GET['test'] == 1) {
34
+ print_r("Request: ".$url);
35
+ print_r($params."<br />");
36
+ print_r("Result from API: ");
37
+ print_r($result);
38
+ } */
39
+
40
+ if ( ( $result->response->status == "OK" && $result->response->open != 1 ) || $result->response->status == "NOK" ) {
41
+ $is_payair_active = FALSE;
42
+ echo "<ul class=\"messages\"><li class=\"error-msg\">Sorry but the store is closed for ordering at this time.<br />Please visit us during business hours.</li></ul>";
43
+ } elseif( $result->response->status == "OK" && $result->response->open != 1 ) {
44
+ //Do NOTHING
45
+ }
46
+ }
47
+
48
+ ?>
49
+ <script>
50
+ var payStatus = Class.create();
51
+ payStatus.prototype = {
52
+ startProcessing: false,
53
+ initialize: function(link){
54
+ this.link = link;
55
+ this.startProcessing = true;
56
+ this.checkStatus();
57
+ },
58
+ checkStatus: function() {
59
+ if (this.startProcessing) {
60
+ var checkPayStatus = this.ajaxCallPayStatus();
61
+ }
62
+ },
63
+ ajaxCallPayStatus: function(){
64
+ var $this = this;
65
+ var url = '<?php echo Mage::getBaseUrl(); ?>payaircallback/index/payStatus/link/'+this.link;
66
+ var ajax = new MakeAjaxRequest();
67
+ ajax.onreadystatechange=function() {
68
+ if (ajax.readyState==4) {
69
+ if (ajax.status==200) {
70
+ var reponseData = ajax.responseText;
71
+ switch(reponseData) {
72
+ case 'running' :
73
+ var myCheckStatusInt = setInterval(function(){$this.checkStatus();},5000);
74
+ break;
75
+ case 'success' :
76
+ window.location = '<?php echo Mage::getBaseUrl(); ?>';
77
+ break;
78
+ case 'declined' :
79
+ window.location = '<?php echo Mage::getBaseUrl(); ?>';
80
+ break;
81
+ default :
82
+ window.clearInterval(myCheckStatusInt);
83
+ break;
84
+ }
85
+ }
86
+ }
87
+ }
88
+
89
+ ajax.open("GET", url, false);
90
+ ajax.send(null);
91
+ }
92
+ }
93
+
94
+ function MakeAjaxRequest() {
95
+ var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
96
+ if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
97
+ for (var i=0; i<activexmodes.length; i++) {
98
+ try {
99
+ return new ActiveXObject(activexmodes[i])
100
+ }
101
+ catch(e) {
102
+ //suppress error
103
+ }
104
+ }
105
+ }
106
+ else if (window.XMLHttpRequest) // if Mozilla, Safari etc
107
+ return new XMLHttpRequest()
108
+ else
109
+ return false
110
+ }
111
+
112
+ var ajax = new MakeAjaxRequest();
113
+
114
+ function ajaxCallCart(url) {
115
+ ajax.onreadystatechange=function() {
116
+ if (ajax.readyState==4) {
117
+ if (ajax.status==200) {
118
+ //var text = ajax.responseText;
119
+ var obj = JSON.parse(ajax.responseText);
120
+ var text = obj.text;
121
+ var file = obj.file;
122
+ if(text.length != 10) {
123
+ hideScanInfo();
124
+ hideScanWrapper();
125
+ alert(text);
126
+ return false;
127
+ } else {
128
+ Payair_DATA.setQR_data(text);
129
+ new payStatus(file);
130
+ }
131
+ } else {
132
+ hideScanInfo();
133
+ hideScanWrapper();
134
+ alert("An error has occured making the request");
135
+ return false;
136
+ }
137
+ }
138
+ }
139
+
140
+ ajax.open("GET", url, true);
141
+ ajax.send(null);
142
+ }
143
+
144
+ function GetQRData() {
145
+ //poller = setInterval('StartPolling()', 4001);
146
+
147
+ ajaxCallCart('<?php echo Mage::getBaseUrl(); ?>payaircallback/index/cart/');
148
+
149
+ var elementt = document.getElementById("QRholder");
150
+ if (elementt != null) {
151
+ elementt.style.display = "block";
152
+ }
153
+ }
154
+ // May be used later on
155
+ /*function ClearQRData() {
156
+ clearInterval(poller);
157
+ qr_data = '';
158
+ var elementt = document.getElementById("QRholder");
159
+ if (elementt != null) {
160
+ elementt.style.display = "none";
161
+ }
162
+ }
163
+ function StartPolling() {
164
+ CheckStatus();
165
+ }
166
+
167
+ function CheckStatus() {
168
+
169
+ }
170
+
171
+ function GetOrderOnSuccess(result) {
172
+ if (result.Status == 1) {
173
+ clearInterval(poller);
174
+ var url = "/Checkout/Finished.aspx?identifier=" + result.OrderIdentifier + "&key=" + result.MAC;
175
+ //alert("\n---Result.status\n----- " + result.Status + "\n\n---OrderIdentifier\n----- " + result.OrderIdentifier + "\n\n---MAC / KEY\n----- " + result.MAC + "\n\n---URL\n----- " + url);
176
+ document.location = url;
177
+ //ShowOrderComplete(result);
178
+ }
179
+ }
180
+
181
+ function ShowOrderComplete(result) {
182
+ var url = "/Checkout/Finished.aspx?identifier=" + result.OrderIdentifier + "&key=" + result.MAC;
183
+ document.location = url;
184
+ }
185
+ var poller = false;
186
+ */
187
+ </script>
188
+
189
+ <?php
190
+ $payair_checkout_img = Mage::helper('gate')->getBannerImages('background');
191
+ $payair_android_small_img = Mage::helper('gate')->getBannerImages('video');
192
+ ?>
193
+ <div class="payair-banner-wrapper">
194
+ <div class="payair-banner-inner">
195
+ <div style="background-image:url(<?php echo $payair_checkout_img;?>);" class="payair-banner-container">
196
+ <div class="payair-btn-wrapper">
197
+ <!-- Button code start -->
198
+ <?php
199
+
200
+ $grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
201
+ $checkout_price = number_format($grandTotal,2,'.','');
202
+
203
+ $button_js = '<script src="'.$payair_script.'?checkout_price='.$checkout_price.'&checkout_currency='.Mage::app()->getStore()->getCurrentCurrencyCode().'" type="text/javascript" id="Payair_QR"></script>';
204
+
205
+ if ($is_payair_inlocation_active) {
206
+ // Custom location delivery active
207
+ $payair_js_display = 'none';
208
+ ?>
209
+ <div id="render_dialog_form" class="render-dialog-form"><img onmouseover="this.style.opacity = 0.75;" onmouseout="this.style.opacity = 1;" src="https://test.payair.com/embed/img/payair_button.png"></div>
210
+
211
+ <?php } else {
212
+ $payair_js_display = 'block';
213
+ }
214
+ ?>
215
+
216
+ <span style="display:<?php echo $payair_js_display; ?>"><?php echo $button_js; ?> </span>
217
+ <!-- Button Code Stop -->
218
+
219
+ <!-- Video code start -->
220
+ <div class="payair-video-btn-container1">
221
+ <a onmouseout="this.style.opacity=1;" onmouseover="this.style.opacity=0.5;" onclick="startIframeInfoOnly(); return false;">
222
+ <img width="52" height="33" alt="" src="<?php echo $payair_android_small_img; ?>">
223
+ </a>
224
+ </div>
225
+ <!-- Video code ends-->
226
+ </div>
227
+ </div>
228
+ <div class="payair-div-clear"></div>
229
+ </div>
230
+ </div>
231
+ <?php }?>
app/design/frontend/default/default/template/gate/product.phtml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ //Check the status
3
+ $is_payair_active = Mage::getStoreConfig('payment/gate/active');
4
+ $is_inlocation_installed = Mage::helper('core')->isModuleEnabled('Payair_Inlocationdelivery');
5
+ $is_payair_inlocation_active = Mage::getStoreConfig('carriers/inlocation/active');
6
+ // If the Payair inlocation is uninstalled
7
+ if (!$is_inlocation_installed) $is_payair_inlocation_active = 0;
8
+
9
+ if ($is_payair_active) {
10
+ // Load helper
11
+ $payair_script = Mage::helper('gate')->getEnvironmentJavascript();
12
+ $payair_checkout_img = Mage::helper('gate')->getBannerImages('background');
13
+ $payair_android_small_img = Mage::helper('gate')->getBannerImages('video');
14
+
15
+ $product = Mage::registry('current_product');
16
+ $button_js = '<script src="'.$payair_script.'?merchantreference='.Mage::getStoreConfig('payment/gate/gate_marchantref').'&amp;articleID='.$product->getId().'&amp;product_name='.urlencode($product->getName()).'&amp;product_price='.number_format($product->getPrice(),2,'.','').'&amp;product_currency='.Mage::app()->getStore()->getCurrentCurrencyCode().'" type="text/javascript" charset="latin1" id="Payair_QR"></script>';
17
+
18
+ if ($is_payair_inlocation_active) {
19
+ // Custom location delivery active
20
+ $payair_js_display = 'none';
21
+ $button_html = '<div id="render_dialog_form" class="render-dialog-form"><img onmouseover="this.style.opacity = 0.75;" onmouseout="this.style.opacity = 1;" src="https://test.payair.com/embed/img/payair_button.png"></div>';
22
+ } else {
23
+
24
+ $payair_js_display = 'block';
25
+ $button_html = '';
26
+ }
27
+ $qr_info = '<div class="payair-banner-wrapper">
28
+ <div class="payair-banner-inner">
29
+ <div style="background-image: url('.$payair_checkout_img.');" class="payair-banner-container">
30
+ <div class="payair-btn-wrapper">
31
+ <!-- Button code start -->
32
+ <span style="display:'.$payair_js_display.';">'.$button_js.'</span> '.$button_html.'
33
+ </div>
34
+ <div class="payair-video-btn-container">
35
+ <a onmouseout="this.style.opacity=1;" onmouseover="this.style.opacity=0.5;" onclick="startIframeInfoOnly(); return false">
36
+ <img width="52" height="33" alt="" src="'.$payair_android_small_img.'">
37
+ </a>
38
+ </div>
39
+ </div>
40
+ <div class="payair-div-clear">
41
+ </div>
42
+ </div>
43
+ </div>';
44
+
45
+ // Display QR info
46
+
47
+ echo $qr_info;
48
+ }
49
+ ?>
app/etc/modules/Payair_Adminhtml.xml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Payair_Adminhtml>
5
+ <active>true</active>
6
+ <codePool>community</codePool>
7
+ </Payair_Adminhtml>
8
+ </modules>
9
+ </config>
app/etc/modules/Payair_Gate.xml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <modules>
4
+ <Payair_Gate>
5
+ <active>true</active>
6
+ <codePool>community</codePool>
7
+ <depends>
8
+ <Mage_Payment />
9
+ </depends>
10
+ </Payair_Gate>
11
+ </modules>
12
+ </config>
media/payair/android_video_thumb_small.png ADDED
Binary file
media/payair/express_checkout_banner_v3.png ADDED
Binary file
media/payair/express_checkout_bg_383.png ADDED
Binary file
package.xml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <package>
3
+ <name>Payair_gate</name>
4
+ <version>4.0.0.23</version>
5
+ <stability>stable</stability>
6
+ <license>GPL</license>
7
+ <channel>community</channel>
8
+ <extends/>
9
+ <summary>Payair payment gateway version 4</summary>
10
+ <description>We can payment through mobile phone using Payair app and Payair payment method.</description>
11
+ <notes>All issues fixed.</notes>
12
+ <authors><author><name>vikas</name><user>vikas</user><email>vikass@chetu.com</email></author></authors>
13
+ <date>2013-09-06</date>
14
+ <time>17:57:00</time>
15
+ <contents><target name="mageetc"><dir name="modules"><file name="Payair_Gate.xml" hash="ab09c7de9ca9ce3629379a8375ae7fc3"/><file name="Payair_Adminhtml.xml" hash="051013e3888ebf812048921073dae688"/></dir></target><target name="magecommunity"><dir name="Payair"><dir name="Gate"><dir name="Block"><file name="Paycheckout.php" hash="80d88175ae9a5e5070e9c18e40bb6249"/><file name="Paymentjs.php" hash="0b609f0c6f4eee18661d0bbb789c9d58"/><file name="Payproduct.php" hash="aa7ae8f31495bdc5a86c4a5103affd9f"/></dir><dir name="Helper"><file name="Data.php" hash="d57a44055ef38461cb28fe3879db9d4b"/></dir><dir name="Model"><file name="Checkout.php" hash="393cb22fb500e95d79ab254c0464b56f"/><file name="Display.php" hash="9f7c3918df8535f1256759271e50f86e"/><file name="Environment.php" hash="f131e5aa46136420acbaffcbef41a10b"/><file name="Observer.php" hash="65a788233ddee12440477d940d8ca927"/><dir name="Order"><dir name="Api"><file name="V2.php" hash="918fdca710f1e424093bc6e8f386bf3c"/></dir><file name="Api.php" hash="73bf707e89776d73fb7acba455bb157e"/></dir><file name="Payair.php" hash="99d39c96bbfdb533249f7746f882c057"/><file name="RestConnect_Model_Oauth_Client.php" hash="2b25cd997acb20d8b67cb2443357bb5c"/></dir><dir name="controllers"><file name="IndexController.php" hash="76f9daa8d1ba7ca6c8ca0b5507206fbf"/></dir><dir name="etc"><file name="config.xml" hash="cf1b4df4baf2e1d7fec1fe995f8fa4d3"/><file name="system.xml" hash="5fda863ccaf4ccc70e92f00fbfc7bc2f"/></dir></dir></dir></target><target name="magedesign"><dir name="frontend"><dir name="default"><dir name="default"><dir name="template"><dir name="gate"><file name="button.phtml" hash="fae99d344c5a3900c6bf52104b633e17"/><file name="checkout.phtml" hash="06b37288aafb0a4da7d735dc89c93804"/><file name="product.phtml" hash="cac4a0d9dbc33f80086042c8868e5918"/></dir></dir><dir name="layout"><file name="payair.xml" hash="d16063df8cdf9475bff196a8d2187158"/></dir></dir></dir></dir></target><target name="mageskin"><dir name="frontend"><dir name="default"><dir name="default"><dir name="css"><file name="payair.css" hash="9faab5311b422d70708626ac641251ea"/></dir><dir name="js"><dir name="payair"><file name="payaircheckout.js" hash="d37d8ae1ddb2dee75ced96bc1db970c9"/></dir></dir></dir></dir></dir></target><target name="magemedia"><dir name="payair"><file name="android_video_thumb_small.png" hash="21253916e7b3141eaf6993e6962bc798"/><file name="express_checkout_banner_v3.png" hash="e5ea47cbd4545abd43e4fae504ebdea2"/><file name="express_checkout_bg_383.png" hash="72de32e7645b966296c321a421ccee84"/></dir></target></contents>
16
+ <compatible/>
17
+ <dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies>
18
+ </package>
skin/frontend/default/default/css/payair.css ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Payair CSS
3
+ **
4
+ */
5
+
6
+ .payair-button {
7
+ margin: 10px 0 0 69px;
8
+ }
9
+
10
+ .payair-banner-wrapper {
11
+ padding: 20px 0;
12
+ }
13
+ .payair-banner-inner {
14
+ height: 118px;
15
+ overflow: hidden;
16
+ }
17
+ .payair-banner-container {
18
+ background-repeat: no-repeat;
19
+ position: relative;
20
+ width: 383px;
21
+ height: 118px;
22
+ }
23
+ .payair-btn-wrapper {
24
+ position: absolute;
25
+ left: 225px;
26
+ top: 20px;
27
+
28
+ }
29
+
30
+ .payair-video-btn-container {
31
+ position: absolute;
32
+ width: 52px;
33
+ left: 73px;
34
+ top: 78px;
35
+ }
36
+
37
+ .payair-video-btn-container1 {
38
+ position: absolute;
39
+ width: 52px;
40
+ left: -155px;
41
+ top: 56px;
42
+ }
43
+
44
+
45
+ .payair-video-btn-container a {
46
+ cursor: pointer; opacity: 1;
47
+ }
48
+
49
+ .payair-video-btn-container1 a {
50
+ cursor: pointer; opacity: 1;
51
+ }
52
+
53
+ .payair-div-clear {
54
+ clear: both;
55
+ }
56
+
57
+ .render-dialog-form {
58
+ display: inline;
59
+ z-index: 10000;
60
+ }
61
+
62
+ .render-dialog-form-button {
63
+ margin: 10px 0 0 69px;
64
+ }
65
+
66
+ #render_dialog_form img {
67
+ cursor: pointer;
68
+ opacity: 1;
69
+ }
skin/frontend/default/default/js/payair/payaircheckout.js ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ var Payair = Class.create();
2
+ Payair.prototype = {
3
+ initialize: function(){
4
+
5
+ this.payment_method = $$('input:checked[type="radio"][name="payment[method]"]').pluck('value');
6
+ this.preventDefaultClickEvent();
7
+ },
8
+
9
+ preventDefaultClickEvent: function(ga) {
10
+
11
+ if( ga != undefined) {
12
+ this.payment_method = ga;
13
+ }
14
+
15
+ var e = $$('div#payment-buttons-container button.button')[0];
16
+
17
+ if(this.payment_method=='gate') {
18
+ e.setAttribute('onclick','return false;');
19
+ }
20
+ else {
21
+ e.setAttribute('onclick','payment.save();');
22
+ }
23
+ },
24
+
25
+ displayQR: function() {
26
+
27
+ $$('div#payment-buttons-container button.button').invoke('observe','click',function(){
28
+
29
+ selectedPaymentMethod = $$('input:checked[type="radio"][name="payment[method]"]').pluck('value');
30
+
31
+ if(selectedPaymentMethod == 'gate') {
32
+ //The choosed mathod is payair. Call the payair js code here. And can prevent the default click event
33
+ Payair_DATA.releaseHelpActive();
34
+ GetQRData();
35
+ showScanInfo();
36
+ showScanWrapper();
37
+ return false;
38
+ }
39
+ else {
40
+ // The choosed method is something else. Proceed further
41
+ return true;
42
+ }
43
+ });
44
+ }
45
+ }
46
+
47
+ var QR = new Payair();
48
+ payment.addBeforeInitFunction(QR,QR.displayQR);
49
+
50
+ $('co-payment-form').on('change', '.radio', function() {
51
+ var payment_method = $$('input:checked[type="radio"][name="payment[method]"]').pluck('value');
52
+ QR.preventDefaultClickEvent(payment_method);
53
+
54
+ });