Apruve_B2B_Payment_Gateway - Version 2.0.0

Version Notes

Stable Version

Download this release

Release Info

Developer Apruve
Extension Apruve_B2B_Payment_Gateway
Version 2.0.0
Comparing to
See all releases


Code changes from version 1.0.15 to 2.0.0

Files changed (27) hide show
  1. app/code/community/Apruve/ApruvePayment/Block/Adminhtml/Sales/Order/View.php +40 -0
  2. app/code/community/Apruve/ApruvePayment/Helper/Data.php +46 -9
  3. app/code/community/Apruve/ApruvePayment/Model/Api/Abstract.php +147 -24
  4. app/code/community/Apruve/ApruvePayment/Model/Api/Payment.php +126 -25
  5. app/code/community/Apruve/ApruvePayment/Model/Api/PaymentRequest.php +0 -211
  6. app/code/community/Apruve/ApruvePayment/Model/Api/Rest.php +24 -129
  7. app/code/community/Apruve/ApruvePayment/Model/Api/Rest/Invoice.php +246 -0
  8. app/code/community/Apruve/ApruvePayment/Model/Api/Rest/Order.php +187 -0
  9. app/code/community/Apruve/ApruvePayment/Model/Api/Rest/Shipment.php +214 -0
  10. app/code/community/Apruve/ApruvePayment/Model/Entity.php +97 -0
  11. app/code/community/Apruve/ApruvePayment/Model/Mode.php +8 -28
  12. app/code/community/Apruve/ApruvePayment/Model/Mysql4/Setup.php +0 -6
  13. app/code/community/Apruve/ApruvePayment/Model/Observer.php +258 -12
  14. app/code/community/Apruve/ApruvePayment/Model/PaymentMethod.php +95 -28
  15. app/code/community/Apruve/ApruvePayment/Model/Resource/Entity.php +31 -0
  16. app/code/community/Apruve/ApruvePayment/Model/Resource/Entity/Collection.php +31 -0
  17. app/code/community/Apruve/ApruvePayment/Model/Sales/Service/Order.php +70 -0
  18. app/code/community/Apruve/ApruvePayment/Model/Version.php +53 -0
  19. app/code/community/Apruve/ApruvePayment/controllers/WebhookController.php +115 -46
  20. app/code/community/Apruve/ApruvePayment/etc/config.xml +136 -88
  21. app/code/community/Apruve/ApruvePayment/etc/system.xml +27 -0
  22. app/code/community/Apruve/ApruvePayment/sql/apruvepayment_setup/install-2.0.0.php +64 -0
  23. app/design/frontend/base/default/layout/apruvepayment.xml +2 -2
  24. app/design/frontend/base/default/template/apruvepayment/payment/form.phtml +33 -12
  25. app/etc/modules/Apruve_ApruvePayment.xml +28 -1
  26. js/Apruve/ApruvePayment.js +13 -5
  27. package.xml +4 -4
