Signifyd_Connect - Version 3.15.0

Version Notes

Supports all versions of Magento

Download this release

Release Info

Developer signifyd
Extension Signifyd_Connect
Version 3.15.0
Comparing to
See all releases


Code changes from version 3.13.1 to 3.15.0

Files changed (65) hide show
  1. app/code/community/Signifyd/Connect/Block/Adminhtml/Sales/Order.php +13 -13
  2. app/code/community/Signifyd/Connect/Block/Adminhtml/Sales/Order/Grid.php +134 -134
  3. app/code/community/Signifyd/Connect/Block/Renderer.php +28 -28
  4. app/code/community/Signifyd/Connect/Block/Url.php +10 -0
  5. app/code/community/Signifyd/Connect/Helper/Data.php +790 -794
  6. app/code/community/Signifyd/Connect/Helper/Log.php +25 -0
  7. app/code/community/Signifyd/Connect/Model/Authnet.php +17 -17
  8. app/code/community/Signifyd/Connect/Model/Case.php +29 -10
  9. app/code/community/Signifyd/Connect/Model/Cron.php +136 -9
  10. app/code/community/Signifyd/Connect/Model/Link.php +9 -9
  11. app/code/community/Signifyd/Connect/Model/Observer.php +299 -316
  12. app/code/community/Signifyd/Connect/Model/Order.php +412 -0
  13. app/code/community/Signifyd/Connect/Model/Order/Payment.php +29 -0
  14. app/code/community/Signifyd/Connect/Model/Resource/Case.php +10 -10
  15. app/code/community/Signifyd/Connect/Model/Resource/Case/Collection.php +9 -9
  16. app/code/community/Signifyd/Connect/Model/Resource/Retries.php +10 -10
  17. app/code/community/Signifyd/Connect/Model/Resource/Retries/Collection.php +9 -9
  18. app/code/community/Signifyd/Connect/Model/Retries.php +10 -10
  19. app/code/community/Signifyd/Connect/Model/Setup.php +53 -53
  20. app/code/community/Signifyd/Connect/Model/System/Config/Source/Options/Accepted.php +19 -0
  21. app/code/community/Signifyd/Connect/Model/System/Config/Source/Options/Declined.php +19 -0
  22. app/code/community/Signifyd/Connect/Model/System/Config/Source/Options/Negative.php +0 -22
  23. app/code/community/Signifyd/Connect/Model/System/Config/Source/Options/Positive.php +0 -18
  24. app/code/community/Signifyd/Connect/controllers/Adminhtml/SignifydController.php +22 -27
  25. app/code/community/Signifyd/Connect/controllers/ConnectController.php +523 -593
  26. app/code/community/Signifyd/Connect/etc/adminhtml.xml +16 -16
  27. app/code/community/Signifyd/Connect/etc/config.xml +214 -199
  28. app/code/community/Signifyd/Connect/etc/system.xml +133 -222
  29. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.1.1.php +13 -13
  30. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.12.0.php +26 -26
  31. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.3.0.php +19 -19
  32. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.4.0.php +21 -21
  33. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.4.5.php +21 -21
  34. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.7.0.php +18 -18
  35. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-install-3.8.0.php +19 -19
  36. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.10.0-3.10.1.php +8 -8
  37. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.10.1-3.11.0.php +8 -8
  38. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.11.0-3.11.1.php +8 -8
  39. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.11.1-3.12.0.php +17 -17
  40. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.12.0-3.13.0.php +15 -15
  41. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.14.0-3.15.0.php +10 -0
  42. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.2.0-3.2.1.php +5 -5
  43. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.2.1-3.2.2.php +17 -17
  44. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.2.2-3.2.3.php +8 -8
  45. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.2.3-3.3.0.php +10 -10
  46. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.3.0-3.4.0.php +11 -11
  47. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.0-3.4.1.php +10 -10
  48. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.1-3.4.2.php +8 -8
  49. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.2-3.4.3.php +8 -8
  50. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.3-3.4.4.php +8 -8
  51. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.4-3.4.5.php +13 -13
  52. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.5-3.4.6.php +8 -8
  53. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.6-3.4.7.php +8 -8
  54. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.7-3.4.8.php +8 -8
  55. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.4.8-3.5.0.php +8 -8
  56. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.5.0-3.5.1.php +8 -8
  57. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.5.1-3.5.2.php +8 -8
  58. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.5.2-3.5.3.php +8 -8
  59. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.5.3-3.6.0.php +8 -8
  60. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.6.0-3.7.0.php +31 -31
  61. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.7.0-3.8.0.php +10 -10
  62. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.8.0-3.9.0.php +8 -8
  63. app/code/community/Signifyd/Connect/sql/signifyd_connect_setup/mysql4-upgrade-3.9.0-3.10.0.php +8 -8
  64. app/etc/modules/Signifyd_Connect.xml +9 -9
  65. package.xml +6 -6
