CDev_XPaymentsConnector - Version 1.3.2

Version Notes

Version number: 1.3.2

Download this release

Release Info

Developer Valerii Demidov
Extension CDev_XPaymentsConnector
Version 1.3.2
Comparing to
See all releases


Code changes from version 1.3.1 to 1.3.2

Files changed (29) hide show
  1. app/code/community/Cdev/XPaymentsConnector/Block/Adminhtml/Sales/Order/View/Tab/Xporderstate.php +3 -1
  2. app/code/community/Cdev/XPaymentsConnector/Block/Checkout/Onepage/Orderdetail.php +93 -0
  3. app/code/community/Cdev/XPaymentsConnector/Block/Recurring/Profile/View.php +9 -0
  4. app/code/community/Cdev/XPaymentsConnector/Helper/Data.php +659 -265
  5. app/code/community/Cdev/XPaymentsConnector/Model/Observer.php +217 -160
  6. app/code/community/Cdev/XPaymentsConnector/Model/Payment/Cc.php +239 -129
  7. app/code/community/Cdev/XPaymentsConnector/Model/Payment/Savedcards.php +58 -35
  8. app/code/community/Cdev/XPaymentsConnector/Model/Quote.php +31 -7
  9. app/code/community/Cdev/XPaymentsConnector/Model/Quote/Address/Total/Nominal.php +10 -1
  10. app/code/community/Cdev/XPaymentsConnector/Model/Quote/Address/Total/Nominal/Recurring/Initialfee/Tax.php +66 -0
  11. app/code/community/Cdev/XPaymentsConnector/Model/Sales/Recurring/Profile.php +62 -7
  12. app/code/community/Cdev/XPaymentsConnector/controllers/CustomerController.php +1 -1
  13. app/code/community/Cdev/XPaymentsConnector/controllers/ProcessingController.php +270 -207
  14. app/code/community/Cdev/XPaymentsConnector/etc/config.xml +6 -2
  15. app/code/community/Cdev/XPaymentsConnector/sql/xpaymentsconnector_setup/mysql4-upgrade-1.0.9-1.1.0.php +29 -0
  16. app/code/community/Cdev/XPaymentsConnector/sql/xpaymentsconnector_setup/mysql4-upgrade-1.1.0-1.1.1.php +29 -0
  17. app/design/adminhtml/default/default/template/xpaymentsconnector/order/view/tab/xporderstate.phtml +189 -183
  18. app/design/frontend/default/default/layout/xpaymentsconnector.xml +2 -0
  19. app/design/frontend/default/default/template/xpaymentsconnector/checkout/onepage/order-detail.phtml +59 -0
  20. app/design/frontend/default/default/template/xpaymentsconnector/checkout/onepage/xpayment-iframe.phtml +6 -5
  21. app/design/frontend/default/default/template/xpaymentsconnector/form/cc.phtml +3 -3
  22. app/design/frontend/rwd/default/layout/xpaymentsconnector.xml +2 -0
  23. app/design/frontend/rwd/default/template/xpaymentsconnector/checkout/onepage/order-detail.phtml +59 -0
  24. app/design/frontend/rwd/default/template/xpaymentsconnector/checkout/onepage/xpayment-iframe.phtml +6 -5
  25. app/design/frontend/rwd/default/template/xpaymentsconnector/form/cc.phtml +3 -3
  26. app/locale/en_US/Cdev_XPaymentsConnector.csv +11 -4
  27. js/xpayment/checkout-submit.js +3 -1
  28. js/xpayment/settings.css +8 -0
  29. package.xml +5 -5
