KANCART_MobileAPI - Version 2.0.4

Version Notes

Fix: Fail to fetch currencies if there is only 1 currency is configured.
Add: Add support of offline payment methods(beta)

Download this release

Release Info

Developer Kancart.com
Extension KANCART_MobileAPI
Version 2.0.4
Comparing to
See all releases


Code changes from version 2.0.3 to 2.0.4

app/code/community/Kancart/MobileApi/Model/Abstract.php CHANGED
@@ -33,11 +33,10 @@ abstract class Kancart_MobileApi_Model_Abstract extends Mage_Core_Model_Abstract
33
  return Mage::app()->getTranslator()->translate($args);
34
  }
35
 
36
- protected function isLoggedIn() {
37
- return Mage::getSingleton('customer/session')->isLoggedIn();
38
- }
39
-
40
  public function toAddressData($address) {
 
 
 
41
  if (!$address->getLastname() && strpos($address->getFirstname(), ' ') > 0) {
42
  $name = explode(' ', $address->getFirstname());
43
  $address->setFirstname($name[0]);
@@ -75,36 +74,16 @@ abstract class Kancart_MobileApi_Model_Abstract extends Mage_Core_Model_Abstract
75
  return Mage::app()->getRequest();
76
  }
77
 
78
- public function getCurrencyPrice($price, $format = false, $includeContainer = false) {
79
- return Mage::helper('core')->currency($price, $format, $includeContainer);
80
  }
81
 
82
- /**
83
- * Fix for the plugin,some fields of billng address may be null,
84
- * so we keep them same with the shipping address
85
- */
86
- public function makeBillingSameAsShipping() {
87
- $shippingAddress = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress();
88
- empty($shippingAddress) && $shippingAddress = Mage::getSingleton('customer/session')->getCustomer()->getPrimaryBillingAddress();
89
- //Only the followng fields need to be set
90
- if ($shippingAddress && is_object($shippingAddress)) {
91
- $billingData = array();
92
- $billingData['firstname'] = $shippingAddress->getFirstname();
93
- $billingData['lastname'] = $shippingAddress->getLastname();
94
- $billingData['city'] = $shippingAddress->getCity();
95
- $billingData['street'] = $shippingAddress->getStreetFull();
96
- $billingData['region'] = $shippingAddress->getRegion();
97
- $billingData['region_id'] = $shippingAddress->getRegionId();
98
- $billingData['postcode'] = $shippingAddress->getPostcode();
99
- $billingData['country_id'] = $shippingAddress->getCountryId();
100
- $billingData['telephone'] = $shippingAddress->getTelephone();
101
- $billingData['fax'] = $shippingAddress->getFax();
102
 
103
- $this->getQuote()
104
- ->getBillingAddress()
105
- ->addData($billingData)
106
- ->save();
107
- }
108
  }
109
 
110
  }
33
  return Mage::app()->getTranslator()->translate($args);
34
  }
35
 
 
 
 
 
36
  public function toAddressData($address) {
37
+ if (!$address) {
38
+ return array();
39
+ }
40
  if (!$address->getLastname() && strpos($address->getFirstname(), ' ') > 0) {
41
  $name = explode(' ', $address->getFirstname());
42
  $address->setFirstname($name[0]);
74
  return Mage::app()->getRequest();
75
  }
76
 
77
+ public function getOnepage() {
78
+ return Mage::getSingleton('checkout/type_onepage');
79
  }
80
 
81
+ public function isLoggedIn() {
82
+ return Mage::getSingleton('customer/session')->isLoggedIn();
83
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ public function getCurrencyPrice($price, $format = false, $includeContainer = false) {
86
+ return Mage::helper('core')->currency($price, $format, $includeContainer);
 
 
 
87
  }
88
 
89
  }
app/code/community/Kancart/MobileApi/Model/Cart.php CHANGED
@@ -46,7 +46,7 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
46
  $cartInfo['messages'] = sizeof($this->errors) ? $this->errors : $this->getMessage();
47
  $cartInfo['cart_items_count'] = Mage::helper('checkout/cart')->getSummaryCount();
48
  $cartInfo['price_infos'] = $this->getPriceInfos($quote);
49
- $this->addPaymentInfo($cartInfo);
50
 
51
  return array(true, '0x0000', $cartInfo);
52
  }
@@ -177,9 +177,11 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
177
  return $PriceInfos;
178
  }
179
 
180
- private function addPaymentInfo(&$cartInfo) {
181
  if ($this->isPaymentMethodAvaiable('paypal_express')) {
182
- $cartInfo['payment_methods'][] = 'paypalec';
 
 
183
  }
184
  }
185
 
@@ -470,9 +472,11 @@ class Kancart_MobileApi_Model_Cart extends Kancart_MobileApi_Model_Abstract {
470
  $this->errors[] = $warning;
471
  }
472
 
473
- foreach ($cart->getQuote()->getErrors() as $message) {
474
- if ($message) {
475
- $this->errors[] = $message->getText();
 
 
476
  }
477
  }
478
 
46
  $cartInfo['messages'] = sizeof($this->errors) ? $this->errors : $this->getMessage();
47
  $cartInfo['cart_items_count'] = Mage::helper('checkout/cart')->getSummaryCount();
48
  $cartInfo['price_infos'] = $this->getPriceInfos($quote);
49
+ $cartInfo['payment_methods'] = $this->getPaymentInfo();
50
 
51
  return array(true, '0x0000', $cartInfo);
52
  }
177
  return $PriceInfos;
178
  }
179
 
180
+ private function getPaymentInfo() {
181
  if ($this->isPaymentMethodAvaiable('paypal_express')) {
182
+ return array('paypalec');
183
+ } else {
184
+ return array();
185
  }
186
  }
187
 
472
  $this->errors[] = $warning;
473
  }
474
 
475
+ if (($messages = $cart->getQuote()->getErrors())) {
476
+ foreach ($messages as $message) {
477
+ if ($message) {
478
+ $this->errors[] = $message->getText();
479
+ }
480
  }
481
  }
482
 
app/code/community/Kancart/MobileApi/Model/Checkout.php CHANGED
@@ -27,11 +27,6 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
27
  protected $_customer;
28
  protected $_checkout;
29
  protected $_quote;
30
- protected $_address;
31
- protected $_countryCollection;
32
- protected $_regionCollection;
33
- protected $_addressesCollection;
34
- protected $_order; /* @var $_order Mage_Sales_Model_Order */
35
 
36
  public function kancart_shoppingcart_addresses_update() {
37
  $addressData = $this->getRequest()->getParams();
@@ -45,49 +40,54 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
45
  list($result, $code, $address_id) = Kancart::getModel('User')->kancart_user_address_update();
46
  if ($result === false) {
47
  $address['street'] = array($address['address1'], $address['address2']);
48
- $address['region'] = $address['state'];
49
- $address['region_id'] = null;
50
  $address['region_id'] = $address['zone_id'];
51
- $address['region'] = $address['zone_name'];
52
  $address_id = null;
53
  }
54
  }
55
 
56
  $address['same_as_billing'] = 1;
57
- $this->getOnepage()->saveShipping($address, $address_id);
 
 
 
 
58
 
59
  return $this->shoppingCartCheckoutDetail();
60
  }
61
 
62
  public function kancart_shoppingcart_checkout_detail() {
63
- if (!$this->isLoggedIn()) {
 
 
64
  return array(false, '0x0002', 'You need login first.');
65
  }
 
66
  return $this->shoppingCartCheckoutDetail();
67
  }
68
 
69
  public function shoppingCartCheckoutDetail() {
70
  $this->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
71
  $checkoutDetailArr = array();
72
- $checkoutDetailArr['shipping_address'] = $this->getShippingAddress();
73
- $checkoutDetailArr['billing_address'] = $this->getBillingAddress();
74
- $checkoutDetailArr['review_orders'] = array($this->getOrderReview());
75
- $checkoutDetailArr['price_infos'] = $this->getPriceInfos();
76
  $checkoutDetailArr['is_virtual'] = $is_virtual = $this->getQuote()->isVirtual();
77
  $checkoutDetailArr['need_shipping_address'] = defined('NEED_SHIPPING_ADDRESS') ? NEED_SHIPPING_ADDRESS : $is_virtual;
78
- $checkoutDetailArr['need_billing_address'] = defined('NEED_BILLING_ADDRESS') ? NEED_BILLING_ADDRESS : false;
 
 
 
 
79
  $checkoutDetailArr['payment_methods'] = $this->getPaymentMethods();
80
 
81
- if ($_SESSION['checkout_messages']) {
82
  $checkoutDetailArr['messages'] = $_SESSION['checkout_messages'];
83
  unset($_SESSION['checkout_messages']);
84
  }
85
  return array(true, '0x0000', $checkoutDetailArr);
86
  }
87
 