app/code/community/Apruve/ApruvePayment/Block/Adminhtml/Sales/Order/View.php ADDED
@@ -0,0 +1,40 @@
1
+ <?php
2
+
3
+ /**
4
+ * Apruve
5
+ *
6
+ * NOTICE OF LICENSE
7
+ *
8
+ * This source file is subject to the Apache License, Version 2.0
9
+ * that is bundled with this package in the file LICENSE.txt.
10
+ * It is also available through the world-wide-web at this URL:
11
+ * http://opensource.org/licenses/Apache-2.0
12
+ * If you did not receive a copy of the license and are unable to
13
+ * obtain it through the world-wide-web, please send an email
14
+ * to license@apruve.com so we can send you a copy immediately.
15
+ *
16
+ * @category Apruve
17
+ * @package Apruve_Payment
18
+ * @copyright Copyright (coffee) 2017 Apruve, Inc. (http://www.apruve.com).
19
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
20
+ * @author Echidna Team
21
+ *
22
+ */
23
+
24
+ /**
25
+ * Adminhtml sales order view
26
+ */
27
+ class Apruve_ApruvePayment_Block_Adminhtml_Sales_Order_View extends Mage_Adminhtml_Block_Sales_Order_View
28
+ {
29
+
30
+ protected function _isAllowedAction($action)
31
+ {
32
+ if($action == 'invoice') {
33
+ $order = $this->getOrder();
34
+ if($order->getPayment()->getMethod() == Apruve_ApruvePayment_Model_PaymentMethod::PAYMENT_METHOD_CODE) {
35
+ return false;
36
+ }
37
+ }
38
+ return parent::_isAllowedAction($action);
39
+ }
40
+ }
app/code/community/Apruve/ApruvePayment/Helper/Data.php CHANGED
@@ -21,14 +21,11 @@
21
class Apruve_ApruvePayment_Helper_Data extends Mage_Core_Helper_Abstract
22
{
23
/**
24
- * @return Apruve_ApruvePayment_Model_Api_PaymentRequest
25
*/
26
- public function getPaymentRequestApiModel()
27
{
28
- return Mage::getModel(
29
- 'apruvepayment/api_paymentRequest',
30
- Mage::getSingleton('checkout/session')->getQuote()
31
- );
32
}
33
34
public function getMode()
@@ -38,6 +35,11 @@ class Apruve_ApruvePayment_Helper_Data extends Mage_Core_Helper_Abstract
38
return $sourceArray[Mage::getStoreConfig('payment/apruvepayment/mode')];
39
}
40
41
public function isAutoSubmit()
42
{
43
return Mage::getStoreConfig('payment/apruvepayment/autosubmit');
@@ -45,8 +47,43 @@ class Apruve_ApruvePayment_Helper_Data extends Mage_Core_Helper_Abstract
45
46
public function getSrc()
47
{
48
- $sourceModel = Mage::getModel('apruvepayment/mode');
49
- $sourceArray = $sourceModel->toSrcArray();
50
- return $sourceArray[Mage::getStoreConfig('payment/apruvepayment/mode')];
51
}
52
}
21
class Apruve_ApruvePayment_Helper_Data extends Mage_Core_Helper_Abstract
22
{
23
/**
24
+ * @return Apruve_ApruvePayment_Model_Api_Payment
25
*/
26
+ public function getPaymentApiModel()
27
{
28
+ return Mage::getModel('apruvepayment/api_payment');
29
}
30
31
public function getMode()
35
return $sourceArray[Mage::getStoreConfig('payment/apruvepayment/mode')];
36
}
37
38
+ public function getApiVersion()
39
+ {
40
+ return Mage::getStoreConfig('payment/apruvepayment/version');
41
+ }
42
+
43
public function isAutoSubmit()
44
{
45
return Mage::getStoreConfig('payment/apruvepayment/autosubmit');
47
48
public function getSrc()
49
{
50
+ $apruveUrl = Mage::getModel('apruvepayment/api_payment')->getBaseUrl();
51
+ return $apruveUrl . 'js/apruve.js?display=compact';
52
+ }
53
+
54
+ /**
55
+ * Log the messages and data to apruve.log if log is enabled
56
+ *
57
+ * @var string|array|object $data
58
+ * @return void
59
+ */
60
+ public function logException($data)
61
+ {
62
+ $isEnabled = Mage::getStoreConfig('payment/apruvepayment/log');
63
+ if($isEnabled) {
64
+ Mage::log($data, 7, 'apruve.log', true);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Retrieve only the visible items from a item collection for order, invoice and shipment
70
+ *
71
+ * @param Mage_Sales_Model_Abstract $object
72
+ * @return Mage_Core_Model_Abstract[]
73
+ */
74
+ public function getAllVisibleItems($object)
75
+ {
76
+ $items = array();
77
+ foreach ($object->getItemsCollection() as $item) {
78
+ $orderItem = $item->getOrderItem();
79
+ if (!$orderItem->isDeleted() && !$orderItem->getParentItemId()) {
80
+ $qty = (int) $item->getQty();
81
+ $qty = $qty > 0 ? $qty : (int) $item->getQtyOrdered();
82
+ if ($qty) {
83
+ $items[] = $item;
84
+ }
85
+ }
86
+ }
87
+ return $items;
88
}
89
}
app/code/community/Apruve/ApruvePayment/Model/Api/Abstract.php CHANGED
@@ -1,7 +1,6 @@
1
<?php
2
-
3
/**
4
- * Magento
5
*
6
* NOTICE OF LICENSE
7
*
@@ -17,6 +16,13 @@
17
* @package Apruve_Payment
18
* @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
19
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
20
*/
21
22
abstract class Apruve_ApruvePayment_Model_Api_Abstract
@@ -24,9 +30,7 @@ abstract class Apruve_ApruvePayment_Model_Api_Abstract
24
/**
25
* @var string
26
*/
27
- protected $_version = 'v3';
28
- //protected $_testMode;
29
-
30
31
/**
32
* Generate headers for rest request
@@ -35,9 +39,107 @@ abstract class Apruve_ApruvePayment_Model_Api_Abstract
35
protected function getHeaders()
36
{
37
return array(
38
- 'Content-type: application/json',
39
- 'Apruve-Api-Key: ' . $this->getApiKey(),
40
- );
41
}
42
43
/**
@@ -71,33 +173,57 @@ abstract class Apruve_ApruvePayment_Model_Api_Abstract
71
return Mage::getStoreConfig('payment/apruvepayment/mode');
72
}
73
74
-
75
/**
76
- * Get Apruve base url based on mode
77
- * @param bool $secure
78
- * @return string
79
*/
80
- public function getBaseUrl($secure = false)
81
{
82
- $http = $secure ? 'https://' : 'http://';
83
- if($this->getIsTestMode()) {
84
- return $http.'test.apruve.com/';
85
} else {
86
- return $http.'app.apruve.com/';
87
}
88
}
89
90
91
/**
92
- * Get api url part based on version
93
* @return string
94
*/
95
- protected function getApiUrl()
96
{
97
- return 'api/'.$this->_version.'/';
98
}
99
100
-
101
/**
102
* Convert price to needed value
103
* As current version supports only USD, convert price to cents
@@ -258,7 +384,4 @@ abstract class Apruve_ApruvePayment_Model_Api_Abstract
258
259
return $result;
260
}
261
-
262
-
263
-
264
}
1
<?php
2
/**
3
+ * Apruve
4
*
5
* NOTICE OF LICENSE
6
*
16
* @package Apruve_Payment
17
* @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
+ */
21
+
22
+ /**
23
+ * Class Apruve_ApruvePayment_Model_Api_Abstract
24
+ *
25
+ * This is an abstract for Apruve payment gateway.
26
*/
27
28
abstract class Apruve_ApruvePayment_Model_Api_Abstract
30
/**
31
* @var string
32
*/
33
+ const DATE_FORMAT = DateTime::ATOM;
34
35
/**
36
* Generate headers for rest request
39
protected function getHeaders()
40
{
41
return array(
42
+ "accept: application/json",
43
+ "apruve-api-key: " . $this->getApiKey(),
44
+ "content-type: application/json"
45
+ );
46
+ }
47
+
48
+ /**
49
+ * Get the API version selected for the store
50
+ * @return string
51
+ */
52
+ protected function getApiVersion()
53
+ {
54
+ return Mage::helper('apruvepayment')->getApiVersion();
55
+ }
56
+
57
+
58
+ /**
59
+ * Get api url part based on version
60
+ * @return string
61
+ */
62
+ protected function getApiUrl()
63
+ {
64
+ return 'api/'.$this->getApiVersion().'/';
65
+ }
66
+
67
+ /**
68
+ * Prepare the response array for the API call
69
+ *
70
+ * @var string|JSON $response
71
+ * @var string $url
72
+ * @var string $err
73
+ * @var string|integer $http_status
74
+ * @var string|[] $curlOptions
75
+ * @return string[] $result
76
+ */
77
+ protected function _prepareResponse($response, $url = '', $err = '', $http_status = '', $curlOptions = '')
78
+ {
79
+ $result = [];
80
+ $success = true;
81
+ $message = '';
82
+ if ($err) {
83
+ $message = "Request Error:" . $err;
84
+ $success = false;
85
+ }
86
+
87
+ if ($http_status < 200 || $http_status >= 300) {
88
+ $message = "Request Error: Request could not be processed";
89
+ $success = false;
90
+ }
91
+
92
+ $result['success'] = $success;
93
+ $result['code'] = $http_status;
94
+ $result['messsage'] = $message;
95
+ $result['response'] = Mage::helper('core')->jsonDecode($response);
96
+ $result['post_data'] = $curlOptions;
97
+ $result['url'] = $url;
98
+ Mage::helper('apruvepayment')->logException($result);
99
+ return $result;
100
+ }
101
+
102
+ /**
103
+ * Returns a formatted date based on the constant DATE_FORMAT
104
+ *
105
+ * @return date
106
+ */
107
+ protected function getDateFormatted($date)
108
+ {
109
+ return date(self::DATE_FORMAT, strtotime($date));
110
+ }
111
+
112
+ /**
113
+ * Returns an expiry date in future for the order items created in apruve
114
+ *
115
+ * @return date
116
+ */
117
+ protected function getExpiryDate()
118
+ {
119
+ return $this->getDateFormatted('+1 week');
120
+ }
121
+
122
+ /**
123
+ * Get the current store currency
124
+ *
125
+ * @return date
126
+ */
127
+ protected function getCurrency()
128
+ {
129
+ return Mage::app()->getStore()->getBaseCurrencyCode();
130
+ }
131
+
132
+ /**
133
+ * Get the order item's vendor/manufacturer data
134
+ *
135
+ * @return string
136
+ */
137
+ protected function getVendor($orderItem)
138
+ {
139
+ $product = $orderItem->getProduct();
140
+ $attributeCode = Mage::getStoreConfig('payment/apruvepayment/product_vendor');
141
+ $vendor = $product->getData($attributeCode);
142
+ return $vendor;
143
}
144
145
/**
173
return Mage::getStoreConfig('payment/apruvepayment/mode');
174
}
175
176
/**
177
+ * Build Discount Line item
178
+ * @param Mage_Sales_Model_Quote|Mage_Sales_Model_Order $object
179
+ * @return array
180
*/
181
+ protected function _getDiscountItem($object)
182
{
183
+ $helper = Mage::helper('apruvepayment');
184
+ $discountItem = [];
185
+ $discountItem['quantity'] = 1;
186
+ $discountItem['currency'] = $this->getCurrency();
187
+ $discountItem['description'] = $helper->__('Cart Discount');
188
+ $discountItem['sku'] = $helper->__('Discount');
189
+ $discountItem['title'] = $helper->__('Discount');
190
+
191
+ if($object instanceof Mage_Sales_Model_Quote) {
192
+ $discountAmount = $this->convertPrice($object->getBaseSubtotal() - $object->getBaseSubtotalWithDiscount());
193
+ } elseif($object instanceof Mage_Sales_Model_Order) {
194
+ $discountAmount = $this->convertPrice($object->getBaseDiscountAmount());
195
+ } elseif($object instanceof Mage_Sales_Model_Order_Invoice) {
196
+ $discountAmount = $this->convertPrice($object->getBaseDiscountAmount());
197
} else {
198
+ return false;
199
+ }
200
+ if($discountAmount) {
201
+ $discountAmount = -1 * abs($discountAmount);
202
+ $discountItem['price_ea_cents'] = $discountAmount;
203
+ $discountItem['price_total_cents'] = $discountAmount;
204
+
205
+ return $discountItem;
206
+ } else {
207
+ return false;
208
}
209
}
210
211
212
/**
213
+ * Get Apruve base url based on mode
214
+ * @param bool $secure
215
* @return string
216
*/
217
+ public function getBaseUrl($secure = true)
218
{
219
+ $http = $secure ? 'https://' : 'http://';
220
+ if($this->getIsTestMode()) {
221
+ return $http . 'test.apruve.com/';
222
+ } else {
223
+ return $http . 'app.apruve.com/';
224
+ }
225
}
226
227
/**
228
* Convert price to needed value
229
* As current version supports only USD, convert price to cents
384
385
return $result;
386
}
387
}
app/code/community/Apruve/ApruvePayment/Model/Api/Payment.php CHANGED
@@ -1,7 +1,6 @@
1
<?php
2
-
3
/**
4
- * Magento
5
*
6
* NOTICE OF LICENSE
7
*
@@ -17,23 +16,102 @@
17
* @package Apruve_Payment
18
* @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
19
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
20
*/
21
22
23
class Apruve_ApruvePayment_Model_Api_Payment extends Apruve_ApruvePayment_Model_Api_Abstract
24
{
25
- /** @var Mage_Sales_Model_Order */
26
- private $order;
27
28
- /** @var Mage_Sales_Model_Quote */
29
- private $quote;
30
31
- private $amounts;
32
33
- function __construct(Mage_Sales_Model_Order $order)
34
{
35
- $this->order = $order;
36
- $this->quote = $order->getQuote();
37
}
38
39
/**
@@ -44,7 +122,7 @@ class Apruve_ApruvePayment_Model_Api_Payment extends Apruve_ApruvePayment_Model_
44
public function getAmount($key)
45
{
46
if (empty($this->amounts)) {
47
- $this->amounts = $this->getAmountsFromOrder($this->order);
48
}
49
50
if (isset($this->amounts[$key])) {
@@ -55,36 +133,55 @@ class Apruve_ApruvePayment_Model_Api_Payment extends Apruve_ApruvePayment_Model_
55
}
56
57
/**
58
- * Generate payment request by given order
59
- *
60
* @return array
61
*/
62
- public function getPayment()
63
{
64
- return array(
65
- 'amount_cents' => $this->convertPrice($this->getAmount('amount_cents')),
66
- 'payment_items' => $this->getLineItems($this->order),
67
- 'issue_on_create' => !$this->quote->getIsMultiShipping()
68
- );
69
}
70
71
/**
72
* Build Line items array
73
- * @param Mage_Sales_Model_Order $itemsParent
74
* @return array
75
*/
76
protected function getLineItems($itemsParent)
77
{
78
$result = array();
79
- /** @var Mage_Sales_Model_Order_Item[] $visibleItems */
80
$visibleItems = $itemsParent->getAllVisibleItems();
81
foreach ($visibleItems as $item) {
82
83
$result[] = array(
84
'title' => $item->getName(),
85
- 'amount_cents' => $this->convertPrice($item->getPrice()) * $item->getQtyOrdered(),
86
- 'price_ea_cents' => $this->convertPrice($item->getPrice()),
87
- 'quantity' => $item->getQtyOrdered(),
88
'description' => $this->getShortDescription($item),
89
'variant_info' => $this->getVariantInfo($item),
90
'sku' => $item->getSku(),
@@ -92,7 +189,11 @@ class Apruve_ApruvePayment_Model_Api_Payment extends Apruve_ApruvePayment_Model_
92
);
93
94
}
95
96
return $result;
97
}
98
- }
1
<?php
2
/**
3
+ * Apruve
4
*
5
* NOTICE OF LICENSE
6
*
16
* @package Apruve_Payment
17
* @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
*/
21
22
23
+ /**
24
+ * Class Apruve_ApruvePayment_Model_Api_Payment
25
+ * Provide methods to build payment
26
+ * @see https://apruvit.atlassian.net/wiki/display/DOCCO/payment_request
27
+ */
28
class Apruve_ApruvePayment_Model_Api_Payment extends Apruve_ApruvePayment_Model_Api_Abstract
29
{
30
+ private $_quote;
31
32
+ private $_amounts;
33
34
+ /**
35
+ * Post request general fields
36
+ * @var array
37
+ */
38
+ protected $_postFields = array(
39
+ //required
40
+ 'merchant_id',
41
+ 'amount_cents',
42
+ //optional
43
+ 'currency',
44
+ 'tax_cents',
45
+ 'shipping_cents',
46
+ 'line_items' => array(),
47
+ );
48
49
+ /**
50
+ * Line Items Fields
51
+ * @var array
52
+ */
53
+ protected $_lineItemFields = array(
54
+ //required
55
+ 'title',
56
+ 'amount_cents', // if qty -> should chanfe
57
+ 'price_ea_cents',
58
+ 'description',
59
+ 'variant_info',
60
+ 'sku',
61
+ 'vendor',
62
+ 'view_product_url',
63
+ );
64
+
65
+ /**
66
+ * @var array
67
+ */
68
+ protected $_paymentRequest;
69
+
70
+ /**
71
+ * Get current quote
72
+ * @return Mage_Sales_Model_Quote
73
+ */
74
+ public function getQuote()
75
+ {
76
+ if($this->_quote == null) {
77
+ $this->_quote = Mage::getSingleton('checkout/session')->getQuote();
78
+ }
79
+
80
+ return $this->_quote;
81
+ }
82
+
83
+ /**
84
+ * Get json encoded payment request
85
+ * @return string
86
+ */
87
+ public function getPaymentRequestJSON()
88
{
89
+ return json_encode($this->_getPaymentRequest());
90
+ }
91
+
92
+ /**
93
+ * Get secure hash
94
+ * @see https://apruvit.atlassian.net/wiki/display/DOCCO/Checkout+Page+Tutorial#CheckoutPageTutorial-1b:CreatingaSecureHash
95
+ * @return string
96
+ */
97
+ public function getSecureHash()
98
+ {
99
+ $concatString = $this->getApiKey();
100
+
101
+ foreach ($this->_getPaymentRequest() as $val) {
102
+ if (!is_array($val)) {
103
+ $concatString .= $val;
104
+ } else {
105
+ foreach ($val as $v) {
106
+ foreach ($v as $s) {
107
+ $concatString .= $s;
108
+ }
109
+
110
+ }
111
+ }
112
+ }
113
+
114
+ return hash('sha256', $concatString);
115
}
116
117
/**
122
public function getAmount($key)
123
{
124
if (empty($this->amounts)) {
125
+ $this->amounts = $this->getAmountsFromQuote($this->getQuote());
126
}
127
128
if (isset($this->amounts[$key])) {
133
}
134
135
/**
136
+ * Build Payment Request Array
137
* @return array
138
*/
139
+ protected function _getPaymentRequest()
140
+ {
141
+ if($this->_paymentRequest == null) {
142
+ $this->_paymentRequest = array(
143
+ 'merchant_id' => $this->getMerchantKey(),
144
+ 'amount_cents' => $this->convertPrice($this->getAmount('amount_cents')),
145
+ 'currency' => $this->getCurrency(),
146
+ 'tax_cents' => $this->convertPrice($this->getAmount('tax_cents')),
147
+ 'shipping_cents' => $this->convertPrice($this->getAmount('shipping_cents')),
148
+ 'line_items' => $this->getLineItems($this->getQuote())
149
+ );
150
+ }
151
+
152
+ return $this->_paymentRequest;
153
+ }
154
+
155
+ /**
156
+ * @param Mage_Sales_Model_Quote $quote
157
+ */
158
+ public function getShopperInfo($attrName)
159
{
160
+ $method = 'get' . ucfirst($attrName);
161
+ if ($this->getQuote()->getCustomerIsGuest()) {
162
+ return $this->getQuote()->getBillingAddress()->$method();
163
+ }
164
+
165
+ return $this->getQuote()->getCustomer()->$method();
166
}
167
168
/**
169
* Build Line items array
170
+ * @param Mage_Sales_Model_Quote $itemsParent
171
* @return array
172
*/
173
protected function getLineItems($itemsParent)
174
{
175
$result = array();
176
+ /** @var Mage_Sales_Model_Quote_Item[] $visibleItems */
177
$visibleItems = $itemsParent->getAllVisibleItems();
178
foreach ($visibleItems as $item) {
179
180
$result[] = array(
181
'title' => $item->getName(),
182
+ 'amount_cents' => $this->convertPrice($item->getBaseRowTotal()),
183
+ 'price_ea_cents' => $this->convertPrice($item->getBasePrice()),
184
+ 'quantity' => $item->getQty(),
185
'description' => $this->getShortDescription($item),
186
'variant_info' => $this->getVariantInfo($item),
187
'sku' => $item->getSku(),
189
);
190
191
}
192
+ // get discount line item
193
+ if(($discountItem = $this->_getDiscountItem($itemsParent))) {
194
+ $result[] = $discountItem;
195
+ }
196
197
return $result;
198
}
199
+ }
app/code/community/Apruve/ApruvePayment/Model/Api/PaymentRequest.php DELETED
@@ -1,211 +0,0 @@
1
- <?php
2
-
3
- /**
4
- * Magento
5
- *
6
- * NOTICE OF LICENSE
7
- *
8
- * This source file is subject to the Apache License, Version 2.0
9
- * that is bundled with this package in the file LICENSE.txt.
10
- * It is also available through the world-wide-web at this URL:
11
- * http://opensource.org/licenses/Apache-2.0
12
- * If you did not receive a copy of the license and are unable to
13
- * obtain it through the world-wide-web, please send an email
14
- * to license@apruve.com so we can send you a copy immediately.
15
- *
16
- * @category Apruve
17
- * @package Apruve_Payment
18
- * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
19
- * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
20
- */
21
-
22
-
23
- /**
24
- * Class Apruve_ApruvePayment_Model_Api_PaymentRequest
25
- * Provide methods to build paymentRequest
26
- * @see https://apruvit.atlassian.net/wiki/display/DOCCO/payment_request
27
- */
28
- class Apruve_ApruvePayment_Model_Api_PaymentRequest extends Apruve_ApruvePayment_Model_Api_Abstract
29
- {
30
- private $quote;
31
-
32
- private $amounts;
33
-
34
- /**
35
- * Post request general fields
36
- * @var array
37
- */
38
- protected $_postFields = array(
39
- //required
40
- 'merchant_id',
41
- 'amount_cents',
42
- //optional
43
- 'currency',
44
- 'tax_cents',
45
- 'shipping_cents',
46
- 'line_items' => array(),
47
- );
48
-
49
- /**
50
- * Line Items Fields
51
- * @var array
52
- */
53
- protected $_lineItemFields = array(
54
- //required
55
- 'title',
56
- 'amount_cents', // if qty -> should chanfe
57
- 'price_ea_cents',
58
- 'description',
59
- 'variant_info',
60
- 'sku',
61
- 'vendor',
62
- 'view_product_url',
63
- );
64
-
65
- /**
66
- * @var array
67
- */
68
- protected $_paymentRequest;
69
-
70
-
71
- public function __construct(Mage_Sales_Model_Quote $quote)
72
- {
73
- $this->quote = $quote;
74
- $this->_paymentRequest = $this->setPaymentRequest();
75
- }
76
-
77
- /**
78
- * Get json encoded payment request
79
- * @return string
80
- */
81
- public function getPaymentRequestJSON()
82
- {
83
- return json_encode($this->_paymentRequest);
84
- }
85
-
86
- /**
87
- * Get secure hash
88
- * @see https://apruvit.atlassian.net/wiki/display/DOCCO/Checkout+Page+Tutorial#CheckoutPageTutorial-1b:CreatingaSecureHash
89
- * @return string
90
- */
91
- public function getSecureHash()
92
- {
93
- $concatString = $this->getApiKey();
94
-
95
- foreach ($this->_paymentRequest as $val) {
96
- if (!is_array($val)) {
97
- $concatString .= $val;
98
- } else {
99
- foreach ($val as $v) {
100
- foreach ($v as $s) {
101
- $concatString .= $s;
102
- }
103
-
104
- }
105
- }
106
- }
107
-
108
- return hash('sha256', $concatString);
109
- }
110
-
111
- /**
112
- * Return amount_cents, shipping_cents or tax_cents
113
- * @param $key
114
- * @return float | bool
115
- */
116
- public function getAmount($key)
117
- {
118
- if (empty($this->amounts)) {
119
- $this->amounts = $this->getAmountsFromQuote($this->quote);
120
- }
121
-
122
- if (isset($this->amounts[$key])) {
123
- return $this->amounts[$key];
124
- }
125
-
126
- return false;
127
- }
128
-
129
- /**
130
- * Build Payment Request Array
131
- * @return array
132
- */
133
- protected function setPaymentRequest()
134
- {
135
-
136
- $paymentRequest = array(
137
- 'merchant_id' => $this->getMerchantKey(),
138
- 'amount_cents' => $this->convertPrice($this->getAmount('amount_cents')),
139
- 'currency' => 'USD',
140
- 'tax_cents' => $this->convertPrice($this->getAmount('tax_cents')),
141
- 'shipping_cents' => $this->convertPrice($this->getAmount('shipping_cents')),
142
- 'line_items' => $this->getLineItems($this->quote)
143
- );
144
-
145
- return $paymentRequest;
146
- }
147
-
148
- public function updatePaymentRequest($token, $orderId)
149
- {
150
- /** @var Apruve_ApruvePayment_Model_Api_Rest $rest */
151
- $rest = Mage::getModel('apruvepayment/api_rest');
152
- $pRequest = Mage::registry('apruve_request_updated' . $token);
153
- if ($pRequest === null) {
154
-
155
- $pRequest = $rest->updatePaymentRequest(
156
- $token,
157
- $this->getAmount('amount_cents'),
158
- $this->getAmount('shipping_cents'),
159
- $this->getAmount('tax_cents'),
160
- $orderId
161
- );
162
-
163
- Mage::register('apruve_request_updated' . $token, $pRequest);
164
- }
165
- return $pRequest;
166
- }
167
-
168
-
169
- /**
170
- * @param Mage_Sales_Model_Quote $quote
171
- */
172
- public function getShopperInfo($attrName)
173
- {
174
- $method = 'get' . ucfirst($attrName);
175
- if ($this->quote->getCustomerIsGuest()) {
176
- return $this->quote->getBillingAddress()->$method();
177
- }
178
-
179
- return $this->quote->getCustomer()->$method();
180
- }
181
-
182
- /**
183
- * Build Line items array
184
- * @param Mage_Sales_Model_Quote $itemsParent
185
- * @return array
186
- */
187
- protected function getLineItems($itemsParent)
188
- {
189
- $result = array();
190
- /** @var Mage_Sales_Model_Quote_Item[] $visibleItems */
191
- $visibleItems = $itemsParent->getAllVisibleItems();
192
- foreach ($visibleItems as $item) {
193
-
194
- $result[] = array(
195
- 'title' => $item->getName(),
196
- 'amount_cents' => $this->convertPrice($item->getPrice()) * $item->getQty(),
197
- 'price_ea_cents' => $this->convertPrice($item->getPrice()),
198
- 'quantity' => $item->getQty(),
199
- 'description' => $this->getShortDescription($item),
200
- 'variant_info' => $this->getVariantInfo($item),
201
- 'sku' => $item->getSku(),
202
- 'view_product_url' => $item->getProduct()->getProductUrl(false),
203
- );
204
-
205
- }
206
-
207
- return $result;
208
- }
209
-
210
- }
211
-
app/code/community/Apruve/ApruvePayment/Model/Api/Rest.php CHANGED
@@ -1,7 +1,6 @@
1
<?php
2
-
3
/**
4
- * Magento
5
*
6
* NOTICE OF LICENSE
7
*
@@ -17,6 +16,7 @@
17
* @package Apruve_Payment
18
* @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
19
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
20
*/
21
22
/**
@@ -27,140 +27,35 @@
27
class Apruve_ApruvePayment_Model_Api_Rest extends Apruve_ApruvePayment_Model_Api_Abstract
28
{
29
/**
30
- * Send Payment object
31
- * @param string $paymentRequestId
32
- * @param array $payment
33
*
34
- * @return bool
35
- */
36
- public function postPayment($paymentRequestId, $payment)
37
- {
38
- $data = json_encode($payment);
39
-
40
- $c = curl_init($this->getPaymentUrl($paymentRequestId));
41
-
42
- curl_setopt($c, CURLOPT_HTTPHEADER, $this->getHeaders());
43
- curl_setopt($c, CURLOPT_POST, true);
44
- curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
45
- curl_setopt($c, CURLOPT_POSTFIELDS, $data);
46
- $response = curl_exec($c);
47
- $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
48
- curl_close($c);
49
-
50
- if ($http_status == '201') {
51
- return json_decode($response);
52
- } else {
53
- return false;
54
- }
55
-
56
- }
57
-
58
- /**
59
- * Update paymentRequest object
60
- * Availible fields to update are: amount_cents, shipping_cents, tax_cents
61
- * @param string $paymentRequestId
62
- * @param float $amount
63
- * @param float $shipping
64
- * @param float $tax
65
- * @return bool
66
*/
67
- public function updatePaymentRequest($paymentRequestId, $amount, $shipping, $tax, $orderIncrementId)
68
{
69
- $data = json_encode(array(
70
- 'merchant_order_id' => $orderIncrementId,
71
- 'amount_cents' => $this->convertPrice($amount),
72
- 'shipping_cents' => $this->convertPrice($shipping),
73
- 'tax_cents' => $this->convertPrice($tax),
74
));
75
76
- $c = curl_init($this->getUpdatePaymentRequestUrl($paymentRequestId));
77
-
78
- curl_setopt($c, CURLOPT_HTTPHEADER, $this->getHeaders());
79
- curl_setopt($c, CURLOPT_CUSTOMREQUEST, "PUT");
80
- curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
81
- curl_setopt($c, CURLOPT_POSTFIELDS, $data);
82
- $response = curl_exec($c);
83
- $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
84
- curl_close($c);
85
-
86
-
87
- if ($http_status == '200') {
88
- return json_decode($response);
89
- } else {
90
- return false;
91
- }
92
- }
93
-
94
- /**
95
- * Finalize paymentRequest object
96
- *
97
- * @param string $paymentRequestId
98
- *
99
- * @return bool
100
- */
101
- public function finalizePaymentRequest($paymentRequestId)
102
- {
103
- $c = curl_init($this->getFinalizePaymentRequestUrl($paymentRequestId));
104
-
105
- curl_setopt($c, CURLOPT_HTTPHEADER, $this->getHeaders());
106
- curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
107
- curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
108
- $response = curl_exec($c);
109
- $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);
110
- curl_close($c);
111
112
113
- if ($http_status == '200') {
114
- return json_decode($response);
115
- } else {
116
- return false;
117
- }
118
- }
119
120
- /**
121
- * GET Apruve Payment Status
122
- * Check whether given status is same as in Apruve.com
123
- * @param $status
124
- * @param $apiUrl
125
- * @return bool
126
- */
127
- public function getApruveOrderStatus($apiUrl, $status)
128
- {
129
- $c = curl_init($apiUrl);
130
- curl_setopt($c, CURLOPT_HTTPHEADER, $this->getHeaders());
131
- curl_setopt($c, CURLOPT_CUSTOMREQUEST, "GET");
132
- curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
133
- curl_setopt($c, CURLOPT_HEADER, true);
134
- }
135
-
136
- /**
137
- * Get url for send payment
138
- * @param string $paymentRequestId
139
- * @return string
140
- */
141
- protected function getPaymentUrl($paymentRequestId)
142
- {
143
- return $this->getBaseUrl(true) . $this->getApiUrl() . 'payment_requests/' . $paymentRequestId . '/payments';
144
- }
145
-
146
-
147
- /**
148
- * Get url for update paymentRequest
149
- * @param string $paymentRequestId
150
- * @return string
151
- */
152
- protected function getUpdatePaymentRequestUrl($paymentRequestId)
153
- {
154
- return $this->getBaseUrl(true) . $this->getApiUrl() . 'payment_requests/' . $paymentRequestId;
155
- }
156
-
157
- /**
158
- * Get url for paymentRequest finalizing
159
- * @param string $paymentRequestId
160
- * @return string
161
- */
162
- protected function getFinalizePaymentRequestUrl($paymentRequestId)
163
- {
164
- return $this->getBaseUrl(true) . $this->getApiUrl() . 'payment_requests/' . $paymentRequestId . '/finalize';
165
}
166
}
1
<?php
2
/**
3
+ * Apruve
4
*
5
* NOTICE OF LICENSE
6
*
16
* @package Apruve_Payment
17
* @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
* @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
*/
21
22
/**
27
class Apruve_ApruvePayment_Model_Api_Rest extends Apruve_ApruvePayment_Model_Api_Abstract
28
{
29
/**
30
+ * Executes all the curl requests
31
*
32
+ * @param $curlOptions string[]
33
+ * @return $response string
34
*/
35
+ public function execCurlRequest($url, $method = 'GET', $curlOptions = [])
36
{
37
+ $curl = curl_init();
38
+
39
+ curl_setopt_array($curl, array(
40
+ CURLOPT_URL => $url,
41
+ CURLOPT_RETURNTRANSFER => true,
42
+ CURLOPT_ENCODING => "",
43
+ CURLOPT_MAXREDIRS => 10,
44
+ CURLOPT_TIMEOUT => 30,
45
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
46
+ CURLOPT_CUSTOMREQUEST => $method,
47
+ CURLOPT_HTTPHEADER => $this->getHeaders(),
48
));
49
50
+ curl_setopt_array($curl, $curlOptions);
51
52
+ $response = curl_exec($curl);
53
+ $err = curl_error($curl);
54
+ $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
55
56
+ curl_close($curl);
57
58
+ $result = $this->_prepareResponse($response, $url, $err, $http_status, $curlOptions);
59
+ return $result;
60
}
61
}
app/code/community/Apruve/ApruvePayment/Model/Api/Rest/Invoice.php ADDED
@@ -0,0 +1,246 @@
1
+ <?php
2
+ /**
3
+ * Apruve
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Apache License, Version 2.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/Apache-2.0
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@apruve.com so we can send you a copy immediately.
14
+ *
15
+ * @category Apruve
16
+ * @package Apruve_Payment
17
+ * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
+ */
21
+
22
+ /**
23
+ * Class Apruve_ApruvePayment_Model_Api_Rest_Invoice
24
+ *
25
+ * Provide rest methods to communicate with apruve
26
+ */
27
+ class Apruve_ApruvePayment_Model_Api_Rest_Invoice extends Apruve_ApruvePayment_Model_Api_Rest
28
+ {
29
+ /**
30
+ * Get url for invoice create
31
+ * @param string $apruveOrderId
32
+ * @return string
33
+ */
34
+ protected function _getCreateInvoiceUrl($apruveOrderId)
35
+ {
36
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'orders/' . $apruveOrderId . '/invoices';
37
+ }
38
+
39
+ /**
40
+ * Get url for invoice retrieve
41
+ * @param string $apruveOrderId
42
+ * @return string
43
+ */
44
+ protected function _getInvoiceUrl($apruveInvoiceId)
45
+ {
46
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'invoices/' . $apruveInvoiceId;
47
+ }
48
+
49
+ /**
50
+ * Get url for invoice cancel
51
+ * @param string $apruveOrderId
52
+ * @return string
53
+ */
54
+ protected function _getCancelInvoiceUrl($apruveInvoiceId)
55
+ {
56
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'invoices/' . $apruveInvoiceId . '/cancel';
57
+ }
58
+
59
+ /**
60
+ * Get url for invoice update
61
+ * @param string $apruveOrderId
62
+ * @return string
63
+ */
64
+ protected function _getUpdateInvoiceUrl($apruveInvoiceId)
65
+ {
66
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'invoices/' . $apruveInvoiceId;
67
+ }
68
+
69
+ /**
70
+ * Retrieve an existing invoice by its ID in apruve
71
+ *
72
+ * @param $id string
73
+ * @return $result string
74
+ */
75
+ public function getInvoice($apruveInvoiceId)
76
+ {
77
+ $result = $this->execCurlRequest($this->_getInvoiceUrl($apruveInvoiceId));
78
+ return $result;
79
+ }
80
+
81
+ /**
82
+ * Update Apruve invoice id to it's corresponding invoice in magento
83
+ *
84
+ * @param $id string
85
+ * @param $invoice Mage_Sales_Model_Order_Invoice
86
+ * @return bool
87
+ * @throws Exception
88
+ */
89
+ protected function _updateInvoiceId($apruveInvoiceId, $apruveInvoiceItemIds, $invoice)
90
+ {
91
+ try {
92
+ $apruveInvoiceItemIds = Mage::helper('core')->jsonEncode($apruveInvoiceItemIds);
93
+ $apruveEntity = Mage::getModel('apruvepayment/entity')->loadByInvoiceId($invoice->getIncrementId());
94
+ $apruveEntity->setApruveId($apruveInvoiceId);
95
+ $apruveEntity->setApruveItemId($apruveInvoiceItemIds);
96
+ $apruveEntity->setMagentoId($invoice->getIncrementId());
97
+ $apruveEntity->setEntityType('invoice');
98
+ $apruveEntity->save();
99
+ } catch(Exception $e) {
100
+ Mage::helper('apruvepayment')->logException($e->getMessage());
101
+ Mage::throwException(Mage::helper('apruvepayment')->__('Couldn\'t update invoice.'));
102
+ }
103
+ return true;
104
+ }
105
+
106
+ /**
107
+ * Retrieve the latest comment from magento invoice
108
+ *
109
+ * @param $invoice Mage_Sales_Model_Order_Invoice
110
+ * @return $comment Mage_Sales_Model_Order_Invoice_Comment
111
+ */
112
+ protected function _getInvoiceComment($invoice)
113
+ {
114
+ $comment = Mage::getResourceModel('sales/order_invoice_comment_collection')
115
+ ->setInvoiceFilter($invoice->getId())
116
+ ->setOrder('created_at', 'DESC')
117
+ ->setPageSize(1)
118
+ ->getFirstItem();
119
+
120
+ return $comment;
121
+ }
122
+
123
+ /**
124
+ * Prepare invoice data for Apruve
125
+ *
126
+ * @param $shipment Mage_Sales_Model_Order_Invoice
127
+ * @return $data []
128
+ */
129
+ protected function _getInvoiceData($invoice)
130
+ {
131
+ $invoiceItems = Mage::helper('apruvepayment')->getAllVisibleItems($invoice);
132
+
133
+ $items = [];
134
+ foreach($invoiceItems as $invoiceItem) {
135
+ $orderItem = $invoiceItem->getOrderItem();
136
+ /* create invoice item for apruve */
137
+ $item = [];
138
+ $item['price_ea_cents'] = $this->convertPrice($invoiceItem->getBasePrice());
139
+ $item['quantity'] = $invoiceItem->getQty();
140
+ $item['price_total_cents'] = $this->convertPrice($invoiceItem->getBaseRowTotal());
141
+ $item['currency'] = $this->getCurrency();
142
+ $item['title'] = $invoiceItem->getName();
143
+ $item['merchant_notes'] = $invoiceItem->getAdditionalData();
144
+ $item['description'] = $invoiceItem->getDescription();
145
+ $item['sku'] = $invoiceItem->getSku();
146
+ $item['variant_info'] = $orderItem->getProductOptions();
147
+ $item['vendor'] = $this->getVendor($orderItem);
148
+ /* add invoice item to $items array */
149
+ $items[] = $item;
150
+ }
151
+ // get discount line item
152
+ if(($discountItem = $this->_getDiscountItem($invoice))) {
153
+ $items[] = $discountItem;
154
+ }
155
+
156
+ /* latest shipment comment */
157
+ $comment = $this->_getInvoiceComment($invoice);
158
+
159
+ /* prepare invoice data */
160
+ $data = json_encode([
161
+ 'invoice' => [
162
+ 'amount_cents' => $this->convertPrice($invoice->getBaseGrandTotal()),
163
+ 'currency' => $this->getCurrency(),
164
+ 'shipping_cents' => $this->convertPrice($invoice->getBaseShippingAmount()),
165
+ 'tax_cents' => $this->convertPrice($invoice->getBaseTaxAmount()),
166
+ 'merchant_notes' => $comment->getComment(),
167
+ 'merchant_invoice_id' => $invoice->getIncrementId(),
168
+ //'due_at' => '2016-06-01T13:54:21Z',
169
+ 'invoice_items' => $items,
170
+ 'issue_on_create' => true
171
+ ]
172
+ ]);
173
+
174
+ return $data;
175
+ }
176
+
177
+ /**
178
+ * Create new invoice in Apruve for an order based on invoice created in Magento
179
+ *
180
+ * @param $apruveOrderId string
181
+ * @return $result string[]
182
+ */
183
+ public function createInvoice($apruveOrderId, $invoice)
184
+ {
185
+ $data = $this->_getInvoiceData($invoice);
186
+
187
+ $curlOptions = [];
188
+ $curlOptions[CURLOPT_POSTFIELDS] = $data;
189
+
190
+ $result = $this->execCurlRequest($this->_getCreateInvoiceUrl($apruveOrderId), 'POST', $curlOptions);
191
+ $apruveInvoiceId = isset($result['response']['id']) ? $result['response']['id'] : '';
192
+ $apruveInvoiceItemIds = isset($result['response']['invoice_items']) ? $result['response']['invoice_items'] : '';
193
+ if($result['success'] == true) {
194
+ $this->_updateInvoiceId($apruveInvoiceId, $apruveInvoiceItemIds, $invoice);
195
+ }
196
+
197
+ return $result;
198
+ }
199
+
200
+ /**
201
+ * Update an existing invoice in Apruve
202
+ *
203
+ * @param $id string
204
+ * @return $result string
205
+ */
206
+ public function updateInvoice($apruveInvoiceId, $invoice)
207
+ {
208
+ $data = $this->_getInvoiceData($invoice);
209
+
210
+ $curlOptions = [];
211
+ $curlOptions[CURLOPT_POSTFIELDS] = $data;
212
+
213
+ $result = $this->execCurlRequest($this->_getUpdateInvoiceUrl($apruveInvoiceId), 'PUT', $curlOptions);
214
+
215
+ return $result;
216
+ }
217
+
218
+ /**
219
+ * Retrieve an existing invoice item IDS based on its ID in apruve
220
+ *
221
+ * @param $id string
222
+ * @return $result string
223
+ */
224
+ public function getInvoiceItemIds($apruveInvoiceId)
225
+ {
226
+ $invoice = $this->getInvoice($apruveInvoiceId);
227
+ $invoiceArray = json_decode($invoice);
228
+ $items = [];
229
+ foreach($invoiceArray['invoice_items'] as $item) {
230
+ $items[] = $item['id'];
231
+ }
232
+ return $items;
233
+ }
234
+
235
+ /**
236
+ * cancel an existing invoice by its ID in apruve
237
+ *
238
+ * @param $id string
239
+ * @return $result string
240
+ */
241
+ public function cancelInvoice($apruveInvoiceId)
242
+ {
243
+ $result = $this->execCurlRequest($this->_getCancelInvoiceUrl($apruveInvoiceId), 'POST');
244
+ return $result;
245
+ }
246
+ }
app/code/community/Apruve/ApruvePayment/Model/Api/Rest/Order.php ADDED
@@ -0,0 +1,187 @@
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Apache License, Version 2.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/Apache-2.0
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@apruve.com so we can send you a copy immediately.
14
+ *
15
+ * @category Apruve
16
+ * @package Apruve_Payment
17
+ * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ */
20
+
21
+ /**
22
+ * Class Apruve_ApruvePayment_Model_Api_Rest_Order
23
+ *
24
+ * Provide rest methods to communicate with apruve
25
+ */
26
+ class Apruve_ApruvePayment_Model_Api_Rest_Order extends Apruve_ApruvePayment_Model_Api_Rest
27
+ {
28
+ /**
29
+ * Get url order url
30
+ * @param string $apruveOrderId
31
+ * @return string
32
+ */
33
+ protected function _getOrderUrl($apruveOrderId)
34
+ {
35
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'orders/' . $apruveOrderId;
36
+ }
37
+
38
+
39
+ /**
40
+ * Get url for update order
41
+ * @param string $apruveOrderId
42
+ * @return string
43
+ */
44
+ protected function _getUpdateOrderUrl($apruveOrderId)
45
+ {
46
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'orders/' . $apruveOrderId;
47
+ }
48
+
49
+ /**
50
+ * Get url for order finalizing
51
+ * @param string $apruveOrderId
52
+ * @return string
53
+ */
54
+ protected function _getFinalizeOrderUrl($apruveOrderId)
55
+ {
56
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'orders/' . $apruveOrderId . '/finalize';
57
+ }
58
+
59
+ /**
60
+ * Get url for order cancel
61
+ * @param string $apruveOrderId
62
+ * @return string
63
+ */
64
+ protected function _getCancelOrderUrl($apruveOrderId)
65
+ {
66
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'orders/' . $apruveOrderId . '/cancel';
67
+ }
68
+
69
+ /**
70
+ * Retrieve an existing order by its ID in apruve
71
+ *
72
+ * @param $id string
73
+ * @return $result string
74
+ */
75
+ public function getOrder($apruveOrderId)
76
+ {
77
+ $result = $this->execCurlRequest($this->_getOrderUrl($apruveOrderId));
78
+ return $result;
79
+ }
80
+
81
+ /**
82
+ * Update Apruve order id to it's corresponding order in magento
83
+ *
84
+ * @param $id string
85
+ * @param $order Mage_Sales_Model_Order
86
+ * @return bool
87
+ * @throws Mage_Core_Exception
88
+ */
89
+ protected function _updateOrderId($apruveOrderId, $order)
90
+ {
91
+ try {
92
+ $apruveEntity = Mage::getModel('apruvepayment/entity')->loadByOrderId($order->getIncrementId());
93
+ $apruveEntity->setApruveId($apruveOrderId);
94
+ $apruveEntity->setMagentoId($order->getIncrementId());
95
+ $apruveEntity->setEntityType('order');
96
+ $apruveEntity->save();
97
+ } catch(Exception $e) {
98
+ Mage::helper('apruvepayment')->logException('Couldn\'t update the order: ' . $e->getMessage());
99
+ Mage::throwException(Mage::helper('apruvepayment')->__('Couldn\'t update order.'));
100
+ }
101
+ return true;
102
+ }
103
+
104
+ /**
105
+ * Update an existing order by its ID in apruve
106
+ *
107
+ * @param string $apruveOrderId
108
+ * @param Mage_Sales_Model_Order $order
109
+ * @return string $result
110
+ */
111
+ public function updateOrder($apruveOrderId, $order)
112
+ {
113
+ $lineItems = [];
114
+ // get discount line item
115
+ if(($discountItem = $this->_getDiscountItem($order))) {
116
+ $lineItems[] = $discountItem;
117
+ }
118
+
119
+ $data = json_encode(array(
120
+ 'order' => array(
121
+ 'merchant_order_id' => $order->getIncrementId(),
122
+ 'amount_cents' => $this->convertPrice($order->getBaseGrandTotal()),
123
+ 'shipping_cents' => $this->convertPrice($order->getBaseShippingAmount()),
124
+ 'tax_cents' => $this->convertPrice($order->getBaseTaxAmount()),
125
+ 'invoice_on_create' => 'false',
126
+ 'order_items' => $lineItems
127
+ )
128
+ ));
129
+
130
+ $curlOptions = [];
131
+ $curlOptions[CURLOPT_POSTFIELDS] = $data;
132
+
133
+ $result = $this->execCurlRequest($this->_getUpdateOrderUrl($apruveOrderId), 'PUT', $curlOptions);
134
+ if($result['success'] == true) {
135
+ Mage::helper('apruvepayment')->logException('Order updated successfully...');
136
+ $this->_updateOrderId($apruveOrderId, $order);
137
+ }
138
+ return $result;
139
+ }
140
+
141
+ /**
142
+ * Get order from quote
143
+ *
144
+ * @param $quote Mage_Sales_Model_Quote
145
+ * @return $order Mage_Sales_Model_Order
146
+ * @throws Mage_Core_Exception
147
+ */
148
+ protected function _getOrderFromQuote($quote)
149
+ {
150
+ $orderIncrementId = $quote->getReservedOrderId();
151
+ $order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
152
+ if(!$order->getId()) {
153
+ Mage::throwException(Mage::helper('apruvepayment')->__('Couldn\'t load the order.'));
154
+ }
155
+ return $order;
156
+ }
157
+
158
+ /**
159
+ * Finalize an existing order by its ID in apruve
160
+ *
161
+ * @param $apruveOrderId string
162
+ * @param $order Mage_Sales_Model_Order
163
+ * @return $result string
164
+ */
165
+ public function finalizeOrder($apruveOrderId, $order)
166
+ {
167
+ $result = $this->execCurlRequest($this->_getFinalizeOrderUrl($apruveOrderId), 'POST');
168
+ if($result['success'] == true) {
169
+ $this->_updateOrderId($apruveOrderId, $order);
170
+ Mage::helper('apruvepayment')->logException('Order finalized successfully...');
171
+ }
172
+
173
+ return $result;
174
+ }
175
+
176
+ /**
177
+ * Cancel an existing order by its ID in apruve
178
+ *
179
+ * @param $id string
180
+ * @return $result string
181
+ */
182
+ public function cancelOrder($apruveOrderId)
183
+ {
184
+ $result = $this->execCurlRequest($this->_getCancelOrderUrl($apruveOrderId), 'POST');
185
+ return $result;
186
+ }
187
+ }
app/code/community/Apruve/ApruvePayment/Model/Api/Rest/Shipment.php ADDED
@@ -0,0 +1,214 @@
1
+ <?php
2
+ /**
3
+ * Apruve
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Apache License, Version 2.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/Apache-2.0
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@apruve.com so we can send you a copy immediately.
14
+ *
15
+ * @category Apruve
16
+ * @package Apruve_Payment
17
+ * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
+ */
21
+
22
+ /**
23
+ * Class Apruve_ApruvePayment_Model_Api_Rest_Shipment
24
+ *
25
+ * Provide rest methods to communicate with apruve
26
+ */
27
+ class Apruve_ApruvePayment_Model_Api_Rest_Shipment extends Apruve_ApruvePayment_Model_Api_Rest
28
+ {
29
+ /**
30
+ * Get url for shipment create
31
+ * @param string $apruveInvoiceId
32
+ * @return string
33
+ */
34
+ protected function _getCreateShipmentUrl($apruveInvoiceId)
35
+ {
36
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'invoices/' . $apruveInvoiceId . '/shipments';
37
+ }
38
+
39
+ /**
40
+ * Get url for shipment retrieve
41
+ * @param string $apruveInvoiceId
42
+ * @param string $apruveShipmentId
43
+ * @return string
44
+ */
45
+ protected function _getShipmentUrl($apruveInvoiceId, $apruveShipmentId)
46
+ {
47
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'invoices/' . $apruveInvoiceId . '/shipments/' . $apruveShipmentId;
48
+ }
49
+
50
+ /**
51
+ * Get url for shipment update
52
+ * @param string $apruveInvoiceId
53
+ * @param string $apruveShipmentId
54
+ * @return string
55
+ */
56
+ protected function _getUpdateShipmentUrl($apruveInvoiceId, $apruveShipmentId)
57
+ {
58
+ return $this->getBaseUrl(true) . $this->getApiUrl() . 'invoices/' . $apruveInvoiceId . '/shipments/' . $apruveShipmentId;
59
+ }
60
+
61
+ /**
62
+ * Retrieve an existing shipment by its ID in apruve
63
+ *
64
+ * @param $id string
65
+ * @return $result string
66
+ */
67
+ public function getShipment($apruveInvoiceId, $apruveShipmentId)
68
+ {
69
+ $result = $this->execCurlRequest($this->_getShipmentUrl($apruveInvoiceId, $apruveShipmentId));
70
+ return $result;
71
+ }
72
+
73
+ /**
74
+ * Retrieve the latest comment from magento shipment
75
+ *
76
+ * @param $shipment Mage_Sales_Model_Order_Shipment
77
+ * @return $comment Mage_Sales_Model_Order_Shipment_Comment
78
+ */
79
+ protected function _getShipmentComment($shipment)
80
+ {
81
+ $comment = Mage::getResourceModel('sales/order_shipment_comment_collection')
82
+ ->setShipmentFilter($shipment->getId())
83
+ ->setOrder('created_at', 'DESC')
84
+ ->setPageSize(1)
85
+ ->getFirstItem();
86
+
87
+ return $comment;
88
+ }
89
+
90
+ /**
91
+ * Retrieve the latest tracking info from magento shipment
92
+ *
93
+ * @param $shipment Mage_Sales_Model_Order_Shipment
94
+ * @return $comment Mage_Sales_Model_Order_Shipment_Track
95
+ */
96
+ protected function _getShipmentTrack($shipment)
97
+ {
98
+ $track = Mage::getResourceModel('sales/order_shipment_track_collection')
99
+ ->setShipmentFilter($shipment->getId())
100
+ ->setOrder('updated_at', 'DESC')
101
+ ->setPageSize(1)
102
+ ->getFirstItem();
103
+
104
+ return $track;
105
+ }
106
+
107
+ /**
108
+ * Prepare shipment data for Apruve
109
+ *
110
+ * @param $shipment Mage_Sales_Model_Order_Shipment
111
+ * @param $invoice Mage_Sales_Model_Order_Invoice
112
+ * @return $data []
113
+ */
114
+ protected function _getShipmentData($shipment, $invoice)
115
+ {
116
+ $items = [];
117
+
118
+ foreach ($shipment->getAllItems() as $item) {
119
+ $shipmentItem = [];
120
+ $shipmentItem['price_total_cents'] = $this->convertPrice($item->getPriceInclTax() * $item->getQty());
121
+ $shipmentItem['tax_cents'] = $this->convertPrice($item->getTaxAmount());
122
+ $shipmentItem['description'] = $item->getDescription();
123
+ $shipmentItem['title'] = $item->getName();
124
+ $shipmentItem['sku'] = $item->getSku();
125
+ $shipmentItem['price_ea_cents'] = $this->convertPrice($item->getPrice());
126
+ $shipmentItem['quantity'] = $item->getQty();
127
+ $items[] = $shipmentItem;
128
+ }
129
+
130
+ /* latest shipment comment */
131
+ $comment = $this->_getShipmentComment($shipment);
132
+ /* latest shipment tracking */
133
+ $trackingInfo = $this->_getShipmentTrack($shipment);
134
+ /* prepare invoice data */
135
+ $data = json_encode([
136
+ 'amount_cents' => $this->convertPrice($invoice->getBaseGrandTotal()),
137
+ 'tax_cents' => $this->convertPrice($invoice->getTaxAmount()),
138
+ 'shipping_cents' => $this->convertPrice($invoice->getShippingAmount()),
139
+ 'shipper' => $trackingInfo->getTitle(),
140
+ 'tracking_number' => $trackingInfo->getTrackNumber(),
141
+ 'shipped_at' => $this->getDateFormatted($trackingInfo->getCreatedAt()),
142
+ 'delivered_at' => '',
143
+ 'currency' => $this->getCurrency(),
144
+ 'merchant_notes' => $comment->getComment(),
145
+ 'shipment_items' => $items,
146
+ 'status' => 'FULFILLED'
147
+ ]);
148
+
149
+ return $data;
150
+ }
151
+
152
+ /**
153
+ * Update Apruve shipment id to it's corresponding shipment in magento
154
+ *
155
+ * @param $id string
156
+ * @param $shipment Mage_Sales_Model_Order_Shipment
157
+ * @return bool
158
+ * @throws Exception
159
+ */
160
+ protected function _updateShipmentId($apruveShipmentId, $shipment)
161
+ {
162
+ try {
163
+ $apruveEntity = Mage::getModel('apruvepayment/entity')->loadByShipmentId($shipment->getIncrementId(), 'magento_id');
164
+ $apruveEntity->setApruveId($apruveShipmentId);
165
+ $apruveEntity->setMagentoId($shipment->getIncrementId());
166
+ $apruveEntity->setEntityType('shipping');
167
+ $apruveEntity->save();
168
+ } catch(Exception $e) {
169
+ Mage::helper('apruvepayment')->logException($e->getMessage());
170
+ Mage::throwException(Mage::helper('apruvepayment')->__('Couldn\'t update shipment.'));
171
+ }
172
+ return true;
173
+ }
174
+
175
+ /**
176
+ * Create new shipment in Apruve for an invoice based on shipment created in Magento
177
+ *
178
+ * @param string $apruveInvoiceId
179
+ * @param Mage_Sales_Model_Order_Shipment $shipment
180
+ * @param Mage_Sales_Model_Order_Invoice $invoice
181
+ * @return $result string[]
182
+ */
183
+ public function createShipment($apruveInvoiceId, $shipment, $invoice)
184
+ {
185
+ $data = $this->_getShipmentData($shipment, $invoice);
186
+
187
+ $curlOptions = [];
188
+ $curlOptions[CURLOPT_POSTFIELDS] = $data;
189
+
190
+ $result = $this->execCurlRequest($this->_getCreateShipmentUrl($apruveInvoiceId), 'POST', $curlOptions);
191
+ $apruveShipmentId = isset($result['response']['id']) ? $result['response']['id'] : '';
192
+ if($result['success'] == true) {
193
+ $this->_updateShipmentId($apruveShipmentId, $shipment);
194
+ }
195
+ return $result;
196
+ }
197
+
198
+ /**
199
+ * Create new invoice in Apruve for an order based on invoice created in Magento
200
+ *
201
+ * @param $id string
202
+ * @return $result string
203
+ */
204
+ public function updateShipment($apruveInvoiceId, $apruveShipmentId, $shipment, $invoice)
205
+ {
206
+ $data = $this->_getShipmentData($shipment, $invoice);
207
+
208
+ $curlOptions = [];
209
+ $curlOptions[CURLOPT_POSTFIELDS] = $data;
210
+
211
+ $result = $this->execCurlRequest($this->_getUpdateShipmentUrl($apruveInvoiceId, $apruveShipmentId), 'PUT', $curlOptions);
212
+ return $result;
213
+ }
214
+ }
app/code/community/Apruve/ApruvePayment/Model/Entity.php ADDED
@@ -0,0 +1,97 @@
1
+ <?php
2
+ /**
3
+ * Apruve
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Apache License, Version 2.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/Apache-2.0
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@apruve.com so we can send you a copy immediately.
14
+ *
15
+ * @category Apruve
16
+ * @package Apruve_Payment
17
+ * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
+ */
21
+
22
+ /**
23
+ * Model to access apruve object ids stored in magento
24
+ */
25
+ class Apruve_ApruvePayment_Model_Entity extends Mage_Core_Model_Abstract
26
+ {
27
+ protected function _construct()
28
+ {
29
+ $this->_init('apruvepayment/entity');
30
+ }
31
+
32
+ /**
33
+ * Get the order item from apruve_entity table based on order id
34
+ *
35
+ * @param string $id
36
+ * @return Apruve_ApruvePayment_Model_Entity
37
+ */
38
+ public function loadByOrderId($id)
39
+ {
40
+ $itemsData = $this->getCollection()->addFieldToFilter('magento_id', $id)->addFieldToFilter('entity_type', 'order')->setPageSize(1)->getData();
41
+ if(isset($itemsData[0])) {
42
+ $this->setData($itemsData[0]);
43
+ }
44
+ return $this;
45
+ }
46
+
47
+ /**
48
+ * Get the invoice item from apruve_entity table based on invoice id
49
+ *
50
+ * @param string $id
51
+ * @return Apruve_ApruvePayment_Model_Entity
52
+ */
53
+ public function loadByInvoiceId($id)
54
+ {
55
+ $itemsData = $this->getCollection()->addFieldToFilter('magento_id', $id)->addFieldToFilter('entity_type', 'invoice')->setPageSize(1)->getData();
56
+ if(isset($itemsData[0])) {
57
+ $this->setData($itemsData[0]);
58
+ }
59
+ return $this;
60
+ }
61
+
62
+ /**
63
+ * Get the shipment item from apruve_entity table based on shipment id
64
+ *
65
+ * @param string $id
66
+ * @return Apruve_ApruvePayment_Model_Entity
67
+ */
68
+ public function loadByShipmentId($id)
69
+ {
70
+ $itemsData = $this->getCollection()->addFieldToFilter('magento_id', $id)->addFieldToFilter('entity_type', 'shipment')->setPageSize(1)->getData();
71
+ if(isset($itemsData[0])) {
72
+ $this->setData($itemsData[0]);
73
+ }
74
+ return $this;
75
+ }
76
+
77
+ /**
78
+ * Retrieve only the apruve item ids in an array
79
+ *
80
+ * @return []|bool
81
+ */
82
+ public function getItemIds()
83
+ {
84
+ if($this->getId()) {
85
+ $items = Mage::helper('core')->jsonDecode($this->getApruveItemId());
86
+
87
+ $itemIds = [];
88
+ foreach ($items as $item) {
89
+ $itemIds[] = ['id' => $item['id']];
90
+ }
91
+
92
+ return $itemIds;
93
+ }
94
+ return false;
95
+ }
96
+
97
+ }
app/code/community/Apruve/ApruvePayment/Model/Mode.php CHANGED
@@ -1,32 +1,26 @@
1
<?php
2
/**
3
- * Magento
4
*
5
* NOTICE OF LICENSE
6
*
7
- * This source file is subject to the Open Software License (OSL 3.0)
8
* that is bundled with this package in the file LICENSE.txt.
9
* It is also available through the world-wide-web at this URL:
10
- * http://opensource.org/licenses/osl-3.0.php
11
* If you did not receive a copy of the license and are unable to
12
* obtain it through the world-wide-web, please send an email
13
- * to license@magentocommerce.com so we can send you a copy immediately.
14
*
15
- * DISCLAIMER
16
*
17
- * Do not edit or add to this file if you wish to upgrade Magento to newer
18
- * versions in the future. If you wish to customize Magento for your
19
- * needs please refer to http://www.magentocommerce.com for more information.
20
- *
21
- * @category Mage
22
- * @package Mage_Adminhtml
23
- * @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
24
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
*/
26
27
/**
28
* Used in creating options for Yes|No config value selection
29
- *
30
*/
31
class Apruve_ApruvePayment_Model_Mode
32
{
@@ -57,18 +51,4 @@ class Apruve_ApruvePayment_Model_Mode
57
2 => Mage::helper('apruvepayment')->__('staging'),
58
);
59
}
60
-
61
- /**
62
- * Get options' src urls in "key-value" format
63
- *
64
- * @return array
65
- */
66
- public function toSrcArray()
67
- {
68
- return array(
69
- 0 => "https://app.apruve.com/js/apruve.js?display=compact",
70
- 1 => "https://test.apruve.com/js/apruve.js?display=compact",
71
- );
72
- }
73
-
74
}
1
<?php
2
/**
3
+ * Apruve
4
*
5
* NOTICE OF LICENSE
6
*
7
+ * This source file is subject to the Apache License, Version 2.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/Apache-2.0
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@apruve.com so we can send you a copy immediately.
14
*
15
+ * @category Apruve
16
+ * @package Apruve_Payment
17
+ * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
*
20
*/
21
22
/**
23
* Used in creating options for Yes|No config value selection
24
*/
25
class Apruve_ApruvePayment_Model_Mode
26
{
51
2 => Mage::helper('apruvepayment')->__('staging'),
52
);
53
}
54
}
app/code/community/Apruve/ApruvePayment/Model/Mysql4/Setup.php DELETED
@@ -1,6 +0,0 @@
1
- <?php
2
-
3
- class Apruve_ApruvePayment_Model_Mysql4_Setup extends Mage_Catalog_Model_Resource_Eav_Mysql4_Setup
4
- {
5
-
6
- }
app/code/community/Apruve/ApruvePayment/Model/Observer.php CHANGED
@@ -1,24 +1,270 @@
1
<?php
2
3
class Apruve_ApruvePayment_Model_Observer
4
{
5
6
- public function finalizePayment($observer)
7
{
8
- /** @var Mage_Sales_Model_Quote $quote */
9
- $quote = $observer->getQuote();
10
- $payment = $quote->getPayment();
11
- if ($quote->getIsMultiShipping()
12
- && $payment->getMethod() == 'apruvepayment'
13
) {
14
- $additionalInformation = $payment->getAdditionalInformation();
15
- $token = $additionalInformation['aprt'];
16
- if ($token) {
17
- /** @var Apruve_ApruvePayment_Model_Api_Rest $apiHelper */
18
- $apiHelper = Mage::getModel('apruvepayment/api_rest');
19
- $apiHelper->finalizePaymentRequest($token);
20
}
21
}
22
}
23
24
}
1
<?php
2
+ /**
3
+ * Apruve
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Apache License, Version 2.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/Apache-2.0
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@apruve.com so we can send you a copy immediately.
14
+ *
15
+ * @category Apruve
16
+ * @package Apruve_Payment
17
+ * @copyright Copyright (coffee) 2014 Apruve, Inc. (http://www.apruve.com).
18
+ * @license http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
19
+ *
20
+ */
21
22
+ /**
23
+ * This is an observer created to be triggered based on Magento's event
24
+ * to update Apruve using Apruve's API calls.
25
+ */
26
class Apruve_ApruvePayment_Model_Observer
27
{
28
+ /**
29
+ * Get order and payment objects from observer
30
+ *
31
+ * @param Varien_Event_Observer $observer
32
+ * @return []
33
+ */
34
+ protected function _getOrderInfo($observer)
35
+ {
36
+ $order = null;
37
+ $payment = null;
38
+
39
+ if ($order = $observer->getEvent()->getOrder()) {
40
+ $payment = $order->getPayment();
41
+ } elseif ($orders = $observer->getEvent()->getOrders()) {
42
+ if ($order = array_shift($orders)) {
43
+ $payment = $order->getPayment();
44
+ }
45
+ }
46
+ return array($order, $payment);
47
+ }
48
+
49
+ /**
50
+ * Finalize the order in Apruve
51
+ *
52
+ * @param Varien_Event_Observer $observer
53
+ * @return void
54
+ */
55
+ public function finalizeOrder($observer)
56
+ {
57
+ list($order, $payment) = $this->_getOrderInfo($observer);
58
+
59
+ if ($payment->getMethod() == Apruve_ApruvePayment_Model_PaymentMethod::PAYMENT_METHOD_CODE) {
60
+ try {
61
+ /**
62
+ * @var Apruve_ApruvePayment_Helper_Data $apiVersion
63
+ */
64
+ $apiVersion = Mage::helper('apruvepayment')->getApiVersion();
65
+ $additionalInformation = $payment->getAdditionalInformation();
66
+ $token = $additionalInformation['aprt'];
67
+ if ($token && !$order->getApruveOrderId()) {
68
+ /**
69
+ * @var Apruve_ApruvePayment_Model_Api_Rest_Order $orderApi
70
+ */
71
+ $orderApi = Mage::getModel('apruvepayment/api_rest_order');
72
+ $result = $orderApi->finalizeOrder($token, $order);
73
+ if(!$result || !$result['success']) {
74
+ Mage::throwException($result['message']);
75
+ }
76
+ }
77
+ } catch(Exception $e) {
78
+ Mage::throwException($e->getMessage());
79
+ }
80
+ }
81
+
82
+ }
83
84
+ /**
85
+ * Cancel the order in Apruve
86
+ *
87
+ * @param Varien_Event_Observer $observer
88
+ * @return void
89
+ */
90
+ public function cancelOrder($observer)
91
{
92
+ /**
93
+ * @var Mage_Sales_Model_Order $order
94
+ */
95
+ list($order, $payment) = $this->_getOrderInfo($observer);
96
+
97
+ if ($order->getId() && $payment->getMethod() == Apruve_ApruvePayment_Model_PaymentMethod::PAYMENT_METHOD_CODE) {
98
+ $apruveEntity = Mage::getModel('apruvepayment/entity')->loadByOrderId($order->getIncrementId(), 'magento_id');
99
+ $apruveOrderId = $apruveEntity->getApruveId();
100
+
101
+ /**
102
+ * @var Apruve_ApruvePayment_Model_Api_Rest_Order $orderApi
103
+ */
104
+ $orderApi = Mage::getModel('apruvepayment/api_rest_order');
105
+ $result = $orderApi->cancelOrder($apruveOrderId);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Create invoice in Apruve
111
+ *
112
+ * @param Varien_Event_Observer $observer
113
+ * @return void
114
+ */
115
+ public function createInvoice($observer)
116
+ {
117
+ $invoice = $observer->getEvent()->getInvoice();
118
+
119
+ /**
120
+ * @var Mage_Sales_Model_Order $order
121
+ */
122
+ $order = $invoice->getOrder();
123
+ $payment = $order->getPayment();
124
+
125
+ if ($order->getId() && $invoice->getIncrementId()
126
+ && $payment->getMethod() == Apruve_ApruvePayment_Model_PaymentMethod::PAYMENT_METHOD_CODE
127
) {
128
+ /**
129
+ * @var Apruve_ApruvePayment_Model_Api_Rest_Invoice $invoiceApi
130
+ */
131
+ $invoiceApi = Mage::getModel('apruvepayment/api_rest_invoice');
132
+
133
+ $apruveEntity = Mage::getModel('apruvepayment/entity')->loadByInvoiceId($invoice->getIncrementId());
134
+ $apruveInvoiceId = $apruveEntity->getApruveId();
135
+ if($apruveInvoiceId && $invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_CANCELED) {
136
+ $result = $invoiceApi->updateInvoice($apruveInvoiceId, $invoice);
137
+ } elseif($apruveInvoiceId && $invoice->getState() == Mage_Sales_Model_Order_Invoice::STATE_CANCELED) {
138
+ $result = $invoiceApi->cancelInvoice($apruveInvoiceId);
139
+ } else {
140
+ $apruveEntity = Mage::getModel('apruvepayment/entity')->loadByOrderId($order->getIncrementId());
141
+ $apruveOrderId = $apruveEntity->getApruveId();
142
+ $result = $invoiceApi->createInvoice($apruveOrderId, $invoice);
143
+ }
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Get Apruve Invoice from the shipment for an order in magento
149
+ *
150
+ * @param Mage_Sales_Model_Order_Shipment $shipment
151
+ * @return Mage_Sales_Model_Order_Invoice
152
+ */
153
+ protected function _getInvoiceFromShipment($shipment)
154
+ {
155
+ $order = $shipment->getOrder();
156
+
157
+ $shipmentDetails = [];
158
+ foreach ($shipment->getAllItems() as $item) {
159
+ $shipmentDetails[$item->getSku()] = $item->getQty();
160
+ }
161
+
162
+ $hasInvoices = $order->hasInvoices();
163
+ $invoices = $order->getInvoiceCollection();
164
+
165
+ /* if only one invoice is there then return it's apruve id */
166
+ if($hasInvoices && $invoices->getSize() == 1) {
167
+ return $invoices->getFirstItem();
168
+ } elseif($hasInvoices) {
169
+ /* if order has more invoices we have to s