app/code/community/Cdev/XPaymentsConnector/Block/Adminhtml/Sales/Order/View/Tab/Xporderstate.php CHANGED
@@ -112,7 +112,6 @@ class Cdev_XPaymentsConnector_Block_Adminhtml_Sales_Order_View_Tab_Xporderstate
112
if($this->transactionStatus){
113
$this->transactionInfo[$currentOrder->getIncrementId()]["payment"]["xpc_txnid"] = $this->txnid;
114
}
115
-
116
}
117
118
while(!is_null($parentOrder = $currentOrder->getRelationParentId())){
@@ -149,6 +148,9 @@ class Cdev_XPaymentsConnector_Block_Adminhtml_Sales_Order_View_Tab_Xporderstate
149
case ($xpOrderStateData["refundedAmountAvailGateway"] > 0 && $xpOrderStateData["capturedAmountAvailGateway"] < 0.01):
150
$actionAmount = $xpOrderStateData["refundedAmountAvailGateway"];
151
break;
152
}
153
return $actionAmount;
154
}
112
if($this->transactionStatus){
113
$this->transactionInfo[$currentOrder->getIncrementId()]["payment"]["xpc_txnid"] = $this->txnid;
114
}
115
}
116
117
while(!is_null($parentOrder = $currentOrder->getRelationParentId())){
148
case ($xpOrderStateData["refundedAmountAvailGateway"] > 0 && $xpOrderStateData["capturedAmountAvailGateway"] < 0.01):
149
$actionAmount = $xpOrderStateData["refundedAmountAvailGateway"];
150
break;
151
+ case ($actionAmount < 0.01 && $xpOrderStateData["chargedAmount"] > 0):
152
+ $actionAmount = $xpOrderStateData["chargedAmount"];
153
+ break;
154
}
155
return $actionAmount;
156
}
app/code/community/Cdev/XPaymentsConnector/Block/Checkout/Onepage/Orderdetail.php ADDED
@@ -0,0 +1,93 @@
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
+ * @author Valerii Demidov
16
+ * @category Cdev
17
+ * @package Cdev_XPaymentsConnector
18
+ * @copyright (c) Qualiteam Software Ltd. <info@qtmsoft.com>. All rights reserved.
19
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
20
+ */
21
+
22
+ /**
23
+ * Block for additional information about 'recurring items'
24
+ */
25
+
26
+ class Cdev_XPaymentsConnector_Block_Checkout_Onepage_Orderdetail extends Mage_Core_Block_Template
27
+ {
28
+
29
+ public function getRecurringQuoteItems(){
30
+ $checkoutSession = Mage::getSingleton('checkout/session');
31
+ $quoteItems = $checkoutSession->getQuote()->getAllItems();
32
+ $result = array();
33
+
34
+ foreach ($quoteItems as $quoteItem) {
35
+ if ($quoteItem) {
36
+ $product = $quoteItem->getProduct();
37
+ $issetRecurringOreder = (bool)$product->getIsRecurring();
38
+ if ($issetRecurringOreder) {
39
+ $result[] = $quoteItem;
40
+ }
41
+ }
42
+ }
43
+
44
+ return $result;
45
+ }
46
+
47
+ /**
48
+ * @param Mage_Sales_Model_Quote_Item $recQuoteItem
49
+ * @return mixed
50
+ */
51
+ public function getRecurringItemMessage(Mage_Sales_Model_Quote_Item $recQuoteItem){
52
+
53
+ $xpHelper = Mage::helper('xpaymentsconnector');
54
+ $recurringItemMessage = '';
55
+ $initialFeeMessage = '';
56
+ $rowTotal = $recQuoteItem->getNominalRowTotal();
57
+
58
+ $currency_symbol = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
59
+
60
+ $product = $recQuoteItem->getProduct();
61
+ $productAdditionalInfo = unserialize($product->getCustomOption('info_buyRequest')->getValue());
62
+ $deferredDateStamp = strtotime($productAdditionalInfo['recurring_profile_start_datetime']);
63
+ if($deferredDateStamp){
64
+ $initialFeeMessage = $this->__(" (initial fee only, 1st recurring fee will be charged on %s)",date('d-M-Y',$deferredDateStamp));
65
+ $rowTotal = $recQuoteItem->getXpRecurringInitialFee() + $recQuoteItem->getInitialfeeTaxAmount();
66
+ }
67
+
68
+ $recurringItemMessage = $xpHelper
69
+ ->__("%s%s for recurring product '%s' in your cart.",
70
+ $rowTotal, $currency_symbol,$recQuoteItem->getName());
71
+
72
+ $mainMessage = $recurringItemMessage.$initialFeeMessage;
73
+
74
+ return $mainMessage;
75
+
76
+ }
77
+
78
+ public function getSimpleQuoteItemMessage(){
79
+ $checkoutSession = Mage::getSingleton('checkout/session');
80
+ $quot = $checkoutSession->getQuote();
81
+ $simpleQuoteItemMessage = '';
82
+ if($quot->getGrandTotal()){
83
+ $currency_symbol = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
84
+ $xpHelper = Mage::helper('xpaymentsconnector');
85
+ $simpleQuoteItemMessage = $this->__("%s%s for all non-recurring products in your cart.",$quot->getGrandTotal(), $currency_symbol);
86
+ }
87
+
88
+ return $simpleQuoteItemMessage;
89
+
90
+ }
91
+
92
+
93
+ }
app/code/community/Cdev/XPaymentsConnector/Block/Recurring/Profile/View.php CHANGED
@@ -40,6 +40,15 @@ class Cdev_XPaymentsConnector_Block_Recurring_Profile_View extends Mage_Sales_Bl
40
'is_amount' => true,
41
));
42
}
43
}
44
45
}
40
'is_amount' => true,
41
));
42
}
43
+ $initialFeeTaxAmount = $orderItemInfo["initialfee_tax_amount"];
44
+ if($initialFeeTaxAmount){
45
+ $initialFeeTaxNominalModel = Mage::getModel("xpaymentsconnector/quote_address_total_nominal_recurring_initialfee_tax");
46
+ $this->_addInfo(array(
47
+ 'label' => $initialFeeTaxNominalModel->getLabel(),
48
+ 'value' => Mage::helper('core')->formatCurrency($initialFeeTaxAmount, false),
49
+ 'is_amount' => true,
50
+ ));
51
+ }
52
}
53
54
}
app/code/community/Cdev/XPaymentsConnector/Helper/Data.php CHANGED
@@ -21,7 +21,7 @@
21
22
/**
23
* Common helper
24
- *
25
* @package Cdev_XPaymentsConnector
26
* @see ____class_see____
27
* @since 1.0.0
@@ -33,11 +33,17 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
33
const WEEK_TIME_STAMP = 604800;
34
const SEMI_MONTH_TIME_STAMP = 1209600;
35
36
- const STATE_XPAYMENT_PENDING_PAYMENT = "xp_pending_payment";
37
- const XPAYMENTS_LOG_FILE = "xpayments.log";
38
-
39
-
40
41
42
/**
43
* This function return 'IncrementId' for feature order.
@@ -48,15 +54,15 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
48
* return
49
* @return bool or int
50
*/
51
- public function getOrderKey(){
52
- $xpaymentPrepareOrderData = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
53
- if($xpaymentPrepareOrderData && isset($xpaymentPrepareOrderData["prepare_order_id"])){
54
- return $xpaymentPrepareOrderData["prepare_order_id"];
55
}
56
return false;
57
}
58
59
-
60
/**
61
* This function create 'IncrementId' for feature order.
62
* Xpayment Prepare Order Mas(xpayment_prepare_order):
@@ -68,29 +74,54 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
68
*/
69
public function prepareOrderKey()
70
{
71
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
72
if(!isset($xpaymentPrepareOrder["prepare_order_id"])){
73
- $isRecurringOrder = $this->checkIsRecurringOrder();
74
- if($isRecurringOrder){
75
- $useStartDateParam = $this->checkStartDateData();
76
- if ($useStartDateParam["success"]) {
77
- $xpaymentPrepareOrder["prepare_order_id"] = "subscription";
78
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order",$xpaymentPrepareOrder);
79
- return;
80
- }
81
- }
82
- $storeId = Mage::app()->getStore()->getStoreId();
83
- $prepareOrderId = Mage::getSingleton('eav/config')
84
- ->getEntityType('order')
85
- ->fetchNewIncrementId($storeId);
86
87
- $xpaymentPrepareOrder["prepare_order_id"] = $prepareOrderId;
88
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order", $xpaymentPrepareOrder);
89
90
}
91
92
}
93
94
/**
95
* This function set 'place_display' flag for feature x-payment form.
96
* Xpayment Prepare Order Mas(xpayment_prepare_order):
@@ -104,10 +135,10 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
104
public function setIframePlaceDisplaySettings()
105
{
106
$useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
107
- if($useIframe){
108
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
109
- $xpaymentPrepareOrder["place_display"] = Mage::getStoreConfig('payment/xpayments/placedisplay');
110
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order", $xpaymentPrepareOrder);
111
}
112
}
113
@@ -115,9 +146,10 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
115
* check 'xpayment' config settigs
116
* @return bool
117
*/
118
- public function isIframePaymentPlaceDisplay(){
119
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
120
- if(isset($xpaymentPrepareOrder["place_display"]) && ($xpaymentPrepareOrder["place_display"] == "payment" )){
121
return true;
122
}
123
return false;
@@ -132,10 +164,11 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
132
* return
133
* @return bool or int
134
*/
135
- public function getXpaymentResponse(){
136
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
137
- if($xpaymentPrepareOrder && isset($xpaymentPrepareOrder["xpayment_response"])){
138
- return $xpaymentPrepareOrder["xpayment_response"];
139
}
140
return false;
141
}
@@ -151,36 +184,78 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
151
*/
152
public function getIframeToken()
153
{
154
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
155
- if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder["token"]) && !empty($xpaymentPrepareOrder["token"])) {
156
- return $xpaymentPrepareOrder["token"];
157
} else {
158
$api = Mage::getModel('xpaymentsconnector/payment_cc');
159
$result = $api->sendIframeHandshakeRequest();
160
- $xpaymentPrepareOrder["token"] = $result['response']['token'];
161
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order", $xpaymentPrepareOrder);
162
- return $xpaymentPrepareOrder["token"];
163
}
164
165
}
166
167
/**
168
* Unset prepare order params
169
* @param array $unsetParams
170
*/
171
- public function unsetXpaymentPrepareOrder($unsetParams = array()){
172
- if(!empty($unsetParams)){
173
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
174
- foreach($unsetParams as $param){
175
- if( is_array($xpaymentPrepareOrder) && isset($xpaymentPrepareOrder[$param])){
176
unset($xpaymentPrepareOrder[$param]);
177
}
178
}
179
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order",$xpaymentPrepareOrder);
180
return;
181
}
182
183
- Mage::getSingleton("checkout/session")->unsetData("xpayment_prepare_order");
184
}
185
186
/**
@@ -190,26 +265,26 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
190
*/
191
public function savePaymentResponse($responseData)
192
{
193
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
194
- $xpaymentPrepareOrder["xpayment_response"] = $responseData;
195
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order", $xpaymentPrepareOrder);
196
}
197
198
/**
199
* Save all allowed payments for current checkout session in store.
200
* - allowed_payments
201
- * @param array $methods
202
*/
203
public function setAllowedPaymentsMethods($methodsInstances)
204
{
205
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
206
- $xpaymentPrepareOrder["allowed_payments"] = $methodsInstances;
207
$methods = array();
208
- foreach($methodsInstances as $methodInstance){
209
- $methods[]["method_code"] = $methodInstance->getCode();
210
}
211
- $xpaymentPrepareOrder["allowed_payments"] = $methods;
212
- Mage::getSingleton("checkout/session")->setData("xpayment_prepare_order", $xpaymentPrepareOrder);
213
}
214
215
/**
@@ -218,9 +293,9 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
218
*/
219
public function getAllowedPaymentsMethods()
220
{
221
- $xpaymentPrepareOrder = Mage::getSingleton("checkout/session")->getData("xpayment_prepare_order");
222
- if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder["allowed_payments"]) && !empty($xpaymentPrepareOrder["allowed_payments"])) {
223
- return $xpaymentPrepareOrder["allowed_payments"];
224
}
225
return false;
226
}
@@ -229,10 +304,11 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
229
public function getReviewButtonTemplate($name, $block)
230
{
231
$quote = Mage::getSingleton('checkout/session')->getQuote();
232
- $useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
233
if ($quote) {
234
$payment = $quote->getPayment();
235
- if ($payment && $payment->getMethod() == "xpayments" && $useIframe) {
236
return $name;
237
}
238
}
@@ -244,115 +320,190 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
244
return '';
245
}
246
247
- public function isNeedToSaveUserCard(){
248
- $result = (bool) Mage::getSingleton("checkout/session")->getData("user_card_save");
249
return $result;
250
}
251
252
public function isRegisteredUser()
253
{
254
- $currentCustomerState = Mage::getSingleton('checkout/type_onepage')->getCheckoutMethod();
255
- $registerMethod = Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER;
256
- $customerMethod = Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER;
257
- if (($currentCustomerState == $registerMethod) || ($currentCustomerState == $customerMethod)) {
258
- return true;
259
- } else {
260
- return false;
261
- }
262
- }
263
-
264
- public function isXpaymentsMethod($currentPaymentCode){
265
- $xpaymentPaymentCode = Mage::getModel("xpaymentsconnector/payment_cc")->getCode();
266
- $saveCardsPaymentCode = Mage::getModel("xpaymentsconnector/payment_savedcards")->getCode();
267
- $prepaidpayments = Mage::getModel("xpaymentsconnector/payment_prepaidpayments")->getCode();
268
- $usePaymetCodes = array($xpaymentPaymentCode,$saveCardsPaymentCode,$prepaidpayments);
269
- if (in_array($currentPaymentCode, $usePaymetCodes)){
270
return true;
271
- }else{
272
return false;
273
}
274
}
275
276
/**
277
* @param Mage_Payment_Model_Recurring_Profile $recurringProfile
278
* @param bool $isFirstRecurringOrder
279
* @return int
280
*/
281
- public function createOrder(Mage_Payment_Model_Recurring_Profile $recurringProfile,$isFirstRecurringOrder = false){
282
283
- $orderItemInfo = $recurringProfile->getData("order_item_info");
284
285
- if(!is_array($orderItemInfo)){
286
- $orderItemInfo = unserialize($orderItemInfo);
287
}
288
- $initialFeeAmount = $orderItemInfo["recurring_initial_fee"];
289
- $orderSubtotal = ($isFirstRecurringOrder) ? $orderItemInfo["row_total"]+$initialFeeAmount : $orderItemInfo["row_total"];
290
-
291
- //check is set related orders
292
- $useDiscount = current($recurringProfile->getChildOrderIds()) > 0;
293
- $discountAmount = ($useDiscount) ? 0 : $orderItemInfo["discount_amount"];
294
-
295
- $taxAmount = $recurringProfile->getData("tax_amount");
296
- $shippingAmount = $recurringProfile->getData("shipping_amount");
297
-
298
- $productItemInfo = new Varien_Object;
299
- $productItemInfo->setDiscountAmount($discountAmount);
300
- $productItemInfo->setPaymentType(Mage_Sales_Model_Recurring_Profile::PAYMENT_TYPE_REGULAR);
301
- $productItemInfo->setTaxAmount($taxAmount);
302
- $productItemInfo->setShippingAmount($shippingAmount);
303
- $productItemInfo->setPrice($orderSubtotal);
304
-
305
- Mage::dispatchEvent('before_recurring_profile_order_create', array('profile' => $recurringProfile,'product_item_info'=>$productItemInfo));
306
- $order = $recurringProfile->createOrder($productItemInfo);
307
- if($isFirstRecurringOrder){
308
- if($orderKey = $this->getOrderKey()){
309
- $order->setIncrementId($orderKey);
310
- }
311
}
312
- Mage::dispatchEvent('before_recurring_profile_order_save', array('order' => $order));
313
314
- $order->save();
315
- $recurringProfile->addOrderRelation($order->getId());
316
317
- return $order->getId();
318
}
319
320
/**
321
* @param Mage_Payment_Model_Recurring_Profile $recurringProfile
322
* @return int
323
*/
324
- public function getCurrentBillingPeriodTimeStamp(Mage_Payment_Model_Recurring_Profile $recurringProfile){
325
- $periodUnit = $recurringProfile->getData("period_unit"); //day
326
- $periodFrequency = $recurringProfile->getData("period_frequency");
327
//$masPeriodUnits = $recurringProfile->getAllPeriodUnits();
328
$billingTimeStamp = 0;
329
- switch ($periodUnit){
330
- case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_DAY:
331
- $billingTimeStamp = self::DAY_TIME_STAMP;
332
- break;
333
- case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_WEEK;
334
- $billingTimeStamp = self::WEEK_TIME_STAMP;
335
- break;
336
- case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_SEMI_MONTH;
337
- $billingTimeStamp = self::SEMI_MONTH_TIME_STAMP;
338
- break;
339
- case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_MONTH;
340
- $startDateTime = strtotime($recurringProfile->getStartDatetime());
341
- $lastSuccessTransactionDate = strtotime($recurringProfile->getXpSuccessTransactionDate());
342
- $lastActionDate = ($startDateTime > $lastSuccessTransactionDate) ? $startDateTime : $lastSuccessTransactionDate;
343
- $nextMonth = mktime(date("H",$lastActionDate), date("i",$lastActionDate) ,date("s",$lastActionDate) , date("m",$lastActionDate)+1, date("d",$lastActionDate), date("Y",$lastActionDate));
344
- $billingTimeStamp = $nextMonth - $lastActionDate;
345
-
346
- break;
347
- case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_YEAR;
348
- $startDateTime = strtotime($recurringProfile->getStartDatetime());
349
- $lastSuccessTransactionDate = strtotime($recurringProfile->getXpSuccessTransactionDate());
350
- $lastActionDate = ($startDateTime > $lastSuccessTransactionDate) ? $startDateTime : $lastSuccessTransactionDate;
351
- $nextYear = mktime(date("H",$lastActionDate), date("i",$lastActionDate) ,date("s",$lastActionDate) , date("m",$lastActionDate), date("d",$lastActionDate), date("Y",$lastActionDate)+1);
352
- $billingTimeStamp = $nextYear - $lastActionDate;
353
-
354
- break;
355
- }
356
357
$billingPeriodTimeStamp = round($billingTimeStamp / $periodFrequency);
358
@@ -364,10 +515,11 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
364
* @param Mage_Payment_Model_Recurring_Profile $recurringProfile
365
* @return array
366
*/
367
- public function getProfileOrderCardData(Mage_Payment_Model_Recurring_Profile $recurringProfile){
368
$txnId = $recurringProfile->getReferenceId();
369
- $cardData = Mage::getModel("xpaymentsconnector/usercards")->load($txnId,"txnid");
370
- return $cardData;
371
}
372
373
/**
@@ -375,17 +527,18 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
375
* @param bool $result
376
* @param timestamp $newTransactionDate
377
*/
378
- public function updateCurrentBillingPeriodTimeStamp(Mage_Payment_Model_Recurring_Profile $recurringProfile, bool $result,$newTransactionDate = null){
379
- if(!$result){
380
$currentCycleFailureCount = $recurringProfile->getXpCycleFailureCount();
381
//add failed attempt
382
$currentCycleFailureCount++;
383
$recurringProfile->setXpCycleFailureCount($currentCycleFailureCount);
384
$maxPaymentFailure = $recurringProfile->getSuspensionThreshold();
385
- if($currentCycleFailureCount > $maxPaymentFailure){
386
$recurringProfile->cancel();
387
}
388
- }else{
389
$recurringProfile->setXpCycleFailureCount(0);
390
391
// update date of success transaction
@@ -402,12 +555,41 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
402
403
}
404
405
- public function checkIsRecurringOrder(){
406
$checkoutSession = Mage::getSingleton('checkout/session');
407
- $quoteItem = current($checkoutSession->getQuote()->getAllItems());
408
- if($quoteItem){
409
- $isRecurringOreder = (bool) $quoteItem->getProduct()->getIsRecurring();
410
- return $isRecurringOreder;
411
}
412
413
return false;
@@ -420,10 +602,11 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
420
*/
421
public function payDeferredSubscription(Mage_Payment_Model_Recurring_Profile $recurringProfile)
422
{
423
- $orderItemInfo = $recurringProfile->getData("order_item_info");
424
- $useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
425
- $infoBuyRequest = unserialize($orderItemInfo["info_buyRequest"]);
426
- $startDateTime = $infoBuyRequest["recurring_profile_start_datetime"];
427
428
if (!empty($startDateTime)) {
429
$dateTimeStamp = strtotime($startDateTime);
@@ -433,159 +616,210 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
433
if ($zendDate->getTimestamp() > $currentZendDate->getTimestamp()) {
434
//set start date time
435
$recurringProfile->setStartDatetime($zendDate->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));
436
437
- $initialFeeAmount = $orderItemInfo["recurring_initial_fee"];
438
- if ($initialFeeAmount) {
439
- $grandTotal = $initialFeeAmount;
440
- } else {
441
- $grandTotal = floatval(Mage::getStoreConfig("xpaymentsconnector/settings/xpay_minimum_payment_recurring_amount"));
442
}
443
444
445
- $paymentMethodCode = $recurringProfile->getData("method_code");
446
447
$cardData = NULL;
448
switch ($paymentMethodCode) {
449
- case(Mage::getModel("xpaymentsconnector/payment_savedcards")->getCode()):
450
-
451
- $paymentCardNumber = $recurringProfile->getQuote()->getPayment()->getData("xp_payment_card");
452
-
453
- $cardData = Mage::getModel("xpaymentsconnector/usercards")->load($paymentCardNumber);
454
- $cardData = $cardData->getData();
455
456
- $response = Mage::getModel("xpaymentsconnector/payment_cc")->sendAgainTransactionRequest(NULL, NULL, $grandTotal, $cardData);
457
-
458
-
459
- $recurringProfile->setReferenceId($cardData["txnId"]);
460
- if ($response["success"]) {
461
- $recurringProfile->activate();
462
- } else {
463
- Mage::getSingleton("checkout/session")->addError($response["error_message"]);
464
- $recurringProfile->cancel();
465
}
466
- return true;
467
468
break;
469
- case(Mage::getModel("xpaymentsconnector/payment_cc")->getCode()):
470
- if ($useIframe) {
471
$cardData = $this->getXpaymentResponse();
472
- $recurringProfile->setReferenceId($cardData["txnId"]);
473
- //check transaction state
474
- list($status, $response) = Mage::getModel("xpaymentsconnector/payment_cc")->requestPaymentInfo($cardData["txnId"]);
475
-
476
- if (
477
- $status
478
- && in_array($response['status'], array(Cdev_XPaymentsConnector_Model_Payment_Cc::AUTH_STATUS, Cdev_XPaymentsConnector_Model_Payment_Cc::CHARGED_STATUS))
479
- ) {
480
- Mage::getSingleton("checkout/session")->setData("user_card_save",true);
481
- Mage::getModel("xpaymentsconnector/payment_cc")->saveUserCard($cardData, Cdev_XPaymentsConnector_Model_Usercards::RECURRING_CARD);
482
- $recurringProfile->activate();
483
} else {
484
- $this->addRecurringTransactionError($response);
485
- $recurringProfile->cancel();
486
- }
487
- return true;
488
-
489
- }else{
490
- $cardData = $this->getXpaymentResponse();
491
492
- //check transaction state
493
- list($status, $response) = Mage::getModel("xpaymentsconnector/payment_cc")->requestPaymentInfo($cardData["txnId"]);
494
- if (
495
- $status
496
- && in_array($response['status'], array(Cdev_XPaymentsConnector_Model_Payment_Cc::AUTH_STATUS, Cdev_XPaymentsConnector_Model_Payment_Cc::CHARGED_STATUS))
497
- ) {
498
- // save user card
499
- Mage::getSingleton("checkout/session")->setData("user_card_save",true);
500
- Mage::getModel("xpaymentsconnector/payment_cc")->saveUserCard($cardData,$usageType = Cdev_XPaymentsConnector_Model_Usercards::RECURRING_CARD);
501
-
502
- $recurringProfile->setReferenceId($cardData["txnId"]);
503
- $recurringProfile->activate();
504
- $recurringProfile->save();
505
- return true;
506
- }else{
507
- $recurringProfile->cancel();
508
}
509
- }
510
- break;
511
}
512
513
}
514
}
515
return false;
516
}
517
518
- public function checkStartDateData(){
519
$result = array();
520
- $quoteItem = current(Mage::getSingleton("checkout/session")->getQuote()->getAllItems());
521
- if($quoteItem){
522
- $productAdditionalInfo = unserialize($quoteItem->getProduct()->getCustomOption('info_buyRequest')->getValue());
523
- $dateTimeStamp = strtotime($productAdditionalInfo["recurring_profile_start_datetime"]);
524
- if ($dateTimeStamp) {
525
- $userSetTime = new Zend_Date($productAdditionalInfo["recurring_profile_start_datetime"]);
526
- $currentZendDate = new Zend_Date(time());
527
- if ($userSetTime->getTimestamp() > $currentZendDate->getTimestamp()) {
528
- $result["success"] = true;
529
- $recurringProfileData = $quoteItem->getProduct()->getData("recurring_profile");
530
- $initAmount = $recurringProfileData["init_amount"];
531
- $defaultMinimumPayment = floatval(Mage::getStoreConfig("xpaymentsconnector/settings/xpay_minimum_payment_recurring_amount"));
532
- $minimumPaymentAmount = ($initAmount) ? $initAmount : $defaultMinimumPayment;
533
- $result["minimal_payment_amount"] = $minimumPaymentAmount;
534
- return $result;
535
} else {
536
- $result["success"] = false;
537
- return $result;
538
}
539
} else {
540
- $result["success"] = false;
541
- return $result;
542
}
543
}
544
- $result["success"] = false;
545
return $result;
546
}
547
548
- public function getRecurringProfileState(){
549
$maxPaymentFailureMessage = $this->__('This profile has run out of maximal limit of unsuccessful payment attempts.');
550
551
if (Mage::app()->getStore()->isAdmin()) {
552
Mage::getSingleton('adminhtml/session')->addNotice($maxPaymentFailureMessage);
553
- }else{
554
Mage::getSingleton('core/session')->addNotice($maxPaymentFailureMessage);
555
}
556
}
557
558
- public function addRecurringTransactionError($response = array()){
559
- $this->unsetXpaymentPrepareOrder();
560
- if(!empty($response)){
561
- if (!empty($response["error_message"])) {
562
- $errorMessage = $this->__('%s. The subscription has been canceled.', $response["error_message"]);
563
- Mage::getSingleton("checkout/session")->addError($errorMessage);
564
- } else {
565
- $transactionStatusLabel = Mage::getModel("xpaymentsconnector/payment_cc")->getTransactionStatusLabels();
566
- $errorMessage = $this->__("Transaction status is '%s'. The subscription has been canceled.", $transactionStatusLabel[$response['status']]);
567
- Mage::getSingleton("checkout/session")->addError($errorMessage);
568
- }
569
- }else{
570
- $errorMessage = $this->__('The subscription has been canceled.');
571
- Mage::getSingleton("checkout/session")->addError($errorMessage);
572
- }
573
}
574
575
- public function setRecurringProductDiscount(){
576
$quote = Mage::getSingleton('checkout/session')->getQuote();
577
$items = $quote->getAllVisibleItems();
578
- foreach($items as $item){
579
$discount = $item->getDiscountAmount();
580
$profile = $item->getProduct()->getRecurringProfile();
581
- $profile["discount_amount"] = $discount;
582
$item->getProduct()->setRecurringProfile($profile)->save();
583
}
584
}
585
586
- public function getIframeUrl(){
587
- $xpaymentFormData = Mage::helper('payment')->getMethodInstance("xpayments")->getFormFields();
588
- $xpaymentFormUrl = Mage::helper('payment')->getMethodInstance("xpayments")->getUrl();
589
590
$this->prepareOrderKey();
591
$token = $this->getIframeToken();
@@ -594,4 +828,164 @@ class Cdev_XPaymentsConnector_Helper_Data extends Mage_Payment_Helper_Data
594
return $iframeUrl;
595
}
596
597
}
21
22
/**
23
* Common helper
24
+ *
25
* @package Cdev_XPaymentsConnector
26
* @see ____class_see____
27
* @since 1.0.0
33
const WEEK_TIME_STAMP = 604800;
34
const SEMI_MONTH_TIME_STAMP = 1209600;
35
36
+ const STATE_XPAYMENT_PENDING_PAYMENT = 'xp_pending_payment';
37
+ const XPAYMENTS_LOG_FILE = 'xpayments.log';
38
+ const RECURRING_ORDER_TYPE = 'recurring';
39
+ const SIMPLE_ORDER_TYPE = 'simple';
40
41
+ /**
42
+ * save/update qty for createOrder function.
43
+ * @var int
44
+ */
45
+ protected $itemsQty = null;
46
+ public $payDeferredProfileId = null;
47
48
/**
49
* This function return 'IncrementId' for feature order.
54
* return
55
* @return bool or int
56
*/
57
+ public function getOrderKey()
58
+ {
59
+ $xpaymentPrepareOrderData = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
60
+ if ($xpaymentPrepareOrderData && isset($xpaymentPrepareOrderData['prepare_order_id'])) {
61
+ return $xpaymentPrepareOrderData['prepare_order_id'];
62
}
63
return false;
64
}
65
66
/**
67
* This function create 'IncrementId' for feature order.
68
* Xpayment Prepare Order Mas(xpayment_prepare_order):
74
*/
75
public function prepareOrderKey()
76
{
77
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
78
if(!isset($xpaymentPrepareOrder["prepare_order_id"])){
79
+ $this->prepareSimpleOrderKey();
80
+ }
81
82
+ }
83
84
+ public function updateRecurringMasKeys(Mage_Payment_Model_Recurring_Profile $recurringProfile)
85
+ {
86
+ $orderItemInfo = $recurringProfile->getData('order_item_info');
87
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
88
+ $xpaymentPrepareOrder['recurring_mas'][$orderItemInfo['product_id']] = $this->getOrderKey();
89
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
90
+ }
91
+
92
+ public function getPrepareRecurringMasKey(Mage_Payment_Model_Recurring_Profile $recurringProfile)
93
+ {
94
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
95
+ if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder['recurring_mas'])) {
96
+ $orderItemInfo = $recurringProfile->getData('order_item_info');
97
+ $prodId = $orderItemInfo['product_id'];
98
+ if (isset($xpaymentPrepareOrder['recurring_mas'][$prodId])) {
99
+ return $xpaymentPrepareOrder['recurring_mas'][$prodId];
100
+ }
101
}
102
+ return false;
103
+ }
104
+
105
+
106
+ /**
107
+ * @return mixed
108
+ */
109
+ public function prepareSimpleOrderKey()
110
+ {
111
+ $storeId = Mage::app()->getStore()->getStoreId();
112
+ $prepareOrderId = Mage::getSingleton('eav/config')
113
+ ->getEntityType('order')
114
+ ->fetchNewIncrementId($storeId);
115
+
116
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
117
+ $xpaymentPrepareOrder['prepare_order_id'] = $prepareOrderId;
118
+
119
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
120
+ return $prepareOrderId;
121
122
}
123
124
+
125
/**
126
* This function set 'place_display' flag for feature x-payment form.
127
* Xpayment Prepare Order Mas(xpayment_prepare_order):
135
public function setIframePlaceDisplaySettings()
136
{
137
$useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
138
+ if ($useIframe) {
139
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
140
+ $xpaymentPrepareOrder['place_display'] = Mage::getStoreConfig('payment/xpayments/placedisplay');
141
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
142
}
143
}
144
146
* check 'xpayment' config settigs
147
* @return bool
148
*/
149
+ public function isIframePaymentPlaceDisplay()
150
+ {
151
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
152
+ if (isset($xpaymentPrepareOrder['place_display']) && ($xpaymentPrepareOrder['place_display'] == 'payment')) {
153
return true;
154
}
155
return false;
164
* return
165
* @return bool or int
166
*/
167
+ public function getXpaymentResponse()
168
+ {
169
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
170
+ if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder['xpayment_response'])) {
171
+ return $xpaymentPrepareOrder['xpayment_response'];
172
}
173
return false;
174
}
184
*/
185
public function getIframeToken()
186
{
187
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
188
+ if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder['token']) && !empty($xpaymentPrepareOrder['token'])) {
189
+ return $xpaymentPrepareOrder['token'];
190
} else {
191
$api = Mage::getModel('xpaymentsconnector/payment_cc');
192
$result = $api->sendIframeHandshakeRequest();
193
+ $xpaymentPrepareOrder['token'] = $result['response']['token'];
194
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
195
+ return $xpaymentPrepareOrder['token'];
196
}
197
198
}
199
200
+ /**
201
+ * This function sets a type for prepared order
202
+ * Xpayment Prepare Order Mas(xpayment_prepare_order):
203
+ * - prepare_order_id (int)
204
+ * - xpayment_response
205
+ * - type (string)
206
+ * - is_recurring
207
+ */
208
+ public function setPrepareOrderType()
209
+ {
210
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
211
+ $result = $this->checkIssetRecurringOrder();
212
+ if ($result['isset']) {
213
+ $xpaymentPrepareOrder['type'] = self::RECURRING_ORDER_TYPE;
214
+ } else {
215
+ $xpaymentPrepareOrder['type'] = self::SIMPLE_ORDER_TYPE;
216
+ }
217
+
218
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
219
+ }
220
+
221
+ /**
222
+ * This function checks a type for prepared order
223
+ * Xpayment Prepare Order Mas(xpayment_prepare_order):
224
+ * - prepare_order_id (int)
225
+ * - xpayment_response
226
+ * - type (string)
227
+ * - is_recurring
228
+ * @return bool
229
+ */
230
+ public function checkIsRecurringPrepareOrderType()
231
+ {
232
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
233
+ if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder['type']) && !empty($xpaymentPrepareOrder['type'])) {
234
+ ($xpaymentPrepareOrder['type'] == self::RECURRING_ORDER_TYPE) ? true : false;
235
+ return ($xpaymentPrepareOrder['type'] == self::RECURRING_ORDER_TYPE) ? true : false;
236
+ } else {
237
+ return false;
238
+ }
239
+ }
240
+
241
/**
242
* Unset prepare order params
243
* @param array $unsetParams
244
*/
245
+ public function unsetXpaymentPrepareOrder($unsetParams = array())
246
+ {
247
+ if (!empty($unsetParams)) {
248
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
249
+ foreach ($unsetParams as $param) {
250
+ if (is_array($xpaymentPrepareOrder) && isset($xpaymentPrepareOrder[$param])) {
251
unset($xpaymentPrepareOrder[$param]);
252
}
253
}
254
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
255
return;
256
}
257
258
+ Mage::getSingleton('checkout/session')->unsetData('xpayment_prepare_order');
259
}
260
261
/**
265
*/
266
public function savePaymentResponse($responseData)
267
{
268
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
269
+ $xpaymentPrepareOrder['xpayment_response'] = $responseData;
270
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
271
}
272
273
/**
274
* Save all allowed payments for current checkout session in store.
275
* - allowed_payments
276
+ * @param array $methods
277
*/
278
public function setAllowedPaymentsMethods($methodsInstances)
279
{
280
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
281
+ $xpaymentPrepareOrder['allowed_payments'] = $methodsInstances;
282
$methods = array();
283
+ foreach ($methodsInstances as $methodInstance) {
284
+ $methods[]['method_code'] = $methodInstance->getCode();
285
}
286
+ $xpaymentPrepareOrder['allowed_payments'] = $methods;
287
+ Mage::getSingleton('checkout/session')->setData('xpayment_prepare_order', $xpaymentPrepareOrder);
288
}
289
290
/**
293
*/
294
public function getAllowedPaymentsMethods()
295
{
296
+ $xpaymentPrepareOrder = Mage::getSingleton('checkout/session')->getData('xpayment_prepare_order');
297
+ if ($xpaymentPrepareOrder && isset($xpaymentPrepareOrder['allowed_payments']) && !empty($xpaymentPrepareOrder['allowed_payments'])) {
298
+ return $xpaymentPrepareOrder['allowed_payments'];
299
}
300
return false;
301
}
304
public function getReviewButtonTemplate($name, $block)
305
{
306
$quote = Mage::getSingleton('checkout/session')->getQuote();
307
+ $useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
308
+ $xpCcMethodCode = Mage::getModel('xpaymentsconnector/payment_cc')->getCode();
309
if ($quote) {
310
$payment = $quote->getPayment();
311
+ if ($payment && $payment->getMethod() == $xpCcMethodCode && $useIframe) {
312
return $name;
313
}
314
}
320
return '';
321
}
322
323
+ public function isNeedToSaveUserCard()
324
+ {
325
+ $result = (bool)Mage::getSingleton('checkout/session')->getData('user_card_save');
326
return $result;
327
}
328
329
+ public function userCardSaved(){
330
+ Mage::getSingleton('checkout/session')->setData('user_card_save',false);
331
+ }
332
+
333
public function isRegisteredUser()
334
{
335
+ $currentCustomerState = Mage::getSingleton('checkout/type_onepage')->getCheckoutMethod();
336
+ $registerMethod = Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER;
337
+ $customerMethod = Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER;
338
+ if (($currentCustomerState == $registerMethod) || ($currentCustomerState == $customerMethod)) {
339
return true;
340
+ } else {
341
+ return false;
342
+ }
343
+ }
344
+
345
+ public function isXpaymentsMethod($currentPaymentCode)
346
+ {
347
+ $xpaymentPaymentCode = Mage::getModel('xpaymentsconnector/payment_cc')->getCode();
348
+ $saveCardsPaymentCode = Mage::getModel('xpaymentsconnector/payment_savedcards')->getCode();
349
+ $prepaidpayments = Mage::getModel('xpaymentsconnector/payment_prepaidpayments')->getCode();
350
+ $usePaymetCodes = array($xpaymentPaymentCode, $saveCardsPaymentCode, $prepaidpayments);
351
+ if (in_array($currentPaymentCode, $usePaymetCodes)) {
352
+ return true;
353
+ } else {
354
return false;
355
}
356
}
357
358
+ /**
359
+ * This function prepare order keys for recurring orders
360
+ * @return int
361
+ */
362
+ public function prepareOrderKeyByRecurringProfile(Mage_Payment_Model_Recurring_Profile $recurringProfile)
363
+ {
364
+ $quote = $recurringProfile->getQuote();
365
+ $this->itemsQty = $quote->getItemsCount();
366
+ $orderItemInfo = $recurringProfile->getData('order_item_info');
367
+ $quote->getItemById($orderItemInfo['item_id'])->isDeleted(true);
368
+
369
+ if ($this->itemsQty > 1) {
370
+ // update order key
371
+ $unsetParams = array('prepare_order_id');
372
+ $this->unsetXpaymentPrepareOrder($unsetParams);
373
+ $this->prepareOrderKey();
374
+ }
375
+ }
376
+
377
/**
378
* @param Mage_Payment_Model_Recurring_Profile $recurringProfile
379
* @param bool $isFirstRecurringOrder
380
* @return int
381
*/
382
+ public function createOrder(Mage_Payment_Model_Recurring_Profile $recurringProfile, $isFirstRecurringOrder = false,$orderAmountData = array())
383
+ {
384
+ $orderItemInfo = $recurringProfile->getData('order_item_info');
385
386
+ if (!is_array($orderItemInfo)) {
387
+ $orderItemInfo = unserialize($orderItemInfo);
388
+ }
389
+ $initialFeeAmount = $recurringProfile->getInitAmount();
390
391
+ $productSubtotal = ($isFirstRecurringOrder) ? $orderItemInfo['row_total'] + $initialFeeAmount : $orderItemInfo['row_total'];
392
+ $price = $productSubtotal / $orderItemInfo['qty'];
393
+ if(isset($orderAmountData['product_subtotal']) && $initialFeeAmount > 0 ){
394
+ $productSubtotal = $orderAmountData['product_subtotal'];
395
+ $price = $orderAmountData['product_subtotal'] / $orderItemInfo['qty'];
396
+ }
397
+
398
+ //check is set related orders
399
+
400
+ $useDiscount = ($recurringProfile->getXpCountSuccessTransaction() > 0) ? false : true;
401
+ $discountAmount = ($useDiscount) ? $orderItemInfo['discount_amount'] : 0;
402
+ if(isset($orderAmountData['discount_amount'])){
403
+ $discountAmount = $orderAmountData['discount_amount'];
404
+ }
405
+
406
+ $taxAmount = $recurringProfile->getData('tax_amount');
407
+ if(isset($orderAmountData['tax_amount'])){
408
+ $taxAmount = $orderAmountData['tax_amount'];
409
+ }
410
+
411
+ if($isFirstRecurringOrder && !isset($orderAmountData['tax_amount'])){
412
+ $taxAmount += $orderItemInfo['initialfee_tax_amount'];
413
+ }
414
+
415
+ $shippingAmount = $recurringProfile->getData('shipping_amount');
416
+ if(isset($orderAmountData['shipping_amount'])){
417
+ $shippingAmount = $orderAmountData['shipping_amount'];
418
+ }
419
+
420
+ $productItemInfo = new Varien_Object;
421
+ $productItemInfo->setDiscountAmount($discountAmount);
422
+ $productItemInfo->setPaymentType(Mage_Sales_Model_Recurring_Profile::PAYMENT_TYPE_REGULAR);
423
+ $productItemInfo->setTaxAmount($taxAmount);
424
+ $productItemInfo->setShippingAmount($shippingAmount);
425
+ $productItemInfo->setPrice($price);
426
+ $productItemInfo->setQty($orderItemInfo['qty']);
427
+ $productItemInfo->setRowTotal($productSubtotal);
428
+ $productItemInfo->setBaseRowTotal($productSubtotal);
429
+ $productItemInfo->getOriginalPrice($price);
430
+
431
+ if($initialFeeAmount > 0){
432
+ if(isset($orderAmountData['grand_total'])){
433
+ $productItemInfo->setRowTotalInclTax($orderAmountData['grand_total']);
434
+ $productItemInfo->setBaseRowTotalInclTax($orderAmountData['grand_total']);
435
}
436
+ }
437
+
438
+ Mage::dispatchEvent('before_recurring_profile_order_create', array('profile' => $recurringProfile, 'product_item_info' => $productItemInfo));
439
+ $order = $recurringProfile->createOrder($productItemInfo);
440
+ $order->setCustomerId($recurringProfile->getCustomerId());
441
+
442
+ if ($isFirstRecurringOrder) {
443
+ $orderKey = 0;
444
+ if ($this->getPrepareRecurringMasKey($recurringProfile)) {
445
+ $orderKey = $this->getPrepareRecurringMasKey($recurringProfile);
446
+ } elseIf ($this->getOrderKey()) {
447
+ $orderKey = $this->getOrderKey();
448
}
449
+ if ($orderKey) {
450
+ $order->setIncrementId($orderKey);
451
+ //unset order Key
452
+ $unsetParams = array('prepare_order_id');
453
+ $this->unsetXpaymentPrepareOrder($unsetParams);
454
+ }
455
+ }
456
+ if(isset($orderAmountData['shipping_amount'])){
457
+ $order->setShippingAmount($orderAmountData['shipping_amount']);
458
+ $order->setBaseShippingAmount($orderAmountData['shipping_amount']);
459
+ }
460
+
461
462
+ Mage::dispatchEvent('before_recurring_profile_order_save', array('order' => $order));
463
464
+ $order->save();
465
+ $recurringProfile->addOrderRelation($order->getId());
466
+
467
+ return $order->getId();
468
}
469
470
/**
471
* @param Mage_Payment_Model_Recurring_Profile $recurringProfile
472
* @return int
473
*/
474
+ public function getCurrentBillingPeriodTimeStamp(Mage_Payment_Model_Recurring_Profile $recurringProfile)
475
+ {
476
+ $periodUnit = $recurringProfile->getData('period_unit'); //day
477
+ $periodFrequency = $recurringProfile->getData('period_frequency');
478
//$masPeriodUnits = $recurringProfile->getAllPeriodUnits();
479
$billingTimeStamp = 0;
480
+ switch ($periodUnit) {
481
+ case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_DAY:
482
+ $billingTimeStamp = self::DAY_TIME_STAMP;
483
+ break;
484
+ case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_WEEK;
485
+ $billingTimeStamp = self::WEEK_TIME_STAMP;
486
+ break;
487
+ case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_SEMI_MONTH;
488
+ $billingTimeStamp = self::SEMI_MONTH_TIME_STAMP;
489
+ break;
490
+ case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_MONTH;
491
+ $startDateTime = strtotime($recurringProfile->getStartDatetime());
492
+ $lastSuccessTransactionDate = strtotime($recurringProfile->getXpSuccessTransactionDate());
493
+ $lastActionDate = ($startDateTime > $lastSuccessTransactionDate) ? $startDateTime : $lastSuccessTransactionDate;
494
+ $nextMonth = mktime(date('H', $lastActionDate), date('i', $lastActionDate), date('s', $lastActionDate), date('m', $lastActionDate) + 1, date('d', $lastActionDate), date('Y', $lastActionDate));
495
+ $billingTimeStamp = $nextMonth - $lastActionDate;
496
+
497
+ break;
498
+ case Mage_Payment_Model_Recurring_Profile::PERIOD_UNIT_YEAR;
499
+ $startDateTime = strtotime($recurringProfile->getStartDatetime());
500
+ $lastSuccessTransactionDate = strtotime($recurringProfile->getXpSuccessTransactionDate());
501
+ $lastActionDate = ($startDateTime > $lastSuccessTransactionDate) ? $startDateTime : $lastSuccessTransactionDate;
502
+ $nextYear = mktime(date('H', $lastActionDate), date('i', $lastActionDate), date('s', $lastActionDate), date('m', $lastActionDate), date('d', $lastActionDate), date('Y', $lastActionDate) + 1);
503
+ $billingTimeStamp = $nextYear - $lastActionDate;
504
+
505
+ break;
506
+ }
507
508
$billingPeriodTimeStamp = round($billingTimeStamp / $periodFrequency);
509
515
* @param Mage_Payment_Model_Recurring_Profile $recurringProfile
516
* @return array
517
*/
518
+ public function getProfileOrderCardData(Mage_Payment_Model_Recurring_Profile $recurringProfile)
519
+ {
520
$txnId = $recurringProfile->getReferenceId();
521
+ $cardData = Mage::getModel('xpaymentsconnector/usercards')->load($txnId, 'txnid');
522
+ return $cardData;
523
}
524
525
/**
527
* @param bool $result
528
* @param timestamp $newTransactionDate
529
*/
530
+ public function updateCurrentBillingPeriodTimeStamp(Mage_Payment_Model_Recurring_Profile $recurringProfile, bool $result, $newTransactionDate = null)
531
+ {
532
+ if (!$result) {
533
$currentCycleFailureCount = $recurringProfile->getXpCycleFailureCount();
534
//add failed attempt
535
$currentCycleFailureCount++;
536
$recurringProfile->setXpCycleFailureCount($currentCycleFailureCount);
537
$maxPaymentFailure = $recurringProfile->getSuspensionThreshold();
538
+ if ($currentCycleFailureCount > $maxPaymentFailure) {
539
$recurringProfile->cancel();
540
}
541
+ } else {
542
$recurringProfile->setXpCycleFailureCount(0);
543
544
// update date of success transaction
555
556
}
557
558
+ public function checkIssetRecurringOrder()
559
+ {
560
$checkoutSession = Mage::getSingleton('checkout/session');
561
+ $quoteItems = $checkoutSession->getQuote()->getAllItems();
562
+ $result = array();
563
+
564
+ foreach ($quoteItems as $quoteItem) {
565
+ if ($quoteItem) {
566
+ $product = $quoteItem->getProduct();
567
+ $issetRecurringOreder = (bool)$product->getIsRecurring();
568
+ if ($issetRecurringOreder) {
569
+ $result['isset'] = $issetRecurringOreder;
570
+ $result['quote_item'] = $quoteItem;
571
+ return $result;
572
+ }
573
+ }
574
+ }
575
+ $result['isset'] = false;
576
+
577
+ return $result;
578
+ }
579
+
580
+ public function checkIssetSimpleOrder()
581
+ {
582
+ $checkoutSession = Mage::getSingleton('checkout/session');
583
+ $quoteItems = $checkoutSession->getQuote()->getAllItems();
584
+
585
+ foreach ($quoteItems as $quoteItem) {
586
+ if ($quoteItem) {
587
+ $product = $quoteItem->getProduct();
588
+ $issetRecurringOreder = (bool)$product->getIsRecurring();
589
+ if (!$issetRecurringOreder) {
590
+ return true;
591
+ }
592
+ }
593
}
594
595
return false;
602
*/
603
public function payDeferredSubscription(Mage_Payment_Model_Recurring_Profile $recurringProfile)
604
{
605
+
606
+ $orderItemInfo = $recurringProfile->getData('order_item_info');
607
+ $infoBuyRequest = unserialize($orderItemInfo['info_buyRequest']);
608
+ $startDateTime = $infoBuyRequest['recurring_profile_start_datetime'];
609
+ $xpaymentCCModel = Mage::getModel('xpaymentsconnector/payment_cc');
610
611
if (!empty($startDateTime)) {
612
$dateTimeStamp = strtotime($startDateTime);
616
if ($zendDate->getTimestamp() > $currentZendDate->getTimestamp()) {
617
//set start date time
618
$recurringProfile->setStartDatetime($zendDate->toString(Varien_Date::DATETIME_INTERNAL_FORMAT));
619
+ $orderAmountData = $this->preparePayDeferredOrderAmountData($recurringProfile);
620
621
+ if (!isset($orderItemInfo['recurring_initial_fee'])) {
622
+ $orderAmountData['grand_total'] = floatval(Mage::getStoreConfig('xpaymentsconnector/settings/xpay_minimum_payment_recurring_amount'));
623
}
624
625
626
+ $paymentMethodCode = $recurringProfile->getData('method_code');
627
628
$cardData = NULL;
629
switch ($paymentMethodCode) {
630
+ case(Mage::getModel('xpaymentsconnector/payment_savedcards')->getCode()):
631
632
+ if(!is_null($recurringProfile->getInitAmount())){
633
+ $paymentCardNumber = $recurringProfile->getQuote()->getPayment()->getData('xp_payment_card');
634
+ $card = Mage::getModel('xpaymentsconnector/usercards')->load($paymentCardNumber);
635
+ $cardData = $card->getData();
636
+ $this->resendPayDeferredRecurringTransaction($recurringProfile, $orderAmountData, $cardData);
637
}
638
+ $this->payDeferredProfileId = $recurringProfile->getProfileId();
639
+ $recurringProfile->activate();
640
641
+ return true;
642
break;
643
+ case($xpaymentCCModel->getCode()):
644
$cardData = $this->getXpaymentResponse();
645
+ if (!is_null($this->payDeferredProfileId)) {
646
+ $this->resendPayDeferredRecurringTransaction($recurringProfile, $orderAmountData, $cardData);
647
} else {
648
+ $recurringProfile->setReferenceId($cardData['txnId']);
649
+ //check transaction state
650
+ list($status, $response) = $xpaymentCCModel->requestPaymentInfo($cardData['txnId']);
651
+ if (
652
+ $status
653
+ && in_array($response['status'], array(Cdev_XPaymentsConnector_Model_Payment_Cc::AUTH_STATUS, Cdev_XPaymentsConnector_Model_Payment_Cc::CHARGED_STATUS))
654
+ ) {
655
+ if(!is_null($recurringProfile->getInitAmount())){
656
+ //create order
657
+ $orderId = $this->createOrder($recurringProfile, $isFirstRecurringOrder = true, $orderAmountData);
658
+ //update order
659
+ $xpaymentCCModel->updateOrderByXpaymentResponse($orderId, $cardData['txnId']);
660
+ }
661
+
662
+ Mage::getSingleton('checkout/session')->setData('user_card_save', true);
663
+ $xpaymentCCModel->saveUserCard($cardData, Cdev_XPaymentsConnector_Model_Usercards::RECURRING_CARD);
664
+ $recurringProfile->activate();
665
+ } else {
666
+ $this->addRecurringTransactionError($response);
667
+ $recurringProfile->cancel();
668
+ }
669
670
}
671
+
672
+ $this->payDeferredProfileId = $recurringProfile->getProfileId();
673
+ return true;
674
}
675
676
}
677
}
678
+
679
+ $this->payDeferredProfileId = $recurringProfile->getProfileId();
680
return false;
681
}
682
683
+ /**
684
+ * @param Mage_Payment_Model_Recurring_Profile $recurringProfile
685
+ * @param $orderAmountData
686
+ * @param $cardData
687
+ */
688
+ public function resendPayDeferredRecurringTransaction(Mage_Payment_Model_Recurring_Profile $recurringProfile, $orderAmountData, $cardData)
689
+ {
690
+ $xpaymentCCModel = Mage::getModel('xpaymentsconnector/payment_cc');
691
+ $recurringProfile->setReferenceId($cardData['txnId']);
692
+ $orderId = NULL;
693
+ //create order
694
+ if (!is_null($recurringProfile->getInitAmount())) {
695
+ $orderId = $this->createOrder($recurringProfile, $isFirstRecurringOrder = true, $orderAmountData);
696
+ }
697
+ $response = $xpaymentCCModel->sendAgainTransactionRequest(
698
+ $orderId,
699
+ NULL,
700
+ $orderAmountData['grand_total'],
701
+ $cardData);
702
+
703
+ //update order
704
+ if(!is_null($orderId)){
705
+ $xpaymentCCModel->updateOrderByXpaymentResponse($orderId, $response['response']['transaction_id']);
706
+ }
707
+
708
+ if ($response['success']) {
709
+ $recurringProfile->activate();
710
+ } else {
711
+ Mage::getSingleton('checkout/session')->addError($response['error_message']);
712
+ $recurringProfile->cancel();
713
+ }
714
+ }
715
+
716
+ public function checkStartDateData()
717
+ {
718
$result = array();
719
+ $result['total_min_amount'] = 0;
720
+ $quoteItems = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
721
+ foreach ($quoteItems as $quoteItem) {
722
+ if ($quoteItem) {
723
+ $currentProduct = $quoteItem->getProduct();
724
+ $isRecurringProduct = (bool)$currentProduct->getIsRecurring();
725
+ if ($isRecurringProduct) {
726
+ $checkQuoteItemResult = $this->checkStartDateDataByProduct($currentProduct,$quoteItem);
727
+ if ($checkQuoteItemResult[$currentProduct->getId()]['success']) {
728
+ $minimumPaymentAmount = $checkQuoteItemResult[$currentProduct->getId()]['minimal_payment_amount'];
729
+ $result['total_min_amount'] += $minimumPaymentAmount;
730
+ }
731
+
732
+ $result['items'] = $checkQuoteItemResult;
733
} else {
734
+ $result['items'][$currentProduct->getId()] = false;
735
}
736
+ }
737
+ }
738
+
739
+ return $result;
740
+ }
741
+
742
+ /**
743
+ * @param $product
744
+ * @param null $quoteItem
745
+ * @return mixed
746
+ */
747
+ public function checkStartDateDataByProduct($product,$quoteItem = false)
748
+ {
749
+ $productAdditionalInfo = unserialize($product->getCustomOption('info_buyRequest')->getValue());
750
+ $dateTimeStamp = strtotime($productAdditionalInfo['recurring_profile_start_datetime']);
751
+
752
+ if ($dateTimeStamp) {
753
+ $userSetTime = new Zend_Date($productAdditionalInfo['recurring_profile_start_datetime']);
754
+ $currentZendDate = new Zend_Date(time());
755
+ if ($userSetTime->getTimestamp() > $currentZendDate->getTimestamp()) {
756
+ $result[$product->getId()]['success'] = true;
757
+ $recurringProfileData = $product->getData('recurring_profile');
758
+ if($quoteItem){
759
+ $initAmount = $quoteItem->getXpRecurringInitialFee();
760
+ }else{
761
+ $initAmount = $recurringProfileData['init_amount'];
762
+ }
763
+
764
+ $defaultMinimumPayment = floatval(Mage::getStoreConfig('xpaymentsconnector/settings/xpay_minimum_payment_recurring_amount'));
765
+ $minimumPaymentAmount = ($initAmount) ? $initAmount : $defaultMinimumPayment;
766
+ $result[$product->getId()]['minimal_payment_amount'] = $minimumPaymentAmount;
767
+
768
} else {
769
+ $result[$product->getId()]['success'] = false;
770
}
771
+ } else {
772
+ $result[$product->getId()]['success'] = false;
773
}
774
return $result;
775
}
776
777
+ public function getRecurringProfileState()
778
+ {
779
$maxPaymentFailureMessage = $this->__('This profile has run out of maximal limit of unsuccessful payment attempts.');
780
781
if (Mage::app()->getStore()->isAdmin()) {
782
Mage::getSingleton('adminhtml/session')->addNotice($maxPaymentFailureMessage);
783
+ } else {
784
Mage::getSingleton('core/session')->addNotice($maxPaymentFailureMessage);
785
}
786
}
787
788
+ public function addRecurringTransactionError($response = array())
789
+ {
790
+ $this->unsetXpaymentPrepareOrder();
791
+ if (!empty($response)) {
792
+ if (!empty($response['error_message'])) {
793
+ $errorMessage = $this->__("%s. The subscription has been canceled.", $response['error_message']);
794
+ Mage::getSingleton('checkout/session')->addError($errorMessage);
795
+ } else {
796
+ $transactionStatusLabel = Mage::getModel('xpaymentsconnector/payment_cc')->getTransactionStatusLabels();
797
+ $errorMessage = $this->__("Transaction status is '%s'. The subscription has been canceled.", $transactionStatusLabel[$response['status']]);
798
+ Mage::getSingleton('checkout/session')->addError($errorMessage);
799
+ }
800
+ } else {
801
+ $errorMessage = $this->__('The subscription has been canceled.');
802
+ Mage::getSingleton('checkout/session')->addError($errorMessage);
803
+ }
804
}
805
806
+ public function setRecurringProductDiscount()
807
+ {
808
$quote = Mage::getSingleton('checkout/session')->getQuote();
809
$items = $quote->getAllVisibleItems();
810
+ foreach ($items as $item) {
811
$discount = $item->getDiscountAmount();
812
$profile = $item->getProduct()->getRecurringProfile();
813
+ $profile['discount_amount'] = $discount;
814
$item->getProduct()->setRecurringProfile($profile)->save();
815
}
816
}
817
818
+ public function getIframeUrl()
819
+ {
820
+
821
+ $xpaymentFormData = Mage::helper('payment')->getMethodInstance('xpayments')->getFormFields();
822
+ $xpaymentFormUrl = Mage::helper('payment')->getMethodInstance('xpayments')->getUrl();
823
824
$this->prepareOrderKey();
825
$token = $this->getIframeToken();
828
return $iframeUrl;
829
}
830
831
+ /**
832
+ * This function fixed magento bug. Magento can't create user
833
+ * during checkout with recurring products.
834
+ * @return mixed
835
+ * @throws Exception
836
+ */
837
+ public function registeredUser()
838
+ {
839
+ $transaction = Mage::getModel('core/resource_transaction');
840
+ $quote = Mage::getSingleton('checkout/session')->getQuote();
841
+ if ($quote->getCustomerId()) {
842
+ $customer = $quote->getCustomer();
843
+ $transaction->addObject($customer);
844
+ }
845
+
846
+ try {
847
+ $transaction->save();
848
+ $customer->save();
849
+ return $customer;
850
+ } catch (Exception $e) {
851
+
852
+ if (!Mage::getSingleton('customer/session')->isLoggedIn()) {
853
+ // reset customer ID's on exception, because customer not saved
854
+ $quote->getCustomer()->setId(null);
855
+ }
856
+
857
+ throw $e;
858
+ }
859
+ return false;
860
+ }
861
+
862
+ /**
863
+ * Save custom calculating initial fee amount
864
+ * @param Mage_Catalog_Model_Product $product
865
+ */
866
+ public function updateRecurringQuoteItem(Mage_Catalog_Model_Product $product)
867
+ {
868
+ $quote = Mage::getModel('checkout/cart')->getQuote();
869
+ if ($product->getIsRecurring()) {
870
+ $quoteItem = $quote->getItemByProduct($product);
871
+ $recurringProfile = $product->getRecurringProfile();
872
+ $initAmount = $recurringProfile['init_amount'];
873
+ if(!is_null($initAmount)){
874
+ $qty = $quoteItem->getQty();
875
+ $totalInitAmount = $qty * $initAmount;
876
+
877
+ if (isset($recurringProfile['init_amount']) &&
878
+ !empty($recurringProfile['init_amount']) &&
879
+ $recurringProfile['init_amount'] > 0
880
+ ) {
881
+
882
+ $quoteItem->setXpRecurringInitialFee($totalInitAmount);
883
+ $initialFeeTax = $this->calculateTaxForProductCustomPrice($product,$totalInitAmount);
884
+ if($initialFeeTax){
885
+ $quoteItem->setInitialfeeTaxAmount($initialFeeTax);
886
+ }
887
+
888
+ $quoteItem->save();
889
+ }
890
+ }
891
+ }
892
+
893
+ }
894
+
895
+ public function updateAllRecurringQuoteItem()
896
+ {
897
+ $quote = Mage::getModel('checkout/cart')->getQuote();
898
+ $quoteItems = $quote->getAllVisibleItems();
899
+ foreach ($quoteItems as $quoteItem) {
900
+ $product = $quoteItem->getProduct();
901
+ $this->updateRecurringQuoteItem($product);
902
+ }
903
+
904
+ }
905
+
906
+ /**
907
+ * Add default settings for submitRecurringProfile function
908
+ * @param Mage_Payment_Model_Recurring_Profile $profile
909
+ */
910
+ public function addXpDefaultRecurringSettings(Mage_Payment_Model_Recurring_Profile $profile){
911
+ $quote = $profile->getQuote();
912
+ $customerId = $quote->getCustomer()->getId();
913
+ if (is_null($customerId)) {
914
+ $customer = $this->registeredUser();
915
+ if($customer){
916
+ $customerId = $customer->getId();
917
+ }
918
+ }
919
+ $profile->setCustomerId($customerId);
920
+ $orderItemInfo = $profile->getOrderItemInfo();
921
+ if($orderItemInfo['xp_recurring_initial_fee']){
922
+ $profile->setInitAmount($orderItemInfo['xp_recurring_initial_fee']);
923
+ }
924
+
925
+ $quoteItemInfo = $profile->getQuoteItemInfo();
926
+ if(!is_null($quoteItemInfo)){
927
+ $currentProduct = $quoteItemInfo->getProduct();
928
+ $this->updateRecurringQuoteItem($currentProduct);
929
+ }
930
+
931
+ }
932
+
933
+ /**
934
+ * Calculate tax for product custom price.
935
+ * @param $product
936
+ * @param $price
937
+ * @return mixed
938
+ */
939
+ public function calculateTaxForProductCustomPrice($product, $price)
940
+ {
941
+ $quote = Mage::getSingleton('checkout/session')->getQuote();
942
+ $store = Mage::app()->getStore($quote->getStoreId());
943
+ $request = Mage::getSingleton('tax/calculation')->getRateRequest(null, null, null, $store);
944
+ $taxClassId = $product->getData('tax_class_id');
945
+ $percent = Mage::getSingleton('tax/calculation')->getRate($request->setProductClassId($taxClassId));
946
+ $tax = $price * ($percent / 100);
947
+
948
+ return $tax;
949
+ }
950
+
951
+ /**
952
+ * orderAmountData
953
+ * - discount_amount
954
+ * - tax_amount
955
+ * - shipping_amount
956
+ * - product_subtotal
957
+ * @param Mage_Payment_Model_Recurring_Profile $recurringProfile
958
+ * @return array
959
+ */
960
+ public function preparePayDeferredOrderAmountData(Mage_Payment_Model_Recurring_Profile $recurringProfile)
961
+ {
962
+ $quoteItemInfo = $recurringProfile->getQuoteItemInfo();
963
+
964
+ if(!is_null($quoteItemInfo)){
965
+ $currentProduct = $quoteItemInfo->getProduct();
966
+ }else{
967
+ $orderItemInfo = $recurringProfile->getOrderItemInfo();
968
+ if(is_string($orderItemInfo)){
969
+ $orderItemInfo = unserialize($orderItemInfo);
970
+ }
971
+ $currentProduct = Mage::getModel('catalog/product')->load($orderItemInfo['product_id']);
972
+ }
973
+
974
+ $orderAmountData = array();
975
+ if(!is_null($recurringProfile->getInitAmount())){
976
+ $orderAmountData['discount_amount'] = 0;
977
+ if(isset($orderItemInfo['initialfee_tax_amount']) && !empty($orderItemInfo['initialfee_tax_amount']) ){
978
+ $orderAmountData['tax_amount'] = $orderItemInfo['initialfee_tax_amount'];
979
+ }else{
980
+ $orderAmountData['tax_amount'] =
981
+ $this->calculateTaxForProductCustomPrice($currentProduct,$recurringProfile->getInitAmount());
982
+ }
983
+ $orderAmountData['shipping_amount'] = 0;
984
+ $orderAmountData['product_subtotal'] = $recurringProfile->getInitAmount();
985
+ $orderAmountData['grand_total'] = $orderAmountData['tax_amount'] + $orderAmountData['product_subtotal'];
986
+ }
987
+
988
+ return $orderAmountData;
989
+ }
990
+
991
}
app/code/community/Cdev/XPaymentsConnector/Model/Observer.php CHANGED
@@ -25,28 +25,22 @@
25
26
class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model_Observer
27
{
28
29
public function preDispatchCheckout($observer)
30
{
31
32
- Mage::getSingleton("checkout/session")->unsetData("user_card_save");
33
34
//unset x-payment form place settings
35
- $unsetParams = array("place_display");
36
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder($unsetParams);
37
38
//set recurring product discount
39
- $isRecurrnigProduct = Mage::helper("xpaymentsconnector")->checkIsRecurringOrder();
40
- if ($isRecurrnigProduct) {
41
- Mage::helper("xpaymentsconnector")->setRecurringProductDiscount();
42
- $useStartDateParam = Mage::helper("xpaymentsconnector")->checkStartDateData();
43
- if ($useStartDateParam["success"]) {
44
- $currency_symbol = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
45
- $noticeMessage = Mage::helper("xpaymentsconnector")
46
- ->__("To create a subscription that uses an X-Payments method, your card will be charged a minimal payment - %s%s",
47
- $useStartDateParam["minimal_payment_amount"], $currency_symbol);
48
- Mage::getSingleton("core/session")->addNotice($noticeMessage);
49
- }
50
}
51
52
}
@@ -56,19 +50,19 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
56
$event = $observer->getEvent();
57
$method = $event->getMethodInstance();
58
$result = $event->getResult();
59
- $saveCardsPaymentCode = Mage::getModel("xpaymentsconnector/payment_savedcards")->getCode();
60
- $prepaidpayments = Mage::getModel("xpaymentsconnector/payment_prepaidpayments")->getCode();
61
62
if (($method->getCode() == $saveCardsPaymentCode) || ($method->getCode() == $prepaidpayments)) {
63
$quote = $event->getQuote();
64
if ($quote) {
65
- $customerId = $quote->getData("customer_id");
66
$isBalanceCard = Cdev_XPaymentsConnector_Model_Usercards::SIMPLE_CARD;
67
if ($method->getCode() == $prepaidpayments) {
68
$isBalanceCard = Cdev_XPaymentsConnector_Model_Usercards::BALANCE_CARD;
69
}
70
if ($customerId) {
71
- $cardsCount = Mage::getModel("xpaymentsconnector/usercards")
72
->getCollection()
73
->addFieldToFilter('user_id', $customerId)
74
->addFieldToFilter('usage_type', $isBalanceCard)
@@ -91,48 +85,61 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
91
92
public function updateOrder($observer)
93
{
94
$event = $observer->getEvent();
95
$order = $event->getOrder();
96
- $refId = Mage::helper("xpaymentsconnector")->getOrderKey();
97
$paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
98
- $xpaymentPaymentCode = Mage::getModel("xpaymentsconnector/payment_cc")->getCode();
99
- $saveCardsPaymentCode = Mage::getModel("xpaymentsconnector/payment_savedcards")->getCode();
100
101
if ($paymentMethod == $xpaymentPaymentCode) {
102
$order->setCanSendNewEmailFlag(false);
103
- $useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
104
105
- $request = Mage::helper("xpaymentsconnector")->getXpaymentResponse();
106
107
108
if ($useIframe) {
109
/*update order table*/
110
$order->setData('xpc_txnid', $request['txnId']);
111
- $order->setData("xp_card_data", serialize($request));
112
$order->save();
113
114
- $result = Mage::getModel("xpaymentsconnector/payment_cc")->updateOrderByXpaymentResponse($order->getId(), $request['txnId']);
115
- if ($result["success"]) {
116
/* save credit card to user profile */
117
- $response = Mage::helper("xpaymentsconnector")->getXpaymentResponse();
118
- Mage::getModel("xpaymentsconnector/payment_cc")->saveUserCard($response);
119
/* end (save payment card) */
120
} else {
121
- Mage::getSingleton("checkout/session")->addError($result["error_message"]);
122
}
123
}
124
125
} elseif ($paymentMethod == $saveCardsPaymentCode) {
126
$order->setCanSendNewEmailFlag(false);
127
- $response = Mage::getModel("xpaymentsconnector/payment_cc")->sendAgainTransactionRequest($order->getId());
128
- if ($response["success"]) {
129
- $result = Mage::getModel("xpaymentsconnector/payment_cc")->updateOrderByXpaymentResponse($order->getId(), $response["response"]['transaction_id']);
130
- if (!$result["success"]) {
131
- Mage::getSingleton("checkout/session")->addError($result["error_message"]);
132
}
133
} else {
134
- Mage::getSingleton("checkout/session")->addError($response["error_message"]);
135
}
136
}
137
138
@@ -144,7 +151,7 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
144
*/
145
public function orderSuccessAction($observer)
146
{
147
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder();
148
}
149
150
@@ -154,35 +161,35 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
154
public function postdispatchAdminhtmlSalesOrderCreateSave($observer)
155
{
156
$quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
157
- $incrementId = $quote->getData("reserved_order_id");
158
$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');
159
$paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
160
$admSession = Mage::getSingleton('adminhtml/session');
161
- $saveCardsPaymentCode = Mage::getModel("xpaymentsconnector/payment_savedcards")->getCode();
162
- $prepaidpayments = Mage::getModel("xpaymentsconnector/payment_prepaidpayments")->getCode();
163
164
if ($paymentMethod == $saveCardsPaymentCode) {
165
$orderId = $order->getId();
166
- $grandTotal = $quote->getData("grand_total");
167
$this->adminhtmlSendSaveCardsPaymentTransaction($orderId,$grandTotal);
168
} elseif ($paymentMethod == $prepaidpayments) {
169
- $xpPrepaidPaymentsCard = $admSession->getData("xp_prepaid_payments");
170
- $currentUserCard = Mage::getModel("xpaymentsconnector/usercards")->load($xpPrepaidPaymentsCard);
171
- $txnid = $currentUserCard->getData("txnId");
172
$lastTransId = $txnid;
173
174
- $order->setData("xpc_txnid",$txnid);
175
$order->getPayment()->setTransactionId($txnid);
176
$api = Mage::getModel('xpaymentsconnector/payment_cc');
177
list($status, $response) = $api->requestPaymentInfo($txnid,false,true);
178
179
if($status){
180
- $currentTransaction = end($response["transactions"]);
181
- $lastTransId = $currentTransaction["txnid"];
182
}
183
184
$order->getPayment()->setLastTransId($lastTransId);
185
- $order->setData("xp_card_data",serialize($currentUserCard->getData()));
186
$order->setState(
187
Mage_Sales_Model_Order::STATE_PROCESSING,
188
(bool)Mage_Sales_Model_Order::STATE_PROCESSING,
@@ -190,8 +197,8 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
190
);
191
$order->save();
192
}
193
- $admSession->unsetData("xp_payment_card");
194
- $admSession->unsetData("xp_prepaid_payments");
195
196
}
197
@@ -234,13 +241,13 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
234
protected function adminhtmlSendSaveCardsPaymentTransaction($orderId,$grandTotal,$checkOrderAmount = true)
235
{
236
$admSession = Mage::getSingleton('adminhtml/session');
237
- $xpCreditCards = $admSession->getData("xp_payment_card");
238
239
- $response = Mage::getModel("xpaymentsconnector/payment_cc")->sendAgainTransactionRequest($orderId, $xpCreditCards, $grandTotal);
240
- if ($response["success"]) {
241
- Mage::getModel("xpaymentsconnector/payment_cc")->updateOrderByXpaymentResponse($orderId, $response["response"]['transaction_id'],$checkOrderAmount);
242
} else {
243
- Mage::getSingleton("adminhtml/session")->addError($response["error_message"]);
244
}
245
246
}
@@ -249,17 +256,17 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
249
{
250
$quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
251
$paymentMethod = $quote->getPayment()->getMethodInstance()->getCode();
252
- $prepaidpayments = Mage::getModel("xpaymentsconnector/payment_prepaidpayments")->getCode();
253
if ($paymentMethod == $prepaidpayments) {
254
$admSession = Mage::getSingleton('adminhtml/session');
255
- $xpPrepaidPaymentsCard = $admSession->getData("xp_prepaid_payments");
256
- $currentUserCard = Mage::getModel("xpaymentsconnector/usercards")->load($xpPrepaidPaymentsCard);
257
- $grandTotal = $quote->getData("grand_total");
258
$cardAmount = $currentUserCard->getAmount();
259
if ($cardAmount < $grandTotal) {
260
- $errorMessage = Mage::helper("xpaymentsconnector")
261
->__("You can't make an order using card (**%s) worth over %s",
262
- $currentUserCard->getData("last_4_cc_num"),
263
Mage::helper('core')->currency($cardAmount));
264
$admSession->addError($errorMessage);
265
/*redirect to last page*/
@@ -280,20 +287,20 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
280
281
public function adminhtmlSavePaymentCard()
282
{
283
- $payment = Mage::app()->getRequest()->getPost("payment");
284
- $saveCardsPaymentCode = Mage::getModel("xpaymentsconnector/payment_savedcards")->getCode();
285
- $prepaidpayments = Mage::getModel("xpaymentsconnector/payment_prepaidpayments")->getCode();
286
287
if ($payment) {
288
- if ($payment["method"] == $saveCardsPaymentCode) {
289
- if ($payment["xp_payment_card"]) {
290
$admSession = Mage::getSingleton('adminhtml/session');
291
- $admSession->setData("xp_payment_card", $payment["xp_payment_card"]);
292
}
293
- } elseif ($payment["method"] == $prepaidpayments) {
294
- if ($payment["xp_prepaid_payments"]) {
295
$admSession = Mage::getSingleton('adminhtml/session');
296
- $admSession->setData("xp_prepaid_payments", $payment["xp_prepaid_payments"]);
297
}
298
}
299
}
@@ -302,8 +309,8 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
302
public function unsetXpaymentSelectedCard()
303
{
304
$admSession = Mage::getSingleton('adminhtml/session');
305
- $admSession->unsetData("xp_payment_card");
306
- $admSession->unsetData("xp_prepaid_payments");
307
}
308
309
public function orderInvoiceSaveBefore($observer)
@@ -311,8 +318,8 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
311
$invoice = $observer->getEvent()->getInvoice();
312
$order = $invoice->getOrder();
313
$paymentCode = $order->getPayment()->getMethodInstance()->getCode();
314
- if (Mage::helper("xpaymentsconnector")->isXpaymentsMethod($paymentCode)) {
315
- $txnid = $order->getData("xpc_txnid");
316
$invoice->setTransactionId($txnid);
317
}
318
}
@@ -322,78 +329,117 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
322
$invoice = $observer->getInvoice();
323
$order = $invoice->getOrder();
324
$paymentCode = $order->getPayment()->getMethodInstance()->getCode();
325
- if (Mage::helper("xpaymentsconnector")->isXpaymentsMethod($paymentCode)) {
326
$data = array(
327
- 'txnId' => $order->getData("xpc_txnid"),
328
'amount' => number_format($invoice->getGrandTotal(), 2, '.', ''),
329
);
330
- Mage::getModel("xpaymentsconnector/payment_cc")->authorizedTransactionRequest('void', $data);
331
}
332
}
333
334
public function createOrdersByCustomerSubscriptions($observer)
335
{
336
- $xpaymentsHelper = Mage::helper("xpaymentsconnector");
337
$recurringProfileList = Mage::getModel('sales/recurring_profile')
338
->getCollection()
339
- ->addFieldToFilter("state", Mage_Sales_Model_Recurring_Profile::STATE_ACTIVE);
340
if ($recurringProfileList->getSize() > 0) {
341
foreach ($recurringProfileList as $profile) {
342
- $startDateTime = strtotime($profile->getStartDatetime());
343
- $lastSuccessTransactionDate = strtotime($profile->getXpSuccessTransactionDate());
344
- $lastActionDate = ($startDateTime > $lastSuccessTransactionDate) ? $startDateTime : $lastSuccessTransactionDate;
345
-
346
- $profilePeriodValue = $xpaymentsHelper->getCurrentBillingPeriodTimeStamp($profile);
347
- $newTransactionDate = $lastActionDate + $profilePeriodValue;
348
-
349
- $currentDateObj = new Zend_Date(time());
350
- $currentDateStamp = $currentDateObj->getTimestamp();
351
-
352
- //var_dump("current = ".date("Y-m-d H:m:s",$currentDateStamp),"start = ".date("Y-m-d H:m:s",$startDateTime),"last = ".date("Y-m-d H:m:s",$lastActionDate),"new = ".date("Y-m-d H:m:s",$newTransactionDate),"profile_id = ".$profile->getProfileId());die;
353
-
354
- $timePassed = $currentDateStamp - $lastActionDate;
355
-
356
- if ($timePassed >= $profilePeriodValue) {
357
- // check by count of success transaction
358
- $currentSuccessCycles = $profile->getXpCountSuccessTransaction();
359
- $periodMaxCycles = $profile->getPeriodMaxCycles();
360
-
361
- if ($periodMaxCycles >= $currentSuccessCycles) {
362
- $orderItemInfo = $profile->getData("order_item_info");
363
- if (!is_array($orderItemInfo)) {
364
- $orderItemInfo = unserialize($orderItemInfo);
365
- }
366
- $grandTotal = $orderItemInfo["nominal_row_total"];
367
- $initialFeeAmount = $orderItemInfo["recurring_initial_fee"];
368
-
369
- // add discount for grand total amount
370
- $useDiscount = current($profile->getChildOrderIds()) > 0;
371
- $discountAmount = ($useDiscount) ? $orderItemInfo["discount_amount"] : 0;
372
-
373
- $orderId = $xpaymentsHelper->createOrder($profile);
374
- $cardData = $xpaymentsHelper->getProfileOrderCardData($profile);
375
-
376
- $response = Mage::getModel("xpaymentsconnector/payment_cc")->sendAgainTransactionRequest($orderId, NULL, $grandTotal - $initialFeeAmount + $discountAmount, $cardData);
377
378
- if ($response["success"]) {
379
- $result = Mage::getModel("xpaymentsconnector/payment_cc")->updateOrderByXpaymentResponse($orderId, $response["response"]['transaction_id']);
380
- $xpaymentsHelper->updateCurrentBillingPeriodTimeStamp($profile, $result["success"], $newTransactionDate);
381
- if (!$result["success"]) {
382
- Mage::log($result["error_message"], null, $xpaymentsHelper::XPAYMENTS_LOG_FILE, true);
383
}
384
385
- } else {
386
- $xpaymentsHelper->updateCurrentBillingPeriodTimeStamp($profile, $response["success"], $newTransactionDate);
387
- Mage::log($response["error_message"], null, $xpaymentsHelper::XPAYMENTS_LOG_FILE, true);
388
}
389
-
390
- } else {
391
- // Subscription is completed
392
- $profile->cancel();
393
-
394
}
395
}
396
-
397
}
398
399
}
@@ -407,15 +453,15 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
407
*/
408
public function addRedirectForXpaymentMethod($observer)
409
{
410
- $profiles = $observer->getData("recurring_profiles");
411
if (!empty($profiles)) {
412
$profile = current($profiles);
413
- $currentPaymentMethodCode = $profile->getData("method_code");
414
- $xpaymentPaymentCode = Mage::getModel("xpaymentsconnector/payment_cc")->getCode();
415
$useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
416
if (($currentPaymentMethodCode == $xpaymentPaymentCode) && !$useIframe) {
417
$redirectUrl = Mage::getUrl('xpaymentsconnector/processing/redirect', array('_secure' => true));
418
- Mage::getSingleton("checkout/session")->setRedirectUrl($redirectUrl);
419
}
420
421
}
@@ -425,25 +471,34 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
425
/**
426
* Set discount for recurring product(for ajax cart item quantity update)
427
* Remove X-Payments token
428
* @param $observer
429
*/
430
public function updateCartItem($observer)
431
{
432
- $unsetParams = array("token");
433
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder($unsetParams);
434
435
//set recurring product discount
436
- Mage::helper("xpaymentsconnector")->setRecurringProductDiscount();
437
}
438
439
/**
440
- * Remove X-Payments token
441
* @param $observer
442
*/
443
public function checkoutCartAdd($observer)
444
{
445
- $unsetParams = array("token");
446
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder($unsetParams);
447
}
448
449
/**
@@ -452,8 +507,8 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
452
*/
453
public function postdispatchCartDelete($observer)
454
{
455
- $unsetParams = array("token", "prepare_order_id");
456
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder($unsetParams);
457
}
458
459
@@ -463,7 +518,7 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
463
*/
464
public function predispatchSaveShippingMethod()
465
{
466
- Mage::helper("xpaymentsconnector")->setIframePlaceDisplaySettings();
467
}
468
469
/**
@@ -472,10 +527,11 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
472
*/
473
public function postdispatchSaveShippingMethod($observer)
474
{
475
- $isPaymentPlaceDisplayFlag = Mage::helper("xpaymentsconnector")->isIframePaymentPlaceDisplay();
476
if (!$isPaymentPlaceDisplayFlag) {
477
- $unsetParams = array("token");
478
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder($unsetParams);
479
}
480
}
481
@@ -483,19 +539,20 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
483
{
484
$quote = Mage::getSingleton('checkout/session')->getQuote();
485
$paymentMethodCode = $quote->getPayment()->getMethodInstance()->getCode();
486
- $xpaymentPaymentCode = Mage::getModel("xpaymentsconnector/payment_cc")->getCode();
487
488
- $isXpayments = Mage::helper("xpaymentsconnector")->isXpaymentsMethod($paymentMethodCode);
489
if ($isXpayments) {
490
- Mage::helper("xpaymentsconnector")->prepareOrderKey();
491
}
492
if ($paymentMethodCode == $xpaymentPaymentCode) {
493
- $saveCard = Mage::app()->getRequest()->getPost("savecard");
494
if ($saveCard) {
495
- Mage::getSingleton("checkout/session")->setData("user_card_save", $saveCard);
496
}
497
} else {
498
- Mage::getSingleton("checkout/session")->unsetData("user_card_save");
499
}
500
}
501
@@ -505,15 +562,15 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
505
*/
506
public function preDispatchCartIndex($observer)
507
{
508
- $unsetXpPrepareOrder = Mage::app()->getRequest()->getParam("unset_xp_prepare_order");
509
if (isset($unsetXpPrepareOrder)) {
510
- $unsetParams = array("token");
511
- Mage::helper("xpaymentsconnector")->unsetXpaymentPrepareOrder($unsetParams);
512
}
513
514
-
515
//set recurring product discount
516
- Mage::helper("xpaymentsconnector")->setRecurringProductDiscount();
517
518
}
519
@@ -528,14 +585,14 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
528
529
if(!empty($xpTransactionData)
530
&& isset($xpTransactionData['xpaction'])
531
- && isset($xpTransactionData["xpc_txnid"])
532
- && isset($xpTransactionData["transaction_amount"])
533
){
534
535
- $xpaymentModel = Mage::getModel("xpaymentsconnector/payment_cc");
536
$data = array(
537
- 'txnId' => $xpTransactionData["xpc_txnid"],
538
- 'amount' => number_format($xpTransactionData["transaction_amount"], 2, '.', ''),
539
);
540
$result = array();
541
switch ($xpTransactionData['xpaction']) {
@@ -551,7 +608,7 @@ class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model
551
}
552
553
if(empty($result['error_message'])){
554
- $message = Mage::helper("xpaymentsconnector")->__("Transaction '%s' to order (%s) was successful!",
555
$xpTransactionData['xpaction'],
556
$xpTransactionData['orderid']);
557
Mage::getSingleton('adminhtml/session')->addSuccess($message);
25
26
class Cdev_XPaymentsConnector_Model_Observer extends Mage_CatalogInventory_Model_Observer
27
{
28
+ protected $_current_customer_id = null;
29
30
public function preDispatchCheckout($observer)
31
{
32
33
+ Mage::getSingleton('checkout/session')->unsetData('user_card_save');
34
35
//unset x-payment form place settings
36
+ $unsetParams = array('place_display');
37
+ $xpHelper = Mage::helper('xpaymentsconnector');
38
+ $xpHelper->unsetXpaymentPrepareOrder($unsetParams);
39
40
//set recurring product discount
41
+ $issetRecurrnigProduct = $xpHelper->checkIssetRecurringOrder();
42
+ if ($issetRecurrnigProduct['isset']) {
43
+ $xpHelper->setRecurringProductDiscount();
44
}
45
46
}
50
$event = $observer->getEvent();
51
$method = $event->getMethodInstance();
52
$result = $event->getResult();
53
+ $saveCardsPaymentCode = Mage::getModel('xpaymentsconnector/payment_savedcards')->getCode();
54
+ $prepaidpayments = Mage::getModel('xpaymentsconnector/payment_prepaidpayments')->getCode();
55
56
if (($method->getCode() == $saveCardsPaymentCode) || ($method->getCode() == $prepaidpayments)) {
57
$quote = $event->getQuote();
58
if ($quote) {
59
+ $customerId = $quote->getData('customer_id');
60
$isBalanceCard = Cdev_XPaymentsConnector_Model_Usercards::SIMPLE_CARD;
61
if ($method->getCode() == $prepaidpayments) {
62
$isBalanceCard = Cdev_XPaymentsConnector_Model_Usercards::BALANCE_CARD;
63
}
64
if ($customerId) {
65
+ $cardsCount = Mage::getModel('xpaymentsconnector/usercards')
66
->getCollection()
67
->addFieldToFilter('user_id', $customerId)
68
->addFieldToFilter('usage_type', $isBalanceCard)
85
86
public function updateOrder($observer)
87
{
88
+ $xpHelper = Mage::helper('xpaymentsconnector');
89
$event = $observer->getEvent();
90
$order = $event->getOrder();
91
+
92
+ $checkoutSession = Mage::getSingleton('checkout/session');
93
$paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
94
+ $paymentCcModel = Mage::getModel('xpaymentsconnector/payment_cc');
95
+ $xpaymentPaymentCode = $paymentCcModel->getCode();
96
+ $saveCardsPaymentCode = Mage::getModel('xpaymentsconnector/payment_savedcards')->getCode();
97
+ $useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
98
+ $quote = $observer->getQuote();
99
100
if ($paymentMethod == $xpaymentPaymentCode) {
101
$order->setCanSendNewEmailFlag(false);
102
103
+ $request = $xpHelper->getXpaymentResponse();
104
105
106
if ($useIframe) {
107
/*update order table*/
108
$order->setData('xpc_txnid', $request['txnId']);
109
+ $order->setData('xp_card_data', serialize($request));
110
$order->save();
111
112
+ $result = $paymentCcModel->updateOrderByXpaymentResponse($order->getId(), $request['txnId']);
113
+ if ($result['success']) {
114
/* save credit card to user profile */
115
+ $response = $xpHelper->getXpaymentResponse();
116
+ $paymentCcModel->saveUserCard($response);
117
/* end (save payment card) */
118
} else {
119
+ $checkoutSession->addError($result['error_message']);
120
}
121
+
122
}
123
124
} elseif ($paymentMethod == $saveCardsPaymentCode) {
125
+
126
$order->setCanSendNewEmailFlag(false);
127
+ $paymentCardNumber = NULL;
128
+ $grandTotal = NULL;
129
+ $cardData = NULL;
130
+ $paymentCardNumber = $quote->getPayment()->getData('xp_payment_card');
131
+ $cardData = Mage::getModel('xpaymentsconnector/usercards')->load($paymentCardNumber);
132
+
133
+ $response = $paymentCcModel->sendAgainTransactionRequest($order->getId(),$paymentCardNumber,$grandTotal,$cardData);
134
+ if ($response['success']) {
135
+ $result = $paymentCcModel->updateOrderByXpaymentResponse($order->getId(), $response['response']['transaction_id']);
136
+ if (!$result['success']) {
137
+ $checkoutSession->addError($result['error_message']);
138
}
139
} else {
140
+ $checkoutSession->addError($response['error_message']);
141
}
142
+
143
}
144
145
151
*/
152
public function orderSuccessAction($observer)
153
{
154
+ Mage::helper('xpaymentsconnector')->unsetXpaymentPrepareOrder();
155
}
156
157
161
public function postdispatchAdminhtmlSalesOrderCreateSave($observer)
162
{
163
$quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
164
+ $incrementId = $quote->getData('reserved_order_id');
165
$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');
166
$paymentMethod = $order->getPayment()->getMethodInstance()->getCode();
167
$admSession = Mage::getSingleton('adminhtml/session');
168
+ $saveCardsPaymentCode = Mage::getModel('xpaymentsconnector/payment_savedcards')->getCode();
169
+ $prepaidpayments = Mage::getModel('xpaymentsconnector/payment_prepaidpayments')->getCode();
170
171
if ($paymentMethod == $saveCardsPaymentCode) {
172
$orderId = $order->getId();
173
+ $grandTotal = $quote->getData('grand_total');
174
$this->adminhtmlSendSaveCardsPaymentTransaction($orderId,$grandTotal);
175
} elseif ($paymentMethod == $prepaidpayments) {
176
+ $xpPrepaidPaymentsCard = $admSession->getData('xp_prepaid_payments');
177
+ $currentUserCard = Mage::getModel('xpaymentsconnector/usercards')->load($xpPrepaidPaymentsCard);
178
+ $txnid = $currentUserCard->getData('txnId');
179
$lastTransId = $txnid;
180
181
+ $order->setData('xpc_txnid',$txnid);
182
$order->getPayment()->setTransactionId($txnid);
183
$api = Mage::getModel('xpaymentsconnector/payment_cc');
184
list($status, $response) = $api->requestPaymentInfo($txnid,false,true);
185
186
if($status){
187
+ $currentTransaction = end($response['transactions']);
188
+ $lastTransId = $currentTransaction['txnid'];
189
}
190
191
$order->getPayment()->setLastTransId($lastTransId);
192
+ $order->setData('xp_card_data',serialize($currentUserCard->getData()));
193
$order->setState(
194
Mage_Sales_Model_Order::STATE_PROCESSING,
195
(bool)Mage_Sales_Model_Order::STATE_PROCESSING,
197
);
198
$order->save();
199
}
200
+ $admSession->unsetData('xp_payment_card');
201
+ $admSession->unsetData('xp_prepaid_payments');
202
203
}
204
241
protected function adminhtmlSendSaveCardsPaymentTransaction($orderId,$grandTotal,$checkOrderAmount = true)
242
{
243
$admSession = Mage::getSingleton('adminhtml/session');
244
+ $xpCreditCards = $admSession->getData('xp_payment_card');
245
246
+ $response = Mage::getModel('xpaymentsconnector/payment_cc')->sendAgainTransactionRequest($orderId, $xpCreditCards, $grandTotal);
247
+ if ($response['success']) {
248
+ Mage::getModel('xpaymentsconnector/payment_cc')->updateOrderByXpaymentResponse($orderId, $response['response']['transaction_id'],$checkOrderAmount);
249
} else {
250
+ Mage::getSingleton('adminhtml/session')->addError($response['error_message']);
251
}
252
253
}
256
{
257
$quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
258
$paymentMethod = $quote->getPayment()->getMethodInstance()->getCode();
259
+ $prepaidpayments = Mage::getModel('xpaymentsconnector/payment_prepaidpayments')->getCode();
260
if ($paymentMethod == $prepaidpayments) {
261
$admSession = Mage::getSingleton('adminhtml/session');
262
+ $xpPrepaidPaymentsCard = $admSession->getData('xp_prepaid_payments');
263
+ $currentUserCard = Mage::getModel('xpaymentsconnector/usercards')->load($xpPrepaidPaymentsCard);
264
+ $grandTotal = $quote->getData('grand_total');
265
$cardAmount = $currentUserCard->getAmount();
266
if ($cardAmount < $grandTotal) {
267
+ $errorMessage = Mage::helper('xpaymentsconnector')
268
->__("You can't make an order using card (**%s) worth over %s",
269
+ $currentUserCard->getData('last_4_cc_num'),
270
Mage::helper('core')->currency($cardAmount));
271
$admSession->addError($errorMessage);
272
/*redirect to last page*/
287
288
public function adminhtmlSavePaymentCard()
289
{
290
+ $payment = Mage::app()->getRequest()->getPost('payment');
291
+ $saveCardsPaymentCode = Mage::getModel('xpaymentsconnector/payment_savedcards')->getCode();
292
+ $prepaidpayments = Mage::getModel('xpaymentsconnector/payment_prepaidpayments')->getCode();
293
294
if ($payment) {
295
+ if ($payment['method'] == $saveCardsPaymentCode) {
296
+ if ($payment['xp_payment_card']) {
297
$admSession = Mage::getSingleton('adminhtml/session');
298
+ $admSession->setData('xp_payment_card', $payment['xp_payment_card']);
299
}
300
+ } elseif ($payment['method'] == $prepaidpayments) {
301
+ if ($payment['xp_prepaid_payments']) {
302
$admSession = Mage::getSingleton('adminhtml/session');
303
+ $admSession->setData('xp_prepaid_payments', $payment['xp_prepaid_payments']);
304
}
305
}
306
}
309
public function unsetXpaymentSelectedCard()
310
{
311
$admSession = Mage::getSingleton('adminhtml/session');
312
+ $admSession->unsetData('xp_payment_card');
313
+ $admSession->unsetData('xp_prepaid_payments');
314
}
315
316
public function orderInvoiceSaveBefore($observer)
318
$invoice = $observer->getEvent()->getInvoice();
319
$order = $invoice->getOrder();
320
$paymentCode = $order->getPayment()->getMethodInstance()->getCode();
321
+ if (Mage::helper('xpaymentsconnector')->isXpaymentsMethod($paymentCode)) {
322
+ $txnid = $order->getData('xpc_txnid');
323
$invoice->setTransactionId($txnid);
324
}
325
}
329
$invoice = $observer->getInvoice();
330
$order = $invoice->getOrder();
331
$paymentCode = $order->getPayment()->getMethodInstance()->getCode();
332
+ if (Mage::helper('xpaymentsconnector')->isXpaymentsMethod($paymentCode)) {
333
$data = array(
334
+ 'txnId' => $order->getData('xpc_txnid'),
335
'amount' => number_format($invoice->getGrandTotal(), 2, '.', ''),
336
);
337
+ Mage::getModel('xpaymentsconnector/payment_cc')->authorizedTransactionRequest('void', $data);
338
}
339
}
340
341
public function createOrdersByCustomerSubscriptions($observer)
342
{
343
+ $xpaymentsHelper = Mage::helper('xpaymentsconnector');
344
$recurringProfileList = Mage::getModel('sales/recurring_profile')
345
->getCollection()
346
+ ->addFieldToFilter('state', array('neq' => Mage_Sales_Model_Recurring_Profile::STATE_CANCELED));
347
+
348
+ $userTransactionHasBeenSend = false;
349
if ($recurringProfileList->getSize() > 0) {
350
foreach ($recurringProfileList as $profile) {
351
+ $customerId = $profile->getCustomerId();
352
+ if($this->_current_customer_id != $customerId){
353
+ $this->_current_customer_id = $customerId;
354
+ $userTransactionHasBeenSend = false;
355
+ }
356
357
+ if(!$userTransactionHasBeenSend){
358
+ if ($profile->getState() == Mage_Sales_Model_Recurring_Profile::STATE_UNKNOWN) {
359
+ $cardData = $xpaymentsHelper->getProfileOrderCardData($profile);
360
+ $orderAmountData = $xpaymentsHelper->preparePayDeferredOrderAmountData($profile);
361
+ if(!empty($orderAmountData)){
362
+ $xpaymentsHelper->resendPayDeferredRecurringTransaction($profile, $orderAmountData, $cardData);
363
+ $userTransactionHasBeenSend = true;
364
+ }else{
365
+ $profile->activate();
366
}
367
+ continue;
368
+ } elseif ($profile->getState() == Mage_Sales_Model_Recurring_Profile::STATE_ACTIVE) {
369
+ $startDateTime = strtotime($profile->getStartDatetime());
370
+ $lastSuccessTransactionDate = strtotime($profile->getXpSuccessTransactionDate());
371
+ $lastActionDate = ($startDateTime > $lastSuccessTransactionDate) ? $startDateTime : $lastSuccessTransactionDate;
372
+
373
+ $profilePeriodValue = $xpaymentsHelper->getCurrentBillingPeriodTimeStamp($profile);
374
+ $newTransactionDate = $lastActionDate + $profilePeriodValue;
375
+
376
+ $currentDateObj = new Zend_Date(time());
377
+ $currentDateStamp = $currentDateObj->getTimestamp();
378
+ /*
379
+ var_dump('period_stamp ='.$profilePeriodValue / 3600 ."(h)",
380
+ "current = ".date("Y-m-d H:m:s",$currentDateStamp),
381
+ "start = ".date("Y-m-d H:m:s",$startDateTime),
382
+ "last = ".date("Y-m-d H:m:s",$lastActionDate),
383
+ "new = ".date("Y-m-d H:m:s",$newTransactionDate),
384
+ "profile_id = ".$profile->getProfileId());die;
385
+ */
386
+
387
+ $timePassed = $currentDateStamp - $lastActionDate;
388
+
389
+ if ($timePassed >= $profilePeriodValue) {
390
+ // check by count of success transaction
391
+ $currentSuccessCycles = $profile->getXpCountSuccessTransaction();
392
+ $periodMaxCycles = $profile->getPeriodMaxCycles();
393
+
394
+ if (($periodMaxCycles > $currentSuccessCycles) || is_null($periodMaxCycles)) {
395
+ $orderItemInfo = $profile->getData('order_item_info');
396
+ if (!is_array($orderItemInfo)) {
397
+ $orderItemInfo = unserialize($orderItemInfo);
398
+ }
399
+
400
+ $initialFeeAmount = $orderItemInfo['recurring_initial_fee'];
401
+
402
+
403
+
404
+ $isFirstRecurringOrder = false;
405
+
406
+ //calculate grand total
407
+ $billingAmount = $profile->getBillingAmount();
408
+ $shippingAmount = $profile->getShippingAmount();
409
+ $taxAmount = $profile->getTaxAmount();
410
+
411
+ $initialFeeTax = ($profile->getInitiaFeePaid()) ? 0 : 123;
412
+ // add discount for transaction amount
413
+ $useDiscount = ($profile->getXpCountSuccessTransaction() > 0) ? false : true;
414
+ $discountAmount = ($useDiscount) ? $orderItemInfo['discount_amount'] : 0;
415
+
416
+ $transactionAmount = $billingAmount + $shippingAmount + $taxAmount - $discountAmount ;
417
+
418
+ $orderId = $xpaymentsHelper->createOrder($profile,$isFirstRecurringOrder);
419
+ $cardData = $xpaymentsHelper->getProfileOrderCardData($profile);
420
+
421
+ $response = Mage::getModel('xpaymentsconnector/payment_cc')->sendAgainTransactionRequest($orderId, NULL, $transactionAmount , $cardData);
422
+ $userTransactionHasBeenSend = true;
423
+ if ($response['success']) {
424
+ $result = Mage::getModel('xpaymentsconnector/payment_cc')->updateOrderByXpaymentResponse($orderId, $response['response']['transaction_id']);
425
+ $xpaymentsHelper->updateCurrentBillingPeriodTimeStamp($profile, $result['success'], $newTransactionDate);
426
+ if (!$result['success']) {
427
+ Mage::log($result['error_message'], null, $xpaymentsHelper::XPAYMENTS_LOG_FILE, true);
428
+ }
429
+
430
+ } else {
431
+ $xpaymentsHelper->updateCurrentBillingPeriodTimeStamp($profile, $response['success'], $newTransactionDate);
432
+ Mage::log($response['error_message'], null, $xpaymentsHelper::XPAYMENTS_LOG_FILE, true);
433
+ }
434
+
435
+ } else {
436
+ // Subscription is completed
437
+ $profile->cancel();
438
439
+ }
440
}
441
}
442
}
443
}
444
445
}
453
*/
454
public function addRedirectForXpaymentMethod($observer)
455
{
456
+ $profiles = $observer->getData('recurring_profiles');
457
if (!empty($profiles)) {
458
$profile = current($profiles);
459
+ $currentPaymentMethodCode = $profile->getData('method_code');
460
+ $xpaymentPaymentCode = Mage::getModel('xpaymentsconnector/payment_cc')->getCode();
461
$useIframe = Mage::getStoreConfig('payment/xpayments/use_iframe');
462
if (($currentPaymentMethodCode == $xpaymentPaymentCode) && !$useIframe) {
463
$redirectUrl = Mage::getUrl('xpaymentsconnector/processing/redirect', array('_secure' => true));
464
+ Mage::getSingleton('checkout/session')->setRedirectUrl($redirectUrl);
465
}
466
467
}
471
/**
472
* Set discount for recurring product(for ajax cart item quantity update)
473
* Remove X-Payments token
474
+ * Update initial Fee for recurring product;
475
* @param $observer
476
*/
477
public function updateCartItem($observer)
478
{
479
+ $unsetParams = array('token');
480
+ $xpHelper = Mage::helper('xpaymentsconnector');
481
+ $xpHelper->unsetXpaymentPrepareOrder($unsetParams);
482
483
//set recurring product discount
484
+ Mage::helper('xpaymentsconnector')->setRecurringProductDiscount();
485
+ $xpHelper->updateAllRecurringQuoteItem();
486
}
487
488
/**
489
+ * Remove X-Payments token;
490
+ * Update initial Fee for recurring product;
491
* @param $observer
492
*/
493
public function checkoutCartAdd($observer)
494
{
495
+ $xpHelper = Mage::helper('xpaymentsconnector');
496
+ $unsetParams = array('token');
497
+ $xpHelper->unsetXpaymentPrepareOrder($unsetParams);
498
+
499
+ $product = $observer->getProduct();
500
+ $xpHelper->updateRecurringQuoteItem($product);
501
+
502
}
503
504
/**
507
*/
508
public function postdispatchCartDelete($observer)
509
{
510
+ $unsetParams = array('token', 'prepare_order_id');
511
+ Mage::helper('xpaymentsconnector')->unsetXpaymentPrepareOrder($unsetParams);
512
}
513
514
518
*/
519
public function predispatchSaveShippingMethod()
520
{
521
+ Mage::helper('xpaymentsconnector')->setIframePlaceDisplaySettings();
522
}
523
524
/**
527
*/
528
public function postdispatchSaveShippingMethod($observer)
529
{
530
+ $xpHelper = Mage::helper('xpaymentsconnector');
531
+ $isPaymentPlaceDisplayFlag = $xpHelper->isIframePaymentPlaceDisplay();
532
if (!$isPaymentPlaceDisplayFlag) {
533
+ $unsetParams = array('token');
534
+ $xpHelper->unsetXpaymentPrepareOrder($unsetParams);
535
}
536
}
537
539
{
540
$quote = Mage::getSingleton('checkout/session')->getQuote();
541
$paymentMethodCode = $quote->getPayment()->getMethodInstance()->getCode();
542
+ $xpaymentPaymentCode = Mage::getModel('xpaymentsconnector/payment_cc')->getCode();
543
+ $xpHelper = Mage::helper('xpaymentsconnector');
544
545
+ $isXpayments = $xpHelper->isXpaymentsMethod($paymentMethodCode);
546
if ($isXpayments) {
547
+ $xpHelper->prepareOrderKey();
548
}
549
if ($paymentMethodCode == $xpaymentPaymentCode) {
550
+ $saveCard = Mage::app()->getRequest()->getPost('savecard');
551
if ($saveCard) {
552
+ Mage::getSingleton('checkout/session')->setData('user_card_save', $saveCard);
553
}
554
} else {
555
+ Mage::getSingleton('checkout/session')->unsetData('user_card_save');
556
}
557
}
558
562
*/
563
public function preDispatchCartIndex($observer)
564
{
565
+ $unsetXpPrepareOrder = Mage::app()->getRequest()->getParam('unset_xp_prepare_order');
566
+ $xpHelper = Mage::helper('xpaymentsconnector');
567
if (isset($unsetXpPrepareOrder)) {
568
+ $unsetParams = array('token');
569
+ $xpHelper->unsetXpaymentPrepareOrder($unsetParams);
570
}
571
572
//set recurring product discount
573
+ $xpHelper->setRecurringProductDiscount();
574
575
}
576
585
586
if(!empty($xpTransactionData)
587
&& isset($xpTransactionData['xpaction'])
588
+ && isset($xpTransactionData['xpc_txnid'])
589
+ && isset($xpTransactionData['transaction_amount'])
590
){
591
592
+ $xpaymentModel = Mage::getModel('xpaymentsconnector/payment_cc');
593
$data = array(
594
+ 'txnId' => $xpTransactionData['xpc_txnid'],
595
+ 'amount' => number_format($xpTransactionData['transaction_amount'], 2, '.', ''),
596
);
597
$result = array();
598
switch ($xpTransactionData['xpaction']) {
608
}
609
610
if(empty($result['error_message'])){
611
+ $message = Mage::helper('xpaymentsconnector')->__("Transaction '%s' to order (%s) was successful!",
612
$xpTransactionData['xpaction'],
613
$xpTransactionData['orderid']);
614
Mage::getSingleton('adminhtml/session')->addSuccess($message);
app/code/community/Cdev/XPaymentsConnector/Model/Payment/Cc.php CHANGED
@@ -90,7 +90,7 @@ class Cdev_XPaymentsConnector_Model_Payment_Cc extends Mage_Payment_Model_Method
90
// Root-level tag for all XML messages
91
const TAG_ROOT = 'data';
92
93
- // Value of the "type" attribute for list items in XML
94
const TYPE_CELL = 'cell';
95
96
// Payment statuses
@@ -177,6 +177,10 @@ class Cdev_XPaymentsConnector_Model_Payment_Cc extends Mage_Payment_Model_Method
177
*/
178
protected $_order = null;
179
180
/**
181
* Get order
182
*
@@ -251,12 +255,12 @@ class Cdev_XPaymentsConnector_Model_Payment_Cc extends Mage_Payment_Model_Method
251
public function canCapture()
252
{
253
$order = $this->getOrder();
254
- list($status, $response) = $this->requestPaymentInfo($order->getData("xpc_txnid"));
255
if($status){
256
- if($response["status"] == self::CHARGED_STATUS){
257
return false;
258
}
259
- elseif($response["status"] == self::AUTH_ACTION){
260
return true;
261
}
262
}else{
@@ -501,7 +505,7 @@ class Cdev_XPaymentsConnector_Model_Payment_Cc extends Mage_Payment_Model_Method
501
'confId' => intval($this->getPaymentConfiguration()->getData('confid')),
502
'refId' => $refId,
503
'cart' => $cart,
504
- 'returnUrl' => Mage::getUrl('xpaymentsconnector/processing/return', array('order_id' => $refId,'_secure' => true)),
505
'callbackUrl' => Mage::getUrl('xpaymentsconnector/processing/callback', array('order_id' => $refId,'_secure' => true)),
506
'template' => 'default',
507
'saveCard' => 'Y',
@@ -522,7 +526,11 @@ class Cdev_XPaymentsConnector_Model_Payment_Cc extends Mage_Payment_Model_Method
522
Mage::getSingleton('checkout/session')->setData('xpayments_token', $response['token']);
523
}
524
525
- return $status;
526
}