88
- private function getBillingAddress() {
89
  $billing_address = $this->getQuote()->getBillingAddress();
90
- if (!$billing_address->getData('country_id')) {
91
  $billing_address = $this->getCustomer()->getPrimaryBillingAddress();
92
  if (empty($billing_address)) {
93
  $billing_address = current($this->getCustomer()->getAddresses());
@@ -105,9 +105,9 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
105
  return $this->toAddressData($billing_address);
106
  }
107
 
108
- private function getShippingAddress() {
109
  $shipping_address = $this->getQuote()->getShippingAddress();
110
- if (!$shipping_address->getData('country_id')) {
111
  $shipping_address = $this->getCustomer()->getPrimaryShippingAddress();
112
  if (empty($shipping_address)) {
113
  $shipping_address = current($this->getCustomer()->getAddresses());
@@ -135,7 +135,7 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
135
  $methods = $paymentHelper->getStoreMethods($store, $quote);
136
  $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
137
  foreach ($methods as $key => $method) {
138
- if ($this->_canUseMethod($method)
139
  && ($total != 0
140
  || $method->getCode() == 'free'
141
  || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
@@ -146,21 +146,21 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
146
  $code = 'paypalwpp';
147
  }
148
  if ($code == 'paypal' || $code == 'paypalwpp') {
149
- $payment[] =
150
- array('pm_id' => $code,
151
- 'pm_title' => $method->getTitle(),
152
- 'pm_code' => $method->getCode(),
153
- 'description' => $method->getDescription(),
154
- 'img_url' => '');
155
  }
156
  }
157
  unset($methods[$key]);
158
  }
 
159
 
160
- return $payment;
161
  }
162
 
163
- protected function _canUseMethod($method) {
164
  if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
165
  return false;
166
  }
@@ -223,9 +223,11 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
223
 
224
  public function getShippingMethods() {
225
  try {
 
226
  $this->getOnepage()->getQuote()->getShippingAddress()->setCollectShippingRates(true);
227
  $this->getOnepage()->getQuote()->collectTotals()->save();
228
- $_shippingRateGroups = $this->getShippingRates();
 
229
  if (!$this->getQuote()->getShippingAddress()->getShippingMethod())
230
  $setDefaultSM = true;
231
  if ($_shippingRateGroups) {
@@ -243,7 +245,7 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
243
  if ($_rate->getErrorMessage()) {
244
  $rateArr['error_message'] = strip_tags($_rate->getErrorMessage());
245
  } else {
246
- $price = Mage::helper('tax')->getShippingPrice($_rate->getPrice(), Mage::helper('tax')->displayShippingPriceIncludingTax(), $this->getAddress());
247
  $shippingMethodArr['price'] = $store->convertPrice($price, false, false);
248
  }
249
  $shippingMethodArr['currency'] = Mage::getModel('core/store')->load(Mage::app()->getStore()->getId())->getCurrentCurrencyCode();
@@ -264,14 +266,11 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
264
  }
265
  }
266
 
267
- protected function _getCart() {
268
- return Mage::getSingleton('checkout/cart');
269
- }
270
-
271
  public function kancart_shoppingcart_coupons_update() {
272
  try {
273
  $params = $this->getRequest()->getParams();
274
- if (!$this->_getCart()->getQuote()->getItemsCount()) {
 
275
  throw new Exception('Cart is empty.');
276
  }
277
  $couponCode = $params['coupon_id'];
@@ -290,23 +289,19 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
290
  return $this->shoppingCartCheckoutDetail();
291
  }
292
 
293
- protected function _getQuote() {
294
- return $this->getCheckout()->getQuote();
295
- }
296
-
297
  public function updateCoupon($couponCode) {
298
- $oldCouponCode = $this->_getQuote()->getCouponCode();
299
  if (!strlen($couponCode) && !strlen($oldCouponCode)) {
300
  throw new Exception('No coupon code in current quote.');
301
  }
302
  $message = '';
303
  try {
304
- $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
305
- $this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
306
  ->collectTotals()
307
  ->save();
308
  if (strlen($couponCode)) {
309
- if ($couponCode == $this->_getQuote()->getCouponCode()) {
310
  $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode));
311
  } else {
312
  $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode));
@@ -325,45 +320,27 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
325
 
326
  public function kancart_shoppingcart_checkout() {
327
  $requestData = $this->getRequest()->getParams();
 
328
 
329
  if (!$this->isLoggedIn()) {
330
  return array(false, '0x0002', 'You need login first.');
331
  }
332
- if ($requestData['payment_method_id'] === 'paypal')
333
- $requestData['payment_method_id'] = 'paypal_standard';
334
- else if ($requestData['payment_method_id'] === 'paypalwpp')
335
- $requestData['payment_method_id'] = 'paypal_express';
336
- $payment = array('method' => $requestData['payment_method_id']);
 
 
 
 
337
  try {
338
- $paypalParams = array();
339
- $this->makeBillingSameAsShipping();
340
- if ($requestData['payment_method_id'] === 'paypal_standard') {
341
- // $this->getOnepage()->savePayment($payment);
342
- $placeOrderResult = $this->saveOrder($payment);
343
- //some error occurred during the saving order process
344
- if (is_string($placeOrderResult)) {
345
- return array(false, '0x9000', $placeOrderResult);
346
- }
347
- $checkOutSession = Mage::getSingleton('checkout/session');
348
- $checkOutSession->setPaypalStandardQuoteId($checkOutSession->getQuoteId());
349
- $standard = Mage::getModel('paypal/standard');
350
- foreach ($standard->getStandardCheckoutFormFields() as $field => $value) {
351
- $paypalParams[$field] = $value;
352
- }
353
- $paypalParams['bn'] = 'PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted';
354
- $paypalParams['shopping_url'] = $requestData['shoppingcart_url'];
355
- $paypalParams['return'] = $requestData['return_url'];
356
- $paypalParams['cancel_return'] = $requestData['cancel_url'];
357
- if (abs(intval($paypalParams['discount_amount'])) == 0) {
358
- // for mobile optimization
359
- unset($paypalParams['discount_amount']);
360
- }
361
- $paypalRedirectUrl = $standard->getConfig()->getPaypalUrl();
362
- return array(true, '0x0000', array('paypal_redirect_url' => $paypalRedirectUrl, 'paypal_params' => $paypalParams));
363
- } else if ($requestData['payment_method_id'] === 'paypal_express') {
364
  return Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_start('commit');
365
  } else {
366
- return $this->_placeOrder($payment);
367
  }
368
  } catch (Mage_Core_Exception $e) {
369
  return array(false, '0x9000', $e->getMessage());
@@ -373,157 +350,50 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
373
  }
374
 
375
  /**
376
- * from mobile payment
377
- * @param array $payment
378
  */
379
- public function _placeOrder($payment) {
380
- $comments = 'From mobile payment ' . $payment['method'];
381
- $payment['method'] = 'checkmo'; //money order
382
- $info = $this->saveOrder($payment, $comments, $order);
383
- if ($info === true) {
384
- $orderId = $this->getOnepage()->getCheckout()->getLastRealOrderId();
385
- $data = Kancart::getModel('Order')->getPaymentOrderInfo($order, $orderId);
386
- return array(true, '0x0000', $data);
387
- } else {
388
- return array(false, '0x9000', $info);
389
- }
390
- }
391
-
392
- public function getRequest() {
393
- return Mage::app()->getRequest();
394
- }
395
-
396
- /**
397
- * save order 2012-05-24
398
- * @return bool
399
- */
400
- private function saveOrder($payment, $comment = 'from mobile', &$newOrder = null) {
401
- $result = array();
402
- $success = true;
403
- try {
404
- if ($requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds()) {
405
- $postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
406
- if ($diff = array_diff($requiredAgreements, $postedAgreements)) {
407
- $result['success'] = false;
408
- $result['error'] = true;
409
- $result['error_messages'] = $this->__('Please agree to all the terms and conditions before placing the order.');
410
- $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
411
- return $result;
412
- }
413
- }
414
- $this->getOnepage()->getQuote()->getPayment()->importData($payment);
415
- $this->getOnepage()->saveOrder();
416
-
417
- $storeId = Mage::app()->getStore()->getId();
418
- $paymentHelper = Mage::helper("payment");
419
- $zeroSubTotalPaymentAction = $paymentHelper->getZeroSubTotalPaymentAutomaticInvoice($storeId);
420
- if ($paymentHelper->isZeroSubTotal($storeId)
421
- && $this->_getOrder()->getGrandTotal() == 0
422
- && $zeroSubTotalPaymentAction == Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE
423
- && $paymentHelper->getZeroSubTotalOrderStatus($storeId) == 'pending') {
424
- $invoice = $this->_initInvoice();
425
- $invoice->getOrder()->setIsInProcess(true);
426
- $invoice->save();
427
- }
428
-
429
- $newOrderIncrementId = $this->getOnepage()->getCheckout()->getLastRealOrderId();
430
- $newOrder = $this->_initOrder($newOrderIncrementId);
431
- $newOrder->addStatusToHistory(false, $comment, false);
432
- $newOrder->save();
433
-
434
- $result['success'] = true;
435
- $result['error'] = false;
436
- } catch (Mage_Payment_Model_Info_Exception $e) {
437
- $message = $e->getMessage();
438
- if (!empty($message)) {
439
- $result['error_messages'] = $message;
440
- }
441
- $result['goto_section'] = 'payment';
442
- $result['update_section'] = array(
443
- 'name' => 'payment-method',
444
- 'html' => $this->_getPaymentMethodsHtml()
445
- );
446
- $success = false;
447
- } catch (Mage_Core_Exception $e) {
448
- Mage::logException($e);
449
- Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage());
450
- $result['success'] = false;
451
- $result['error'] = true;
452
- $result['error_messages'] = $e->getMessage();
453
-
454
- if ($gotoSection = $this->getOnepage()->getCheckout()->getGotoSection()) {
455
- $result['goto_section'] = $gotoSection;
456
- $this->getOnepage()->getCheckout()->setGotoSection(null);
457
- }
458
-
459
- if ($updateSection = $this->getOnepage()->getCheckout()->getUpdateSection()) {
460
- if (isset($this->_sectionUpdateFunctions[$updateSection])) {
461
- $updateSectionFunction = $this->_sectionUpdateFunctions[$updateSection];
462
- $result['update_section'] = array(
463
- 'name' => $updateSection,
464
- 'html' => $this->$updateSectionFunction()
465
- );
466
  }
467
- $this->getOnepage()->getCheckout()->setUpdateSection(null);
468
- }
469
- $success = false;
470
- } catch (Exception $e) {
471
- Mage::logException($e);
472
- Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage());
473
- $result['success'] = false;
474
- $result['error'] = true;
475
- $result['error_messages'] = $this->__('There was an error processing your order. Please contact us or try again later.');
476
- $success = false;
477
  }
478
- $this->getOnepage()->getQuote()->save();
479
- return $success ? $success : $result['error_messages'];
480
- }
481
-
482
- /**
483
- * Initialize basic order model
484
- *
485
- * @param mixed $orderIncrementId
486
- * @return Mage_Sales_Model_Order
487
- */
488
- protected function _initOrder($orderIncrementId) {
489
- $order = Mage::getModel('sales/order');
490
-
491
- /* @var $order Mage_Sales_Model_Order */
492
- $order->loadByIncrementId($orderIncrementId);
493
- return $order;
494
- }
495
 
496
- /**
497
- * Get Order by quoteId
498
- *
499
- * @return Mage_Sales_Model_Order
500
- */
501
- protected function _getOrder() {
502
- if (is_null($this->_order)) {
503
- $this->_order = Mage::getModel('sales/order')->load($this->getOnepage()->getQuote()->getId(), 'quote_id');
504
- if (!$this->_order->getId()) {
505
- throw new Mage_Payment_Model_Info_Exception(Mage::helper('core')->__("Can not create invoice. Order was not found."));
506
- }
507
- }
508
- return $this->_order;
509
  }
510
 
511
  /**
512
- * Create invoice
513
- *
514
- * @return Mage_Sales_Model_Order_Invoice
515
  */
516
- protected function _initInvoice() {
517
- $items = array();
518
- foreach ($this->getOnepage()->getQuote()->getAllItems() as $item) {
519
- $items[$item->getId()] = $item->getQty();
 
 
 
 
 
 
 
 
 
 
 
 
 
520
  }
521
- /* @var $invoice Mage_Sales_Model_Service_Order */
522
- $invoice = Mage::getModel('sales/service_order', $this->_getOrder())->prepareInvoice($items);
523
- $invoice->setEmailSent(true);
524
 
525
- Mage::register('current_invoice', $invoice);
526
- return $invoice;
527
  }
528
 
529
  public function getCustomer() {
@@ -547,69 +417,4 @@ class Kancart_MobileApi_Model_Checkout extends Kancart_MobileApi_Model_Abstract
547
  return $this->_quote;
548
  }
549
 
550
- public function getTotals() {
551
- return $this->getQuote()->getTotals();
552
- }
553
-
554
- protected $_api = null;
555
- protected $_config = null;
556
-
557
- protected function getApi() {
558
- if (null === $this->_api) {
559
- $this->_config = Mage::getModel('paypal/config', array('paypal_express'));
560
- $tShoppingCartCheckouthis->_api = Mage::getModel('paypal/api_nvp')->setConfigObject($this->_config);
561
- }
562
- return $this->_api;
563
- }
564
-
565
- public function getOnepage() {
566
- return Mage::getSingleton('checkout/type_onepage');
567
- }
568
-
569
- public function getShippingRates() {
570
- if (empty($this->_rates)) {
571
- $this->getAddress()->collectShippingRates()->save();
572
- $groups = $this->getAddress()->getGroupedAllShippingRates();
573
- return $this->_rates = $groups;
574
- }
575
- return $this->_rates;
576
- }
577
-
578
- public function getAddress() {
579
- if (empty($this->_address)) {
580
- $this->_address = $this->getQuote()->getShippingAddress();
581
- }
582
- return $this->_address;
583
- }
584
-
585
- public function getCarrierName($carrierCode) {
586
- if ($name = Mage::getStoreConfig('carriers/' . $carrierCode . '/title')) {
587
- return $name;
588
- }
589
- return $carrierCode;
590
- }
591
-
592
- public function getAddressShippingMethod() {
593
- return $this->getAddress()->getShippingMethod();
594
- }
595
-
596
- public function getShippingPrice($price, $flag) {
597
- return $this->getQuote()->getStore()->convertPrice(Mage::helper('tax')->getShippingPrice($price, $flag, $this->getAddress()), true);
598
- }
599
-
600
- public function _grandTotal_includeTax($total) {
601
- if ($total->getAddress()->getGrandTotal()) {
602
- return $this->_getTaxConfig()->displayCartTaxWithGrandTotal($this->_getStore());
603
- }
604
- return false;
605
- }
606
-
607
- public function _getStore() {
608
- return Mage::app()->getStore();
609
- }
610
-
611
- public function _getTaxConfig() {
612
- return Mage::getSingleton('tax/config');
613
- }
614
-
615
  }
27
  protected $_customer;
28
  protected $_checkout;
29
  protected $_quote;
 
 
 
 
 
30
 
31
  public function kancart_shoppingcart_addresses_update() {
32
  $addressData = $this->getRequest()->getParams();
40
  list($result, $code, $address_id) = Kancart::getModel('User')->kancart_user_address_update();
41
  if ($result === false) {
42
  $address['street'] = array($address['address1'], $address['address2']);
43
+ $address['region'] = isset($address['state']) ? $address['state'] : $address['zone_name'];
 
44
  $address['region_id'] = $address['zone_id'];
 
45
  $address_id = null;
46
  }
47
  }
48
 
49
  $address['same_as_billing'] = 1;
50
+ if ($this->getQuote()->isVirtual()) {
51
+ $this->getOnepage()->saveBilling($address, $address_id);
52
+ } else {
53
+ $this->getOnepage()->saveShipping($address, $address_id);
54
+ }
55
 
56
  return $this->shoppingCartCheckoutDetail();
57
  }
58
 
59
  public function kancart_shoppingcart_checkout_detail() {
60
+ if ($this->getRequest()->getParam('payment_method_id') == 'paypalwpp') {
61
+ Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_detail();
62
+ } else if (!$this->isLoggedIn()) {
63
  return array(false, '0x0002', 'You need login first.');
64
  }
65
+
66
  return $this->shoppingCartCheckoutDetail();
67
  }
68
 
69
  public function shoppingCartCheckoutDetail() {
70
  $this->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
71
  $checkoutDetailArr = array();
 
 
 
 
72
  $checkoutDetailArr['is_virtual'] = $is_virtual = $this->getQuote()->isVirtual();
73
  $checkoutDetailArr['need_shipping_address'] = defined('NEED_SHIPPING_ADDRESS') ? NEED_SHIPPING_ADDRESS : $is_virtual;
74
+ $checkoutDetailArr['need_billing_address'] = $need_billing_address = defined('NEED_BILLING_ADDRESS') ? NEED_BILLING_ADDRESS : false;
75
+ $checkoutDetailArr['shipping_address'] = $this->getShippingAddress($is_virtual);
76
+ $checkoutDetailArr['billing_address'] = $this->getBillingAddress($is_virtual, $need_billing_address);
77
+ $checkoutDetailArr['review_orders'] = array($this->getOrderReview());
78
+ $checkoutDetailArr['price_infos'] = $this->getPriceInfos();
79
  $checkoutDetailArr['payment_methods'] = $this->getPaymentMethods();
80
 
81
+ if (isset($_SESSION['checkout_messages']) && $_SESSION['checkout_messages']) {
82
  $checkoutDetailArr['messages'] = $_SESSION['checkout_messages'];
83
  unset($_SESSION['checkout_messages']);
84
  }
85
  return array(true, '0x0000', $checkoutDetailArr);
86
  }
87
 
88
+ private function getBillingAddress($is_virtual, $need_billing_address) {
89
  $billing_address = $this->getQuote()->getBillingAddress();
90
+ if (!$billing_address->getData('street') && (($is_virtual && $need_billing_address) || !$is_virtual)) {
91
  $billing_address = $this->getCustomer()->getPrimaryBillingAddress();
92
  if (empty($billing_address)) {
93
  $billing_address = current($this->getCustomer()->getAddresses());
105
  return $this->toAddressData($billing_address);
106
  }
107
 
108
+ private function getShippingAddress($is_virtual) {
109
  $shipping_address = $this->getQuote()->getShippingAddress();
110
+ if (!$shipping_address->getData('country_id') && !$is_virtual) {
111
  $shipping_address = $this->getCustomer()->getPrimaryShippingAddress();
112
  if (empty($shipping_address)) {
113
  $shipping_address = current($this->getCustomer()->getAddresses());
135
  $methods = $paymentHelper->getStoreMethods($store, $quote);
136
  $total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
137
  foreach ($methods as $key => $method) {
138
+ if ($this->isAviable($method)
139
  && ($total != 0
140
  || $method->getCode() == 'free'
141
  || ($quote->hasRecurringItems() && $method->canManageRecurringProfiles()))) {
146
  $code = 'paypalwpp';
147
  }
148
  if ($code == 'paypal' || $code == 'paypalwpp') {
149
+ $payment[$code] = array('pm_id' => $code,
150
+ 'pm_title' => $method->getTitle(),
151
+ 'pm_code' => $method->getCode(),
152
+ 'description' => $method->getDescription(),
153
+ 'img_url' => '');
 
154
  }
155
  }
156
  unset($methods[$key]);
157
  }
158
+ krsort($payment);
159
 
160
+ return array_values($payment);
161
  }
162
 
163
+ protected function isAviable($method) {
164
  if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
165
  return false;
166
  }
223
 
224
  public function getShippingMethods() {
225
  try {
226
+ $setDefaultSM = false;
227
  $this->getOnepage()->getQuote()->getShippingAddress()->setCollectShippingRates(true);
228
  $this->getOnepage()->getQuote()->collectTotals()->save();
229
+ $this->getQuote()->getShippingAddress()->collectShippingRates()->save();
230
+ $_shippingRateGroups = $this->getQuote()->getShippingAddress()->getGroupedAllShippingRates();
231
  if (!$this->getQuote()->getShippingAddress()->getShippingMethod())
232
  $setDefaultSM = true;
233
  if ($_shippingRateGroups) {
245
  if ($_rate->getErrorMessage()) {
246
  $rateArr['error_message'] = strip_tags($_rate->getErrorMessage());
247
  } else {
248
+ $price = Mage::helper('tax')->getShippingPrice($_rate->getPrice(), Mage::helper('tax')->displayShippingPriceIncludingTax(), $this->getQuote()->getShippingAddress());
249
  $shippingMethodArr['price'] = $store->convertPrice($price, false, false);
250
  }
251
  $shippingMethodArr['currency'] = Mage::getModel('core/store')->load(Mage::app()->getStore()->getId())->getCurrentCurrencyCode();
266
  }
267
  }
268
 
 
 
 
 
269
  public function kancart_shoppingcart_coupons_update() {
270
  try {
271
  $params = $this->getRequest()->getParams();
272
+ $cart = Mage::getSingleton('checkout/cart');
273
+ if (!$cart->getQuote()->getItemsCount()) {
274
  throw new Exception('Cart is empty.');
275
  }
276
  $couponCode = $params['coupon_id'];
289
  return $this->shoppingCartCheckoutDetail();
290
  }
291
 
 
 
 
 
292
  public function updateCoupon($couponCode) {
293
+ $oldCouponCode = $this->getQuote()->getCouponCode();
294
  if (!strlen($couponCode) && !strlen($oldCouponCode)) {
295
  throw new Exception('No coupon code in current quote.');
296
  }
297
  $message = '';
298
  try {
299
+ $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
300
+ $this->getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
301
  ->collectTotals()
302
  ->save();
303
  if (strlen($couponCode)) {
304
+ if ($couponCode == $this->getQuote()->getCouponCode()) {
305
  $message = $this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode));
306
  } else {
307
  $message = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode));
320
 
321
  public function kancart_shoppingcart_checkout() {
322
  $requestData = $this->getRequest()->getParams();
323
+ $payment_id = $real_payment_id = trim($requestData['payment_method_id']);
324
 
325
  if (!$this->isLoggedIn()) {
326
  return array(false, '0x0002', 'You need login first.');
327
  }
328
+ if ($payment_id === 'paypal') {
329
+ $real_payment_id = 'paypal_standard';
330
+ } else if ($payment_id === 'paypalwpp') {
331
+ $real_payment_id = 'paypal_express';
332
+ } else {
333
+ $real_payment_id = 'checkmo'; //money order
334
+ }
335
+ $payment = array('method' => $real_payment_id);
336
+ $this->getOnepage()->savePayment($payment);
337
  try {
338
+ if ($payment_id === 'paypal') {
339
+ return Kancart::getModel('PayPalWPS')->buildPaypalWPSParams();
340
+ } else if ($payment_id === 'paypalwpp') {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  return Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_start('commit');
342
  } else {
343
+ return Kancart::getModel('Payment')->placeOrder($payment, $payment_id);
344
  }
345
  } catch (Mage_Core_Exception $e) {
346
  return array(false, '0x9000', $e->getMessage());
350
  }
351
 
352
  /**
353
+ * apply for offline payment
 
354
  */
355
+ public function kancart_checkout_start() {
356
+ $requestData = $this->getRequest()->getParams();
357
+ $payment_id = $real_payment_id = trim($requestData['payment_method_id']);
358
+ switch ($_REQUEST['checkout_type']) {
359
+ case 'cart':
360
+ if ($payment_id == 'paypalec') {
361
+ return Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_start();
362
+ } else {
363
+ return $this->kancart_shoppingcart_checkout();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  }
365
+ break;
366
+ case 'order':
367
+ break;
368
+ default : break;
 
 
 
 
 
 
369
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
 
371
+ return array(FALSE, '0xFFFF', 'Unknow Error!');
 
 
 
 
 
 
 
 
 
 
 
 
372
  }
373
 
374
  /**
375
+ * apply for offline payment
 
 
376
  */
377
+ public function kancart_checkout_done() {
378
+ $payment_id = $this->getRequest()->getParam('payment_method_id');
379
+ $comment = $this->getRequest()->getParam('custom_kc_comments');
380
+ $checkout_type = $this->getRequest()->getParam('checkout_type');
381
+ switch ($checkout_type) {
382
+ case 'cart':
383
+ if ($payment_id == 'paypalwpp') {
384
+ return Kancart::getModel('PayPalEC')->kancart_shoppingcart_paypalec_pay($comment);
385
+ } elseif ($payment_id == 'paypal') {
386
+ return Kancart::getModel('PayPalWPS')->kancart_shoppingcart_paypalwps_done();
387
+ } else {
388
+ return Kancart::getModel('Payment')->kancart_payment_done(trim($_REQUEST['order_id']), $comment, $_REQUEST['payment_status']);
389
+ }
390
+ break;
391
+ case 'order':
392
+ break;
393
+ default : break;
394
  }
 
 
 
395
 
396
+ return array(FALSE, '0xFFFF', 'Unknow Error!');
 
397
  }
398
 
399
  public function getCustomer() {
417
  return $this->_quote;
418
  }
419
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  }
app/code/community/Kancart/MobileApi/Model/ErrorHandler.php CHANGED
@@ -19,7 +19,7 @@ class KancartErrorHandler {
19
  // UNCATCHABLE ERRORS
20
  public static function captureFatalError() {
21
  $error = error_get_last();
22
- if ($error) {
23
  if($error['type']==E_ERROR){
24
  $errormsg = "FATAL ERROR: {$error['message']} in {$error['file']} on line {$error['line']} ";
25
  die(json_encode(array('result' => 'fail', 'code' => '0xFFFF', 'info' => $errormsg)));
19
  // UNCATCHABLE ERRORS
20
  public static function captureFatalError() {
21
  $error = error_get_last();
22
+ if ($error) {
23
  if($error['type']==E_ERROR){
24
  $errormsg = "FATAL ERROR: {$error['message']} in {$error['file']} on line {$error['line']} ";
25
  die(json_encode(array('result' => 'fail', 'code' => '0xFFFF', 'info' => $errormsg)));
app/code/community/Kancart/MobileApi/Model/Item.php CHANGED
@@ -706,9 +706,13 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
706
  $_finalPrice = $product->getFinalPrice();
707
  if ($DisplayMinimalPrice && $_minimalPriceValue && $_minimalPriceValue < $_finalPrice) {
708
  if (!$UseLinkForAsLowAs) {
709
- $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
 
 
710
  if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
711
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
 
 
712
  }
713
  }
714
  } else {
@@ -722,7 +726,11 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
722
  }
723
  } else {
724
  if ($DisplayMinimalPrice && $_minimalPriceValue) {
725
- $this->addtoDisplayPrices($display_prices, $this->__('Starting at:'), $this->getCurrencyPrice($_minimalPriceValue));
 
 
 
 
726
  }
727
  $_finalPrice = $_minimalPriceValue;
728
  }
@@ -742,9 +750,13 @@ class Kancart_MobileApi_Model_Item extends Kancart_MobileApi_Model_Abstract {
742
  list($_minimalPrice, $_maximalPrice) = $product->getPriceModel()->getPrices($product);
743
  $_finalPrice = $product->getFinalPrice();
744
  if ($product->getPriceView()) {
745
- $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
 
 
746
  if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
747
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPrice, true, false), 0, 'free');
 
 
748
  }
749
  } else {
750
  if ($_minimalPrice <> $_maximalPrice) {
706
  $_finalPrice = $product->getFinalPrice();
707
  if ($DisplayMinimalPrice && $_minimalPriceValue && $_minimalPriceValue < $_finalPrice) {
708
  if (!$UseLinkForAsLowAs) {
709
+ if ($_finalPrice > 0) {
710
+ $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
711
+ }
712
  if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
713
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
714
+ } else if (!$_finalPrice) {
715
+ $this->addtoDisplayPrices($display_prices, $this->__('As low as: '), $this->getCurrencyPrice($_minimalPriceValue));
716
  }
717
  }
718
  } else {
726
  }
727
  } else {
728
  if ($DisplayMinimalPrice && $_minimalPriceValue) {
729
+ if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
730
+ $this->addtoDisplayPrices($display_prices, $this->__('Starting at:') . $this->getCurrencyPrice($_minimalPriceValue, true, false), 0, 'free');
731
+ } else {
732
+ $this->addtoDisplayPrices($display_prices, $this->__('Starting at:'), $this->getCurrencyPrice($_minimalPriceValue));
733
+ }
734
  }
735
  $_finalPrice = $_minimalPriceValue;
736
  }
750
  list($_minimalPrice, $_maximalPrice) = $product->getPriceModel()->getPrices($product);
751
  $_finalPrice = $product->getFinalPrice();
752
  if ($product->getPriceView()) {
753
+ if ($_finalPrice > 0) {
754
+ $this->addtoDisplayPrices($display_prices, 'Price: ', $this->getCurrencyPrice($_finalPrice));
755
+ }
756
  if (stripos($_REQUEST['method'], 'Items.Get') !== false) { //items list show different
757
  $this->addtoDisplayPrices($display_prices, $this->__('As low as: ') . $this->getCurrencyPrice($_minimalPrice, true, false), 0, 'free');
758
+ } else if (!$_finalPrice) {
759
+ $this->addtoDisplayPrices($display_prices, $this->__('As low as: '), $this->getCurrencyPrice($_minimalPrice));
760
  }
761
  } else {
762
  if ($_minimalPrice <> $_maximalPrice) {
app/code/community/Kancart/MobileApi/Model/Items.php CHANGED
@@ -44,10 +44,10 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
44
 
45
  if (isset($params['item_ids'])) {
46
  // get by item ids
47
- $products = $this->getSpecifiedProducts($params['item_ids']);
48
- } else if ($params['is_specials']) {
49
- // get specials products
50
- $products = $this->getProductsByCategory($cid, $pageNo, $pageSize, $order, $direction);
51
  } else if ($params['query']) {
52
  // get by query
53
  $products = $this->getProductsByQuery($query, $pageNo, $pageSize, $order, $direction);
@@ -61,24 +61,83 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
61
  }
62
  }
63
 
64
- private function getSpecifiedProducts($ids) {
65
- $products = array();
 
 
 
 
 
 
 
 
66
  if ($ids) {
67
  is_string($ids) && $ids = explode(',', $ids);
68
- $items = array();
69
- $itemObject = Kancart::getModel('Item');
70
- foreach ($ids as $id) {
71
- $itemObject->loadProduct($id);
 
 
 
 
 
 
 
 
72
  $itemObject->getItemBaseInfo();
73
  $itemObject->getItemPrices();
74
  $items[] = $itemObject->getItem();
75
  $itemObject->clear();
76
  }
77
-
78
- $products['items'] = $items;
79
- $products['total_results'] = sizeof($ids);
80
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  return $products;
83
  }
84
 
@@ -142,10 +201,9 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
142
  return $products;
143
  }
144
 
145
- public function getProductsByCategory($cid = false, $pageNo = 1, $pageSize = 20, $order = 'entity_id', $direction = 'desc') {
146
  $list = Mage::getBlockSingleton('Catalog/Product_List');
147
 
148
- $cid == -1 && $cid = Mage::app()->getStore()->getRootCategoryId();
149
  $category = Mage::getModel('catalog/category')->load($cid);
150
  $layer = $list->getLayer()->setCurrentCategory($category);
151
  $collection = $layer->getProductCollection()
@@ -161,7 +219,7 @@ class Kancart_MobileApi_Model_Items extends Kancart_MobileApi_Model_Abstract {
161
  $itemObject = Kancart::getModel('Item');
162
  foreach ($productList as $product) {
163
  if ($product->getId()) {
164
- Mage::getModel('cataloginventory/stock_item')->assignProduct($product);
165
  $itemObject->setProduct($product);
166
  $itemObject->getItemBaseInfo();
167
  $itemObject->getItemPrices();
44
 
45
  if (isset($params['item_ids'])) {
46
  // get by item ids
47
+ $products = $this->getSpecifiedProducts($params['item_ids'], $pageNo, $pageSize, $order, $direction);
48
+ } else if ($cid == -1) {
49
+ // get all products
50
+ $products = $this->getAllProducts($pageNo, $pageSize, $order, $direction);
51
  } else if ($params['query']) {
52
  // get by query
53
  $products = $this->getProductsByQuery($query, $pageNo, $pageSize, $order, $direction);
61
  }
62
  }
63
 
64
+ private function getSpecifiedProducts($ids, $pageNo, $pageSize, $order, $direction) {
65
+ $collection = Mage::getResourceModel('catalog/product_collection')
66
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
67
+ ->addMinimalPrice()
68
+ ->addFinalPrice()
69
+ ->addTaxPercents()
70
+ ->setCurPage($pageNo)
71
+ ->setPageSize($pageSize)
72
+ ->setOrder($order, $direction);
73
+
74
  if ($ids) {
75
  is_string($ids) && $ids = explode(',', $ids);
76
+ $collection->addIdFilter($ids);
77
+ }
78
+
79
+ $collection->load();
80
+ $size = $collection->getSize();
81
+ $productList = $collection->getItems();
82
+
83
+ $items = array();
84
+ $itemObject = Kancart::getModel('Item');
85
+ foreach ($productList as $product) {
86
+ if ($product->getId()) {
87
+ $itemObject->setProduct($product);
88
  $itemObject->getItemBaseInfo();
89
  $itemObject->getItemPrices();
90
  $items[] = $itemObject->getItem();
91
  $itemObject->clear();
92
  }
 
 
 
93
  }
94
+ $products = array();
95
+ $products['items'] = $items;
96
+ $products['total_results'] = $size;
97
+ return $products;
98
+ }
99
+
100
+ private function getAllProducts($pageNo, $pageSize, $order, $direction) {
101
+ $collection = Mage::getResourceModel('catalog/product_collection')
102
+ ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
103
+ ->addMinimalPrice()
104
+ ->addFinalPrice()
105
+ ->addTaxPercents()
106
+ ->setCurPage($pageNo)
107
+ ->setPageSize($pageSize)
108
+ ->setOrder($order, $direction);
109
+ Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
110
+
111
+ $storeId = Mage::app()->getStore()->getId();
112
+ $table = $collection->getTable('catalog/category_product_index');
113
+ $visibility = Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds();
114
+ $visibility = join(',', $visibility);
115
+ $sql = "SELECT DISTINCT product_id FROM $table WHERE store_id='$storeId' AND visibility IN($visibility)";
116
+ $rows = $collection->getConnection()->fetchAll($sql);
117
+ $ids = array();
118
+ foreach ($rows as $row) {
119
+ $ids[] = $row['product_id'];
120
+ }
121
+ $collection->addIdFilter($ids);
122
 
123
+ $collection->load();
124
+ $size = $collection->getSize();
125
+ $productList = $collection->getItems();
126
+
127
+ $items = array();
128
+ $itemObject = Kancart::getModel('Item');
129
+ foreach ($productList as $product) {
130
+ if ($product->getId()) {
131
+ $itemObject->setProduct($product);
132
+ $itemObject->getItemBaseInfo();
133
+ $itemObject->getItemPrices();
134
+ $items[] = $itemObject->getItem();
135
+ $itemObject->clear();
136
+ }
137
+ }
138
+ $products = array();
139
+ $products['items'] = $items;
140
+ $products['total_results'] = $size;
141
  return $products;
142
  }
143
 
201
  return $products;
202
  }
203
 
204
+ private function getProductsByCategory($cid = false, $pageNo = 1, $pageSize = 20, $order = 'entity_id', $direction = 'desc') {
205
  $list = Mage::getBlockSingleton('Catalog/Product_List');
206
 
 
207
  $category = Mage::getModel('catalog/category')->load($cid);
208
  $layer = $list->getLayer()->setCurrentCategory($category);
209
  $collection = $layer->getProductCollection()
219
  $itemObject = Kancart::getModel('Item');
220
  foreach ($productList as $product) {
221
  if ($product->getId()) {
222
+ // Mage::getModel('cataloginventory/stock_item')->assignProduct($product);
223
  $itemObject->setProduct($product);
224
  $itemObject->getItemBaseInfo();
225
  $itemObject->getItemPrices();
app/code/community/Kancart/MobileApi/Model/Order.php CHANGED
@@ -189,10 +189,8 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
189
  );
190
  }
191
  $result = $this->_getAttributes($order, 'order');
192
- $result['shipping_address'] = $this->_getAttributes($order->getShippingAddress(), 'order_address');
193
- $result['shipping_address']['street'] = $order->getShippingAddress()->getStreet();
194
- $result['billing_address'] = $this->_getAttributes($order->getBillingAddress(), 'order_address');
195
- $result['billing_address']['street'] = $order->getBillingAddress()->getStreet();
196
  $result['items'] = array();
197
  foreach ($order->getAllVisibleItems() as $item) {
198
  if ($item->getGiftMessageId() > 0) {
@@ -243,81 +241,15 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
243
  return $result;
244
  }
245
 
246
- public function getOrderItemSku($options) {
247
- $i = 0;
248
- $jsonoption = '[';
249
- foreach ($options as $option) {
250
- if ($i == 0) {
251
- $jsonoption.='{"sku_id":"' . $option['label'] . '","value":"' . $option['value'] . '"}';
252
- } else {
253
- $jsonoption.=',{"sku_id":"' . $option['label'] . '","value":"' . $option['value'] . '"}';
254
- }
255
- $i++;
256
- }
257
- $jsonoption.=']';
258
- }
259
-
260
  public function _toOrder($orderid) {
261
  $order = $this->info($orderid);
262
- $billing_add = $order['billing_address']['street'];
263
- $billing_country = Mage::getModel('directory/country')->loadByCode($order['billing_address']['country_id']);
264
- $billing_country->getName();
265
- $billing_zone = Mage::getModel('directory/region')->loadByName($order['billing_address']['region'], $order['billing_address']['country_id']);
266
- $shipping_add = $order['shipping_address']['street'];
267
- $shipping_country = Mage::getModel('directory/country')->loadByCode($order['shipping_address']['country_id']);
268
- $shipping_country->getName();
269
- $shipping_zone = Mage::getModel('directory/region')->loadByName($order['shipping_address']['region'], $order['shipping_address']['country_id']);
270
  $result = array();
271
  $result['order_id'] = $order['increment_id'];
272
  $result['display_id'] = $order['increment_id'];
273
  $result['uname'] = $order['customer_email'];
274
  $result['currency'] = $order['order_currency_code'];
275
- $result['shipping_address'] = array(
276
- 'address_book_id' => $order['shipping_address']['parent_id'],
277
- 'address_type' => $order['shipping_address']['address_type'],
278
- 'lastname' => $order['shipping_address']['lastname'],
279
- 'firstname' => $order['shipping_address']['firstname'],
280
- 'gender' => null,
281
- 'mobile' => null,
282
- 'company' => $order['shipping_address']['company'],
283
- 'fax' => $order['shipping_address']['fax'],
284
- 'telephone' => $order['shipping_address']['telephone'],
285
- 'tax_code' => null,
286
- 'postcode' => $order['shipping_address']['postcode'],
287
- 'city' => $order['shipping_address']['city'],
288
- 'address1' => $shipping_add[0],
289
- 'address2' => $shipping_add[1],
290
- 'country_id' => $shipping_country->getData('country_id'),
291
- 'country_code' => $shipping_country->getData('iso2_code'),
292
- 'country_name' => $shipping_country->getData('name'),
293
- 'zone_id' => $shipping_zone->getData('region_id'),
294
- 'zone_code' => $shipping_zone->getData('code'),
295
- 'zone_name' => $order['shipping_address']['region'],
296
- 'state' => null
297
- );
298
- $result['billing_address'] = array(
299
- 'address_book_id' => $order['billing_address']['parent_id'],
300
- 'address_type' => $order['billing_address']['address_type'],
301
- 'lastname' => $order['billing_address']['lastname'],
302
- 'firstname' => $order['billing_address']['firstname'],
303
- 'gender' => null,
304
- 'mobile' => null,
305
- 'company' => $order['billing_address']['company'],
306
- 'fax' => $order['billing_address']['fax'],
307
- 'telephone' => $order['billing_address']['telephone'],
308
- 'tax_code' => null,
309
- 'postcode' => $order['billing_address']['postcode'],
310
- 'city' => $order['billing_address']['city'],
311
- 'address1' => $billing_add[0],
312
- 'address2' => $billing_add[1],
313
- 'country_id' => $billing_country->getData('country_id'),
314
- 'country_code' => $billing_country->getData('iso2_code'),
315
- 'country_name' => $billing_country->getData('name'),
316
- 'zone_id' => $billing_zone->getData('region_id'),
317
- 'zone_code' => $billing_zone->getData('code'),
318
- 'zone_name' => $order['billing_address']['region'],
319
- 'state' => null
320
- );
321
  $result['uname'] = $order['customer_email'];
322
  $result['payment_method'] = array(
323
  'pm_id' => null,
@@ -389,7 +321,6 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
389
  foreach ($order['items'] as $item) {
390
  $_product = Mage::getModel('catalog/product')->load($item['product_id']);
391
  $options = unserialize($item['product_options']);
392
- // $jsonoption = $this->getOrderItemSku($options['attributes_info']);
393
  $itemOptions = $this->getOrderItemOptions($options);
394
  $result['order_items'][] = array(
395
  'order_item_id' => $item['item_id'],
@@ -406,9 +337,11 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
406
  'virtual_flag' => $item['is_virtual'] == 1
407
  );
408
  }
 
409
  foreach ($order['status_history'] as $status) {
 
410
  $result['order_status'][] = array(
411
- 'status_id' => null,
412
  'status_name' => $status['status'],
413
  'date_added' => $status['created_at'],
414
  'allow_payment' => null,
@@ -416,7 +349,7 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
416
  'comments' => $status['comment']
417
  );
418
  }
419
- $result['last_status_id'] = $order['status'];
420
  $result['order_tax'] = $order['tax_amount'];
421
  $result['order_date_start'] = $order['created_at'];
422
  if ($order['status'] == "complete") {
@@ -468,6 +401,9 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
468
  }
469
 
470
  protected function _getAttributes($object, $type, array $attributes = null) {
 
 
 
471
  $result = array();
472
  if (!is_object($object)) {
473
  return $result;
@@ -530,17 +466,24 @@ class Kancart_MobileApi_Model_Order extends Kancart_MobileApi_Model_Abstract {
530
  }
531
 
532
  public function getPaymentAddress($order) {
533
- $shippingAddress = $order->getShippingAddress();
534
- $address = $shippingAddress->getData();
535
- $street = $shippingAddress->getStreet();
 
 
 
 
 
 
 
536
  $addr = array(
537
- 'city' => $address['city'],
538
- 'country_id' => $address['country_id'],
539
- 'zone_id' => $address['region_id'], //1
540
  'zone_name' => '', //2
541
- 'state' => $address['region'], //3
542
- 'address1' => $street[0],
543
- 'address2' => $street[1],
544
  );
545
 
546
  return $addr;
189
  );
190
  }
191
  $result = $this->_getAttributes($order, 'order');
192
+ $result['shipping_address'] = $this->toAddressData($order->getShippingAddress());
193
+ $result['billing_address'] = $this->toAddressData($order->getBillingAddress());
 
 
194
  $result['items'] = array();
195
  foreach ($order->getAllVisibleItems() as $item) {
196
  if ($item->getGiftMessageId() > 0) {
241
  return $result;
242
  }
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  public function _toOrder($orderid) {
245
  $order = $this->info($orderid);
 
 
 
 
 
 
 
 
246
  $result = array();
247
  $result['order_id'] = $order['increment_id'];
248
  $result['display_id'] = $order['increment_id'];
249
  $result['uname'] = $order['customer_email'];
250
  $result['currency'] = $order['order_currency_code'];
251
+ $result['shipping_address'] = $order['shipping_address'];
252
+ $result['billing_address'] = $order['billing_address'];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  $result['uname'] = $order['customer_email'];
254
  $result['payment_method'] = array(
255
  'pm_id' => null,
321
  foreach ($order['items'] as $item) {
322
  $_product = Mage::getModel('catalog/product')->load($item['product_id']);
323
  $options = unserialize($item['product_options']);
 
324
  $itemOptions = $this->getOrderItemOptions($options);
325
  $result['order_items'][] = array(
326
  'order_item_id' => $item['item_id'],
337
  'virtual_flag' => $item['is_virtual'] == 1
338
  );
339
  }
340
+ $last_status_id = 0;
341
  foreach ($order['status_history'] as $status) {
342
+ strtolower($order['status']) == strtolower($status['status']) && $last_status_id = $status['parent_id'];
343
  $result['order_status'][] = array(
344
+ 'status_id' => $status['parent_id'],
345
  'status_name' => $status['status'],
346
  'date_added' => $status['created_at'],
347
  'allow_payment' => null,
349
  'comments' => $status['comment']
350
  );
351
  }
352
+ $result['last_status_id'] = $last_status_id;
353
  $result['order_tax'] = $order['tax_amount'];
354
  $result['order_date_start'] = $order['created_at'];
355
  if ($order['status'] == "complete") {
401
  }
402
 
403
  protected function _getAttributes($object, $type, array $attributes = null) {
404
+ if (!$object) {
405
+ return array();
406
+ }
407
  $result = array();
408
  if (!is_object($object)) {
409
  return $result;
466
  }
467
 
468
  public function getPaymentAddress($order) {
469
+ if ($order->getIsVirtual()) {
470
+ $address = $order->getBillingAddress();
471
+ } else {
472
+ $address = $order->getShippingAddress();
473
+ }
474
+
475
+ if (!$address) {
476
+ return array();
477
+ }
478
+
479
  $addr = array(
480
+ 'city' => $address->getCity(),
481
+ 'country_id' => $address->getCountryId(),
482
+ 'zone_id' => $address->getRegionId(), //1
483
  'zone_name' => '', //2
484
+ 'state' => $address->getRegion(), //3
485
+ 'address1' => $address->getStreet(1),
486
+ 'address2' => $address->getStreet(2),
487
  );
488
 
489
  return $addr;
app/code/community/Kancart/MobileApi/Model/PayPalEC.php CHANGED
@@ -24,29 +24,31 @@
24
  */
25
  class Kancart_MobileApi_Model_PayPalEC extends Kancart_MobileApi_Model_Abstract {
26
 
27
- const PAYMENT_INFO_TRANSPORT_TOKEN = 'paypal_express_checkout_token';
28
- const PAYMENT_INFO_TRANSPORT_PAYER_ID = 'paypal_express_checkout_payer_id';
29
-
30
- protected $_methodType = 'paypal_express';
31
-
32
  /**
33
- * @var Mage_Paypal_Model_Express_Checkout
 
 
34
  */
35
- protected $_paypalExpressCheckout = null;
36
 
37
- protected function _getSession() {
38
- return Mage::getSingleton('customer/session');
39
- }
 
 
 
 
 
40
 
41
- protected function _initPaypalExpressCheckout() {
42
- $quote = $this->getQuote();
43
  if (!$quote->hasItems() || $quote->getHasError()) {
44
  Mage::throwException(Mage::helper('paypal')->__('Unable to initialize Express Checkout.'));
45
  }
46
  if (is_null($this->_config)) {
47
- $this->_config = Mage::getModel('paypal/config', array('paypal_express'));
48
  }
49
- $this->_paypalExpressCheckout = Mage::getSingleton('paypal/express_checkout', array(
50
  'config' => $this->_config,
51
  'quote' => $quote,
52
  ));
@@ -55,30 +57,33 @@ class Kancart_MobileApi_Model_PayPalEC extends Kancart_MobileApi_Model_Abstract
55
  public function kancart_shoppingcart_paypalec_start($useraction = 'continue') {
56
  $requestData = $this->getRequest()->getParams();
57
  try {
58
- $this->getQuote()->reserveOrderId()->save();
59
- $this->getApi();
60
- $this->_api->setAmount($this->getQuote()->getBaseGrandTotal())
61
- ->setCurrencyCode($this->getQuote()->getBaseCurrencyCode())
62
- //->setInvNum($this->getQuote()->getReservedOrderId())
63
- ->setReturnUrl(urldecode($requestData['return_url']))
64
- ->setCancelUrl(urldecode($requestData['cancel_url']))
65
- ->setSolutionType($this->_config->solutionType)
66
- ->setPaymentAction($this->_config->paymentAction);
67
-
68
- $paypalCart = Mage::getModel('paypal/cart', array($this->getQuote()));
69
- $this->_api->setPaypalCart($paypalCart)
70
- ->setIsLineItemsEnabled($this->_config->lineItemsEnabled);
71
-
72
- $this->_api->callSetExpressCheckout();
73
- $token = $this->_api->getToken();
74
- $this->_initToken($token);
75
- $paypalSite = Mage::getModel('paypal/config')
76
- ->setStoreId(Mage::app()->getStore()->getId())
77
- ->setMethod(Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS)
78
- ->getPaypalUrl(array('cmd' => '_express-checkout-mobile',
79
- 'useraction' => $useraction,
80
- 'token' => $token));
81
- return array(true, '0x0000', array('token' => $token, 'paypal_redirect_url' => $paypalSite));
 
 
 
82
  } catch (Mage_Core_Exception $e) {
83
  return array(false, '0x9000', $e->getMessage());
84
  } catch (Exception $e) {
@@ -86,8 +91,62 @@ class Kancart_MobileApi_Model_PayPalEC extends Kancart_MobileApi_Model_Abstract
86
  }
87
  }
88
 
89
- private function getPaypalSession() {
90
- return Mage::getSingleton('paypal/session');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  }
92
 
93
  /**
@@ -101,109 +160,48 @@ class Kancart_MobileApi_Model_PayPalEC extends Kancart_MobileApi_Model_Abstract
101
  if (null !== $setToken) {
102
  if (false === $setToken) {
103
  // security measure for avoid unsetting token twice
104
- if (!$this->getPaypalSession()->getExpressCheckoutToken()) {
105
  Mage::throwException($this->__('PayPal Express Checkout Token does not exist.'));
106
  }
107
- $this->getPaypalSession()->unsExpressCheckoutToken();
108
  } else {
109
- $this->getPaypalSession()->setExpressCheckoutToken($setToken);
110
  }
111
  return $this;
112
  }
113
- }
114
-
115
- protected function _getPaypalCheckoutToken($requestData) {
116
- if (isset($requestData['token'])) {
117
- if ($requestData['token'] !== $this->getPaypalSession()->getExpressCheckoutToken()) {
118
  Mage::throwException($this->__('Wrong PayPal Express Checkout Token specified.'));
119
  }
120
  } else {
121
- return $this->getPaypalSession()->getExpressCheckoutToken();
122
  }
123
- return $requestData['token'];
124
  }
125
 
126
- public function kancart_shoppingcart_paypalec_detail() {
127
- $requestData = $this->getRequest()->getParams();
128
- try {
129
- $this->_initPaypalExpressCheckout();
130
- $this->_paypalExpressCheckout->returnFromPaypal($this->_getPaypalCheckoutToken($requestData));
131
- return Kancart::getModel('Checkout')->shoppingCartCheckoutDetail();
132
- } catch (Mage_Core_Exception $e) {
133
- return array(false, '0x9000', $e->getMessage());
134
- } catch (Exception $e) {
135
- return array(false, '0x9000', $e->getMessage());
136
- }
137
- }
138
-
139
- public function kancart_shoppingcart_paypalec_pay() {
140
- $requestData = $this->getRequest()->getParams();
141
- try {
142
- $this->makeBillingSameAsShipping();
143
- $payment = $this->getQuote()->getPayment();
144
-
145
- $payment->setMethod($this->_methodType);
146
- Mage::getSingleton('paypal/info')->importToPayment($this->_api, $payment);
147
- $payment->setAdditionalInformation(self::PAYMENT_INFO_TRANSPORT_PAYER_ID, $requestData['payer_id'])
148
- ->setAdditionalInformation(self::PAYMENT_INFO_TRANSPORT_TOKEN, $requestData['token'])
149
- ;
150
- $this->getQuote()->collectTotals()->save();
151
- $this->getOnepage()->saveOrder();
152
- $this->getOnepage()->getQuote()->save();
153
- $order = $this->_initOrder($this->getOnepage()->getLastOrderID());
154
- $order->addStatusToHistory(false, 'from mobile', false);
155
- $order->save();
156
- $this->getOnepage()->getCheckout()->clear();
157
- $info = Kancart::getModel('Order')->getPaymentOrderInfo($order, $order->getIncrementId(), $order->getPayment()->getLastTransId());
158
- return array(true, '0x0000', $info);
159
- } catch (Mage_Core_Exception $e) {
160
- return array(false, '0x9000', $e->getMessage());
161
- } catch (Exception $e) {
162
- return array(false, '0x9000', $e->getMessage());
163
- }
164
- $this->getOnepage()->getQuote()->save();
165
- }
166
-
167
- protected function _initOrder($orderIncrementId) {
168
- $order = Mage::getModel('sales/order');
169
- $order->loadByIncrementId($orderIncrementId);
170
- if (!$order->getId()) {
171
- $this->_fault('Invalid OrderID (Order)');
172
- }
173
- return $order;
174
- }
175
-
176
- protected $_checkout;
177
-
178
- public function getCheckout() {
179
- if (empty($this->_checkout)) {
180
- $this->_checkout = Mage::getSingleton('checkout/session');
181
- }
182
- return $this->_checkout;
183
  }
184
 
185
- protected $_api = null;
186
- protected $_config = null;
187
-
188
- protected function getApi() {
189
- if (null === $this->_api) {
190
- $this->_config = Mage::getModel('paypal/config', array('paypal_express'));
191
- $this->_api = Mage::getModel('paypal/api_nvp')->setConfigObject($this->_config);
192
- }
193
- return $this->_api;
194
  }
195
 
196
- protected $_quote = null;
197
-
198
- public function getQuote() {
199
- if (empty($this->_quote)) {
200
- $this->_quote = $this->getCheckout()->getQuote();
 
 
 
201
  }
202
  return $this->_quote;
203
  }
204
 
205
- public function getOnepage() {
206
- return Mage::getSingleton('checkout/type_onepage');
207
- }
208
-
209
  }
24
  */
25
  class Kancart_MobileApi_Model_PayPalEC extends Kancart_MobileApi_Model_Abstract {
26
 
 
 
 
 
 
27
  /**
28
+ * Config mode type
29
+ *
30
+ * @var string
31
  */
32
+ protected $_configType = 'paypal/config';
33
 
34
+ /**
35
+ * Config method type
36
+ *
37
+ * @var string
38
+ */
39
+ protected $_configMethod = Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS;
40
+ protected $_checkout = null;
41
+ protected $_config = null;
42
 
43
+ protected function _initCheckout() {
44
+ $quote = $this->_getQuote();
45
  if (!$quote->hasItems() || $quote->getHasError()) {
46
  Mage::throwException(Mage::helper('paypal')->__('Unable to initialize Express Checkout.'));
47
  }
48
  if (is_null($this->_config)) {
49
+ $this->_config = Mage::getModel($this->_configType, array($this->_configMethod));
50
  }
51
+ $this->_checkout = Mage::getSingleton('paypal/express_checkout', array(
52
  'config' => $this->_config,
53
  'quote' => $quote,
54
  ));
57
  public function kancart_shoppingcart_paypalec_start($useraction = 'continue') {
58
  $requestData = $this->getRequest()->getParams();
59
  try {
60
+ $this->_initCheckout();
61
+
62
+ if ($this->_getQuote()->getIsMultiShipping()) {
63
+ $this->_getQuote()->setIsMultiShipping(false);
64
+ $this->_getQuote()->removeAllAddresses();
65
+ }
66
+
67
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
68
+ if ($customer && $customer->getId()) {
69
+ $this->_checkout->setCustomerWithAddressChange(
70
+ $customer, $this->_getQuote()->getBillingAddress(), $this->_getQuote()->getShippingAddress()
71
+ );
72
+ }
73
+
74
+ // giropay
75
+ $this->_checkout->prepareGiropayUrls(
76
+ Mage::getUrl('checkout/onepage/success'), Mage::getUrl('paypal/express/cancel'), Mage::getUrl('checkout/onepage/success')
77
+ );
78
+
79
+ $token = $this->_checkout->start($requestData['return_url'], $requestData['cancel_url']);
80
+ if ($token && $url = $this->_checkout->getRedirectUrl()) {
81
+ $this->_initToken($token);
82
+ $url .='&useraction=' . $useraction;
83
+ return array(true, '0x0000', array('token' => $token, 'paypal_redirect_url' => $url));
84
+ } else {
85
+ return array(false, '0x9000', 'Token or paypal redirect url is empty.');
86
+ }
87
  } catch (Mage_Core_Exception $e) {
88
  return array(false, '0x9000', $e->getMessage());
89
  } catch (Exception $e) {
91
  }
92
  }
93
 
94
+ public function kancart_shoppingcart_paypalec_detail() {
95
+ try {
96
+ $this->_initCheckout();
97
+ $this->_checkout->returnFromPaypal($this->_initToken());
98
+ return Kancart::getModel('Checkout')->shoppingCartCheckoutDetail();
99
+ } catch (Mage_Core_Exception $e) {
100
+ return array(false, '0x9000', $e->getMessage());
101
+ } catch (Exception $e) {
102
+ return array(false, '0x9000', $e->getMessage());
103
+ }
104
+ }
105
+
106
+ public function kancart_shoppingcart_paypalec_pay($comments = 'From mobile') {
107
+ try {
108
+ $this->_initCheckout();
109
+ if (!$this->_getQuote()->getPayment()->getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID)) {
110
+ $this->_checkout->returnFromPaypal($this->_initToken());
111
+ }
112
+ $this->_checkout->place($this->_initToken());
113
+ $session = $this->_getCheckoutSession();
114
+ $session->clearHelperData();
115
+
116
+ // "last successful quote"
117
+ $quoteId = $this->_getQuote()->getId();
118
+ $session->setLastQuoteId($quoteId)->setLastSuccessQuoteId($quoteId);
119
+
120
+ // an order may be created
121
+ $order = $this->_checkout->getOrder();
122
+ if ($order) {
123
+ $session->setLastOrderId($order->getId())
124
+ ->setLastRealOrderId($order->getIncrementId());
125
+ // as well a billing agreement can be created
126
+ $agreement = $this->_checkout->getBillingAgreement();
127
+ if ($agreement) {
128
+ $session->setLastBillingAgreementId($agreement->getId());
129
+ }
130
+ }
131
+ $order->addStatusToHistory(false, $comments, false);
132
+
133
+ // recurring profiles may be created along with the order or without it
134
+ $profiles = $this->_checkout->getRecurringPaymentProfiles();
135
+ if ($profiles) {
136
+ $ids = array();
137
+ foreach ($profiles as $profile) {
138
+ $ids[] = $profile->getId();
139
+ }
140
+ $session->setLastRecurringProfileIds($ids);
141
+ }
142
+
143
+ $info = Kancart::getModel('Order')->getPaymentOrderInfo($order, $order->getIncrementId(), $order->getPayment()->getLastTransId());
144
+ return array(true, '0x0000', $info);
145
+ } catch (Mage_Core_Exception $e) {
146
+ return array(false, '0x9000', $e->getMessage());
147
+ } catch (Exception $e) {
148
+ return array(false, '0x9000', $e->getMessage());
149
+ }
150
  }
151
 
152
  /**
160
  if (null !== $setToken) {
161
  if (false === $setToken) {
162
  // security measure for avoid unsetting token twice
163
+ if (!$this->_getSession()->getExpressCheckoutToken()) {
164
  Mage::throwException($this->__('PayPal Express Checkout Token does not exist.'));
165
  }
166
+ $this->_getSession()->unsExpressCheckoutToken();
167
  } else {
168
+ $this->_getSession()->setExpressCheckoutToken($setToken);
169
  }
170
  return $this;
171
  }
172
+ if ($setToken = $this->getRequest()->getParam('token')) {
173
+ if ($setToken !== $this->_getSession()->getExpressCheckoutToken()) {
 
 
 
174
  Mage::throwException($this->__('Wrong PayPal Express Checkout Token specified.'));
175
  }
176
  } else {
177
+ $setToken = $this->_getSession()->getExpressCheckoutToken();
178
  }
179
+ return $setToken;
180
  }
181
 
182
+ private function _getSession() {
183
+ return Mage::getSingleton('paypal/session');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  }
185
 
186
+ /**
187
+ * Return checkout session object
188
+ *
189
+ * @return Mage_Checkout_Model_Session
190
+ */
191
+ private function _getCheckoutSession() {
192
+ return Mage::getSingleton('checkout/session');
 
 
193
  }
194
 
195
+ /**
196
+ * Return checkout quote object
197
+ *
198
+ * @return Mage_Sale_Model_Quote
199
+ */
200
+ private function _getQuote() {
201
+ if (!$this->_quote) {
202
+ $this->_quote = $this->_getCheckoutSession()->getQuote();
203
  }
204
  return $this->_quote;
205
  }
206
 
 
 
 
 
207
  }
app/code/community/Kancart/MobileApi/Model/PayPalWPS.php CHANGED
@@ -25,14 +25,94 @@
25
  class Kancart_MobileApi_Model_PayPalWPS extends Kancart_MobileApi_Model_Abstract {
26
 
27
  protected $_methodType = 'paypal_standard';
 
28
 
29
- protected function _initOrder($orderIncrementId) {
30
- $order = Mage::getModel('sales/order');
31
- $order->loadByIncrementId($orderIncrementId);
32
- if (!$order->getId()) {
33
- $this->_fault('Invalid OrderID (Order)');
 
 
 
34
  }
35
- return $order;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  }
37
 
38
  public function kancart_shoppingcart_paypalwps_done() {
@@ -58,4 +138,46 @@ class Kancart_MobileApi_Model_PayPalWPS extends Kancart_MobileApi_Model_Abstract
58
  return array(true, '0x0000', $info);
59
  }
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
25
  class Kancart_MobileApi_Model_PayPalWPS extends Kancart_MobileApi_Model_Abstract {
26
 
27
  protected $_methodType = 'paypal_standard';
28
+ protected $_order; /* @var $_order Mage_Sales_Model_Order */
29
 
30
+ public function buildPaypalWPSParams() {
31
+ $paypalParams = array();
32
+ $payment = array('method' => 'paypal_standard');
33
+ $requestData = $this->getRequest()->getParams();
34
+ list($result, $msg) = $this->placeOrder($payment, $_REQUEST['custom_kc_comments']);
35
+ //some error occurred during the saving order process
36
+ if ($result === FALSE) {
37
+ return array(false, '0x9000', $msg);
38
  }
39
+ $checkOutSession = Mage::getSingleton('checkout/session');
40
+ $checkOutSession->setPaypalStandardQuoteId($checkOutSession->getQuoteId());
41
+ $standard = Mage::getModel('paypal/standard');
42
+ foreach ($standard->getStandardCheckoutFormFields() as $field => $value) {
43
+ $paypalParams[$field] = $value;
44
+ }
45
+ $paypalParams['bn'] = 'PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted';
46
+ $paypalParams['shopping_url'] = $requestData['shoppingcart_url'];
47
+ $paypalParams['return'] = $requestData['return_url'];
48
+ $paypalParams['cancel_return'] = $requestData['cancel_url'];
49
+ if (abs(intval($paypalParams['discount_amount'])) == 0) {
50
+ // for mobile optimization
51
+ unset($paypalParams['discount_amount']);
52
+ }
53
+ $paypalRedirectUrl = $standard->getConfig()->getPaypalUrl();
54
+
55
+ return array(true, '0x0000', array('paypal_redirect_url' => $paypalRedirectUrl, 'paypal_params' => $paypalParams));
56
+ }
57
+
58
+ /**
59
+ * save order 2012-05-24
60
+ * @return bool
61
+ */
62
+ public function placeOrder($payment, $comment = 'from mobile') {
63
+ $result = FALSE;
64
+ $mesg = NULL;
65
+ try {
66
+ if ($requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds()) {
67
+ $postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
68
+ if ($diff = array_diff($requiredAgreements, $postedAgreements)) {
69
+ $result['error_messages'] = $this->__('Please agree to all the terms and conditions before placing the order.');
70
+ return array(false, $result['error_messages']);
71
+ }
72
+ }
73
+ $this->getOnepage()->getQuote()->getPayment()->importData($payment);
74
+ $this->getOnepage()->saveOrder();
75
+
76
+ $storeId = Mage::app()->getStore()->getId();
77
+ $paymentHelper = Mage::helper("payment");
78
+ $zeroSubTotalPaymentAction = $paymentHelper->getZeroSubTotalPaymentAutomaticInvoice($storeId);
79
+ if ($paymentHelper->isZeroSubTotal($storeId)
80
+ && $this->_getOrder()->getGrandTotal() == 0
81
+ && $zeroSubTotalPaymentAction == Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE
82
+ && $paymentHelper->getZeroSubTotalOrderStatus($storeId) == 'pending') {
83
+ $invoice = $this->_initInvoice();
84
+ $invoice->getOrder()->setIsInProcess(true);
85
+ $invoice->save();
86
+ }
87
+
88
+ $newOrderIncrementId = $this->getOnepage()->getCheckout()->getLastRealOrderId();
89
+ $newOrder = Mage::getModel('sales/order');
90
+ $newOrder->loadByIncrementId($newOrderIncrementId);
91
+ $newOrder->addStatusToHistory(false, $comment, false);
92
+ $newOrder->save();
93
+
94
+ $result = TRUE;
95
+ $mesg = $newOrder;
96
+ } catch (Mage_Payment_Model_Info_Exception $e) {
97
+ $mesg = $e->getMessage();
98
+ } catch (Mage_Core_Exception $e) {
99
+ Mage::logException($e);
100
+ Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage());
101
+ if ($gotoSection = $this->getOnepage()->getCheckout()->getGotoSection()) {
102
+ $this->getOnepage()->getCheckout()->setGotoSection(null);
103
+ }
104
+
105
+ if ($updateSection = $this->getOnepage()->getCheckout()->getUpdateSection()) {
106
+ $this->getOnepage()->getCheckout()->setUpdateSection(null);
107
+ }
108
+ $mesg = $e->getMessage();
109
+ } catch (Exception $e) {
110
+ Mage::logException($e);
111
+ Mage::helper('checkout')->sendPaymentFailedEmail($this->getOnepage()->getQuote(), $e->getMessage());
112
+ $mesg = $e->getMessage();
113
+ }
114
+ $this->getOnepage()->getQuote()->save();
115
+ return array($result, $mesg);
116
  }
117
 
118
  public function kancart_shoppingcart_paypalwps_done() {
138
  return array(true, '0x0000', $info);
139
  }
140
 
141
+ protected function _initOrder($orderIncrementId) {
142
+ $order = Mage::getModel('sales/order');
143
+ $order->loadByIncrementId($orderIncrementId);
144
+ if (!$order->getId()) {
145
+ $this->_fault('Invalid OrderID (Order)');
146
+ }
147
+ return $order;
148
+ }
149
+
150
+ /**
151
+ * Get Order by quoteId
152
+ *
153
+ * @return Mage_Sales_Model_Order
154
+ */
155
+ protected function _getOrder() {
156
+ if (is_null($this->_order)) {
157
+ $this->_order = Mage::getModel('sales/order')->load($this->getOnepage()->getQuote()->getId(), 'quote_id');
158
+ if (!$this->_order->getId()) {
159
+ throw new Mage_Payment_Model_Info_Exception(Mage::helper('core')->__("Can not create invoice. Order was not found."));
160
+ }
161
+ }
162
+ return $this->_order;
163
+ }
164
+
165
+ /**
166
+ * Create invoice
167
+ *
168
+ * @return Mage_Sales_Model_Order_Invoice
169
+ */
170
+ protected function _initInvoice() {
171
+ $items = array();
172
+ foreach ($this->getOnepage()->getQuote()->getAllItems() as $item) {
173
+ $items[$item->getId()] = $item->getQty();
174
+ }
175
+ /* @var $invoice Mage_Sales_Model_Service_Order */
176
+ $invoice = Mage::getModel('sales/service_order', $this->_getOrder())->prepareInvoice($items);
177
+ $invoice->setEmailSent(true);
178
+
179
+ Mage::register('current_invoice', $invoice);
180
+ return $invoice;
181
+ }
182
+
183
  }
app/code/community/Kancart/MobileApi/Model/Payment.php ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ * To change this template, choose Tools | Templates
5
+ * and open the template in the editor.
6
+ */
7
+
8
+ class Kancart_MobileApi_Model_Payment extends Kancart_MobileApi_Model_Abstract {
9
+
10
+ /**
11
+ * from mobile payment
12
+ * @param array $payment
13
+ */
14
+ public function placeOrder($payment, $paymentId) {
15
+ $comments = 'From mobile payment ' . $paymentId;
16
+ $paypal = Kancart::getModel('PayPalWPS');
17
+ list($result, $order) = $paypal->placeOrder($payment, $comments);
18
+ if ($result === true) {
19
+ $orderId = $this->getOnepage()->getCheckout()->getLastRealOrderId();
20
+ $this->getOnepage()->getCheckout()->clear();
21
+ $data = Kancart::getModel('Order')->getPaymentOrderInfo($order, $orderId);
22
+ return array(true, '0x0000', $data);
23
+ } else {
24
+ return array(false, '0x9000', $order);
25
+ }
26
+ }
27
+
28
+ public function kancart_payment_done($orderId, $comments, $state) {
29
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
30
+ if ($order && $order->getId()) {
31
+ $state = strtolower($state) == 'succeed' ? Mage_Sales_Model_Order::STATE_PROCESSING : $order->getState();
32
+ $order->setState($state, TRUE, $comments);
33
+ $order->save();
34
+ $order->sendOrderUpdateEmail(TRUE, 'Your order has been paid on our mobile payment service ' . $_REQUEST['payment_method_id']);
35
+ $data = Kancart::getModel('Order')->getPaymentOrderInfo($order, $orderId);
36
+ return array(true, '0x0000', $data);
37
+ } else {
38
+ return array(false, '0xFFFF', 'Error this order doesn\'t exist.');
39
+ }
40
+ }
41
+
42
+ }
43
+
44
+ ?>
app/code/community/Kancart/MobileApi/Model/Store.php CHANGED
@@ -76,6 +76,9 @@ class Kancart_MobileApi_Model_Store extends Kancart_MobileApi_Model_Abstract {
76
  $Curencies = array();
77
  $defaultCurrencyCode = Mage::app()->getStore()->getDefaultCurrencyCode();
78
  $allowedCurrencies = Mage::getBlockSingleton('Directory/Currency')->getCurrencies();
 
 
 
79
 
80
  /** @var $locale Mage_Core_Model_Locale */
81
  $locale = Mage::app()->getLocale();
@@ -225,6 +228,8 @@ class Kancart_MobileApi_Model_Store extends Kancart_MobileApi_Model_Abstract {
225
  return array(
226
  'cart_type' => 'magento',
227
  'cart_version' => Mage::getVersion(),
 
 
228
  'login_by_mail' => true
229
  );
230
  }
76
  $Curencies = array();
77
  $defaultCurrencyCode = Mage::app()->getStore()->getDefaultCurrencyCode();
78
  $allowedCurrencies = Mage::getBlockSingleton('Directory/Currency')->getCurrencies();
79
+ if (empty($allowedCurrencies)) {
80
+ $allowedCurrencies[$defaultCurrencyCode] = 'default';
81
+ }
82
 
83
  /** @var $locale Mage_Core_Model_Locale */
84
  $locale = Mage::app()->getLocale();
228
  return array(
229
  'cart_type' => 'magento',
230
  'cart_version' => Mage::getVersion(),
231
+ 'plugin_version' => KANCART_PLUGIN_VERSION,
232
+ 'support_kancart_payment' => true,
233
  'login_by_mail' => true
234
  );
235
  }
app/code/community/Kancart/MobileApi/controllers/IndexController.php CHANGED
@@ -1,5 +1,6 @@
1
  <?php
2
 
 
3
  define('KANCART_PLUGIN_VERSION', '2.0.3');
4
  define('KANCART_APP_KEY', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appkey', Mage::app()->getStore()));
5
  define('KANCART_APP_SECRECT', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appsecrect', Mage::app()->getStore()));
1
  <?php
2
 
3
+ error_reporting(E_ALL ^ E_NOTICE);
4
  define('KANCART_PLUGIN_VERSION', '2.0.3');
5
  define('KANCART_APP_KEY', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appkey', Mage::app()->getStore()));
6
  define('KANCART_APP_SECRECT', Mage::getStoreConfig('Kancart/Kancart_group/Kancart_appsecrect', Mage::app()->getStore()));
app/code/community/Kancart/MobileApi/etc/config.xml CHANGED
@@ -31,8 +31,8 @@
31
  <default>
32
  <Kancart>
33
  <Kancart_group>
34
- <Kancart_appkey>11111111</Kancart_appkey>
35
- <Kancart_appsecrect>11111111111111111111111111111111</Kancart_appsecrect>
36
  </Kancart_group>
37
  </Kancart>
38
  </default>
31
  <default>
32
  <Kancart>
33
  <Kancart_group>
34
+ <Kancart_appkey>KANCART_APP_KEY</Kancart_appkey>
35
+ <Kancart_appsecrect>KANCART_APP_SECRET</Kancart_appsecrect>
36
  </Kancart_group>
37
  </Kancart>
38
  </default>
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>KANCART_MobileAPI</name>
4
- <version>2.0.3</version>
5
  <stability>stable</stability>
6
  <license>OSL v3.0</license>
7
  <channel>community</channel>
@@ -9,14 +9,12 @@
9
  <summary>Kancart Mobile API Service</summary>
10
  <description>Kancart.com provides a fast on boarding iOS, Android native app and mobile web site solution.&amp;amp;&#xD;
11
  This is the Magento server side extension to provide API service for all Kancart mobile clients.</description>
12
- <notes>Fix: images path in item description was not translated to absolute path.&#xD;
13
- Fix: items can be added to cart even quantity less than min_qty.&#xD;
14
- Fix: order has item in out of stock status can be check out.&#xD;
15
- Improve: virtual items order does not requires billding address by default.</notes>
16
  <authors><author><name>Kancart.com</name><user>Kancarter</user><email>jiashun.hu@honestwalker.com</email></author></authors>
17
- <date>2013-06-28</date>
18
- <time>09:30:53</time>
19
- <contents><target name="magecommunity"><dir name="Kancart"><dir name="MobileApi"><dir name="Helper"><file name="CryptoUtil.php" hash="2db9a53cbaed6e8bc5f2dae4ed2ec334"/><file name="DES.php" hash="f038974cc0cf453373a52e6d4770ffdb"/><file name="Data.php" hash="ce8f291eec3277eb01b1f00225e5cbd8"/><file name="Rijndael.php" hash="be7c805f21086f7c26f785d0c0e73afd"/></dir><dir name="Model"><file name="Abstract.php" hash="d4771d54a70c1db3c94b7e37f015fd2b"/><file name="Cart.php" hash="36be73ec329833f33329e0bc7b3e37ca"/><file name="Category.php" hash="3c990ccb35dd1c8a51a510701eecb100"/><file name="Checkout.php" hash="ab6ee371a85f1bfd2c6c977717b5dbb0"/><file name="ErrorHandler.php" hash="53e1d720bb1910f470db82f8101665c1"/><file name="Item.php" hash="3c77431c44f7447d60989fdf6a8057a7"/><file name="Items.php" hash="d9017bda431419d800b0ba9f996959de"/><file name="Order.php" hash="c4f2a5462b8bd2843f5b845ec12a11c1"/><file name="PayPalEC.php" hash="922f0913c15c5a30ab4d396e03230b30"/><file name="PayPalWPS.php" hash="02c899dde29f2030a753f79d83b1d700"/><file name="Result.php" hash="9c87b2a0cf679aa6f22e070123dd253b"/><file name="Review.php" hash="9bb76d88732f4af3f69c08965b3b0c3b"/><file name="Store.php" hash="16f14a7fd4cab1c05de8bf8d434b2afb"/><file name="User.php" hash="f38b52e9161a43d6ce0a9bee8e08f782"/></dir><dir name="controllers"><file name="IndexController.php" hash="275c1ffd1b78d465a18d895fb3d6aee2"/></dir><dir name="etc"><file name="adminhtml.xml" hash="3364317d05e33ac33f067aed7a9f6a58"/><file name="config.xml" hash="c21a9d1f04b2232db2a6d13b800c669c"/><file name="system.xml" hash="79209320204981af35bdb4bdcba8fe76"/></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Kancart_MobileApi.xml" hash="17ceeb976f959fc6365da95b532dd616"/></dir></target></contents>
20
  <compatible/>
21
  <dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies>
22
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>KANCART_MobileAPI</name>
4
+ <version>2.0.4</version>
5
  <stability>stable</stability>
6
  <license>OSL v3.0</license>
7
  <channel>community</channel>
9
  <summary>Kancart Mobile API Service</summary>
10
  <description>Kancart.com provides a fast on boarding iOS, Android native app and mobile web site solution.&amp;amp;&#xD;
11
  This is the Magento server side extension to provide API service for all Kancart mobile clients.</description>
12
+ <notes>Fix: Fail to fetch currencies if there is only 1 currency is configured.&#xD;
13
+ Add: Add support of offline payment methods(beta)</notes>
 
 
14
  <authors><author><name>Kancart.com</name><user>Kancarter</user><email>jiashun.hu@honestwalker.com</email></author></authors>
15
+ <date>2013-07-22</date>
16
+ <time>03:59:38</time>
17
+ <contents><target name="magecommunity"><dir name="Kancart"><dir name="MobileApi"><dir name="Helper"><file name="CryptoUtil.php" hash="2db9a53cbaed6e8bc5f2dae4ed2ec334"/><file name="DES.php" hash="f038974cc0cf453373a52e6d4770ffdb"/><file name="Data.php" hash="ce8f291eec3277eb01b1f00225e5cbd8"/><file name="Rijndael.php" hash="be7c805f21086f7c26f785d0c0e73afd"/></dir><dir name="Model"><file name="Abstract.php" hash="2ae3cac0281ac4140991cc74d0c41aba"/><file name="Cart.php" hash="9ccf5977098eccafc794ed56cda2df0a"/><file name="Category.php" hash="3c990ccb35dd1c8a51a510701eecb100"/><file name="Checkout.php" hash="b71a40369246c6dd6293514fdb6c0ab9"/><file name="ErrorHandler.php" hash="45372f596a8673d97fc51cb6369d036c"/><file name="Item.php" hash="c0f3257e0922b260ba706e24073275c5"/><file name="Items.php" hash="232f2d11c209e2a68bd05922cc246c75"/><file name="Order.php" hash="b6748c2e31aef9d710e0a42d2e9974ff"/><file name="PayPalEC.php" hash="d4c3f8f68799a1a2be0daca7aa3325df"/><file name="PayPalWPS.php" hash="19a7fd4ce715e45f2196eab03f6b96e0"/><file name="Payment.php" hash="2e85dbfae1287bd37e3cb81087c3290b"/><file name="Result.php" hash="9c87b2a0cf679aa6f22e070123dd253b"/><file name="Review.php" hash="9bb76d88732f4af3f69c08965b3b0c3b"/><file name="Store.php" hash="c1aedd9f0af3bd69c69f169ba8e41ce3"/><file name="User.php" hash="f38b52e9161a43d6ce0a9bee8e08f782"/></dir><dir name="controllers"><file name="IndexController.php" hash="3bacba68c5df93fdc39b88e0f3cc389f"/></dir><dir name="etc"><file name="adminhtml.xml" hash="3364317d05e33ac33f067aed7a9f6a58"/><file name="config.xml" hash="2f9d3466e651ac2b2b1f387b1a2356ad"/><file name="system.xml" hash="79209320204981af35bdb4bdcba8fe76"/></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Kancart_MobileApi.xml" hash="17ceeb976f959fc6365da95b532dd616"/></dir></target></contents>
18
  <compatible/>
19
  <dependencies><required><php><min>5.2.0</min><max>6.0.0</max></php></required></dependencies>
20
  </package>