app/code/community/Signifyd/Connect/Block/Adminhtml/Sales/Order.php CHANGED
@@ -1,13 +1,13 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Block_Adminhtml_Sales_Order extends Mage_Adminhtml_Block_Widget_Grid_Container
4
- {
5
- public function __construct()
6
- {
7
- $this->_blockGroup = 'signifyd_connect';
8
- $this->_controller = 'adminhtml_sales_order';
9
- $this->_headerText = Mage::helper('signifyd_connect')->__('Signifyd Scores');
10
- parent::__construct();
11
- $this->_removeButton('add');
12
- }
13
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Block_Adminhtml_Sales_Order extends Mage_Adminhtml_Block_Widget_Grid_Container
4
+ {
5
+ public function __construct()
6
+ {
7
+ $this->_blockGroup = 'signifyd_connect';
8
+ $this->_controller = 'adminhtml_sales_order';
9
+ $this->_headerText = Mage::helper('signifyd_connect')->__('Signifyd Scores');
10
+ parent::__construct();
11
+ $this->_removeButton('add');
12
+ }
13
+ }
app/code/community/Signifyd/Connect/Block/Adminhtml/Sales/Order/Grid.php CHANGED
@@ -1,134 +1,134 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Widget_Grid
4
- {
5
- public function __construct()
6
- {
7
- parent::__construct();
8
- $this->setId('signifyd_connect_grid');
9
- $this->setDefaultSort('increment_id');
10
- $this->setDefaultDir('DESC');
11
- $this->setSaveParametersInSession(true);
12
- $this->setUseAjax(true);
13
- }
14
-
15
- public function oldSupport()
16
- {
17
- $model = Mage::getSingleton('signifyd_connect/observer');
18
-
19
- return $model->oldSupport();
20
- }
21
-
22
- protected function _prepareCollection()
23
- {
24
- $collection = Mage::getResourceModel('sales/order_collection');
25
-
26
- if ($this->oldSupport()) {
27
- $collection->getSelect()->joinLeft(
28
- array('signifyd' => Mage::getSingleton('core/resource')->getTableName('signifyd_connect_case')),
29
- 'signifyd.order_increment = e.increment_id',
30
- array(
31
- 'score' => 'score',
32
- )
33
- );
34
- } else {
35
- $collection->addExpressionFieldToSelect(
36
- 'fullname',
37
- 'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})',
38
- array('customer_firstname' => 'main_table.customer_firstname', 'customer_lastname' => 'main_table.customer_lastname')
39
- );
40
-
41
- $collection->getSelect()->joinLeft(
42
- array('signifyd' => Mage::getSingleton('core/resource')->getTableName('signifyd_connect_case')),
43
- 'signifyd.order_increment = main_table.increment_id',
44
- array(
45
- 'score' => 'score',
46
- 'guarantee' => 'guarantee',
47
- )
48
- );
49
- }
50
-
51
- $this->setCollection($collection);
52
- parent::_prepareCollection();
53
- return $this;
54
- }
55
-
56
- protected function _prepareColumns()
57
- {
58
- $helper = Mage::helper('signifyd_connect');
59
- $currency = (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
60
-
61
- $this->addColumn('increment_id', array(
62
- 'header' => $helper->__('Order #'),
63
- 'index' => 'increment_id'
64
- ));
65
-
66
- $this->addColumn('purchased_on', array(
67
- 'header' => $helper->__('Purchased On'),
68
- 'type' => 'datetime',
69
- 'index' => 'created_at'
70
- ));
71
-
72
- if (!$this->oldSupport()) {
73
- $this->addColumn('fullname', array(
74
- 'header' => $helper->__('Name'),
75
- 'index' => 'fullname',
76
- 'filter_index' => 'CONCAT(customer_firstname, \' \', customer_lastname)'
77
- ));
78
- }
79
-
80
- $this->addColumn('grand_total', array(
81
- 'header' => $helper->__('Grand Total'),
82
- 'index' => 'grand_total',
83
- 'type' => 'currency',
84
- 'currency_code' => $currency
85
- ));
86
-
87
- $this->addColumn('shipping_method', array(
88
- 'header' => $helper->__('Shipping Method'),
89
- 'index' => 'shipping_description'
90
- ));
91
-
92
- $this->addColumn('score', array(
93
- 'header' => $helper->__('Signifyd Score'),
94
- 'align' => 'left',
95
- 'type' => 'text',
96
- 'index' => 'score',
97
- 'filter' => false,
98
- 'renderer' => 'signifyd_connect/renderer',
99
- 'width' => '100px',
100
- ));
101
-
102
- $this->addColumn('guarantee', array(
103
- 'header' => $helper->__('Signifyd Guarantee Status'),
104
- 'align' => 'left',
105
- 'type' => 'text',
106
- 'index' => 'guarantee',
107
- 'filter' => false,
108
- 'renderer' => 'signifyd_connect/renderer',
109
- ));
110
-
111
- $this->addColumn('order_status', array(
112
- 'header' => $helper->__('Status'),
113
- 'index' => 'status',
114
- 'type' => 'options',
115
- 'options' => Mage::getSingleton('sales/order_config')->getStatuses(),
116
- ));
117
-
118
- return parent::_prepareColumns();
119
- }
120
-
121
- public function getRowUrl($row)
122
- {
123
- if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
124
- return $this->getUrl('*/sales_order/view', array('order_id' => $row->getId()));
125
- }
126
-
127
- return false;
128
- }
129
-
130
- public function getGridUrl()
131
- {
132
- return $this->getUrl('*/*/grid', array('_current'=>true));
133
- }
134
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Widget_Grid
4
+ {
5
+ public function __construct()
6
+ {
7
+ parent::__construct();
8
+ $this->setId('signifyd_connect_grid');
9
+ $this->setDefaultSort('increment_id');
10
+ $this->setDefaultDir('DESC');
11
+ $this->setSaveParametersInSession(true);
12
+ $this->setUseAjax(true);
13
+ }
14
+
15
+ public function oldSupport()
16
+ {
17
+ $model = Mage::getSingleton('signifyd_connect/observer');
18
+
19
+ return $model->oldSupport();
20
+ }
21
+
22
+ protected function _prepareCollection()
23
+ {
24
+ $collection = Mage::getResourceModel('sales/order_collection');
25
+
26
+ if ($this->oldSupport()) {
27
+ $collection->getSelect()->joinLeft(
28
+ array('signifyd' => Mage::getSingleton('core/resource')->getTableName('signifyd_connect_case')),
29
+ 'signifyd.order_increment = e.increment_id',
30
+ array(
31
+ 'score' => 'score',
32
+ )
33
+ );
34
+ } else {
35
+ $collection->addExpressionFieldToSelect(
36
+ 'fullname',
37
+ 'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})',
38
+ array('customer_firstname' => 'main_table.customer_firstname', 'customer_lastname' => 'main_table.customer_lastname')
39
+ );
40
+
41
+ $collection->getSelect()->joinLeft(
42
+ array('signifyd' => Mage::getSingleton('core/resource')->getTableName('signifyd_connect_case')),
43
+ 'signifyd.order_increment = main_table.increment_id',
44
+ array(
45
+ 'score' => 'score',
46
+ 'guarantee' => 'guarantee',
47
+ )
48
+ );
49
+ }
50
+
51
+ $this->setCollection($collection);
52
+ parent::_prepareCollection();
53
+ return $this;
54
+ }
55
+
56
+ protected function _prepareColumns()
57
+ {
58
+ $helper = Mage::helper('signifyd_connect');
59
+ $currency = (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
60
+
61
+ $this->addColumn('increment_id', array(
62
+ 'header' => $helper->__('Order #'),
63
+ 'index' => 'increment_id'
64
+ ));
65
+
66
+ $this->addColumn('purchased_on', array(
67
+ 'header' => $helper->__('Purchased On'),
68
+ 'type' => 'datetime',
69
+ 'index' => 'created_at'
70
+ ));
71
+
72
+ if (!$this->oldSupport()) {
73
+ $this->addColumn('fullname', array(
74
+ 'header' => $helper->__('Name'),
75
+ 'index' => 'fullname',
76
+ 'filter_index' => 'CONCAT(customer_firstname, \' \', customer_lastname)'
77
+ ));
78
+ }
79
+
80
+ $this->addColumn('grand_total', array(
81
+ 'header' => $helper->__('Grand Total'),
82
+ 'index' => 'grand_total',
83
+ 'type' => 'currency',
84
+ 'currency_code' => $currency
85
+ ));
86
+
87
+ $this->addColumn('shipping_method', array(
88
+ 'header' => $helper->__('Shipping Method'),
89
+ 'index' => 'shipping_description'
90
+ ));
91
+
92
+ $this->addColumn('score', array(
93
+ 'header' => $helper->__('Signifyd Score'),
94
+ 'align' => 'left',
95
+ 'type' => 'text',
96
+ 'index' => 'score',
97
+ 'filter' => false,
98
+ 'renderer' => 'signifyd_connect/renderer',
99
+ 'width' => '100px',
100
+ ));
101
+
102
+ $this->addColumn('guarantee', array(
103
+ 'header' => $helper->__('Signifyd Guarantee Status'),
104
+ 'align' => 'left',
105
+ 'type' => 'text',
106
+ 'index' => 'guarantee',
107
+ 'filter' => false,
108
+ 'renderer' => 'signifyd_connect/renderer',
109
+ ));
110
+
111
+ $this->addColumn('order_status', array(
112
+ 'header' => $helper->__('Status'),
113
+ 'index' => 'status',
114
+ 'type' => 'options',
115
+ 'options' => Mage::getSingleton('sales/order_config')->getStatuses(),
116
+ ));
117
+
118
+ return parent::_prepareColumns();
119
+ }
120
+
121
+ public function getRowUrl($row)
122
+ {
123
+ if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
124
+ return $this->getUrl('*/sales_order/view', array('order_id' => $row->getId()));
125
+ }
126
+
127
+ return false;
128
+ }
129
+
130
+ public function getGridUrl()
131
+ {
132
+ return $this->getUrl('*/*/grid', array('_current'=>true));
133
+ }
134
+ }
app/code/community/Signifyd/Connect/Block/Renderer.php CHANGED
@@ -1,28 +1,28 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Block_Renderer extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
4
- {
5
- public function render(Varien_Object $row)
6
- {
7
- $value = $row->getData($this->getColumn()->getIndex());
8
- $column = $this->getColumn()->getId();
9
- $helper = Mage::helper('signifyd_connect');
10
-
11
- $url = $helper->getCaseUrl($row->getIncrementId());
12
-
13
- if ($column == "score") {
14
- if(!is_numeric($value)) {
15
- return $helper->__('N/A');
16
- }
17
- $value = floor($value);
18
- } else if ($column == "guarantee" && $value == "N/A") {
19
- return $value;
20
- }
21
-
22
- if ($url) {
23
- $value = "<a href=\"$url\" target=\"_blank\">$value</a>";
24
- }
25
-
26
- return $value;
27
- }
28
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Block_Renderer extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
4
+ {
5
+ public function render(Varien_Object $row)
6
+ {
7
+ $value = $row->getData($this->getColumn()->getIndex());
8
+ $column = $this->getColumn()->getId();
9
+ $helper = Mage::helper('signifyd_connect');
10
+
11
+ $url = $helper->getCaseUrl($row->getIncrementId());
12
+
13
+ if ($column == "score") {
14
+ if(!is_numeric($value)) {
15
+ return $helper->__('N/A');
16
+ }
17
+ $value = floor($value);
18
+ } else if ($column == "guarantee" && $value == "N/A") {
19
+ return $value;
20
+ }
21
+
22
+ if ($url) {
23
+ $value = "<a href=\"$url\" target=\"_blank\">$value</a>";
24
+ }
25
+
26
+ return $value;
27
+ }
28
+ }
app/code/community/Signifyd/Connect/Block/Url.php ADDED
@@ -0,0 +1,10 @@
1
+ <?php
2
+
3
+
4
+ class Signifyd_Connect_Block_Url
5
+ {
6
+ public function setForm()
7
+ {
8
+ return Mage::getUrl('/');
9
+ }
10
+ }
app/code/community/Signifyd/Connect/Helper/Data.php CHANGED
@@ -1,794 +1,790 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Helper_Data extends Mage_Core_Helper_Abstract
4
- {
5
- const UNPROCESSED_STATUS = 0;
6
- const ENTITY_CREATED_STATUS = 1;
7
- const CASE_CREATED_STATUS = 2;
8
- const TRANSACTION_SENT_STATUS = 3;
9
-
10
- public function logRequest($message)
11
- {
12
- if (Mage::getStoreConfig('signifyd_connect/log/request')) {
13
- Mage::log($message, null, 'signifyd_connect.log');
14
- }
15
- }
16
-
17
- public function logResponse($message)
18
- {
19
- if (Mage::getStoreConfig('signifyd_connect/log/response')) {
20
- Mage::log($message, null, 'signifyd_connect.log');
21
- }
22
- }
23
-
24
- public function logError($message)
25
- {
26
- if (Mage::getStoreConfig('signifyd_connect/log/error')) {
27
- Mage::log($message, null, 'signifyd_connect.log');
28
- }
29
- }
30
-
31
- public function getProducts($quote)
32
- {
33
- $products = array();
34
-
35
- foreach ($quote->getAllItems() as $item) {
36
- $product_type = $item->getProductType();
37
-
38
- if (!$product_type || $product_type == 'simple' || $product_type == 'downloadable' || $product_type == 'grouped') {
39
- $product_object = $item->getData('product');
40
-
41
- if (!$product_object || !$product_object->getId()) {
42
- $product_object = Mage::getModel('catalog/product')->load($product_type);
43
- }
44
-
45
- if ($product_object) {
46
- $product = array();
47
-
48
- $product['itemId'] = $item->getSku();
49
- $product['itemName'] = $item->getName();
50
- $product['itemUrl'] = $this->getProductUrl($product_object);
51
- $product['itemImage'] = $this->getProductImage($product_object);
52
-
53
- $qty = 1;
54
- if ($item->getQty()) {
55
- $qty = $item->getQty();
56
- } else if ($item->getQtyOrdered()) {
57
- $qty = $item->getQtyOrdered();
58
- }
59
-
60
- $price = 0;
61
- if ($item->getPrice() > 0) {
62
- $price = $item->getPrice();
63
- } else if ($item->getBasePrice() > 0) {
64
- $price = $item->getBasePrice();
65
- } else if ($product_object->getData('price') > 0) {
66
- $price = $product_object->getData('price');
67
- } else {
68
- $parent = $item->getData('parent');
69
-
70
- if (!$parent) {
71
- $parent = $item->getParentItem();
72
- }
73
-
74
- if ($parent) {
75
- if ($parent->getBasePrice() > 0) {
76
- $price = $parent->getBasePrice();
77
- } else if ($parent->getPrice()) {
78
- $price = $parent->getPrice();
79
- }
80
- }
81
- }
82
-
83
- $weight = 0;
84
- if ($item->hasWeight()) {
85
- $weight = $item->getWeight();
86
- } else if ($product_object->hasWeight()) {
87
- $weight = $product_object->getWeight();
88
- }
89
-
90
- $product['itemQuantity'] = intval($qty);
91
- $product['itemPrice'] = floatval($price);
92
- $product['itemWeight'] = floatval($weight);
93
-
94
- $products[] = $product;
95
- }
96
- }
97
- }
98
-
99
- return $products;
100
- }
101
-
102
- public function getIPAddress($order)
103
- {
104
- if ($order->getRemoteIp()) {
105
- if ($order->getXForwardedFor()) {
106
- return $this->filterIp($order->getXForwardedFor());
107
- }
108
-
109
- return $this->filterIp($order->getRemoteIp());
110
- }
111
-
112
- // Checks each configured value in app/etc/local.xml & falls back to REMOTE_ADDR. See app/etc/local.xml.additional for examples.
113
- return $this->filterIp(Mage::helper('core/http')->getRemoteAddr(false));
114
- }
115
-
116
- public function filterIp($ip)
117
- {
118
- $matches = array();
119
-
120
- if (preg_match('/[0-9]{1,3}(?:\.[0-9]{1,3}){3}/', $ip, $matches)) { //ipv4
121
- return current($matches);
122
- }
123
-
124
- if (preg_match('/[a-f0-9]{0,4}(?:\:[a-f0-9]{0,4}){2,7}/', strtolower($ip), $matches)) { //ipv6
125
- return current($matches);
126
- }
127
-
128
- return preg_replace('/[^0-9a-zA-Z:\.]/', '', strtok(str_replace($ip, ',', "\n"), "\n"));
129
- }
130
-
131
- public function formatAvs($value)
132
- {
133
- // http://www.emsecommerce.net/avs_cvv2_response_codes.htm
134
- $codes = array('X', 'Y', 'A', 'W', 'Z', 'N', 'U', 'R', 'E', 'S', 'D', 'M', 'B', 'P', 'C', 'I', 'G');
135
-
136
- if ($value) {
137
- $value = strtoupper($value);
138
-
139
- if (strlen($value) > 1) {
140
- if (preg_match('/\([A-Z]\)/', $value)) {
141
- $matches = array();
142
-
143
- preg_match('/\([A-Z]\)/', $value, $matches);
144
-
145
- foreach ($matches as $match) {
146
- $match = preg_replace('/[^A-Z]/', '', $match);
147
-
148
- if (in_array($match, $codes)) {
149
- $value = $match;
150
- }
151
- }
152
- }
153
- }
154
-
155
- if (strlen($value) > 1) {
156
- $value = substr($value, 0, 1);
157
- }
158
-
159
- if (!in_array($value, $codes)) {
160
- $value = null;
161
- }
162
- }
163
-
164
- return $value;
165
- }
166
-
167
- public function getAvsResponse($payment)
168
- {
169
- $value = null;
170
-
171
- if ($payment->getAdditionalInformation('paypal_avs_code')) {
172
- $value = $payment->getAdditionalInformation('paypal_avs_code');
173
- } else if ($payment->getAdditionalInformation('cc_avs_status')) {
174
- $value = $payment->getAdditionalInformation('cc_avs_status');
175
- }
176
-
177
- return $this->formatAvs($value);
178
- }
179
-
180
- public function getCvvResponse($payment)
181
- {
182
- if ($payment->getAdditionalInformation('paypal_cvv2_match')) {
183
- return $payment->getAdditionalInformation('paypal_cvv2_match');
184
- }
185
-
186
- return null;
187
- }
188
-
189
- private function getVersions()
190
- {
191
- $version = array();
192
- $version['platform'] = 'magento';
193
- $version['platformVersion'] = Mage::getVersion();
194
- $version['pluginVersion'] = (string)(Mage::getConfig()->getNode()->modules->Signifyd_Connect->version);
195
- return $version;
196
- }
197
-
198
- private function getTransactionId($payment)
199
- {
200
- $transId = $payment->getCcTransId();
201
- if(is_array($transId) && is_string($transId[0])) {
202
- $transId = $transId[0];
203
- } else if(!is_string($transId)) {
204
- $transId = null;
205
- }
206
- return $transId;
207
- }
208
-
209
- public function getPurchase($order)
210
- {
211
- $purchase = array();
212
- $payment = $order->getPayment();
213
-
214
- // T715: Send null rather than false when we can't get the IP Address
215
- $purchase['browserIpAddress'] = ($this->getIpAddress($order) ? $this->getIpAddress($order) : null);
216
- $purchase['orderId'] = $order->getIncrementId();
217
- $purchase['createdAt'] = date('c', strtotime($order->getCreatedAt())); // e.g: 2004-02-12T15:19:21+00:00
218
- $purchase['currency'] = $order->getOrderCurrencyCode();
219
- $purchase['totalPrice'] = floatval($order->getGrandTotal());
220
- $purchase['shippingPrice'] = floatval($order->getShippingAmount());
221
- $purchase['products'] = $this->getProducts($order);
222
- $purchase['paymentGateway'] = $payment->getMethod();
223
- $purchase['transactionId'] = $this->getTransactionId($payment);
224
-
225
- $purchase['avsResponseCode'] = $this->getAvsResponse($payment);
226
- $purchase['cvvResponseCode'] = $this->getCvvResponse($payment);
227
-
228
- return $purchase;
229
- }
230
-
231
- public function isPaymentCC($payment)
232
- {
233
- // Although the payment structure only has the entity data for the payment
234
- // the original payment method object is stored within the entity data.
235
- // It's not a requirement, but every CC handler I've found subclasses
236
- // from Mage_Payment_Model_Method_Cc, so we are using that as an
237
- // assumption for whether a method is based on CC data
238
- $method = $payment->getData('method_instance');
239
- if($method)
240
- {
241
- return is_subclass_of($method, 'Mage_Payment_Model_Method_Cc');
242
- }
243
- return false;
244
- }
245
-
246
- public function getCard($order, $payment)
247
- {
248
- $billing = $order->getBillingAddress();
249
-
250
- $card = array();
251
-
252
- $card['cardHolderName'] = null;
253
- $card['bin'] = null;
254
- $card['last4'] = null;
255
- $card['expiryMonth'] = null;
256
- $card['expiryYear'] = null;
257
- $card['hash'] = null;
258
-
259
- $card['billingAddress'] = $this->getSignifydAddress($billing);
260
-
261
- if ($payment->getCcOwner()) {
262
- $card['cardHolderName'] = $payment->getCcOwner();
263
- } else {
264
- $card['cardHolderName'] = $billing->getFirstname() . ' ' . $billing->getLastname();
265
- }
266
-
267
- // Card data may be set on payment even if payment was not with card.
268
- // If it is, we want to ignore the data
269
- if(!$this->isPaymentCC($payment)) return $card;
270
-
271
- if ($payment->getData('cc_last4')) {
272
- $card['last4'] = $payment->getData('cc_last4');
273
- }
274
-
275
- if ($payment->getData('cc_exp_year')) {
276
- $card['expiryYear'] = $payment->getData('cc_exp_year');
277
- }
278
-
279
- if ($payment->getData('cc_exp_month')) {
280
- $card['expiryMonth'] = $payment->getData('cc_exp_month');
281
- }
282
-
283
- if ($payment->getData('cc_number_enc')) {
284
- $card['hash'] = $payment->getData('cc_number_enc');
285
- }
286
-
287
- if ($payment->getData('cc_number') && is_numeric($payment->getData('cc_number')) && strlen((string)$payment->getData('cc_number')) > 6) {
288
- $card['bin'] = substr((string)$payment->getData('cc_number'), 0, 6);
289
- }
290
-
291
- return $card;
292
- }
293
-
294
- public function getSignifydAddress($address_object)
295
- {
296
- $address = array();
297
-
298
- $address['streetAddress'] = $address_object->getStreet1();
299
- $address['unit'] = null;
300
-
301
- if ($address_object->getStreet2()) {
302
- $address['unit'] = $address_object->getStreet2();
303
- }
304
-
305
- $address['city'] = $address_object->getCity();
306
-
307
- $address['provinceCode'] = $address_object->getRegionCode();
308
- $address['postalCode'] = $address_object->getPostcode();
309
- $address['countryCode'] = $address_object->getCountryId();
310
-
311
- $address['latitude'] = null;
312
- $address['longitude'] = null;
313
-
314
- return $address;
315
- }
316
-
317
- public function getRecipient($order)
318
- {
319
- $recipient = array();
320
-
321
- // In the case of non-shipped (ex: downloadable) orders, shipping address will be null so
322
- // in that case, we need to avoid the exception.
323
- $shipping_address = $order->getShippingAddress();
324
- if($shipping_address) {
325
- $recipient['deliveryAddress'] = $this->getSignifydAddress($shipping_address);
326
- $recipient['fullName'] = $shipping_address->getFirstname() . ' ' . $shipping_address->getLastname();
327
- $recipient['confirmationPhone'] = $shipping_address->getTelephone();
328
- // Email: Note that this field is always the same for both addresses
329
- $recipient['confirmationEmail'] = $shipping_address->getEmail();
330
- }
331
- // Some customers have reported seeing "n/a@na.na" come through instead of a valid or null address
332
- // We suspect that it is due to an older version of Magento. If it becomes unnecessary, do remove the extra check.
333
- if (!$recipient['confirmationEmail'] || $recipient['confirmationEmail'] == 'n/a@na.na') {
334
- $recipient['confirmationEmail'] = $order->getCustomerEmail();
335
- }
336
-
337
- return $recipient;
338
- }
339
-
340
- public function getUserAccount($customer, $order)
341
- {
342
- $user = array(
343
- "emailAddress" => null,
344
- "username" => null,
345
- "phone" => null,
346
- "createdDate" => null,
347
- "accountNumber" => null,
348
- "lastOrderId" => null,
349
- "aggregateOrderCount" => null,
350
- "aggregateOrderDollars" => null,
351
- "lastUpdateDate" => null
352
- );
353
-
354
- if ($customer && $customer->getId()) {
355
- $user['emailAddress'] = $customer->getEmail();
356
-
357
- $user['phone'] = $order->getBillingAddress()->getTelephone();
358
-
359
- $user['createdDate'] = date('c', strtotime($customer->getCreatedAt()));
360
- $user['lastUpdateDate'] = date('c', strtotime($customer->getUpdatedAt()));
361
-
362
- $user['accountNumber'] = $customer->getId();
363
-
364
- $last_order_id = null;
365
-
366
- $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id', $customer->getId());
367
- $orders->getSelect()->order('created_at DESC');
368
-
369
- $aggregate_total = 0.;
370
- $order_count = 0;
371
-
372
- foreach ($orders as $order) {
373
- if ($last_order_id === null) {
374
- $last_order_id = $order->getIncrementId();
375
- }
376
-
377
- $aggregate_total += floatval($order->getGrandTotal());
378
- $order_count += 1;
379
- }
380
-
381
- $user['lastOrderId'] = $last_order_id;
382
- $user['aggregateOrderCount'] = $order_count;
383
- $user['aggregateOrderDollars'] = floatval($aggregate_total);
384
- }
385
-
386
- return $user;
387
- }
388
-
389
- public function generateCase($order, $payment, $customer)
390
- {
391
- $case = array();
392
-
393
- $case['purchase'] = $this->getPurchase($order);
394
- $case['recipient'] = $this->getRecipient($order);
395
- $case['card'] = $this->getCard($order, $payment);
396
- $case['userAccount'] = $this->getUserAccount($customer, $order);
397
- $case['clientVersion'] = $this->getVersions();
398
-
399
- return $case;
400
- }
401
-
402
- public function submitCase($case, $url, $auth)
403
- {
404
- $case = json_encode($case);
405
-
406
- return $this->request($url, $case, $auth, 'application/json');
407
- }
408
-
409
- public function getUrl()
410
- {
411
- return Mage::getStoreConfig('signifyd_connect/settings/url') . '/cases';
412
- }
413
-
414
- public function getAuth()
415
- {
416
- return Mage::getStoreConfig('signifyd_connect/settings/key');
417
- }
418
-
419
- public function sendOrderUpdateToSignifyd($order)
420
- {
421
- if ($order && $order->getId() && Mage::getStoreConfig('signifyd_connect/advanced/enable_payment_updates')) {
422
- $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
423
- $caseId = $case->getCode();
424
- if (Mage::getStoreConfig('signifyd_connect/log/request')) {
425
- Mage::log("Created new case: $caseId", null, 'signifyd_connect.log');
426
- }
427
-
428
- $updateData = array();
429
- $payment = $order->getPayment();
430
-
431
- // These are the only supported update fields
432
- $purchase = array();
433
- $purchase['paymentGateway'] = $payment->getMethod();
434
- $purchase['transactionId'] = $this->getTransactionId($payment);
435
- $purchase['avsResponseCode'] = $this->getAvsResponse($payment);
436
- $purchase['cvvResponseCode'] = $this->getCvvResponse($payment);
437
-
438
- // Do not make request if there is no data to send
439
- if( $purchase['transactionId'] == null ||
440
- $purchase['transactionId'] == null ||
441
- $purchase['transactionId'] == null)
442
- {
443
- return "nodata";
444
- }
445
-
446
-
447
- $updateData['purchase'] = $purchase;
448
-
449
- $data = json_encode($updateData);
450
-
451
- $response = $this->request($this->getUrl() . "/$caseId", $data, $this->getAuth(), 'application/json', null, true);
452
-
453
- try {
454
- $response_code = $response->getHttpCode();
455
-
456
- if (substr($response_code, 0, 1) == '2') {
457
- $case->setUpdated(strftime('%Y-%m-%d %H:%M:%S', time()));
458
- $case->setTransactionId($updateData['purchase']['transactionId']);
459
- $case->save();
460
- if (Mage::getStoreConfig('signifyd_connect/log/request')) {
461
- Mage::log("Wrote case to database: $caseId", null, 'signifyd_connect.log');
462
- }
463
- return "sent";
464
- }
465
- } catch (Exception $e) {
466
- Mage::log($e->__toString(), null, 'signifyd_connect.log');
467
- return "error";
468
- }
469
- }
470
- }
471
-
472
- public function bulkSend($controller)
473
- {
474
- try {
475
- $orderIds = $controller->getRequest()->getParam('order_ids');
476
- if(is_string($orderIds))
477
- {
478
- $orderIds = array_map('intval', explode(',', $orderIds));
479
- }
480
- if (!is_array($orderIds)) {
481
- Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')
482
- ->__('Please select order(s)'));
483
- } else {
484
- // Reference T2395
485
- $user = "Unknown";
486
- try {
487
- $user = Mage::getSingleton('admin/session')->getUser()->getUsername();
488
- } catch (Exception $ex) {
489
- $this->logError($ex->__toString());
490
- }
491
- $this->logRequest("Bulk send initiated by: $user");
492
-
493
- $collection = Mage::getModel('sales/order')->getCollection()
494
- ->addFieldToSelect('*')
495
- ->addFieldToFilter('entity_id', array('in' => $orderIds));
496
-
497
- foreach ($collection as $order) {
498
- $result = $this->buildAndSendOrderToSignifyd($order, /*forceSend*/ true);
499
- if($result == "sent") {
500
- Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')
501
- ->__('Successfully sent order ' . $order->getIncrementId() . '.'));
502
- } else if ($result == "exists") {
503
- Mage::getSingleton('adminhtml/session')->addWarning(Mage::helper('adminhtml')
504
- ->__('Order ' . $order->getIncrementId() . ' has already been sent to Signifyd.'));
505
- } else if ($result == "nodata") {
506
- $this->logRequest("Request/Update not sent because there is no data");
507
- } else {
508
- Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')
509
- ->__('Order ' . $order->getIncrementId() . ' failed to send. See log for details.'));
510
- }
511
- }
512
- if (Mage::getStoreConfig('signifyd_connect/log/request')) {
513
- $this->logRequest("Bulk send complete");
514
- }
515
- }
516
- } catch(Exception $ex) {
517
- $this->logError($ex->__toString());
518
- Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')
519
- ->__('Send failed. See log for details'));
520
- }
521
- }
522
-
523
- public function buildAndSendOrderToSignifyd($order, $forceSend = false)
524
- {
525
- if ($order && $order->getId()) {
526
- $processStatus = $this->processedStatus($order);
527
- if ($processStatus > 0 && !$forceSend) {
528
- if($processStatus == self::TRANSACTION_SENT_STATUS) return "exists";
529
- else return $this->sendOrderUpdateToSignifyd($order);
530
- }
531
-
532
- $payments = $order->getPaymentsCollection();
533
- $last_payment = null;
534
- foreach ($payments as $payment) {
535
- $last_payment = $payment;
536
- }
537
-
538
- $state = $order->getState();
539
-
540
- if (!$state || $state == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT) {
541
- return "notready"; // Note: would not be in the order grid if this were the case
542
- }
543
-
544
- $customer = null;
545
- if ($order->getCustomer()) {
546
- $customer = $order->getCustomer();
547
- }
548
-
549
- $case = $this->generateCase($order, $last_payment, $customer);
550
-
551
- $case_object = $this->markProcessed($order);
552
-
553
- $response = $this->submitCase($case, $this->getUrl(), $this->getAuth());
554
-
555
- try {
556
- $response_code = $response->getHttpCode();
557
-
558
- if (substr($response_code, 0, 1) == '2') {
559
- $response_data = json_decode($response->getRawResponse(), true);
560
-
561
- $caseId = $response_data['investigationId'];
562
- $case_object = Mage::getModel('signifyd_connect/case')->load($case_object->getOrderIncrement());
563
- $case_object->setUpdated(strftime('%Y-%m-%d %H:%M:%S', time()));
564
- $case_object->setCode($caseId);
565
- $case_object->setTransactionId($case['purchase']['transactionId']);
566
- $case_object->save();
567
-
568
- $order->addStatusHistoryComment("Signifyd: case $caseId created for order");
569
- $order->save(); // Note: this will trigger recursion
570
-
571
- return "sent";
572
- }
573
- } catch (Exception $e) {
574
- Mage::log($e->__toString(), null, 'signifyd_connect.log');
575
- }
576
- $this->unmarkProcessed($order);
577
- return "error";
578
- }
579
- }
580
-
581
- /**
582
- * Run through up to $max items in the retry queue
583
- * @param int $max The maximum numbers of items to process
584
- */
585
- public function processRetryQueue($max = 99999)
586
- {
587
- $failed_orders = Mage::getModel('signifyd_connect/retries')->getCollection();
588
- $process_count = 0;
589
- try {
590
- foreach ($failed_orders as $order_id) {
591
- if ($process_count++ >= $max) {
592
- return;
593
- }
594
- $order = Mage::getModel('sales/order')->loadByIncrementId($order_id->getOrderIncrement());
595
- $result = "unset";
596
- $this->logRequest("Retrying " . $order_id->getOrderIncrement());
597
- if ($order != null && $this->processedStatus($order) < self::CASE_CREATED_STATUS) {
598
- $result = $this->buildAndSendOrderToSignifyd($order);
599
- }
600
- if ($result !== "error") {
601
- $this->logRequest("Completed retry " . $order_id->getOrderIncrement());
602
- Mage::register('isSecureArea', true);
603
- $order_id->delete();
604
- Mage::unregister('isSecureArea');
605
- } else {
606
- $this->logError("Failed retry " . $order_id->getOrderIncrement());
607
- }
608
- }
609
- } catch (Exception $e) {
610
- $this->logError($e->__toString());
611
- }
612
- }
613
-
614
- public function getProductUrl($product)
615
- {
616
- $url = null;
617
-
618
- try {
619
- $url = $product->getUrlModel()->getProductUrl($product);
620
- } catch (Exception $e) {
621
- $url = null;
622
- }
623
-
624
- return $url;
625
- }
626
-
627
- public function getCaseUrl($order_id)
628
- {
629
- $case = Mage::getModel('signifyd_connect/case')->load($order_id);
630
-
631
- if ($case->getCode()) {
632
- return "https://www.signifyd.com/cases/" . $case->getCode();
633
- }
634
- Mage::log('Case URL not found: '.$order_id, null, 'signifyd_connect.log');
635
- return '';
636
- }
637
-
638
- public function getProductImage($product, $size="150")
639
- {
640
- $image = null;
641
-
642
- try {
643
- $image = (string)Mage::helper('catalog/image')->init($product, 'image')->resize($size, $size)->keepFrame(true)->keepAspectRatio(true);
644
- } catch (Exception $e) {
645
- $image = null;
646
- }
647
-
648
- return $image;
649
- }
650
-
651
- public function getStoreName()
652
- {
653
- return Mage::getStoreConfig('trans_email/ident_general/name', 0);
654
- }
655
-
656
- public function getStoreEmail()
657
- {
658
- return Mage::getStoreConfig('trans_email/ident_general/email', 0);
659
- }
660
-
661
- public function getStoreUrl()
662
- {
663
- return Mage::getBaseUrl();
664
- }
665
-
666
- public function processedStatus($order)
667
- {
668
- $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
669
-
670
- if ($case->getTransactionId)
671
- {
672
- return self::TRANSACTION_SENT_STATUS;
673
- }
674
- else if ($case->getCode())
675
- {
676
- return self::CASE_CREATED_STATUS;
677
- }
678
- else if ($case->getId())
679
- {
680
- return self::ENTITY_CREATED_STATUS;
681
- }
682
-
683
- return self::UNPROCESSED_STATUS;
684
- }
685
-
686
- public function markProcessed($order)
687
- {
688
- $case = Mage::getModel('signifyd_connect/case');
689
- $case->setOrderIncrement($order->getIncrementId());
690
- $case->setCreated(strftime('%Y-%m-%d %H:%M:%S', time()));
691
- $case->setUpdated(strftime('%Y-%m-%d %H:%M:%S', time()));
692
- $case->save();
693
-
694
- return $case;
695
- }
696
-
697
- public function unmarkProcessed($order)
698
- {
699
- $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
700
- if($case && !$case->isObjectNew())
701
- {
702
- Mage::register('isSecureArea', true);
703
- $case->delete();
704
- Mage::unregister('isSecureArea');
705
- }
706
- }
707
-
708
- public function cancelGuarantee($case)
709
- {
710
- $caseId = $case->getCode();
711
- $url = $this->getUrl() . "/$caseId/guarantee";
712
- $body = json_encode(array("guaranteeDisposition" => "CANCELED"));
713
- $response = $this->request($url, $body, $this->getAuth(), 'application/json', null, true);
714
- $code = $response->getHttpCode();
715
- if(substr($code, 0, 1) == '2') {
716
- $case->setGuarantee('CANCELED');
717
- $case->save();
718
- } else {
719
- $this->logError("Guarantee cancel failed");
720
- }
721
- $this->logResponse("Received $code from guarantee cancel");
722
- }
723
-
724
- public function request($url, $data = null, $auth = null, $contenttype = "application/x-www-form-urlencoded",
725
- $accept = null, $is_update = false)
726
- {
727
- if (Mage::getStoreConfig('signifyd_connect/log/request')) {
728
- $authMask = preg_replace ( "/\S/", "*", $auth, strlen($auth) - 4 );
729
- Mage::log("Request:\nURL: $url \nAuth: $authMask\nData: $data", null, 'signifyd_connect.log');
730
- }
731
-
732
- $curl = curl_init();
733
- $response = new Varien_Object;
734
- $headers = array();
735
-
736
- curl_setopt($curl, CURLOPT_URL, $url);
737
-
738
- if (stripos($url, 'https://') === 0) {
739
- curl_setopt($curl, CURLOPT_PORT, 443);
740
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
741
- }
742
-
743
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
744
-
745
- if ($auth) {
746
- curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
747
- curl_setopt($curl, CURLOPT_USERPWD, $auth);
748
- }
749
-
750
- if ($accept) {
751
- $headers[] = 'Accept: ' . $accept;
752
- }
753
-
754
- if ($data) {
755
- if($is_update) curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
756
- else curl_setopt($curl, CURLOPT_POST, 1);
757
-
758
- $headers[] = "Content-Type: $contenttype";
759
- $headers[] = "Content-length: " . strlen($data);
760
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
761
- }
762
-
763
- if (count($headers)) {
764
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
765
- }
766
-
767
- curl_setopt($curl, CURLOPT_TIMEOUT, 4);
768
- curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 4);
769
-
770
- $raw_response = curl_exec($curl);
771
- $response->setRawResponse($raw_response);
772
-
773
- $response_data = curl_getinfo($curl);
774
- $response->addData($response_data);
775
-
776
- if (Mage::getStoreConfig('signifyd_connect/log/response')) {
777
- Mage::log("Response ($url):\n " . print_r($response, true), null, 'signifyd_connect.log');
778
- }
779
-
780
- if ($raw_response === false || curl_errno($curl)) {
781
- $error = curl_error($curl);
782
-
783
- if (Mage::getStoreConfig('signifyd_connect/log/error')) {
784
- Mage::log("ERROR ($url):\n$error", null, 'signifyd_connect.log');
785
- }
786
-
787
- $response->setData('error', $error);
788
- }
789
-
790
- curl_close($curl);
791
-
792
- return $response;
793
- }
794
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Helper_Data extends Mage_Core_Helper_Abstract
4
+ {
5
+ const UNPROCESSED_STATUS = 0;
6
+ const ENTITY_CREATED_STATUS = 1;
7
+ const CASE_CREATED_STATUS = 2;
8
+ const TRANSACTION_SENT_STATUS = 3;
9
+
10
+ const WAITING_SUBMISSION_STATUS = "waiting_submission";
11
+ const IN_REVIEW_STATUS = "in_review";
12
+ const PROCESSING_RESPONSE_STATUS = "processing_response";
13
+ const COMPLETED_STATUS = "completed";
14
+
15
+ public function logRequest($message)
16
+ {
17
+ if (Mage::getStoreConfig('signifyd_connect/log/request')) {
18
+ Mage::log($message, null, 'signifyd_connect.log');
19
+ }
20
+ }
21
+
22
+ public function logResponse($message)
23
+ {
24
+ if (Mage::getStoreConfig('signifyd_connect/log/response')) {
25
+ Mage::log($message, null, 'signifyd_connect.log');
26
+ }
27
+ }
28
+
29
+ public function logError($message)
30
+ {
31
+ if (Mage::getStoreConfig('signifyd_connect/log/error')) {
32
+ Mage::log($message, null, 'signifyd_connect.log');
33
+ }
34
+ }
35
+
36
+ public function getProducts($quote)
37
+ {
38
+ $products = array();
39
+
40
+ foreach ($quote->getAllItems() as $item) {
41
+ $product_type = $item->getProductType();
42
+
43
+ if (!$product_type || $product_type == 'simple' || $product_type == 'downloadable'
44
+ || $product_type == 'grouped' || $product_type == 'virtual' ) {
45
+ $product_object = $item->getData('product');
46
+
47
+ if (!$product_object || !$product_object->getId()) {
48
+ $product_object = Mage::getModel('catalog/product')->load($product_type);
49
+ }
50
+
51
+ if ($product_object) {
52
+ $product = array();
53
+
54
+ $product['itemId'] = $item->getSku();
55
+ $product['itemName'] = $item->getName();
56
+ $product['itemUrl'] = $this->getProductUrl($product_object);
57
+ $product['itemImage'] = $this->getProductImage($product_object);
58
+
59
+ $qty = 1;
60
+ if ($item->getQty()) {
61
+ $qty = $item->getQty();
62
+ } else if ($item->getQtyOrdered()) {
63
+ $qty = $item->getQtyOrdered();
64
+ }
65
+
66
+ $price = 0;
67
+ if ($item->getPrice() > 0) {
68
+ $price = $item->getPrice();
69
+ } else if ($item->getBasePrice() > 0) {
70
+ $price = $item->getBasePrice();
71
+ } else if ($product_object->getData('price') > 0) {
72
+ $price = $product_object->getData('price');
73
+ } else {
74
+ $parent = $item->getData('parent');
75
+
76
+ if (!$parent) {
77
+ $parent = $item->getParentItem();
78
+ }
79
+
80
+ if ($parent) {
81
+ if ($parent->getBasePrice() > 0) {
82
+ $price = $parent->getBasePrice();
83
+ } else if ($parent->getPrice()) {
84
+ $price = $parent->getPrice();
85
+ }
86
+ }
87
+ }
88
+
89
+ $weight = 0;
90
+ if ($item->hasWeight()) {
91
+ $weight = $item->getWeight();
92
+ } else if ($product_object->hasWeight()) {
93
+ $weight = $product_object->getWeight();
94
+ }
95
+
96
+ $product['itemQuantity'] = intval($qty);
97
+ $product['itemPrice'] = floatval($price);
98
+ $product['itemWeight'] = floatval($weight);
99
+
100
+ $products[] = $product;
101
+ }
102
+ }
103
+ }
104
+
105
+ return $products;
106
+ }
107
+
108
+ public function getIPAddress($order)
109
+ {
110
+ if ($order->getRemoteIp()) {
111
+ if ($order->getXForwardedFor()) {
112
+ return $this->filterIp($order->getXForwardedFor());
113
+ }
114
+
115
+ return $this->filterIp($order->getRemoteIp());
116
+ }
117
+
118
+ // Checks each configured value in app/etc/local.xml & falls back to REMOTE_ADDR. See app/etc/local.xml.additional for examples.
119
+ return $this->filterIp(Mage::helper('core/http')->getRemoteAddr(false));
120
+ }
121
+
122
+ public function filterIp($ip)
123
+ {
124
+ $matches = array();
125
+
126
+ if (preg_match('/[0-9]{1,3}(?:\.[0-9]{1,3}){3}/', $ip, $matches)) { //ipv4
127
+ return current($matches);
128
+ }
129
+
130
+ if (preg_match('/[a-f0-9]{0,4}(?:\:[a-f0-9]{0,4}){2,7}/', strtolower($ip), $matches)) { //ipv6
131
+ return current($matches);
132
+ }
133
+
134
+ return preg_replace('/[^0-9a-zA-Z:\.]/', '', strtok(str_replace($ip, ',', "\n"), "\n"));
135
+ }
136
+
137
+ public function formatAvs($value)
138
+ {
139
+ // http://www.emsecommerce.net/avs_cvv2_response_codes.htm
140
+ $codes = array('X', 'Y', 'A', 'W', 'Z', 'N', 'U', 'R', 'E', 'S', 'D', 'M', 'B', 'P', 'C', 'I', 'G');
141
+
142
+ if ($value) {
143
+ $value = strtoupper($value);
144
+
145
+ if (strlen($value) > 1) {
146
+ if (preg_match('/\([A-Z]\)/', $value)) {
147
+ $matches = array();
148
+
149
+ preg_match('/\([A-Z]\)/', $value, $matches);
150
+
151
+ foreach ($matches as $match) {
152
+ $match = preg_replace('/[^A-Z]/', '', $match);
153
+
154
+ if (in_array($match, $codes)) {
155
+ $value = $match;
156
+ }
157
+ }
158
+ }
159
+ }
160
+
161
+ if (strlen($value) > 1) {
162
+ $value = substr($value, 0, 1);
163
+ }
164
+
165
+ if (!in_array($value, $codes)) {
166
+ $value = null;
167
+ }
168
+ }
169
+
170
+ return $value;
171
+ }
172
+
173
+ public function getAvsResponse($payment)
174
+ {
175
+ $value = null;
176
+
177
+ if ($payment->getAdditionalInformation('paypal_avs_code')) {
178
+ $value = $payment->getAdditionalInformation('paypal_avs_code');
179
+ } else if ($payment->getAdditionalInformation('cc_avs_status')) {
180
+ $value = $payment->getAdditionalInformation('cc_avs_status');
181
+ }
182
+
183
+ return $this->formatAvs($value);
184
+ }
185
+
186
+ public function getCvvResponse($payment)
187
+ {
188
+ if ($payment->getAdditionalInformation('paypal_cvv2_match')) {
189
+ return $payment->getAdditionalInformation('paypal_cvv2_match');
190
+ }
191
+
192
+ return null;
193
+ }
194
+
195
+ private function getVersions()
196
+ {
197
+ $version = array();
198
+ $version['platform'] = 'magento';
199
+ $version['platformVersion'] = Mage::getVersion();
200
+ $version['pluginVersion'] = (string)(Mage::getConfig()->getNode()->modules->Signifyd_Connect->version);
201
+ return $version;
202
+ }
203
+
204
+ private function getTransactionId($payment)
205
+ {
206
+ $transId = $payment->getCcTransId();
207
+ if(is_array($transId) && is_string($transId[0])) {
208
+ $transId = $transId[0];
209
+ } else if(!is_string($transId)) {
210
+ $transId = null;
211
+ }
212
+ return $transId;
213
+ }
214
+
215
+ public function getPurchase($order)
216
+ {
217
+ $purchase = array();
218
+ $payment = $order->getPayment();
219
+
220
+ // T715: Send null rather than false when we can't get the IP Address
221
+ $purchase['browserIpAddress'] = ($this->getIpAddress($order) ? $this->getIpAddress($order) : null);
222
+ $purchase['orderId'] = $order->getIncrementId();
223
+ $purchase['createdAt'] = date('c', strtotime($order->getCreatedAt())); // e.g: 2004-02-12T15:19:21+00:00
224
+ $purchase['currency'] = $order->getOrderCurrencyCode();
225
+ $purchase['totalPrice'] = floatval($order->getGrandTotal());
226
+ $purchase['shippingPrice'] = floatval($order->getShippingAmount());
227
+ $purchase['products'] = $this->getProducts($order);
228
+ $purchase['paymentGateway'] = $payment->getMethod();
229
+ $purchase['transactionId'] = $this->getTransactionId($payment);
230
+
231
+ $purchase['avsResponseCode'] = $this->getAvsResponse($payment);
232
+ $purchase['cvvResponseCode'] = $this->getCvvResponse($payment);
233
+
234
+ return $purchase;
235
+ }
236
+
237
+ public function isPaymentCC($payment)
238
+ {
239
+ // Although the payment structure only has the entity data for the payment
240
+ // the original payment method object is stored within the entity data.
241
+ // It's not a requirement, but every CC handler I've found subclasses
242
+ // from Mage_Payment_Model_Method_Cc, so we are using that as an
243
+ // assumption for whether a method is based on CC data
244
+ $method = $payment->getData('method_instance');
245
+ if($method)
246
+ {
247
+ return is_subclass_of($method, 'Mage_Payment_Model_Method_Cc');
248
+ }
249
+ return false;
250
+ }
251
+
252
+ public function getCard($order, $payment)
253
+ {
254
+ $billing = $order->getBillingAddress();
255
+
256
+ $card = array();
257
+
258
+ $card['cardHolderName'] = null;
259
+ $card['bin'] = null;
260
+ $card['last4'] = null;
261
+ $card['expiryMonth'] = null;
262
+ $card['expiryYear'] = null;
263
+ $card['hash'] = null;
264
+
265
+ $card['billingAddress'] = $this->getSignifydAddress($billing);
266
+
267
+ if ($payment->getCcOwner()) {
268
+ $card['cardHolderName'] = $payment->getCcOwner();
269
+ } else {
270
+ $card['cardHolderName'] = $billing->getFirstname() . ' ' . $billing->getLastname();
271
+ }
272
+
273
+ // Card data may be set on payment even if payment was not with card.
274
+ // If it is, we want to ignore the data
275
+ if(!$this->isPaymentCC($payment)) return $card;
276
+
277
+ if ($payment->getData('cc_last4')) {
278
+ $card['last4'] = $payment->getData('cc_last4');
279
+ }
280
+
281
+ if ($payment->getData('cc_exp_year')) {
282
+ $card['expiryYear'] = $payment->getData('cc_exp_year');
283
+ }
284
+
285
+ if ($payment->getData('cc_exp_month')) {
286
+ $card['expiryMonth'] = $payment->getData('cc_exp_month');
287
+ }
288
+
289
+ if ($payment->getData('cc_number_enc')) {
290
+ $card['hash'] = $payment->getData('cc_number_enc');
291
+ }
292
+
293
+ if ($payment->getData('cc_number') && is_numeric($payment->getData('cc_number')) && strlen((string)$payment->getData('cc_number')) > 6) {
294
+ $card['bin'] = substr((string)$payment->getData('cc_number'), 0, 6);
295
+ }
296
+
297
+ return $card;
298
+ }
299
+
300
+ public function getSignifydAddress($address_object)
301
+ {
302
+ $address = array();
303
+
304
+ $address['streetAddress'] = $address_object->getStreet1();
305
+ $address['unit'] = null;
306
+
307
+ if ($address_object->getStreet2()) {
308
+ $address['unit'] = $address_object->getStreet2();
309
+ }
310
+
311
+ $address['city'] = $address_object->getCity();
312
+
313
+ $address['provinceCode'] = $address_object->getRegionCode();
314
+ $address['postalCode'] = $address_object->getPostcode();
315
+ $address['countryCode'] = $address_object->getCountryId();
316
+
317
+ $address['latitude'] = null;
318
+ $address['longitude'] = null;
319
+
320
+ return $address;
321
+ }
322
+
323
+ public function getRecipient($order)
324
+ {
325
+ $recipient = array();
326
+
327
+ // In the case of non-shipped (ex: downloadable) orders, shipping address will be null so
328
+ // in that case, we need to avoid the exception.
329
+ $shipping_address = $order->getShippingAddress();
330
+ if($shipping_address) {
331
+ $recipient['deliveryAddress'] = $this->getSignifydAddress($shipping_address);
332
+ $recipient['fullName'] = $shipping_address->getFirstname() . ' ' . $shipping_address->getLastname();
333
+ $recipient['confirmationPhone'] = $shipping_address->getTelephone();
334
+ // Email: Note that this field is always the same for both addresses
335
+ $recipient['confirmationEmail'] = $shipping_address->getEmail();
336
+ }
337
+ // Some customers have reported seeing "n/a@na.na" come through instead of a valid or null address
338
+ // We suspect that it is due to an older version of Magento. If it becomes unnecessary, do remove the extra check.
339
+ if (!$recipient['confirmationEmail'] || $recipient['confirmationEmail'] == 'n/a@na.na') {
340
+ $recipient['confirmationEmail'] = $order->getCustomerEmail();
341
+ }
342
+
343
+ return $recipient;
344
+ }
345
+
346
+ public function getUserAccount($customer, $order)
347
+ {
348
+ $user = array(
349
+ "emailAddress" => null,
350
+ "username" => null,
351
+ "phone" => null,
352
+ "createdDate" => null,
353
+ "accountNumber" => null,
354
+ "lastOrderId" => null,
355
+ "aggregateOrderCount" => null,
356
+ "aggregateOrderDollars" => null,
357
+ "lastUpdateDate" => null
358
+ );
359
+
360
+ if ($customer && $customer->getId()) {
361
+ $user['emailAddress'] = $customer->getEmail();
362
+
363
+ $user['phone'] = $order->getBillingAddress()->getTelephone();
364
+
365
+ $user['createdDate'] = date('c', strtotime($customer->getCreatedAt()));
366
+ $user['lastUpdateDate'] = date('c', strtotime($customer->getUpdatedAt()));
367
+
368
+ $user['accountNumber'] = $customer->getId();
369
+
370
+ $last_order_id = null;
371
+
372
+ $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id', $customer->getId());
373
+ $orders->getSelect()->order('created_at DESC');
374
+
375
+ $aggregate_total = 0.;
376
+ $order_count = 0;
377
+
378
+ foreach ($orders as $order) {
379
+ if ($last_order_id === null) {
380
+ $last_order_id = $order->getIncrementId();
381
+ }
382
+
383
+ $aggregate_total += floatval($order->getGrandTotal());
384
+ $order_count += 1;
385
+ }
386
+
387
+ $user['lastOrderId'] = $last_order_id;
388
+ $user['aggregateOrderCount'] = $order_count;
389
+ $user['aggregateOrderDollars'] = floatval($aggregate_total);
390
+ }
391
+
392
+ return $user;
393
+ }
394
+
395
+ public function generateCase($order, $payment, $customer)
396
+ {
397
+ $case = array();
398
+
399
+ $case['purchase'] = $this->getPurchase($order);
400
+ $case['recipient'] = $this->getRecipient($order);
401
+ $case['card'] = $this->getCard($order, $payment);
402
+ $case['userAccount'] = $this->getUserAccount($customer, $order);
403
+ $case['clientVersion'] = $this->getVersions();
404
+
405
+ return $case;
406
+ }
407
+
408
+ public function submitCase($case, $url, $auth)
409
+ {
410
+ $case = json_encode($case);
411
+
412
+ return $this->request($url, $case, $auth, 'application/json');
413
+ }
414
+
415
+ public function getUrl()
416
+ {
417
+ // return Mage::getStoreConfig('signifyd_connect/settings/url') . '/cases';
418
+ return 'https://api.signifyd.com/v2/cases/';
419
+ }
420
+
421
+ public function getAuth()
422
+ {
423
+ return Mage::getStoreConfig('signifyd_connect/settings/key');
424
+ }
425
+
426
+ public function sendOrderUpdateToSignifyd($order)
427
+ {
428
+ if ($order && $order->getId() && Mage::getStoreConfig('signifyd_connect/advanced/enable_payment_updates')) {
429
+ $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
430
+ $caseId = $case->getCode();
431
+
432
+ if (Mage::getStoreConfig('signifyd_connect/log/request')) {
433
+ Mage::log("Created new case: $caseId", null, 'signifyd_connect.log');
434
+ }
435
+
436
+ $updateData = array();
437
+ $payment = $order->getPayment();
438
+
439
+ // These are the only supported update fields
440
+ $purchase = array();
441
+ $purchase['paymentGateway'] = $payment->getMethod();
442
+ $purchase['transactionId'] = $this->getTransactionId($payment);
443
+ $purchase['avsResponseCode'] = $this->getAvsResponse($payment);
444
+ $purchase['cvvResponseCode'] = $this->getCvvResponse($payment);
445
+
446
+ // Do not make request if there is no data to send
447
+ if( $purchase['transactionId'] == null &&
448
+ $purchase['avsResponseCode'] == null &&
449
+ $purchase['cvvResponseCode'] == null)
450
+ {
451
+ return "nodata";
452
+ }
453
+ Mage::register('signifyd_action', 1); // Work will now take place
454
+
455
+ $updateData['purchase'] = $purchase;
456
+
457
+ $data = json_encode($updateData);
458
+
459
+ $response = $this->request($this->getUrl() . "/$caseId", $data, $this->getAuth(), 'application/json', null, true);
460
+
461
+ try {
462
+ $response_code = $response->getHttpCode();
463
+
464
+ if (substr($response_code, 0, 1) == '2') {
465
+ // Reload in case a substantial amount of time has passed
466
+ $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
467
+ $case->setUpdated(strftime('%Y-%m-%d %H:%M:%S', time()));
468
+ $case->setTransactionId($updateData['purchase']['transactionId']);
469
+ $case->save();
470
+ if (Mage::getStoreConfig('signifyd_connect/log/request')) {
471
+ Mage::log("Wrote case to database: $caseId", null, 'signifyd_connect.log');
472
+ }
473
+ return "sent";
474
+ }
475
+ } catch (Exception $e) {
476
+ Mage::log($e->__toString(), null, 'signifyd_connect.log');
477
+ return "error";
478
+ }
479
+ }
480
+ }
481
+
482
+ public function buildAndSendOrderToSignifyd($order, $forceSend = false)
483
+ {
484
+ if ($order && $order->getId()) {
485
+ $processStatus = $this->processedStatus($order);
486
+ if ($processStatus > 0 && !$forceSend) {
487
+ if($processStatus == self::TRANSACTION_SENT_STATUS) return "exists";
488
+ else return $this->sendOrderUpdateToSignifyd($order);
489
+ }
490
+
491
+ $payments = $order->getPaymentsCollection();
492
+ $last_payment = null;
493
+ foreach ($payments as $payment) {
494
+ $last_payment = $payment;
495
+ }
496
+
497
+ $state = $order->getState();
498
+
499
+ if (!$state || $state == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT) {
500
+ return "notready"; // Note: would not be in the order grid if this were the case
501
+ }
502
+
503
+ if(is_null(Mage::registry('signifyd_action'))) {
504
+ Mage::register('signifyd_action', 1); // Work will now take place
505
+ }
506
+
507
+ $customer = null;
508
+ if ($order->getCustomer()) {
509
+ $customer = $order->getCustomer();
510
+ }
511
+
512
+ $case = $this->generateCase($order, $last_payment, $customer);
513
+
514
+ $case_object = $this->markProcessed($order);
515
+
516
+ $response = $this->submitCase($case, $this->getUrl(), $this->getAuth());
517
+
518
+ try {
519
+ $response_code = $response->getHttpCode();
520
+
521
+ if (substr($response_code, 0, 1) == '2') {
522
+ $response_data = json_decode($response->getRawResponse(), true);
523
+
524
+ $caseId = $response_data['investigationId'];
525
+ $case_object = Mage::getModel('signifyd_connect/case')->load($case_object->getOrderIncrement());
526
+ $case_object->setUpdated(strftime('%Y-%m-%d %H:%M:%S', time()));
527
+ $case_object->setCode($caseId);
528
+ $case_object->setTransactionId($case['purchase']['transactionId']);
529
+ $case_object->setMagentoStatus(self::IN_REVIEW_STATUS);
530
+ $case_object->save();
531
+
532
+ $order->addStatusHistoryComment("Signifyd: case $caseId created for order");
533
+ $order->save(); // Note: this will trigger recursion
534
+
535
+ return "sent";
536
+ }
537
+ } catch (Exception $e) {
538
+ Mage::log($e->__toString(), null, 'signifyd_connect.log');
539
+ }
540
+ //$this->unmarkProcessed($order);
541
+ return "error";
542
+ }
543
+ }
544
+
545
+ public function getProductUrl($product)
546
+ {
547
+ $url = null;
548
+
549
+ try {
550
+ $url = $product->getUrlModel()->getProductUrl($product);
551
+ } catch (Exception $e) {
552
+ $url = null;
553
+ }
554
+
555
+ return $url;
556
+ }
557
+
558
+ public function getCaseUrl($order_id)
559
+ {
560
+ $case = Mage::getModel('signifyd_connect/case')->load($order_id);
561
+
562
+ if ($case->getCode()) {
563
+ return "https://www.signifyd.com/cases/" . $case->getCode();
564
+ }
565
+ Mage::log('Case URL not found: '.$order_id, null, 'signifyd_connect.log');
566
+ return '';
567
+ }
568
+
569
+ public function getProductImage($product, $size="150")
570
+ {
571
+ $image = null;
572
+
573
+ try {
574
+ $image = (string)Mage::helper('catalog/image')->init($product, 'image')->resize($size, $size)->keepFrame(true)->keepAspectRatio(true);
575
+ } catch (Exception $e) {
576
+ $image = null;
577
+ }
578
+
579
+ return $image;
580
+ }
581
+
582
+ public function getStoreName()
583
+ {
584
+ return Mage::getStoreConfig('trans_email/ident_general/name', 0);
585
+ }
586
+
587
+ public function getStoreEmail()
588
+ {
589
+ return Mage::getStoreConfig('trans_email/ident_general/email', 0);
590
+ }
591
+
592
+ public function getStoreUrl()
593
+ {
594
+ return Mage::getBaseUrl();
595
+ }
596
+
597
+ public function processedStatus($order)
598
+ {
599
+ $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
600
+
601
+ if ($case->getTransactionId())
602
+ {
603
+ return self::TRANSACTION_SENT_STATUS;
604
+ }
605
+ else if ($case->getCode())
606
+ {
607
+ return self::CASE_CREATED_STATUS;
608
+ }
609
+ else if ($case->getId())
610
+ {
611
+ return self::ENTITY_CREATED_STATUS;
612
+ }
613
+
614
+ return self::UNPROCESSED_STATUS;
615
+ }
616
+
617
+ public function markProcessed($order)
618
+ {
619
+ $case = Mage::getModel('signifyd_connect/case');
620
+ $case->setOrderIncrement($order->getIncrementId());
621
+ $case->setCreated(strftime('%Y-%m-%d %H:%M:%S', time()));
622
+ $case->setUpdated(strftime('%Y-%m-%d %H:%M:%S', time()));
623
+ $case->save();
624
+
625
+ return $case;
626
+ }
627
+
628
+ public function unmarkProcessed($order)
629
+ {
630
+ $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
631
+ if($case && !$case->isObjectNew())
632
+ {
633
+ Mage::register('isSecureArea', true);
634
+ $case->delete();
635
+ Mage::unregister('isSecureArea');
636
+ }
637
+ }
638
+
639
+ public function cancelGuarantee($case)
640
+ {
641
+ $caseId = $case->getCode();
642
+ $url = $this->getUrl() . "/$caseId/guarantee";
643
+ $body = json_encode(array("guaranteeDisposition" => "CANCELED"));
644
+ $response = $this->request($url, $body, $this->getAuth(), 'application/json', null, true);
645
+ $code = $response->getHttpCode();
646
+ if(substr($code, 0, 1) == '2') {
647
+ $case->setGuarantee('CANCELED');
648
+ $case->save();
649
+ } else {
650
+ $this->logError("Guarantee cancel failed");
651
+ }
652
+ $this->logResponse("Received $code from guarantee cancel");
653
+ }
654
+
655
+ public function request($url, $data = null, $auth = null, $contenttype = "application/x-www-form-urlencoded",
656
+ $accept = null, $is_update = false)
657
+ {
658
+ if (Mage::getStoreConfig('signifyd_connect/log/request')) {
659
+ $authMask = preg_replace ( "/\S/", "*", $auth, strlen($auth) - 4 );
660
+ Mage::log("Request:\nURL: $url \nAuth: $authMask\nData: $data", null, 'signifyd_connect.log');
661
+ }
662
+
663
+ $curl = curl_init();
664
+ $response = new Varien_Object;
665
+ $headers = array();
666
+
667
+ curl_setopt($curl, CURLOPT_URL, $url);
668
+
669
+ if (stripos($url, 'https://') === 0) {
670
+ curl_setopt($curl, CURLOPT_PORT, 443);
671
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
672
+ }
673
+
674
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
675
+
676
+ if ($auth) {
677
+ curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
678
+ curl_setopt($curl, CURLOPT_USERPWD, $auth);
679
+ }
680
+
681
+ if ($accept) {
682
+ $headers[] = 'Accept: ' . $accept;
683
+ }
684
+
685
+ if ($data) {
686
+ if($is_update) curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
687
+ else curl_setopt($curl, CURLOPT_POST, 1);
688
+
689
+ $headers[] = "Content-Type: $contenttype";
690
+ $headers[] = "Content-length: " . strlen($data);
691
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
692
+ }
693
+
694
+ if (count($headers)) {
695
+ curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
696
+ }
697
+
698
+ curl_setopt($curl, CURLOPT_TIMEOUT, 4);
699
+ curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 4);
700
+
701
+ $raw_response = curl_exec($curl);
702
+ $response->setRawResponse($raw_response);
703
+
704
+ $response_data = curl_getinfo($curl);
705
+ $response->addData($response_data);
706
+
707
+ if (Mage::getStoreConfig('signifyd_connect/log/response')) {
708
+ Mage::log("Response ($url):\n " . print_r($response, true), null, 'signifyd_connect.log');
709
+ }
710
+
711
+ if ($raw_response === false || curl_errno($curl)) {
712
+ $error = curl_error($curl);
713
+
714
+ if (Mage::getStoreConfig('signifyd_connect/log/error')) {
715
+ Mage::log("ERROR ($url):\n$error", null, 'signifyd_connect.log');
716
+ }
717
+
718
+ $response->setData('error', $error);
719
+ }
720
+
721
+ curl_close($curl);
722
+
723
+ return $response;
724
+ }
725
+
726
+ /**
727
+ * Get the order payment status
728
+ * @param $order
729
+ * @return array
730
+ */
731
+ public function getOrderPaymentStatus($order)
732
+ {
733
+ $status = array('authorize' => false, 'capture' => false, 'credit_memo' => false);
734
+ $logger = Mage::helper('signifyd_connect/log');
735
+ $paymentMethod = $order->getPayment();
736
+ $paymentAuthorized = $paymentMethod->getBaseAmountAuthorized();
737
+ $baseTotalPaid = $order->getBaseTotalPaid();
738
+ $baseTotalRefunded = $order->getBaseTotalRefunded();
739
+ // Maybe used in the future
740
+ // $canVoid = $paymentMethod->canVoid($order);
741
+ // $amountPayed = $paymentMethod->getAmountPaid();
742
+ // $baseTotalCanceled = $order->getBaseTotalCanceled();
743
+ // $baseTotalInvoiced = $order->getBaseTotalInvoiced();
744
+
745
+ // Check authorization
746
+ if(!empty($paymentAuthorized)){
747
+ $status['authorize'] = true;
748
+ }
749
+
750
+ // Special case for Paypal payment type "order"
751
+ if($this->isPaypalOrder($paymentMethod)){
752
+ $paymentAdditional = $paymentMethod->getData('additional_information');
753
+ if(isset($paymentAdditional['is_order_action']) && $paymentAdditional['is_order_action']){
754
+ $status['authorize'] = true;
755
+ }
756
+ }
757
+
758
+ // Check capture
759
+ if(!empty($baseTotalPaid)){
760
+ $status['capture'] = true;
761
+ }
762
+
763
+ // Check credit memo
764
+ if(!empty($baseTotalRefunded)){
765
+ $status['credit_memo'] = true;
766
+ }
767
+
768
+ // Log status
769
+ $logger->addLog("Order: {$order->getIncrementId()} has a status of " . json_encode($status));
770
+
771
+ return $status;
772
+ }
773
+
774
+ /**
775
+ * Checking if the payment method si paypal_express
776
+ * @param $paymentMethod
777
+ * @return bool
778
+ */
779
+ public function isPaypalOrder($paymentMethod)
780
+ {
781
+ $code = $paymentMethod->getMethodInstance()->getCode();
782
+ return (stripos($code, 'paypal_express') !== false)? true : false;
783
+ }
784
+
785
+ public function isGuarantyDeclined($order)
786
+ {
787
+ $case = Mage::getModel('signifyd_connect/case')->load($order->getIncrementId());
788
+ return ($case->getGuarantee() == 'DECLINED')? true : false;
789
+ }
790
+ }
app/code/community/Signifyd/Connect/Helper/Log.php ADDED
@@ -0,0 +1,25 @@
1
+ <?php
2
+ /**
3
+ * Log Helper
4
+ *
5
+ * @category Signifyd Connect
6
+ * @package Signifyd_Connect
7
+ * @author Signifyd
8
+ */
9
+ class Signifyd_Connect_Helper_Log extends Mage_Core_Helper_Abstract
10
+ {
11
+ protected $logFile;
12
+
13
+ public function __construct()
14
+ {
15
+ $this->logFile = 'signifyd_connect.log';
16
+ }
17
+
18
+ public function addLog($msg)
19
+ {
20
+ return Mage::log($msg, null, $this->logFile);
21
+ }
22
+ }
23
+
24
+ /* Filename: Log.php */
25
+ /* Location: ../app/code/Community/Signifyd/Connect/Helper/Log.php */
app/code/community/Signifyd/Connect/Model/Authnet.php CHANGED
@@ -1,17 +1,17 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Model_Authnet extends Mage_Paygate_Model_Authorizenet
4
- {
5
- protected function _registercard(varien_object $response, mage_sales_model_order_payment $payment)
6
- {
7
- Mage::log(">: ".$response->getTransactionId(), null, 'signifyd_connect.log');
8
- $card = parent::_registercard($response,$payment);
9
- $card->setCcAvsResultCode($response->getAvsResultCode());
10
- $card->setCcResponseCode($response->getCardCodeResponseCode());
11
- $payment->setCcAvsStatus($response->getAvsResultCode());
12
- $payment->setCcCidStatus($response->getCardCodeResponseCode());
13
- $payment->setCcTransId($response->getTransactionId());
14
- $payment->getCcTransId();
15
- return $card;
16
- }
17
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Model_Authnet extends Mage_Paygate_Model_Authorizenet
4
+ {
5
+ protected function _registercard(varien_object $response, mage_sales_model_order_payment $payment)
6
+ {
7
+ Mage::log(">: ".$response->getTransactionId(), null, 'signifyd_connect.log');
8
+ $card = parent::_registercard($response,$payment);
9
+ $card->setCcAvsResultCode($response->getAvsResultCode());
10
+ $card->setCcResponseCode($response->getCardCodeResponseCode());
11
+ $payment->setCcAvsStatus($response->getAvsResultCode());
12
+ $payment->setCcCidStatus($response->getCardCodeResponseCode());
13
+ $payment->setCcTransId($response->getTransactionId());
14
+ $payment->getCcTransId();
15
+ return $card;
16
+ }
17
+ }
app/code/community/Signifyd/Connect/Model/Case.php CHANGED
@@ -1,10 +1,29 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Model_Case extends Mage_Core_Model_Abstract
4
- {
5
- protected function _construct()
6
- {
7
- $this->_init('signifyd_connect/case');
8
- $this->_isPkAutoIncrement = false;
9
- }
10
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Model_Case extends Mage_Core_Model_Abstract
4
+ {
5
+ protected $logger;
6
+
7
+ protected function _construct()
8
+ {
9
+ $this->_init('signifyd_connect/case');
10
+ $this->_isPkAutoIncrement = false;
11
+ $this->logger = Mage::helper('signifyd_connect/log');
12
+ }
13
+
14
+ public function setMagentoStatusTo($case, $status)
15
+ {
16
+ $id = (is_array($case))? $case['order_increment'] : $case->getId();
17
+ $caseLoaded = Mage::getModel('signifyd_connect/case')->load($id);
18
+ try {
19
+ $caseLoaded->setMagentoStatus($status);
20
+ $caseLoaded->save();
21
+ $this->logger->addLog("Signifyd: Case no:{$caseLoaded->getId()} status set to {$status}");
22
+ } catch (Exception $e){
23
+ $this->logger->addLog("Signifyd: Error setting case no:{$caseLoaded->getId()} status to {$status}");
24
+ return false;
25
+ }
26
+
27
+ return true;
28
+ }
29
+ }
app/code/community/Signifyd/Connect/Model/Cron.php CHANGED
@@ -1,9 +1,136 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Model_Cron
4
- {
5
- public function update()
6
- {
7
- return; // Deprecated
8
- }
9
- }
1
+ <?php
2
+ /**
3
+ * Cron Model
4
+ *
5
+ * @category Signifyd Connect
6
+ * @package Signifyd_Connect
7
+ * @author Signifyd
8
+ */
9
+ class Signifyd_Connect_Model_Cron
10
+ {
11
+ /* The status when a case is created */
12
+ const WAITING_SUBMISSION_STATUS = "waiting_submission";
13
+
14
+ /* The status for a case when the first response from Signifyd is received */
15
+ const IN_REVIEW_STATUS = "in_review";
16
+
17
+ /* The status for a case when the case is processing the response */
18
+ const PROCESSING_RESPONSE_STATUS = "processing_response";
19
+
20
+ /* The status for a case that is completed */
21
+ const COMPLETED_STATUS = "completed";
22
+
23
+ protected $logger;
24
+
25
+ public function __construct()
26
+ {
27
+ $this->logger = Mage::helper('signifyd_connect/log');
28
+ }
29
+
30
+ /**
31
+ * Method to reprocessing the cases than did not fully complete
32
+ */
33
+ public function retry()
34
+ {
35
+ $this->logger->addLog("Main retry method called");
36
+ // Getting all the cases that were not submitted to Signifyd
37
+ $cases_for_resubmit = $this->getRetryCasesByStatus(self::WAITING_SUBMISSION_STATUS);
38
+ foreach ($cases_for_resubmit as $current_case) {
39
+ $this->logger->addLog("Signifyd: preparing for send case no: {$current_case['order_increment']}");
40
+ $current_order_id = $current_case['order_increment'];
41
+ $current_order = Mage::getModel('sales/order')->loadByIncrementId($current_order_id);
42
+ Mage::helper('signifyd_connect')->buildAndSendOrderToSignifyd($current_order,true);
43
+ }
44
+
45
+ // Getting all the cases that are awaiting review from Signifyd
46
+ $cases_for_resubmit = $this->getRetryCasesByStatus(self::IN_REVIEW_STATUS);
47
+ foreach ($cases_for_resubmit as $current_case) {
48
+ $this->logger->addLog("Signifyd: preparing for review case no: {$current_case['order_increment']}");
49
+ $this->processInReviewCase($current_case);
50
+ }
51
+
52
+ // Getting all the cases that need processing after the response was received
53
+ $cases_for_resubmit = $this->getRetryCasesByStatus(self::PROCESSING_RESPONSE_STATUS);
54
+ foreach ($cases_for_resubmit as $current_case) {
55
+ $this->logger->addLog("Signifyd: preparing for review case no: {$current_case['order_increment']}");
56
+ $current_order_id = $current_case['order_increment'];
57
+ $current_order = Mage::getModel('sales/order')->loadByIncrementId($current_order_id);
58
+ // need to refactor this
59
+ $this->loadClass();
60
+ $signifyd_controller = @new Signifyd_Connect_ConnectController();
61
+ $signifyd_controller->processAdditional($current_case,false,$current_order);
62
+ }
63
+
64
+ $this->logger->addLog("Main retry method ended");
65
+ return;
66
+ }
67
+
68
+ /**
69
+ * Getting the retry cases by the status of the case
70
+ * @param $status
71
+ * @return mixed
72
+ */
73
+ public function getRetryCasesByStatus($status)
74
+ {
75
+
76
+ $time = time();
77
+ $lastTime = $time - 60*60*24*7; // not longer than 7 days
78
+ $firstTime = $time - 60*30; // longer than last 30 minuted
79
+ $from = date('Y-m-d H:i:s', $lastTime);
80
+ $to = date('Y-m-d H:i:s', $firstTime);
81
+
82
+ $cases = Mage::getModel('signifyd_connect/case')->getCollection()
83
+ ->addFieldToFilter('updated', array('from' => $from, 'to' => $to))
84
+ ->addFieldToFilter('magento_status', $status);
85
+
86
+ return $cases->getData();
87
+
88
+ }
89
+
90
+ /**
91
+ * Process the cases that are in review
92
+ * @param $case
93
+ */
94
+ public function processInReviewCase($case)
95
+ {
96
+ $case_url = $this->getCaseUrl($case['code']);
97
+ $response = Mage::helper('signifyd_connect')->request($case_url,null,Mage::helper('signifyd_connect')->getAuth(),'application/json');
98
+ try {
99
+ $response_code = $response->getHttpCode();
100
+ if (substr($response_code, 0, 1) == '2') {
101
+ $response_data = $response->getRawResponse();
102
+ // need to refactor this
103
+ $this->loadClass();
104
+ $signifyd_controller = @new Signifyd_Connect_ConnectController();
105
+ $signifyd_controller->processFallback($response_data);
106
+ return;
107
+ }
108
+ } catch (Exception $e) {
109
+ Mage::log($e->__toString(), null, 'signifyd_connect.log');
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Get the cases url
115
+ * @param $case_code
116
+ * @return string
117
+ */
118
+ public function getCaseUrl($case_code)
119
+ {
120
+ // $url = Mage::getStoreConfig('signifyd_connect/settings/url') . '/cases/' . $case_code;
121
+ // return (empty($url))? "https://api.signifyd.com/v2/cases/" . $case_code : $url;
122
+ return 'https://api.signifyd.com/v2/cases/' . $case_code;
123
+ }
124
+
125
+ public function loadClass(){
126
+ if(!@class_exists('Signifyd_Connect_ConnectController')) //in case the class already exists
127
+ {
128
+ $dir = Mage::getModuleDir('controllers', 'Signifyd_Connect');
129
+ require_once($dir . '/ConnectController.php');
130
+ }
131
+ return true;
132
+ }
133
+ }
134
+
135
+ /* Filename: Cron.php */
136
+ /* Location: ../app/code/Community/Signifyd/Connect/Model/Cron.php */
app/code/community/Signifyd/Connect/Model/Link.php CHANGED
@@ -1,9 +1,9 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Model_Link
4
- {
5
- public function getCommentText()
6
- {
7
- return "Turn this on if you would like to receive Signifyd scores. Visit this url to confirm the callback functionality is working: <a href=\"" . Mage::getUrl('signifyd/connect/api') . "\" target=\"_blank\">" . Mage::getUrl('signifyd/connect/api') . "</a>";
8
- }
9
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Model_Link
4
+ {
5
+ public function getCommentText()
6
+ {
7
+ return "<a href=\"" . Mage::getUrl('signifyd/connect/api') . "\" target=\"_blank\">" . Mage::getUrl('signifyd/connect/api') . "</a>";
8
+ }
9
+ }
app/code/community/Signifyd/Connect/Model/Observer.php CHANGED
@@ -1,316 +1,299 @@
1
- <?php
2
-
3
- class Signifyd_Connect_Model_Observer extends Varien_Object
4
- {
5
- public $joins = 0;
6
-
7
- public function openCase($observer)
8
- {
9
- try {
10
- if (!Mage::getStoreConfig('signifyd_connect/settings/enabled') && !$this->getEnabled()) {
11
- return;
12
- }
13
-
14
- $event = $observer->getEvent();
15
-
16
- if ($event->hasOrder()) {
17
- $order = $event->getOrder();
18
- } else if ($event->hasObject()) {
19
- $order = $event->getObject();
20
- }
21
-
22
- $order_model = get_class(Mage::getModel('sales/order'));
23
-
24
- if (!($order instanceof $order_model)) {
25
- return;
26
- }
27
-
28
- $result = Mage::helper('signifyd_connect')->buildAndSendOrderToSignifyd($order);
29
- if($result !== "error") {
30
- if($result !== "notready") {
31
- // Handle two of the retry items in queue
32
- Mage::helper('signifyd_connect')->processRetryQueue(2);
33
- }
34
- return;
35
- }
36
- } catch (Exception $e) {
37
- Mage::log($e->__toString(), null, 'signifyd_connect.log');
38
- }
39
- // If we get here, then we have failed to create the case.
40
- $this->addToRetryQueue($order);
41
- }
42
-
43
- private function addToRetryQueue($order)
44
- {
45
- Mage::log("Add to retries", null, 'signifyd_connect.log');
46
- $order_tag = Mage::getModel('signifyd_connect/retries');
47
- $order_tag->setOrderIncrement($order->getIncrementId());
48
- $order_tag->setCreated(strftime('%Y-%m-%d %H:%M:%S', time()));
49
- $order_tag->save();
50
- }
51
-
52
- public function logData($order, $payment, $quote)
53
- {
54
- // Used to capture data for testing with
55
-
56
- $order_data = json_encode($order->getData());
57
- $billing_data = json_encode($order->getBillingAddress()->getData());
58
- $shipping_data = json_encode($order->getShippingAddress()->getData());
59
- $customer_data = json_encode($order->getCustomer()->getData());
60
- $payment_data = json_encode($payment->getData());
61
- $quote_data = json_encode($quote->getData());
62
- $items = array();
63
- $products = array();
64
-
65
- foreach ($quote->getAllItems() as $item) {
66
- $items[$item->getId()] = $item->getData();
67
- $product = Mage::getModel('catalog/product')->load($item->getProductId());
68
- $products[$item->getId()] = $product->getData();
69
- }
70
-
71
- $items = json_encode($items);
72
- $products = json_encode($products);
73
-
74
- Mage::log("Order:\n $order_data", null, 'signifyd_connect_objects.log');
75
- Mage::log("Billing:\n $billing_data", null, 'signifyd_connect_objects.log');
76
- Mage::log("Shipping:\n $shipping_data", null, 'signifyd_connect_objects.log');
77
- Mage::log("Customer:\n $customer_data", null, 'signifyd_connect_objects.log');
78
- Mage::log("Payment:\n $payment_data", null, 'signifyd_connect_objects.log');
79
- Mage::log("Quote:\n $quote_data", null, 'signifyd_connect_objects.log');
80
- Mage::log("Items:\n $items", null, 'signifyd_connect_objects.log');
81
- Mage::log("Products:\n $products", null, 'signifyd_connect_objects.log');
82
- }
83
-
84
- public function getAdminRoute()
85
- {
86
- $route = false;
87
-
88
- try {
89
- // 1.4.0.0 support means we need to hard code these paths
90
- if ((bool)(string)Mage::getConfig()->getNode('default/admin/url/use_custom_path')) {
91
- $route = Mage::getConfig()->getNode('default/admin/url/custom_path');
92
- } else {
93
- $route = Mage::getConfig()->getNode('admin/routers/adminhtml/args/frontName');
94
- }
95
- } catch (Exception $e) {
96
-
97
- }
98
-
99
- if (!$route) {
100
- $route = 'admin';
101
- }
102
-
103
- return $route;
104
- }
105
-
106
- public function eavCollectionAbstractLoadBefore($observer)
107
- {
108
- $x = $observer->getCollection();
109
-
110
- $request = Mage::app()->getRequest();
111
- $module = $request->getModuleName();
112
- $controller = $request->getControllerName();
113
-
114
- if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
115
- return;
116
- }
117
-
118
- $clss = get_class($x);
119
- if ($clss == 'Mage_Sales_Model_Mysql4_Order_Collection' || $clss == 'Mage_Sales_Model_Mysql4_Order_Grid_Collection') {
120
- $observer->setOrderGridCollection($x);
121
- return $this->salesOrderGridCollectionLoadBefore($observer);
122
- }
123
- }
124
-
125
- public function coreCollectionAbstractLoadBefore($observer)
126
- {
127
- $x = $observer->getCollection();
128
-
129
- $request = Mage::app()->getRequest();
130
- $module = $request->getModuleName();
131
- $controller = $request->getControllerName();
132
-
133
- if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
134
- return;
135
- }
136
-
137
- $clss = get_class($x);
138
-
139
- if ($clss == 'Mage_Sales_Model_Mysql4_Order_Collection' || $clss == 'Mage_Sales_Model_Mysql4_Order_Grid_Collection') {
140
- $observer->setOrderGridCollection($x);
141
- return $this->salesOrderGridCollectionLoadBefore($observer);
142
- }
143
- }
144
-
145
- public function isCe()
146
- {
147
- return !@class_exists('Enterprise_Cms_Helper_Data');
148
- }
149
-
150
- public function oldSupport()
151
- {
152
- $version = Mage::getVersion();
153
-
154
- if ($this->isCe()) {
155
- return version_compare($version, '1.4.1.0', '<');
156
- } else {
157
- return version_compare($version, '1.10.0.0', '<');
158
- }
159
-
160
- return false;
161
- }
162
-
163
- public function belowSix()
164
- {
165
- $version = Mage::getVersion();
166
-
167
- if ($this->isCe()) {
168
- return version_compare($version, '1.6.0.0', '<');
169
- } else {
170
- return version_compare($version, '1.11.0.0', '<');
171
- }
172
-
173
- return false;
174
- }
175
-
176
- public function salesOrderGridCollectionLoadBefore($observer)
177
- {
178
- $request = Mage::app()->getRequest();
179
- $module = $request->getModuleName();
180
- $controller = $request->getControllerName();
181
-
182
- if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
183
- return;
184
- }
185
-
186
- $collection = $observer->getOrderGridCollection();
187
- $select = $collection->getSelect();
188
-
189
- // This will prevent us from rejoining.
190
- if(strchr($select, 'signifyd')) {
191
- return;
192
- }
193
-
194
- $show_scores = Mage::getStoreConfig('signifyd_connect/advanced/show_scores');
195
- $show_guarantee = Mage::getStoreConfig('signifyd_connect/advanced/show_guarantee');
196
- if ($show_scores || $show_guarantee) {
197
- if ($this->oldSupport()) {
198
- $select->joinLeft(array('signifyd'=>$collection->getTable('signifyd_connect/case')), 'signifyd.order_increment=e.increment_id', array('score'=>'score'));
199
- $this->joins++;
200
- } else {
201
- $select->joinLeft(array('signifyd'=>$collection->getTable('signifyd_connect/case')), 'signifyd.order_increment=main_table.increment_id', array('score'=>'score',
202
- 'guarantee' => 'guarantee'));
203
- $this->joins++;
204
- }
205
- }
206
- }
207
-
208
- public function coreBlockAbstractPrepareLayoutBefore(Varien_Event_Observer $observer)
209
- {
210
- if (!Mage::getStoreConfig('signifyd_connect/settings/enabled') && !$this->getEnabled()) {
211
- return;
212
- }
213
-
214
- $block = $observer->getEvent()->getBlock();
215
- if((get_class($block) =='Mage_Adminhtml_Block_Widget_Grid_Massaction'
216
- || get_class($block) == 'Enterprise_SalesArchive_Block_Adminhtml_Sales_Order_Grid_Massaction')
217
- && $block->getRequest()->getControllerName() == 'sales_order')
218
- {
219
- $url = Mage::helper("adminhtml")->getUrl('signifyd_connect/adminhtml_signifyd/send');
220
- if(Mage::getStoreConfig('signifyd_connect/advanced/use_unsecure_requests')){
221
- $url = Mage::getUrl('signifyd/connect/send');
222
- }
223
- $block->setFormFieldName('increment_id');
224
- $block->addItem('signifyd_connect', array(
225
- 'label' => 'Send order(s) to Signifyd',
226
- 'url' => $url,
227
- ));
228
- }
229
- }
230
-
231
- public function coreBlockAbstractToHtmlBefore(Varien_Event_Observer $observer)
232
- {
233
- $show_scores = Mage::getStoreConfig('signifyd_connect/advanced/show_scores');
234
- $show_guarantee = Mage::getStoreConfig('signifyd_connect/advanced/show_guarantee');
235
- if ($show_scores || $show_guarantee) {
236
- $request = Mage::app()->getRequest();
237
- $module = $request->getModuleName();
238
- $controller = $request->getControllerName();
239
-
240
- if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
241
- return;
242
- }
243
-
244
- $helper = Mage::helper('signifyd_connect');
245
- $block = $observer->getEvent()->getBlock();
246
-
247
- if ($block->getId() == 'sales_order_grid') {
248
- if($show_scores) {
249
- $block->addColumnAfter(
250
- 'score',
251
- array(
252
- 'header' => $helper->__('Signifyd Score'),
253
- 'align' => 'left',
254
- 'type' => 'text',
255
- 'index' => 'score',
256
- 'filter' => false,
257
- 'renderer' => 'signifyd_connect/renderer',
258
- 'width' => '100px',
259
- ),
260
- 'status'
261
- );
262
- }
263
- if($show_guarantee) {
264
- $block->addColumnAfter(
265
- 'guarantee',
266
- array(
267
- 'header' => $helper->__('Guarantee Status'),
268
- 'align' => 'left',
269
- 'type' => 'text',
270
- 'index' => 'guarantee',
271
- 'filter' => false,
272
- 'renderer' => 'signifyd_connect/renderer',
273
- 'width' => '100px',
274
- ),
275
- 'status'
276
- );
277
- }
278
- $block->sortColumnsByOrder();
279
- }
280
- }
281
- }
282
-
283
- public function handleCancel($order)
284
- {
285
- $helper = Mage::helper('signifyd_connect');
286
- $case = Mage::getModel('signifyd_connect/case')->load($order);
287
- if($case->isObjectNew()) {
288
- $helper->logError("Guarantee cancel: Signifyd case for order $order does not exist in DB");
289
- return;
290
- }
291
- if($case->getGuarantee() == 'N/A' || $case->getGuarantee() == 'DECLINED') {
292
- $helper->logRequest("Guarantee cancel: Skipped. No guarantee active");
293
- return;
294
- }
295
-
296
- $helper->logRequest("Guarantee cancel for case " . $case->getCode());
297
- $helper->cancelGuarantee($case);
298
- }
299
-
300
- public function salesOrderPaymentCancel($observer)
301
- {
302
- $helper = Mage::helper('signifyd_connect');
303
- try {
304
- $event = $observer->getEvent();
305
- if($event->getPayment()->getOrder()) {
306
- $order = $event->getPayment()->getOrder()->getIncrementId();
307
- } else {
308
- $helper->logError("Event salesOrderPaymentCancel has no order");
309
- return;
310
- }
311
- $this->handleCancel($order);
312
- } catch(Exception $ex) {
313
- $helper->logError("Guarantee cancel: $ex");
314
- }
315
- }
316
- }
1
+ <?php
2
+
3
+ class Signifyd_Connect_Model_Observer extends Varien_Object
4
+ {
5
+ public $joins = 0;
6
+ protected $helper;
7
+
8
+ public function _construct()
9
+ {
10
+ $this->helper = Mage::helper('signifyd_connect');
11
+ }
12
+
13
+
14
+ public function openCase($observer)
15
+ {
16
+ try {
17
+ if (!Mage::getStoreConfig('signifyd_connect/settings/enabled') && !$this->getEnabled()) {
18
+ return;
19
+ }
20
+ if(Mage::registry('signifyd_action') == 1)
21
+ {
22
+ return;
23
+ }
24
+
25
+ $event = $observer->getEvent();
26
+
27
+ if ($event->hasOrder()) {
28
+ $order = $event->getOrder();
29
+ } else if ($event->hasObject()) {
30
+ $order = $event->getObject();
31
+ }
32
+
33
+ $order_model = get_class(Mage::getModel('sales/order'));
34
+
35
+ if (!($order instanceof $order_model)) {
36
+ return;
37
+ }
38
+
39
+ Mage::helper('signifyd_connect')->buildAndSendOrderToSignifyd($order);
40
+ } catch (Exception $e) {
41
+ Mage::log($e->__toString(), null, 'signifyd_connect.log');
42
+ }
43
+ // If we get here, then we have failed to create the case.
44
+
45
+ }
46
+
47
+ public function logData($order, $payment, $quote)
48
+ {
49
+ // Used to capture data for testing with
50
+
51
+ $order_data = json_encode($order->getData());
52
+ $billing_data = json_encode($order->getBillingAddress()->getData());
53
+ $shipping_data = json_encode($order->getShippingAddress()->getData());
54
+ $customer_data = json_encode($order->getCustomer()->getData());
55
+ $payment_data = json_encode($payment->getData());
56
+ $quote_data = json_encode($quote->getData());
57
+ $items = array();
58
+ $products = array();
59
+
60
+ foreach ($quote->getAllItems() as $item) {
61
+ $items[$item->getId()] = $item->getData();
62
+ $product = Mage::getModel('catalog/product')->load($item->getProductId());
63
+ $products[$item->getId()] = $product->getData();
64
+ }
65
+
66
+ $items = json_encode($items);
67
+ $products = json_encode($products);
68
+
69
+ Mage::log("Order:\n $order_data", null, 'signifyd_connect_objects.log');
70
+ Mage::log("Billing:\n $billing_data", null, 'signifyd_connect_objects.log');
71
+ Mage::log("Shipping:\n $shipping_data", null, 'signifyd_connect_objects.log');
72
+ Mage::log("Customer:\n $customer_data", null, 'signifyd_connect_objects.log');
73
+ Mage::log("Payment:\n $payment_data", null, 'signifyd_connect_objects.log');
74
+ Mage::log("Quote:\n $quote_data", null, 'signifyd_connect_objects.log');
75
+ Mage::log("Items:\n $items", null, 'signifyd_connect_objects.log');
76
+ Mage::log("Products:\n $products", null, 'signifyd_connect_objects.log');
77
+ }
78
+
79
+ public function getAdminRoute()
80
+ {
81
+ $route = false;
82
+
83
+ try {
84
+ // 1.4.0.0 support means we need to hard code these paths
85
+ if ((bool)(string)Mage::getConfig()->getNode('default/admin/url/use_custom_path')) {
86
+ $route = Mage::getConfig()->getNode('default/admin/url/custom_path');
87
+ } else {
88
+ $route = Mage::getConfig()->getNode('admin/routers/adminhtml/args/frontName');
89
+ }
90
+ } catch (Exception $e) {
91
+
92
+ }
93
+
94
+ if (!$route) {
95
+ $route = 'admin';
96
+ }
97
+
98
+ return $route;
99
+ }
100
+
101
+ public function eavCollectionAbstractLoadBefore($observer)
102
+ {
103
+ $x = $observer->getCollection();
104
+
105
+ $request = Mage::app()->getRequest();
106
+ $module = $request->getModuleName();
107
+ $controller = $request->getControllerName();
108
+
109
+ if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
110
+ return;
111
+ }
112
+
113
+ $clss = get_class($x);
114
+ if ($clss == 'Mage_Sales_Model_Mysql4_Order_Collection' || $clss == 'Mage_Sales_Model_Mysql4_Order_Grid_Collection') {
115
+ $observer->setOrderGridCollection($x);
116
+ return $this->salesOrderGridCollectionLoadBefore($observer);
117
+ }
118
+ }
119
+
120
+ public function coreCollectionAbstractLoadBefore($observer)
121
+ {
122
+ $x = $observer->getCollection();
123
+
124
+ $request = Mage::app()->getRequest();
125
+ $module = $request->getModuleName();
126
+ $controller = $request->getControllerName();
127
+
128
+ if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
129
+ return;
130
+ }
131
+
132
+ $clss = get_class($x);
133
+
134
+ if ($clss == 'Mage_Sales_Model_Mysql4_Order_Collection' || $clss == 'Mage_Sales_Model_Mysql4_Order_Grid_Collection') {
135
+ $observer->setOrderGridCollection($x);
136
+ return $this->salesOrderGridCollectionLoadBefore($observer);
137
+ }
138
+ }
139
+
140
+ public function isCe()
141
+ {
142
+ return !@class_exists('Enterprise_Cms_Helper_Data');
143
+ }
144
+
145
+ public function oldSupport()
146
+ {
147
+ $version = Mage::getVersion();
148
+
149
+ if ($this->isCe()) {
150
+ return version_compare($version, '1.4.1.0', '<');
151
+ } else {
152
+ return version_compare($version, '1.10.0.0', '<');
153
+ }
154
+
155
+ return false;
156
+ }
157
+
158
+ public function belowSix()
159
+ {
160
+ $version = Mage::getVersion();
161
+
162
+ if ($this->isCe()) {
163
+ return version_compare($version, '1.6.0.0', '<');
164
+ } else {
165
+ return version_compare($version, '1.11.0.0', '<');
166
+ }
167
+
168
+ return false;
169
+ }
170
+
171
+ public function salesOrderGridCollectionLoadBefore($observer)
172
+ {
173
+ $request = Mage::app()->getRequest();
174
+ $module = $request->getModuleName();
175
+ $controller = $request->getControllerName();
176
+
177
+ if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
178
+ return;
179
+ }
180
+
181
+ $collection = $observer->getOrderGridCollection();
182
+ $select = $collection->getSelect();
183
+
184
+ // This will prevent us from rejoining.
185
+ if(strchr($select, 'signifyd')) {
186
+ return;
187
+ }
188
+
189
+ if ($this->oldSupport()) {
190
+ $select->joinLeft(array('signifyd'=>$collection->getTable('signifyd_connect/case')), 'signifyd.order_increment=e.increment_id', array('score'=>'score'));
191
+ $this->joins++;
192
+ } else {
193
+ $select->joinLeft(array('signifyd'=>$collection->getTable('signifyd_connect/case')), 'signifyd.order_increment=main_table.increment_id', array('score'=>'score',
194
+ 'guarantee' => 'guarantee'));
195
+ $this->joins++;
196
+ }
197
+ }
198
+
199
+ public function coreBlockAbstractToHtmlBefore(Varien_Event_Observer $observer)
200
+ {
201
+ $request = Mage::app()->getRequest();
202
+ $module = $request->getModuleName();
203
+ $controller = $request->getControllerName();
204
+
205
+ if ($module != $this->getAdminRoute() || $controller != 'sales_order') {
206
+ return;
207
+ }
208
+
209
+ $helper = Mage::helper('signifyd_connect');
210
+ $block = $observer->getEvent()->getBlock();
211
+
212
+ if ($block->getId() == 'sales_order_grid') {
213
+ $block->addColumnAfter(
214
+ 'score',
215
+ array(
216
+ 'header' => $helper->__('Signifyd Score'),
217
+ 'align' => 'left',
218
+ 'type' => 'text',
219
+ 'index' => 'score',
220
+ 'filter' => false,
221
+ 'renderer' => 'signifyd_connect/renderer',
222
+ 'width' => '100px',
223
+ ),
224
+ 'status'
225
+ );
226
+ $block->addColumnAfter(
227
+ 'guarantee',
228
+ array(
229
+ 'header' => $helper->__('Guarantee Status'),
230
+ 'align' => 'left',
231
+ 'type' => 'text',
232
+ 'index' => 'guarantee',
233
+ 'filter' => false,
234
+ 'renderer' => 'signifyd_connect/renderer',
235
+ 'width' => '100px',
236
+ ),
237
+ 'status'
238
+ );
239
+ $block->sortColumnsByOrder();
240
+ }
241
+ }
242
+
243
+ public function handleCancel($order)
244
+ {