payitsimplepayment - Version 2.0.5

Version Notes

Support new APIs provided by Splitit.

Download this release

Release Info

Developer Eric Benayoun
Extension payitsimplepayment
Version 2.0.5
Comparing to
See all releases


Code changes from version 2.0.4 to 2.0.5

Files changed (33) hide show
  1. app/code/community/PayItSimple/Payment/Block/Adminhtml/Addresses.php +238 -0
  2. app/code/community/PayItSimple/Payment/Block/Form/Pis.php +144 -1
  3. app/code/community/PayItSimple/Payment/Model/Api.php +128 -63
  4. app/code/community/PayItSimple/Payment/Model/Observer.php +102 -0
  5. app/code/community/PayItSimple/Payment/Model/PisMethod.php +529 -84
  6. app/code/community/PayItSimple/Payment/Model/Source/Firstpayment.php +15 -0
  7. app/code/community/PayItSimple/Payment/Model/Source/Frontendpages.php +15 -0
  8. app/code/community/PayItSimple/Payment/Model/Source/Selectinstallmentsetup.php +12 -0
  9. app/code/community/PayItSimple/Payment/controllers/Adminhtml/PayitsimpleController.php +2 -1
  10. app/code/community/PayItSimple/Payment/controllers/PaymentController.php +145 -0
  11. app/code/community/PayItSimple/Payment/etc/config.xml +23 -1
  12. app/code/community/PayItSimple/Payment/etc/system.xml +167 -76
  13. app/design/adminhtml/default/default/layout/payitsimple_notification.xml +11 -0
  14. app/design/adminhtml/default/default/template/payitsimple/system/config/addresses.phtml +247 -0
  15. app/design/adminhtml/default/default/template/payitsimple/system/config/button.phtml +1 -0
  16. app/design/frontend/base/default/layout/pis_payment.xml +10 -0
  17. app/design/frontend/base/default/template/payitsimple/form/method_faq.phtml +29 -2
  18. app/design/frontend/base/default/template/payitsimple/form/pis.phtml +13 -5
  19. app/design/frontend/base/default/template/payitsimple/help.phtml +1 -2
  20. app/design/frontend/base/default/template/payitsimple/splitprice.phtml +49 -0
  21. js/payitsimple/checkout.js +234 -0
  22. js/payitsimple/jquery-1.12.4.js +11010 -0
  23. js/payitsimple/jquery-2.2.4.min.js +4 -0
  24. js/payitsimple/payitsimplepament/Amex_logo.png +0 -0
  25. js/payitsimple/payitsimplepament/LearnMore.png +0 -0
  26. js/payitsimple/payitsimplepament/MC_logo.png +0 -0
  27. js/payitsimple/payitsimplepament/Splitit_by.png +0 -0
  28. js/payitsimple/payitsimplepament/Visa_logo.png +0 -0
  29. js/payitsimple/payitsimplepament/approval-popup-close.png +0 -0
  30. js/payitsimple/payitsimplepament/opc-ajax-loader.gif +0 -0
  31. js/payitsimple/payitsimplepament/splitit_new_logo.png +0 -0
  32. package.xml +5 -5
  33. skin/frontend/base/default/css/pis_checkout.css +88 -0
app/code/community/PayItSimple/Payment/Block/Adminhtml/Addresses.php ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class PayItSimple_Payment_Block_Adminhtml_Addresses extends Mage_Adminhtml_Block_System_Config_Form_Field
3
+ {
4
+ protected $_addRowButtonHtml = array();
5
+ protected $_removeRowButtonHtml = array();
6
+ public function __construct()
7
+ {
8
+ parent::_construct();
9
+ //$this->setTemplate('payitsimple/system/config/button.phtml');
10
+ }
11
+
12
+ protected function _prepareLayout()
13
+ {
14
+ /* $button = $this->getLayout()->createBlock('adminhtml/widget_button')
15
+ ->setData(array(
16
+ 'label' => Mage::helper('catalog')->__('Add Tier'),
17
+ 'onclick' => 'return tierPriceControl.addItem()',
18
+ 'class' => 'add'
19
+ ));
20
+ $button->setName('add_tier_price_item_button');
21
+
22
+ $this->setChild('add_button', $button);
23
+ return parent::_prepareLayout();*/
24
+ }
25
+ /**
26
+ * Returns html part of the setting
27
+ *
28
+ * @param Varien_Data_Form_Element_Abstract $element
29
+ * @return string
30
+ */
31
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
32
+ {
33
+ $this->setElement($element);
34
+ $doctv = Mage::getStoreConfig('payment/pis_cc/depanding_on_cart_total_values');
35
+ $html = "";
36
+ if($doctv == ""){
37
+ $html = $this->getTableHtmlWhenEmpty();
38
+ }else{
39
+ $html = $this->getTableHtmlWhenNotEmpty($doctv);
40
+ }
41
+
42
+
43
+ return $html;
44
+ }
45
+
46
+ // return html when there is not prior configuration is set for Depending on cart total
47
+ protected function getTableHtmlWhenEmpty()
48
+ {
49
+ $html = '<table class="data border splitit" id="tiers_table" cellspacing="0" border="1">
50
+ <div class="tiers_table_overlay"></div>
51
+ <colgroup>
52
+ <col width="120">
53
+ <col width="95">
54
+ <col>
55
+ <col width="1">
56
+ </colgroup>
57
+ <thead>
58
+ <tr class="headings">
59
+ <th style="display:none">Website</th>
60
+ <th>Cart total</th>
61
+ <th>#Installments</th>
62
+ <th>Currency</th>
63
+ <th class="last">Action</th>
64
+ </tr>
65
+ </thead>
66
+ <tbody id="tier_price_container">
67
+ <tr>
68
+ <td>
69
+ From<br><label>'. $this->_getCurrencySymbol() .'</label> <input style="max-width:90%!important;" type="text" class="doctv_from" name="doctv_from" /><br>To<br><label>'. $this->_getCurrencySymbol() .'<input type="text" style="max-width:90%!important;" name="doctv_to" class="doctv_to" />
70
+ </td>
71
+ <td>
72
+ <select id="" name="doctv_installments" class=" select multiselect doctv_installments" size="10" multiple="multiple">
73
+ <option value="2">2 Installments</option>
74
+ <option value="3">3 Installments</option>
75
+ <option value="4">4 Installments</option>
76
+ <option value="5">5 Installments</option>
77
+ <option value="6">6 Installments</option>
78
+ <option value="7">7 Installments</option>
79
+ <option value="8">8 Installments</option>
80
+ <option value="9">9 Installments</option>
81
+ <option value="10">10 Installments</option>
82
+ <option value="11">11 Installments</option>
83
+ <option value="12">12 Installments</option>
84
+ </select>
85
+ </td>
86
+ <td>'.
87
+ /*<select id="" name="doctv_currency" class=" select doctv_currency">
88
+ '.$this->_getCurrencies().'*/
89
+ $this->_getBaseCurrency().'
90
+ </td>
91
+ <td>
92
+ <button title="Delete Tier" type="button" class="scalable delete icon-btn delete-product-option" id="" onclick="deleteRow(this);"><span><span><span>Delete</span></span></span></button>
93
+ </td>
94
+ </tr>
95
+ </tbody>
96
+ <tfoot>
97
+ <tr>
98
+ <td style="display:none"></td>
99
+ <td colspan="4" class="a-right"><button id="id_e33ad31ef8ac28bb6e4a4fd4d54f5f9e" title="Add Tier" type="button" class="scalable add" onclick="addRow();" style=""><span><span><span>Add Tier</span></span></span></button></td>
100
+ </tr>
101
+ </tfoot>
102
+ </table>';
103
+ return $html;
104
+ }
105
+
106
+ // return html when there is prior configuration is set for Depending on cart total
107
+ protected function getTableHtmlWhenNotEmpty($doctv)
108
+ {
109
+ $doctv = json_decode($doctv);
110
+
111
+ $html = '<table class="data border splitit" id="tiers_table" cellspacing="0" border="1">
112
+ <div class="tiers_table_overlay"></div>
113
+ <colgroup>
114
+ <col width="120">
115
+ <col width="95">
116
+ <col>
117
+ <col width="1">
118
+ </colgroup>
119
+ <thead>
120
+ <tr class="headings">
121
+ <th style="display:none">Website</th>
122
+ <th>Cart total</th>
123
+ <th>#Installments</th>
124
+ <th>Currency</th>
125
+ <th class="last">Action</th>
126
+ </tr>
127
+ </thead>
128
+ <tbody id="tier_price_container">';
129
+ $rowHtml = "";
130
+ foreach ($doctv as $key => $value) {
131
+ $rowHtml .= '<tr>';
132
+ $rowHtml .= '<td> From<br><label>'. $this->_getCurrencySymbol() .'</label> <input type="text" style="max-width:90%!important;" class="doctv_from" name="doctv_from" value="'.$value->doctv->from.'" /><br>To<br><label>'. $this->_getCurrencySymbol() .'</label> <input type="text" style="max-width:90%!important;" name="doctv_to" class="doctv_to" value="'.$value->doctv->to.'"/> </td>';
133
+ $rowHtml .= '<td>
134
+ <select id="" name="doctv_installments" class=" select multiselect doctv_installments" size="10" multiple="multiple">';
135
+ $i = 2;
136
+ $installments = explode(",", $value->doctv->installments);
137
+ $selected = "";
138
+ for($i=2; $i<=12; $i++){
139
+ if(in_array($i, $installments)){
140
+ $selected = 'selected="selected"';
141
+ }
142
+ $rowHtml .= '<option value="'.$i.'" '.$selected.'>'.$i.' Installments</option>';
143
+ $selected = "";
144
+
145
+ }
146
+ $rowHtml .= '</select></td>';
147
+
148
+
149
+
150
+ /*$rowHtml .= '<td>
151
+ <select id="" name="doctv_currency" class=" select doctv_currency">
152
+ '.$this->_getSelectedCurrency($value->doctv->currency).'
153
+ </td>'; */
154
+ $rowHtml .= '<td>'.$this->_getBaseCurrency().'</td>';
155
+ $rowHtml .= '<td>
156
+ <button title="Delete Tier" type="button" class="scalable delete icon-btn delete-product-option" id="" onclick="deleteRow(this);"><span><span><span>Delete</span></span></span></button>
157
+ </td>
158
+ </tr>';
159
+
160
+ }
161
+
162
+ $html .= $rowHtml;
163
+ $html .= '</tbody>
164
+ <tfoot>
165
+ <tr>
166
+ <td style="display:none"></td>
167
+ <td colspan="4" class="a-right"><button id="id_e33ad31ef8ac28bb6e4a4fd4d54f5f9e" title="Add Tier" type="button" class="scalable add" onclick="addRow();" style=""><span><span><span>Add Tier</span></span></span></button></td>
168
+ </tr>
169
+ </tfoot>
170
+ </table>';
171
+
172
+ return $html;
173
+ }
174
+
175
+ // get active currencies in the store and show dropdown in table
176
+ protected function _getCurrencies()
177
+ {
178
+ $currencies = array();
179
+ $codes = Mage::app()->getStore()->getAvailableCurrencyCodes(true);//print_r($codes);die;
180
+ $currenyOptions = "";
181
+ if (is_array($codes) && count($codes) > 1) {
182
+ $rates = Mage::getModel('directory/currency')->getCurrencyRates(
183
+ Mage::app()->getStore()->getBaseCurrency(),
184
+ $codes
185
+ );
186
+
187
+ foreach ($codes as $code) {
188
+ if (isset($rates[$code])) {
189
+ $currencies[$code] = Mage::app()->getLocale()
190
+ ->getTranslation($code, 'nametocurrency');
191
+ $currenyOptions .='<option value="'.$code.'">'.$code.'</option>';
192
+ }
193
+ }
194
+ }
195
+ return $currenyOptions;
196
+
197
+ }
198
+
199
+ // get active currencies and make them selected in dropdown in table
200
+ protected function _getSelectedCurrency($currency)
201
+ {
202
+ $currencies = array();
203
+ $codes = Mage::app()->getStore()->getAvailableCurrencyCodes(true);//print_r($codes);die;
204
+ $currenyOptions = "";
205
+ if (is_array($codes) && count($codes) > 1) {
206
+ $rates = Mage::getModel('directory/currency')->getCurrencyRates(
207
+ Mage::app()->getStore()->getBaseCurrency(),
208
+ $codes
209
+ );
210
+ $selected = '';
211
+ foreach ($codes as $code) {
212
+ if (isset($rates[$code])) {
213
+ $currencies[$code] = Mage::app()->getLocale()
214
+ ->getTranslation($code, 'nametocurrency');
215
+ if($code == $currency){
216
+ $selected = "selected=selected";
217
+ }
218
+
219
+ $currenyOptions .='<option value="'.$code.'" '.$selected.'>'.$code.'</option>';
220
+ $selected = '';
221
+ }
222
+ }
223
+ }
224
+ return $currenyOptions;
225
+
226
+ }
227
+
228
+ protected function _getBaseCurrency(){
229
+ $currentCurrency = Mage::app()->getStore()->getBaseCurrencyCode();
230
+ return $currencyLabel = '<input disabled class="doctv_currency" value="'.$currentCurrency.'"/>';
231
+ }
232
+
233
+ protected function _getCurrencySymbol(){
234
+ return Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
235
+ }
236
+
237
+
238
+ }
app/code/community/PayItSimple/Payment/Block/Form/Pis.php CHANGED
@@ -8,7 +8,7 @@ class PayItSimple_Payment_Block_Form_Pis extends Mage_Payment_Block_Form_Cc
8
  $this->setTemplate('payitsimple/form/pis.phtml');
9
  }
10
 
11
- public function getAvailableInstallments()
12
  {
13
  $method = $this->getMethod();
14
  $installments = array();
@@ -20,6 +20,149 @@ class PayItSimple_Payment_Block_Form_Pis extends Mage_Payment_Block_Form_Cc
20
  return $installments;
21
  }
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  public function getMethodLabelAfterHtml(){
24
  $markFaq = Mage::getConfig()->getBlockClassName('core/template');
25
  $markFaq = new $markFaq;
8
  $this->setTemplate('payitsimple/form/pis.phtml');
9
  }
10
 
11
+ public function getAvailableInstallments1()
12
  {
13
  $method = $this->getMethod();
14
  $installments = array();
20
  return $installments;
21
  }
22
 
23
+ public function getAvailableInstallments()
24
+ {
25
+ $method = $this->getMethod();
26
+ $installments = array();
27
+ $totalAmount = Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal();
28
+ $selectInstallmentSetup = Mage::getStoreConfig('payment/pis_cc/select_installment_setup');
29
+ $installmentsInDropdown = [];
30
+ $options = Mage::getModel('pis_payment/source_installments')->toOptionArray();
31
+
32
+ $depandOnCart = 0;
33
+ // $selectInstallmentSetup == "" for checking when merchant first time upgrade extension that time $selectInstallmentSetup will be empty
34
+ if($selectInstallmentSetup == "" || $selectInstallmentSetup == "fixed"){ // Select Fixed installment setup
35
+
36
+ $fixedInstallments = Mage::getStoreConfig('payment/pis_cc/available_installments');
37
+ foreach (explode(',', $fixedInstallments) as $n) {
38
+
39
+ if((array_key_exists($n, $options))){
40
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
41
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
42
+ }
43
+ }
44
+
45
+ }else{ // Select Depanding on cart installment setup
46
+ $depandOnCart = 1;
47
+ $depandingOnCartInstallments = Mage::getStoreConfig('payment/pis_cc/depanding_on_cart_total_values');
48
+ $depandingOnCartInstallmentsArr = json_decode($depandingOnCartInstallments);
49
+ $dataAsPerCurrency = [];
50
+ foreach($depandingOnCartInstallmentsArr as $data){
51
+ $dataAsPerCurrency[$data->doctv->currency][] = $data->doctv;
52
+ }
53
+ $currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
54
+ if(count($dataAsPerCurrency) && isset($dataAsPerCurrency[$currentCurrencyCode])){
55
+
56
+ foreach($dataAsPerCurrency[$currentCurrencyCode] as $data){
57
+ if($totalAmount >= $data->from && !empty($data->to) && $totalAmount <= $data->to){
58
+ foreach (explode(',', $data->installments) as $n) {
59
+
60
+ if((array_key_exists($n, $options))){
61
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
62
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
63
+
64
+ }
65
+ }
66
+ break;
67
+ }else if($totalAmount >= $data->from && empty($data->to)){
68
+ foreach (explode(',', $data->installments) as $n) {
69
+
70
+ if((array_key_exists($n, $options))){
71
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
72
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
73
+
74
+ }
75
+ }
76
+ break;
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+
83
+
84
+ if(count($installments) == 0){
85
+ $installments[] = "Installments are not available.";
86
+ }
87
+ // set how much installments to be show in checkout page dropdown
88
+ Mage::getSingleton('core/session')->setInstallmentsInDropdown($installmentsInDropdown);
89
+
90
+ return $installments;
91
+ }
92
+
93
+ public function getAvailableInstallments_copy()
94
+ {
95
+ $method = $this->getMethod();
96
+ $installments = array();
97
+ $totalAmount = Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal();
98
+ $selectInstallmentSetup = Mage::getStoreConfig('payment/pis_cc/select_installment_setup');
99
+ $installmentsInDropdown = [];
100
+ $options = Mage::getModel('pis_payment/source_installments')->toOptionArray();
101
+ $below100 = 0;
102
+ $depandOnCart = 0;
103
+ if($totalAmount < 100){
104
+ $installments[] = "Splitit only support amount more than 100";
105
+ $below100 = 1;
106
+ }else{
107
+
108
+ if($selectInstallmentSetup == "fixed"){ // Select Fixed installment setup
109
+
110
+ $fixedInstallments = Mage::getStoreConfig('payment/pis_cc/available_installments');
111
+ foreach (explode(',', $fixedInstallments) as $n) {
112
+
113
+ if((array_key_exists($n, $options))){
114
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
115
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
116
+ }
117
+ }
118
+
119
+ }else{ // Select Depanding on cart installment setup
120
+ $depandOnCart = 1;
121
+ $depandingOnCartInstallments = Mage::getStoreConfig('payment/pis_cc/depanding_on_cart_total_values');
122
+ $depandingOnCartInstallmentsArr = json_decode($depandingOnCartInstallments);
123
+ $dataAsPerCurrency = [];
124
+ foreach($depandingOnCartInstallmentsArr as $data){
125
+ $dataAsPerCurrency[$data->doctv->currency][] = $data->doctv;
126
+ }
127
+ $currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
128
+ if(count($dataAsPerCurrency) && isset($dataAsPerCurrency[$currentCurrencyCode])){
129
+
130
+ foreach($dataAsPerCurrency[$currentCurrencyCode] as $data){
131
+ if($totalAmount >= $data->from && !empty($data->to) && $totalAmount <= $data->to){
132
+ foreach (explode(',', $data->installments) as $n) {
133
+
134
+ if((array_key_exists($n, $options))){
135
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
136
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
137
+
138
+ }
139
+ }
140
+ break;
141
+ }else if($totalAmount >= $data->from && empty($data->to)){
142
+ foreach (explode(',', $data->installments) as $n) {
143
+
144
+ if((array_key_exists($n, $options))){
145
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
146
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
147
+
148
+ }
149
+ }
150
+ break;
151
+ }
152
+ }
153
+ }
154
+ }
155
+
156
+
157
+ }
158
+ if($below100 == 0 && $depandOnCart == 1 && count($installments) == 0){
159
+ $installments[] = "Installments are not available.";
160
+ }
161
+ // set how much installments to be show in checkout page dropdown
162
+ Mage::getSingleton('core/session')->setInstallmentsInDropdown($installmentsInDropdown);
163
+
164
+ return $installments;
165
+ }
166
  public function getMethodLabelAfterHtml(){
167
  $markFaq = Mage::getConfig()->getBlockClassName('core/template');
168
  $markFaq = new $markFaq;
app/code/community/PayItSimple/Payment/Model/Api.php CHANGED
@@ -13,6 +13,7 @@ class PayItSimple_Payment_Model_Api extends Mage_Core_Model_Abstract
13
  protected $_apiTerminalKey = null;
14
  protected $_gwUrl = null;
15
 
 
16
  /**
17
  * @param $gwUrl
18
  * @param $params
@@ -20,15 +21,30 @@ class PayItSimple_Payment_Model_Api extends Mage_Core_Model_Abstract
20
  * @return bool|array
21
  */
22
  public function login($gwUrl, $params){
23
- $result = $this->makeRequest($gwUrl, ucfirst(__FUNCTION__), $params);
 
 
 
 
24
  if ($result) {
25
  $this->_sessionId = (isset($result['SessionId']) && $result['SessionId'] != '') ? $result['SessionId'] : null;
26
  if (is_null($this->_sessionId)){
27
- $this->setError(self::ERROR_UNKNOWN, 'Unable get API SessionId');
 
 
 
 
 
 
 
 
28
  return false;
29
  }
30
  $this->_gwUrl = $gwUrl;
31
  $this->_apiTerminalKey = $params['ApiKey'];
 
 
 
32
  }
33
  return $result;
34
  }
@@ -40,18 +56,25 @@ class PayItSimple_Payment_Model_Api extends Mage_Core_Model_Abstract
40
  return (!is_null($this->_sessionId));
41
  }
42
 
43
- /**
44
- * @param array $params
45
- *
46
- * @return array|bool
47
- */
48
- public function createInstallmentPlan(array $params)
49
  {
50
- if (!$this->isLogin()) {
51
  $this->setError(self::ERROR_UNKNOWN, __FUNCTION__ . ' method required Login action first.');
52
  return false;
53
  }
54
- return $this->makeRequest($this->_gwUrl, ucfirst(__FUNCTION__), array_merge($params, array('ApiKey' => $this->_apiTerminalKey, 'SessionId' => $this->_sessionId)));
 
 
 
 
 
 
 
 
 
 
 
55
  }
56
 
57
  /**
@@ -82,6 +105,14 @@ class PayItSimple_Payment_Model_Api extends Mage_Core_Model_Abstract
82
  return $this->makeRequest($this->_gwUrl, ucfirst(__FUNCTION__), array_merge($params, array('ApiKey' => $this->_apiTerminalKey, 'SessionId' => $this->_sessionId)));
83
  }
84
 
 
 
 
 
 
 
 
 
85
  /**
86
  * @param $gwUrl string
87
  * @param $method string
@@ -139,7 +170,8 @@ class PayItSimple_Payment_Model_Api extends Mage_Core_Model_Abstract
139
  $client = new Zend_Http_Client(trim($url,'/') . '/api/' . $method . '?format=JSON');
140
  $client->setConfig(array(
141
  'maxredirects' => 0,
142
- 'timeout' => 30));
 
143
  $client->setMethod(Zend_Http_Client::POST);
144
  $client->setParameterPost($params);
145
  return $client;
@@ -162,67 +194,100 @@ class PayItSimple_Payment_Model_Api extends Mage_Core_Model_Abstract
162
  $this->_error = array('code' => $errorCode, 'message' => $errorMsg);
163
  }
164
 
165
- public function getInstallmentPlanStatusList()
166
- {
167
- return array(
168
- 1 => 'Pending Terms and Conditions approval',
169
- 2 => 'Pending for Shipping',
170
- 3 => 'In process',
171
- 4 => 'Installment plan finished',
172
- 5 => 'Plan cancelled by the customer (during the wizard)',
173
- 6 => 'Installment plan finished and cleared by Splitit',
174
- 7 => 'Pending customer credit card replacement',
175
- 8 => 'Plan frozen (only authorizations continues)',
176
- 9 => 'Plan cancelled by the merchant or by Splitit',
177
- );
178
- }
179
 
180
  public function getCcTypesAvailable()
181
  {
182
  return array(
183
  'MC' => 1,
184
  'VI' => 2,
 
 
 
185
  );
186
  }
187
 
188
- public function getGatewayError($code = null)
189
- {
190
- $errors = array(
191
- 0 => 'The operation completed successfully',
192
- 4 => 'The operation was denied',
193
- 501 => 'Invalid Credentials',
194
- 502 => 'Invalid Installment Plan Number',
195
- 503 => 'Invalid Installment Plan Status',
196
- 504 => 'Card type not supported',
197
- 505 => 'Invalid Number of Installments',
198
- 506 => 'Invalid Amount Format',
199
- 508 => 'Invalid Country Code',
200
- 509 => 'Invalid Response URL',
201
- 510 => 'Invalid Card holder Name',
202
- 511 => 'Invalid Amount',
203
- 520 => 'Invalid CVV',
204
- 521 => 'Invalid Card Number',
205
- 522 => 'Invalid Expiration Date ',
206
- 523 => 'Invalid Consumer Full Name ',
207
- 524 => 'Invalid Email Format',
208
- 525 => 'Invalid Address ',
209
- 526 => 'Invalid ZIP Code ',
210
- 527 => 'Card bin not supported ',
211
- 528 => 'Card issue country not supported',
212
- 599 => 'General Error Occurred',
213
- 600 => 'Gateway failed to process request',
214
- 601 => 'Invalid ZIP Code ',
215
- 602 => 'Invalid Address ',
216
- 603 => 'Invalid CVV',
217
- 604 => 'Invalid Expiration Date ',
218
- 606 => 'Invalid Address or Zip',
219
- 607 => 'Invalid card number',
220
- 608 => 'Problem with card',
221
- 609 => 'Insufficient funds',
222
- 610 => 'Credit card was declined',
223
- 630 => 'Failed to connect to gateway',
224
- 640 => 'Problem with merchant details on gateway',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  );
226
- return (is_null($code)) ? $errors : $errors[$code];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  }
228
  }
13
  protected $_apiTerminalKey = null;
14
  protected $_gwUrl = null;
15
 
16
+
17
  /**
18
  * @param $gwUrl
19
  * @param $params
21
  * @return bool|array
22
  */
23
  public function login($gwUrl, $params){
24
+
25
+ //$result = $this->makeRequest($gwUrl, ucfirst(__FUNCTION__), $params);
26
+
27
+ $result = $this->makePhpCurlRequest($gwUrl, ucfirst(__FUNCTION__), $params);
28
+ $result = Mage::helper('core')->jsonDecode($result);
29
  if ($result) {
30
  $this->_sessionId = (isset($result['SessionId']) && $result['SessionId'] != '') ? $result['SessionId'] : null;
31
  if (is_null($this->_sessionId)){
32
+ if(isset($result["serverError"])){
33
+ $this->getError();
34
+ }else{
35
+ $gatewayErrorCode = $result["ResponseHeader"]["Errors"][0]["ErrorCode"];
36
+ $gatewayErrorMsg = $result["ResponseHeader"]["Errors"][0]["Message"];
37
+
38
+ $this->setError($gatewayErrorCode, $gatewayErrorMsg);
39
+ }
40
+
41
  return false;
42
  }
43
  $this->_gwUrl = $gwUrl;
44
  $this->_apiTerminalKey = $params['ApiKey'];
45
+ // set Splitit session id into session
46
+
47
+ Mage::getSingleton('core/session')->setSplititSessionid($this->_sessionId);
48
  }
49
  return $result;
50
  }
56
  return (!is_null($this->_sessionId));
57
  }
58
 
59
+
60
+ public function createInstallmentPlan($url, array $params)
 
 
 
 
61
  {
62
+ if (Mage::getSingleton('core/session')->getSplititSessionid() == "") {
63
  $this->setError(self::ERROR_UNKNOWN, __FUNCTION__ . ' method required Login action first.');
64
  return false;
65
  }
66
+
67
+ return $this->makePhpCurlRequest($url, "InstallmentPlan/Create",$params);
68
+ }
69
+
70
+ public function startInstallment($url, array $params){
71
+ if (Mage::getSingleton('core/session')->getSplititSessionid() == "") {
72
+ $this->setError(self::ERROR_UNKNOWN, __FUNCTION__ . ' method required Login action first.');
73
+ return false;
74
+ }
75
+
76
+
77
+ return $this->makePhpCurlRequest($url, "InstallmentPlan/StartInstallments",$params);
78
  }
79
 
80
  /**
105
  return $this->makeRequest($this->_gwUrl, ucfirst(__FUNCTION__), array_merge($params, array('ApiKey' => $this->_apiTerminalKey, 'SessionId' => $this->_sessionId)));
106
  }
107
 
108
+ public function updateRefOrderNumber($apiUrl, $params){
109
+ try{
110
+ return $this->makePhpCurlRequest($apiUrl, "InstallmentPlan/Update" , $params);
111
+ }catch(Exception $e){
112
+ echo $e->getMessage();
113
+ }
114
+ }
115
+
116
  /**
117
  * @param $gwUrl string
118
  * @param $method string
170
  $client = new Zend_Http_Client(trim($url,'/') . '/api/' . $method . '?format=JSON');
171
  $client->setConfig(array(
172
  'maxredirects' => 0,
173
+ 'timeout' => 30,
174
+ 'curloptions' => array(CURLOPT_SSL_VERIFYPEER => false)));
175
  $client->setMethod(Zend_Http_Client::POST);
176
  $client->setParameterPost($params);
177
  return $client;
194
  $this->_error = array('code' => $errorCode, 'message' => $errorMsg);
195
  }
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
  public function getCcTypesAvailable()
199
  {
200
  return array(
201
  'MC' => 1,
202
  'VI' => 2,
203
+ /*'AE' => 3,
204
+ 'DI' => 4,
205
+ 'OT' => 5,*/
206
  );
207
  }
208
 
209
+
210
+ public function getValidNumberOfInstallments(){
211
+ if (!$this->isLogin()) {
212
+ $this->setError(self::ERROR_UNKNOWN, __FUNCTION__ . ' method required Login action first.');
213
+ return false;
214
+ }
215
+ $arr = array("RequestHeader"=>array('ApiKey' => $this->_apiTerminalKey, 'SessionId' => trim($this->_sessionId)));
216
+
217
+ //return $this->makeRequest($this->_gwUrl, "InstallmentPlan/GetValidNumberOfInstallments" , $arr);
218
+ return $this->makePhpCurlRequest($this->_gwUrl, "InstallmentPlan/GetValidNumberOfInstallments" , $arr);
219
+
220
+
221
+ }
222
+
223
+ public function installmentplaninit($apiUrl, $params){
224
+ try{
225
+ return $this->makePhpCurlRequest($apiUrl, "InstallmentPlan/Initiate" , $params);
226
+ }catch(Exception $e){
227
+ echo $e->getMessage();
228
+ }
229
+
230
+ }
231
+
232
+ public function getApprovalUrlResponse($approvalUrl){
233
+ $url = $approvalUrl . '&format=json';
234
+ $ch = curl_init($url);
235
+ $jsonData = json_encode($params);
236
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
237
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
238
+ curl_setopt($ch, CURLOPT_POST, 1);
239
+ curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonData);
240
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
241
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
242
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
243
+ 'Content-Type: application/json',
244
+ 'Content-Length:' . strlen($jsonData))
245
+ );
246
+ $result = curl_exec($ch);
247
+
248
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
249
+ $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
250
+ // check for curl error eg: splitit server down.
251
+ if(curl_errno($ch)){
252
+ //echo 'Curl error: ' . curl_error($ch);
253
+ $result["serverError"] = $this->getServerDownMsg();
254
+ return $result = Mage::helper('core')->jsonEncode($result);
255
+ }
256
+ curl_close($ch);
257
+ return $result;
258
+ }
259
+
260
+ public function makePhpCurlRequest($gwUrl, $method, $params){
261
+ $url = trim($gwUrl,'/') . '/api/' . $method . '?format=JSON';
262
+ $ch = curl_init($url);
263
+ $jsonData = json_encode($params);
264
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
265
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
266
+ curl_setopt($ch, CURLOPT_POST, 1);
267
+ curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonData);
268
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
269
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
270
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
271
+ 'Content-Type: application/json',
272
+ 'Content-Length:' . strlen($jsonData))
273
  );
274
+ $result = curl_exec($ch);
275
+
276
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
277
+ $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
278
+ // check for curl error eg: splitit server down.
279
+ if(curl_errno($ch)){
280
+ //echo 'Curl error: ' . curl_error($ch);
281
+ $this->setError($code, $this->getServerDownMsg());
282
+ curl_close($ch);
283
+ $result["serverError"] = $this->getServerDownMsg();
284
+ return $result = Mage::helper('core')->jsonEncode($result);
285
+ }
286
+ curl_close($ch);
287
+ return $result;
288
+ }
289
+
290
+ public function getServerDownMsg(){
291
+ return "Failed to connect to splitit payment server. Please retry again later.";
292
  }
293
  }
app/code/community/PayItSimple/Payment/Model/Observer.php ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class PayItSimple_Payment_Model_Observer
3
+ {
4
+ public function insertBlock($observer)
5
+ {
6
+ $_block = $observer->getBlock();
7
+ $_type = $_block->getType();
8
+ if (($_type == 'catalog/product_price' && $_block->getTemplate()=='catalog/product/price.phtml') or $_type == 'checkout/cart_totals') {
9
+ $_child = clone $_block;
10
+ $_child->setType('payitsimple/block');
11
+ if($_type == 'checkout/cart_totals'){
12
+ $_block->setChild('child', $_child);
13
+ }
14
+ else{
15
+ $_block->setChild('child'.$_child->getProduct()->getId(), $_child);
16
+ }
17
+ $_block->setTemplate('payitsimple/splitprice.phtml');
18
+ }
19
+ }
20
+
21
+ public function paymentMethodIsActive(Varien_Event_Observer $observer) {
22
+
23
+ $event = $observer->getEvent();//print_r($event->getData());die("---sdf");
24
+ $method = $event->getMethodInstance();
25
+ $result = $event->getResult();
26
+ $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
27
+
28
+
29
+ if($method->getCode() == "pis_cc"){
30
+ $result->isAvailable = $this->checkAvailableInstallments();
31
+ }/*else{
32
+ $result->isAvailable = false;
33
+ }*/
34
+
35
+ }
36
+
37
+ private function checkAvailableInstallments(){
38
+ $installments = array();
39
+ $totalAmount = Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal();
40
+ $selectInstallmentSetup = Mage::getStoreConfig('payment/pis_cc/select_installment_setup');
41
+ $installmentsInDropdown = [];
42
+ $options = Mage::getModel('pis_payment/source_installments')->toOptionArray();
43
+
44
+ $depandOnCart = 0;
45
+ // $selectInstallmentSetup == "" for checking when merchant first time upgrade extension that time $selectInstallmentSetup will be empty
46
+ if($selectInstallmentSetup == "" || $selectInstallmentSetup == "fixed"){ // Select Fixed installment setup
47
+
48
+ $fixedInstallments = Mage::getStoreConfig('payment/pis_cc/available_installments');
49
+ foreach (explode(',', $fixedInstallments) as $n) {
50
+
51
+ if((array_key_exists($n, $options))){
52
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
53
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
54
+ }
55
+ }
56
+
57
+ }else{ // Select Depanding on cart installment setup
58
+ $depandOnCart = 1;
59
+ $depandingOnCartInstallments = Mage::getStoreConfig('payment/pis_cc/depanding_on_cart_total_values');
60
+ $depandingOnCartInstallmentsArr = json_decode($depandingOnCartInstallments);
61
+ $dataAsPerCurrency = [];
62
+ foreach($depandingOnCartInstallmentsArr as $data){
63
+ $dataAsPerCurrency[$data->doctv->currency][] = $data->doctv;
64
+ }
65
+ $currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
66
+ if(count($dataAsPerCurrency) && isset($dataAsPerCurrency[$currentCurrencyCode])){
67
+
68
+ foreach($dataAsPerCurrency[$currentCurrencyCode] as $data){
69
+ if($totalAmount >= $data->from && !empty($data->to) && $totalAmount <= $data->to){
70
+ foreach (explode(',', $data->installments) as $n) {
71
+
72
+ if((array_key_exists($n, $options))){
73
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
74
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
75
+
76
+ }
77
+ }
78
+ break;
79
+ }else if($totalAmount >= $data->from && empty($data->to)){
80
+ foreach (explode(',', $data->installments) as $n) {
81
+
82
+ if((array_key_exists($n, $options))){
83
+ $installments[$n] = $n.' Installments of '. Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol().round($totalAmount/$n,2);
84
+ $installmentsInDropdown[$n] = round($totalAmount/$n,2);
85
+
86
+ }
87
+ }
88
+ break;
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+
95
+
96
+ if(count($installments) == 0){
97
+ return false;
98
+ }else{
99
+ return true;
100
+ }
101
+ }
102
+ }
app/code/community/PayItSimple/Payment/Model/PisMethod.php CHANGED
@@ -41,9 +41,9 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
41
  if (empty($no)) {
42
  $errorMsg = $this->_getHelper()->__('Installments are required fields');
43
  }
44
- if (empty($terms)) {
45
  $errorMsg = $this->_getHelper()->__('You should accept terms and conditions');
46
- }
47
  if ($errorMsg) {
48
  Mage::throwException($errorMsg);
49
  }
@@ -59,16 +59,37 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
59
  * @return $this
60
  */
61
  public function authorize(Varien_Object $payment, $amount)
62
- {
63
  if (!$this->canAuthorize()) {
64
  Mage::throwException(
65
  Mage::helper('payment')->__('Authorize action is not available.')
66
  );
67
  }
68
- $api = $this->_initApi($this->getStore());
 
69
  $result = $this->createInstallmentPlan($api, $payment, $amount);
70
-
71
- $payment->setTransactionId($result['InstallmentPlanNumber']);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  $payment->setIsTransactionClosed(0);
73
  $payment->setIsTransactionApproved(true);
74
  foreach (
@@ -82,8 +103,9 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
82
  unset($result[$param]);
83
 
84
  }
85
- $st = $api->getInstallmentPlanStatusList();
86
- $result['InstallmentPlanStatus'] = $st[$result['InstallmentPlanStatus']];
 
87
  $payment->setTransactionAdditionalInfo(
88
  Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS,
89
  $result
@@ -92,14 +114,44 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
92
  $order->addStatusToHistory(
93
  $order->getStatus(),
94
  'Payment InstallmentPlan was created with number ID: '
95
- . $result['InstallmentPlanNumber'],
96
  false
97
  );
 
 
 
 
 
 
 
98
  //$order->save();
99
 
100
  return $this;
101
  }
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  /**
104
  * Capture payment abstract method
105
  *
@@ -108,8 +160,8 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
108
  *
109
  * @return $this
110
  */
111
- public function capture(Varien_Object $payment, $amount)
112
- {
113
  if (!$this->canCapture()) {
114
  Mage::throwException(
115
  Mage::helper('payment')->__('Capture action is not available.')
@@ -121,15 +173,41 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
121
  } else {
122
  $authNumber = $payment->getAuthorizationTransaction()->getTxnId();
123
  }
124
- $api = $this->_initApi($this->getStore());
125
- $result = $api->notifyOrderShipped(
126
- array('InstallmentPlanNumber' => $authNumber)
127
- );
 
 
 
 
 
 
 
 
 
128
  $this->debugData('REQUEST: ' . $api->getRequest());
129
  $this->debugData('RESPONSE: ' . $api->getResponse());
130
  if (!$result) {
131
  $e = $api->getError();
132
- Mage::throwException($e['code'].' '.$e['message']);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  }
134
 
135
  $payment->setIsTransactionClosed(1);
@@ -144,42 +222,26 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
144
  return $this;
145
  }
146
 
147
- /**
148
- * @param $api PayItSimple_Payment_Model_Api
149
- * @param $payment Mage_Sales_Model_Order_Payment
150
- *
151
- * @return array|bool
152
- * @throws Mage_Payment_Exception
153
- */
154
  protected function createInstallmentPlan($api, $payment, $amount)
155
  {
156
- $order = $payment->getOrder();
157
- $billingaddress = $order->getBillingAddress();
158
- $address = $billingaddress->getData('street') . ' '
159
- . $billingaddress->getData('city') . ' '
160
- . $billingaddress->getData('region');
161
- $ccTypes = $api->getCcTypesAvailable();
162
- $params = array(
163
- 'ConsumerFullName' => $order->getCustomerName(),
164
- 'Email' => $order->getCustomerEmail(),
165
- 'AvsAddress' => $address,
166
- 'AvsZip' => $billingaddress->getData('postcode'),
167
- 'CountryId' => $this->getCountryCodePIS($billingaddress->getCountryId()),
168
- 'AmountBeforeFees' => $amount,
169
- 'CardHolder' => $billingaddress->getData('firstname')
170
- . ' ' . $billingaddress->getData('lastname'),
171
- 'CardTypeId' => $ccTypes[$payment->getCcType()],
172
- 'CardNumber' => $payment->getCcNumber(),
173
- 'CardExpMonth' => $payment->getCcExpMonth(),
174
- 'CardExpYear' => $payment->getCcExpYear(),
175
- 'CardCvv' => $payment->getCcCid(),
176
- 'InstallmentNumber' => $payment->getInstallmentsNo(),
177
- 'ParamX' => $order->getIncrementId(),
178
- 'CurrencyName' => Mage::app()->getStore()->getCurrentCurrencyCode()
179
- );
180
- $result = $api->createInstallmentPlan($params);
181
- $this->debugData('REQUEST: ' . $api->getRequest());
182
- $this->debugData('RESPONSE: ' . $api->getResponse());
183
  if (!$result){
184
  $e = $api->getError();
185
  Mage::throwException($e['code'].' '.$e['message']);
@@ -193,7 +255,7 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
193
  * @return PayItSimple_Payment_Model_Api
194
  * @throws Mage_Payment_Exception
195
  */
196
- protected function _initApi($storeId = null){
197
  if (is_null($storeId)) {
198
  $storeId = Mage::app()->getStore()->getId();
199
  }
@@ -201,19 +263,36 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
201
  if ($api->isLogin()) {
202
  return $api;
203
  }
 
 
 
 
 
 
 
 
 
204
  $result = $api->login(
205
  $this->getApiUrl(),
206
  array(
207
- 'ApiKey' => $this->getConfigData('api_terminal_key', $storeId),
208
  'UserName' => $this->getConfigData('api_username'),
209
- 'Password' => $this->getConfigData('api_password')
 
210
  )
211
  );
212
  $this->debugData('REQUEST: ' . $api->getRequest());
213
  $this->debugData('RESPONSE: ' . $api->getResponse());
 
214
  if (!$result || !$api->isLogin()){
215
  $e = $api->getError();
216
- Mage::throwException($e['code'].' '.$e['message']);
 
 
 
 
 
 
217
  }
218
  return $api;
219
  }
@@ -223,41 +302,407 @@ class PayItSimple_Payment_Model_PisMethod extends Mage_Payment_Model_Method_Cc
223
  }
224
 
225
  public function getApiUrl() {
 
226
  if ($this->getConfigData('sandbox_flag')) {
 
227
  return $this->getConfigData('api_url_sandbox');
228
  }
 
229
  return $this->getConfigData('api_url');
230
  }
231
 
232
- public function getCountryCodePIS($countryCode)
233
- {
234
- $countryIds = array(
235
- 'AF' => 4,'AX' => 248,'AL' => 8,'DZ' => 12,'AS' => 16,'AD' => 20,'AO' => 24,'AI' => 660,'AQ' => 10,'AG' => 28,'AR' => 32,
236
- 'AM' => 51,'AW' => 533,'AU' => 36,'AT' => 40,'AZ' => 31,'BS' => 44,'BH' => 48,'BD' => 50,'BB' => 52,'BY' => 112,'BE' => 56,
237
- 'BZ' => 84,'BJ' => 204,'BM' => 60,'BT' => 64,'BO' => 68,'BA' => 70,'BW' => 72,'BV' => 74,'BR' => 76,'IO' => 86,'VG' => 92,
238
- 'BN' => 96,'BG' => 100,'BF' => 854,'BI' => 108,'KH' => 116,'CM' => 120,'CA' => 124,'CV' => 132,'KY' => 136,'CF' => 140,
239
- 'TD' => 148,'CL' => 152,'CN' => 156,'CX' => 162,'CC' => 166,'CO' => 170,'KM' => 174,'CG' => 180,'CD' => 178,'CK' => 184,
240
- 'CR' => 188,'CI' => 384,'HR' => 191,'CU' => 192,'CY' => 196,'CZ' => 203,'DK' => 208,'DJ' => 262,'DM' => 212,'DO' => 214,
241
- 'EC' => 218,'EG' => 818,'SV' => 222,'GQ' => 226,'ER' => 232,'EE' => 233,'ET' => 231,'FK' => 238,'FO' => 234,'FJ' => 242,
242
- 'FI' => 246,'FR' => 250,'GF' => 254,'PF' => 258,'TF' => 260,'GA' => 266,'GM' => 270,'GE' => 268,'DE' => 276,'GH' => 288,
243
- 'GI' => 292,'GR' => 300,'GL' => 304,'GD' => 308,'GP' => 312,'GU' => 316,'GT' => 320,'GG' => 831,'GN' => 324,'GW' => 624,
244
- 'GY' => 328,'HT' => 332,'HM' => 334,'HN' => 340,'HK' => 344,'HU' => 348,'IS' => 352,'IN' => 356,'ID' => 360,'IR' => 364,
245
- 'IQ' => 368,'IE' => 372,'IM' => 833,'IL' => 376,'IT' => 380,'JM' => 388,'JP' => 392,'JE' => 832,'JO' => 400,'KZ' => 398,
246
- 'KE' => 404,'KI' => 296,'KW' => 414,'KG' => 417,'LA' => 418,'LV' => 428,'LB' => 422,'LS' => 426,'LR' => 430,'LY' => 434,
247
- 'LI' => 438,'LT' => 440,'LU' => 442,'MO' => 446,'MK' => 807,'MG' => 450,'MW' => 454,'MY' => 458,'MV' => 462,'ML' => 466,
248
- 'MT' => 470,'MH' => 584,'MQ' => 474,'MR' => 478,'MU' => 480,'YT' => 175,'MX' => 484,'FM' => 583,'MD' => 498,'MC' => 492,
249
- 'MN' => 496,'ME' => 499,'MS' => 500,'MA' => 504,'MZ' => 508,'MM' => 104,'NA' => 516,'NR' => 520,'NP' => 524,'NL' => 528,
250
- 'AN' => 530,'NC' => 540,'NZ' => 554,'NI' => 558,'NE' => 562,'NG' => 566,'NU' => 570,'NF' => 574,'MP' => 580,'KP' => 408,
251
- 'NO' => 578,'OM' => 512,'PK' => 586,'PW' => 585,'PS' => 275,'PA' => 591,'PG' => 598,'PY' => 600,'PE' => 604,'PH' => 608,
252
- 'PN' => 612,'PL' => 616,'PT' => 620,'PR' => 630,'QA' => 634,'RE' => 638,'RO' => 642,'RU' => 643,'RW' => 646,'BL' => '',
253
- 'SH' => 654,'KN' => 659,'LC' => 662,'MF' => '','PM' => 666,'WS' => 882,'SM' => 674,'ST' => 678,'SA' => 682,'SN' => 686,
254
- 'RS' => 688,'SC' => 690,'SL' => 694,'SG' => 702,'SK' => 703,'SI' => 705,'SB' => 90,'SO' => 706,'ZA' => 710,'GS' => 239,
255
- 'KR' => 410,'ES' => 724,'LK' => 144,'VC' => 670,'SD' => 736,'SR' => 740,'SJ' => 744,'SZ' => 748,'SE' => 754,'CH' => 756,
256
- 'SY' => 760,'TW' => 158,'TJ' => 762,'TZ' => 834,'TH' => 764,'TL' => 626,'TG' => 768,'TK' => 772,'TO' => 776,'TT' => 780,
257
- 'TN' => 788,'TR' => 792,'TM' => 795,'TC' => 796,'TV' => 798,'UG' => 800,'UA' => 804,'AE' => 784,'GB' => 826,'US' => 840,
258
- 'UY' => 858,'UM' => 581,'VI' => 850,'UZ' => 860,'VU' => 548,'VA' => 336,'VE' => 862,'VN' => 704,'WF' => 876,'EH' => 732,
259
- 'YE' => 887,'ZM' => 894,'ZW' => 716,
260
- );
261
- return ($countryIds[$countryCode]) ? $countryIds[$countryCode] : 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  }
263
  }
41
  if (empty($no)) {
42
  $errorMsg = $this->_getHelper()->__('Installments are required fields');
43
  }
44
+ /*if (empty($terms)) {
45
  $errorMsg = $this->_getHelper()->__('You should accept terms and conditions');
46
+ }*/
47
  if ($errorMsg) {
48
  Mage::throwException($errorMsg);
49
  }
59
  * @return $this
60
  */
61
  public function authorize(Varien_Object $payment, $amount)
62
+ {
63
  if (!$this->canAuthorize()) {
64
  Mage::throwException(
65
  Mage::helper('payment')->__('Authorize action is not available.')
66
  );
67
  }
68
+ //$api = $this->_initApi($this->getStore());
69
+ $api = $this->getApi();
70
  $result = $this->createInstallmentPlan($api, $payment, $amount);
71
+ $result = Mage::helper('core')->jsonDecode($result);
72
+ // show error if there is any error from spliti it when click on place order
73
+ if(!$result["ResponseHeader"]["Succeeded"]){
74
+ $errorMsg = "";
75
+ if(isset($result["serverError"])){
76
+ $errorMsg = $result["serverError"];
77
+ Mage::throwException(
78
+ Mage::helper('payment')->__($errorMsg)
79
+ );
80
+
81
+ }else{
82
+ foreach ($result["ResponseHeader"]["Errors"] as $key => $value) {
83
+ $errorMsg .= $value["ErrorCode"]." : ".$value["Message"];
84
+ }
85
+ Mage::throwException(
86
+ Mage::helper('payment')->__($errorMsg)
87
+ );
88
+ }
89
+
90
+ }
91
+
92
+ $payment->setTransactionId($result['InstallmentPlan']['InstallmentPlanNumber']);
93
  $payment->setIsTransactionClosed(0);
94
  $payment->setIsTransactionApproved(true);
95
  foreach (
103
  unset($result[$param]);
104
 
105
  }
106
+ //$st = $api->getInstallmentPlanStatusList();
107
+ //$result['InstallmentPlanStatus'] = $st[$result['InstallmentPlan']['InstallmentPlanStatus']['Id']];
108
+
109
  $payment->setTransactionAdditionalInfo(
110
  Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS,
111
  $result
114
  $order->addStatusToHistory(
115
  $order->getStatus(),
116
  'Payment InstallmentPlan was created with number ID: '
117
+ . $result['InstallmentPlan']['InstallmentPlanNumber'],
118
  false
119
  );
120
+ // call InstallmentPlan-UpdatePlan-Params for update "RefOrderNumber" after order creation
121
+ $updateStatus = $this->updateRefOrderNumber($api, $order);
122
+ if($updateStatus["status"] == false){
123
+ Mage::throwException(
124
+ Mage::helper('payment')->__($updateStatus["data"])
125
+ );
126
+ }
127
  //$order->save();
128
 
129
  return $this;
130
  }
131
 
132
+ public function splititCapture($payment, $sessionId, $transactionId){
133
+ $api = $this->getApi();
134
+ //$authNumber = $payment->getAuthorizationTransaction()->getTxnId();
135
+ $params = array(
136
+ "RequestHeader" => ["SessionId" => $sessionId],
137
+ "InstallmentPlanNumber" => $transactionId
138
+ );
139
+ $result = $api->startInstallment($this->getApiUrl(), $params);
140
+ if (!$result){
141
+ $e = $api->getError();
142
+ Mage::throwException($e['code'].' '.$e['message']);
143
+ }
144
+ $payment->setIsTransactionClosed(1);
145
+ $order = $payment->getOrder();
146
+
147
+ $order->addStatusToHistory(
148
+ false,
149
+ 'Payment NotifyOrderShipped was sent with number ID: '.$authNumber, false
150
+ );
151
+ $order->save();
152
+ return $result;
153
+ }
154
+
155
  /**
156
  * Capture payment abstract method
157
  *
160
  *
161
  * @return $this
162
  */
163
+ public function capture(Varien_Object $payment, $amount=null)
164
+ {
165
  if (!$this->canCapture()) {
166
  Mage::throwException(
167
  Mage::helper('payment')->__('Capture action is not available.')
173
  } else {
174
  $authNumber = $payment->getAuthorizationTransaction()->getTxnId();
175
  }
176
+
177
+ $paymentAction = Mage::getStoreConfig('payment/pis_cc/payment_action');
178
+ $params = array('InstallmentPlanNumber' => $authNumber);
179
+ if($paymentAction == "authorize_capture"){
180
+ $api = $this->getApi();
181
+ $sessionId = Mage::getSingleton('core/session')->getSplititSessionid();
182
+ }else{
183
+ $api = $this->_initApi($this->getStore());
184
+ $sessionId = Mage::getSingleton('core/session')->getSplititSessionid();
185
+ }
186
+ $params = array_merge($params, array("RequestHeader"=> array('SessionId' => $sessionId)));
187
+ $result = $api->startInstallment($this->getApiUrl(), $params);
188
+ $result = Mage::helper('core')->jsonDecode($result);
189
  $this->debugData('REQUEST: ' . $api->getRequest());
190
  $this->debugData('RESPONSE: ' . $api->getResponse());
191
  if (!$result) {
192
  $e = $api->getError();
193
+ $errorMsg = "";
194
+
195
+ $errorCode = 503;
196
+ $isErrorCode503Found = 0;
197
+ foreach ($result["ResponseHeader"]["Errors"] as $key => $value) {
198
+ $errorMsg .= $value["ErrorCode"]." : ".$value["Message"];
199
+ if($value["ErrorCode"] == $errorCode){
200
+ $isErrorCode503Found = 1;
201
+ break;
202
+ }
203
+ }
204
+
205
+
206
+ if($isErrorCode503Found == 0)
207
+ Mage::throwException($errorMsg." ".$e['code'].' '.$e['message']);
208
+ }elseif(isset($result["serverError"])){
209
+ $errorMsg = $result["serverError"];
210
+ Mage::throwException($errorMsg);
211
  }
212
 
213
  $payment->setIsTransactionClosed(1);
222
  return $this;
223
  }
224
 
225
+
 
 
 
 
 
 
226
  protected function createInstallmentPlan($api, $payment, $amount)
227
  {
228
+ $params = [
229
+ "RequestHeader" => [
230
+ "SessionId" => Mage::getSingleton('core/session')->getSplititSessionid(),
231
+ "ApiKey" => $this->getConfigData('api_terminal_key', $storeId),
232
+ ],
233
+ "InstallmentPlanNumber" => Mage::getSingleton('core/session')->getInstallmentPlanNumber(),
234
+ "CreditCardDetails" => [
235
+ "CardCvv" => $payment->getCcCid(),
236
+ "CardNumber" => $payment->getCcNumber(),
237
+ "CardExpYear" => $payment->getCcExpYear(),
238
+ "CardExpMonth" => $payment->getCcExpMonth(),
239
+ ],
240
+ "PlanApprovalEvidence" => [
241
+ "AreTermsAndConditionsApproved" => "True"
242
+ ],
243
+ ];
244
+ $result = $api->createInstallmentPlan($this->getApiUrl(),$params);
 
 
 
 
 
 
 
 
 
 
245
  if (!$result){
246
  $e = $api->getError();
247
  Mage::throwException($e['code'].' '.$e['message']);
255
  * @return PayItSimple_Payment_Model_Api
256
  * @throws Mage_Payment_Exception
257
  */
258
+ public function _initApi($storeId = null){
259
  if (is_null($storeId)) {
260
  $storeId = Mage::app()->getStore()->getId();
261
  }
263
  if ($api->isLogin()) {
264
  return $api;
265
  }
266
+ // get magento version
267
+ $m= new Mage;
268
+ $version=$m->getVersion();
269
+
270
+ if($version >= 1.9){
271
+ $touchPointVersion = "M1.9S2.0";
272
+ }elseif($version >= 1.8){
273
+ $touchPointVersion = "M1.8S2.0";
274
+ }
275
  $result = $api->login(
276
  $this->getApiUrl(),
277
  array(
278
+ //'ApiKey' => $this->getConfigData('api_terminal_key', $storeId),
279
  'UserName' => $this->getConfigData('api_username'),
280
+ 'Password' => $this->getConfigData('api_password'),
281
+ 'TouchPoint'=>array("Code" => "MagentoPlugin","Version" => $touchPointVersion)
282
  )
283
  );
284
  $this->debugData('REQUEST: ' . $api->getRequest());
285
  $this->debugData('RESPONSE: ' . $api->getResponse());
286
+ $api["error"] = "";
287
  if (!$result || !$api->isLogin()){
288
  $e = $api->getError();
289
+ // check for request from admin create invoice
290
+ if(Mage::app()->getRequest()->getControllerName() == "sales_order_invoice"){
291
+ Mage::throwException($e['code'].' '.$e['message']);
292
+ }
293
+
294
+ }else if(isset($result["serverError"])){
295
+ Mage::throwException($result["serverError"]);
296
  }
297
  return $api;
298
  }
302
  }
303
 
304
  public function getApiUrl() {
305
+
306
  if ($this->getConfigData('sandbox_flag')) {
307
+ $this->deleteUrls('api_url_sandbox');
308
  return $this->getConfigData('api_url_sandbox');
309
  }
310
+ $this->deleteUrls('api_url');
311
  return $this->getConfigData('api_url');
312
  }
313
 
314
+ public function deleteUrls($path){
315
+ $read = Mage::getSingleton('core/resource')->getConnection('core_read');
316
+ $write = Mage::getSingleton('core/resource')->getConnection('core_write');
317
+ //$result = $read->query("SELECT * FROM `core_config_data` WHERE path='payment/pis_cc/api_url_sandbox'");
318
+ $result = $read->query("SELECT * FROM `core_config_data` WHERE path='".$path."'");
319
+ $row = $result->fetch();
320
+ if(count($result)){
321
+ $transaction = Mage::getSingleton('core/resource')->getConnection('core_write');
322
+ try {
323
+ $transaction->beginTransaction();
324
+ $transaction->query('DELETE FROM `core_config_data` WHERE path like "%'.$path.'%"');
325
+ $transaction->commit();
326
+ } catch (Exception $e) {
327
+ $transaction->rollBack();
328
+ }
329
+ }
330
+
331
+
332
+ }
333
+
334
+
335
+ public function getValidNumberOfInstallments($api){
336
+ return $result = $api->getValidNumberOfInstallments();
337
+
338
+ }
339
+
340
+ public function updateRefOrderNumber($api, $order){
341
+ $params = [
342
+ "RequestHeader" => [
343
+ "SessionId" => Mage::getSingleton('core/session')->getSplititSessionid(),
344
+ ],
345
+ "InstallmentPlanNumber" => Mage::getSingleton('core/session')->getInstallmentPlanNumber(),
346
+ "PlanData" => [
347
+ "ExtendedParams" => [
348
+ "CreateAck" => "Received",
349
+ ],
350
+ "RefOrderNumber" => $order->getIncrementId(),
351
+ ],
352
+ ];
353
+ $response = ["status"=>false, "data" => ""];
354
+ $result = $api->updateRefOrderNumber($this->getApiUrl(), $params);
355
+ $decodedResult = Mage::helper('core')->jsonDecode($result);
356
+ if(isset($decodedResult["ResponseHeader"]["Succeeded"]) && $decodedResult["ResponseHeader"]["Succeeded"] == 1){
357
+ $response["status"] = true;
358
+ }else if(isset($decodedResult["ResponseHeader"]) && count($decodedResult["ResponseHeader"]["Errors"])){
359
+ $errorMsg = "";
360
+ $i = 1;
361
+ foreach ($decodedResult["ResponseHeader"]["Errors"] as $key => $value) {
362
+ $errorMsg .= "Code : ".$value["ErrorCode"]." - ".$value["Message"];
363
+ if($i < count($decodedResult["ResponseHeader"]["Errors"])){
364
+ $errorMsg .= ", ";
365
+ }
366
+ $i++;
367
+ }
368
+
369
+ $response["data"] = $errorMsg;
370
+ }
371
+ return $response;
372
+
373
+ }
374
+
375
+ public function installmentplaninit($api, $selectedInstallment){
376
+ $storeId = Mage::app()->getStore()->getId();
377
+ $session = Mage::getSingleton('checkout/session');
378
+ $quote_id = $session->getQuoteId();
379
+ $firstInstallmentAmount = $this->getFirstInstallmentAmount($selectedInstallment);
380
+ $checkout = Mage::getSingleton('checkout/session')->getQuote();
381
+ $billAddress = $checkout->getBillingAddress();
382
+ $BillingAddressArr = $billAddress->getData();
383
+ $customerInfo = Mage::getSingleton('customer/session')->getCustomer()->getData();
384
+ if(!isset($customerInfo["firstname"])){
385
+ $customerInfo["firstname"] = $billAddress->getFirstname();
386
+ $customerInfo["lastname"] = $billAddress->getLastname();
387
+ $customerInfo["email"] = $billAddress->getEmail();
388
+ }
389
+ $params = [
390
+ "RequestHeader" => [
391
+ "SessionId" => Mage::getSingleton('core/session')->getSplititSessionid(),
392
+ "ApiKey" => $this->getConfigData('api_terminal_key', $storeId),
393
+ ],
394
+ "PlanData" => [
395
+ "Amount" => [
396
+ "Value" => round(Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal(), 2),
397
+ "CurrencyCode" => Mage::app()->getStore()->getCurrentCurrencyCode(),
398
+ ],
399
+ "NumberOfInstallments" => $selectedInstallment,
400
+ "PurchaseMethod" => "ECommerce",
401
+ //"RefOrderNumber" => $quote_id,
402
+ "FirstInstallmentAmount" => [
403
+ "Value" => $firstInstallmentAmount,
404
+ "CurrencyCode" => Mage::app()->getStore()->getCurrentCurrencyCode(),
405
+ ],
406
+ "AutoCapture" => "false",
407
+ "ExtendedParams" => [
408
+ "CreateAck" => "NotReceived"
409
+ ],
410
+ ],
411
+ "BillingAddress" => [
412
+ "AddressLine" => $billAddress->getStreet()[0],
413
+ "AddressLine2" => $billAddress->getStreet()[1],
414
+ "City" => $billAddress->getCity(),
415
+ "State" => $billAddress->getRegion(),
416
+ "Country" => Mage::app()->getLocale()->getCountryTranslation($billAddress->getCountry()),
417
+ "Zip" => $billAddress->getPostcode(),
418
+ ],
419
+ "ConsumerData" => [
420
+ "FullName" => $customerInfo["firstname"]." ".$customerInfo["lastname"],
421
+ "Email" => $customerInfo["email"],
422
+ "PhoneNumber" => $billAddress->getTelephone()
423
+ ],
424
+ ];
425
+ //$api = Mage::getSingleton("pis_payment/pisMethod");
426
+ try{
427
+ $response = ["status"=>false, "data" => ""];
428
+ // check if cunsumer dont filled data
429
+ if($billAddress->getStreet()[0] == "" || $billAddress->getCity() == "" || $billAddress->getPostcode() == "" || $customerInfo["firstname"] == "" || $customerInfo["lastname"] == "" || $customerInfo["email"] == "" || $billAddress->getTelephone() == ""){
430
+ $response["emptyFields"] = true;
431
+ $response["data"] = "Please fill required fields.";
432
+ return $response;
433
+ }
434
+
435
+
436
+ $result = Mage::getSingleton("pis_payment/api")->installmentplaninit($this->getApiUrl(), $params);
437
+ // check for approval URL from response
438
+ $decodedResult = Mage::helper('core')->jsonDecode($result);
439
+
440
+ if(isset($decodedResult) && isset($decodedResult["ApprovalUrl"]) && $decodedResult["ApprovalUrl"] != ""){
441
+ $intallmentPlan = $decodedResult["InstallmentPlan"]["InstallmentPlanNumber"];
442
+ // set Installment plan number into session
443
+ Mage::getSingleton('core/session')->setInstallmentPlanNumber($intallmentPlan);
444
+ $approvalUrlResponse = Mage::getSingleton("pis_payment/api")->getApprovalUrlResponse($decodedResult["ApprovalUrl"]);
445
+ $approvalUrlRes = Mage::helper('core')->jsonDecode($approvalUrlResponse);
446
+ if(isset($approvalUrlRes["Global"]["ResponseResult"]["Errors"]) && count($approvalUrlRes["Global"]["ResponseResult"]["Errors"])){
447
+ $i = 1;
448
+ $errorMsg = "";
449
+ foreach ($approvalUrlRes["Global"]["ResponseResult"]["Errors"] as $key => $value) {
450
+ $errorMsg .= "Code : ".$value["ErrorCode"]." - ".$value["Message"];
451
+ if($i < count($approvalUrlRes["Global"]["ResponseResult"]["Errors"])){
452
+ $errorMsg .= ", ";
453
+ }
454
+ $i++;
455
+ }
456
+ $response["data"] = $errorMsg;
457
+ }else if(isset($approvalUrlRes["serverError"])){
458
+ $response["data"] = $decodedResult["serverError"];
459
+ }else{
460
+ $popupHtml = $this->createPopupHtml($approvalUrlResponse);
461
+ $response["status"] = true;
462
+ $response["data"] = $popupHtml;
463
+ }
464
+
465
+
466
+ //print_r($approvalUrlResponse);die("---approvalUrlResponse");
467
+ }else if(isset($decodedResult["ResponseHeader"]) && count($decodedResult["ResponseHeader"]["Errors"])){
468
+ $errorMsg = "";
469
+ $i = 1;
470
+ foreach ($decodedResult["ResponseHeader"]["Errors"] as $key => $value) {
471
+ $errorMsg .= "Code : ".$value["ErrorCode"]." - ".$value["Message"];
472
+ if($i < count($decodedResult["ResponseHeader"]["Errors"])){
473
+ $errorMsg .= ", ";
474
+ }
475
+ $i++;
476
+ }
477
+
478
+ $response["data"] = $errorMsg;
479
+ }else if(isset($decodedResult["serverError"])){
480
+ $response["data"] = $decodedResult["serverError"];
481
+ }
482
+
483
+ }catch(Exception $e){
484
+ $response["data"] = $e->getMessage();
485
+ }
486
+ return $response;
487
+ //return $result;
488
+ }
489
+
490
+ public function getFirstInstallmentAmount($selectedInstallment){
491
+ $firstPayment = Mage::getStoreConfig('payment/pis_cc/first_payment');
492
+ $percentageOfOrder = Mage::getStoreConfig('payment/pis_cc/percentage_of_order');
493
+ $installmentsInDropdownArr = Mage::getSingleton('core/session')->getInstallmentsInDropdown();
494
+
495
+ $firstInstallmentAmount = 0;
496
+ if($firstPayment == "equal"){
497
+ $firstInstallmentAmount = $installmentsInDropdownArr[$selectedInstallment];
498
+ }else if($firstPayment == "shipping_taxes"){
499
+ $shippingAmount = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingAmount();
500
+ $taxAmount = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData('tax_amount');
501
+ $firstInstallmentAmount = $installmentsInDropdownArr[$selectedInstallment]+$shippingAmount+$taxAmount;
502
+ }else if($firstPayment == "shipping"){
503
+ $shippingAmount = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingAmount();
504
+ $firstInstallmentAmount = $installmentsInDropdownArr[$selectedInstallment]+$shippingAmount;
505
+ }else if($firstPayment == "tax"){
506
+ $taxAmount = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData('tax_amount');
507
+ $firstInstallmentAmount = $installmentsInDropdownArr[$selectedInstallment]+$taxAmount;
508
+ }else if($firstPayment == "percentage"){
509
+ if($percentageOfOrder > 50){
510
+ $percentageOfOrder = 50;
511
+ }
512
+ $firstInstallmentAmount = ((Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal()*$percentageOfOrder)/100);
513
+ }
514
+
515
+ return round($firstInstallmentAmount,2);
516
+ }
517
+
518
+ public function createPopupHtml($approvalUrlResponse){
519
+ $approvalUrlResponseArr = Mage::helper('core')->jsonDecode($approvalUrlResponse);
520
+ $html = '';
521
+ if(!empty($approvalUrlResponseArr) && isset($approvalUrlResponseArr["Global"]["ResponseResult"]) && isset($approvalUrlResponseArr["Global"]["ResponseResult"]["Succeeded"]) && $approvalUrlResponseArr["Global"]["ResponseResult"]["Succeeded"] == 1){
522
+
523
+ $currencySymbol = $approvalUrlResponseArr["Global"]["Currency"]["Symbol"];
524
+ $totalAmount = $approvalUrlResponseArr["HeaderSection"]["InstallmentPlanTotalAmount"]["Amount"];
525
+ $totalText = $approvalUrlResponseArr["HeaderSection"]["InstallmentPlanTotalAmount"]["Text"];
526
+
527
+ $scheduleChargedDateText = $approvalUrlResponseArr["ScheduledPaymentSection"]["ChargedDateText"];
528
+ $scheduleChargedAmountText = $approvalUrlResponseArr["ScheduledPaymentSection"]["ChargedAmountText"];
529
+ $scheduleRequiredAvailableCreditText = $approvalUrlResponseArr["ScheduledPaymentSection"]["RequiredAvailableCreditText"];
530
+
531
+ $termsConditionsText = $approvalUrlResponseArr["ImportantNotesSection"]["AcknowledgeLink"]["Text"];
532
+ $termsConditionsLink = $approvalUrlResponseArr["ImportantNotesSection"]["AcknowledgeLink"]["Link"];
533
+ $servicesText = $approvalUrlResponseArr["LinksSection"]["PrivacyPolicy"]["Text"];
534
+ $servicesLink = $approvalUrlResponseArr["LinksSection"]["PrivacyPolicy"]["Link"];
535
+
536
+ $html .= '<div class="approval-popup_ovelay" style=""></div>';
537
+
538
+ $html .= '<div id="approval-popup" style="">';
539
+
540
+ $html .= '<div id="main">';
541
+ $html .= '<div class="_popup_overlay"></div>';
542
+ $html .= '<!-- Start small inner popup -->';
543
+
544
+ // Start Term and Condition Popup
545
+ $html .= '<div id="termAndConditionpopup" style=" ">
546
+ <div class="popup-block">
547
+ <div class="popup-content" style="">'.$this->getTermnConditionText().'
548
+
549
+ </div>';
550
+ $html .= '<div class="popup-footer" style="">';
551
+ $html .= '<div id="payment-schedule-close-btn" class="popup-btn" style="">';
552
+ $html .= '<div class="popup-btn-area" style=""><span id="termAndConditionpopupCloseBtn" class="popup-btn-icon" style="">Close</span></div>';
553
+ $html .= '</div>';
554
+ $html .= '</div>';
555
+ $html .= '</div>';
556
+ $html .= '</div>';
557
+ // Close Term and Condition Popup
558
+ $html .= '<div id="payment-schedule" style=" ">';
559
+ $html .= '<div class="popup-block">';
560
+ $html .= '<div class="popup-content" style="">';
561
+ $html .= '<table class="popupContentTable" style="">';
562
+ $html .= '<thead>';
563
+ $html .= '<tr>';
564
+ $html .= '<th style="width: 1em;"></th>';
565
+ $html .= '<th style="text-align:center;">'.$scheduleChargedDateText.'</th>';
566
+ $html .= '<th style="text-align:center;">'.$scheduleChargedAmountText.'</th>';
567
+ $html .= '<th style="text-align:center;">'.$scheduleRequiredAvailableCreditText.'</th>';
568
+ $html .= '</tr>';
569
+ $html .= '</thead>';
570
+ $html .= '<tbody>';
571
+ $schedulePayment = ""; //echo $value["DateOfCharge"];//substr($value["DateOfCharge"], 0, strpos($value["DateOfCharge"], "To"));
572
+ if(isset($approvalUrlResponseArr["ScheduledPaymentSection"]["ScheduleItems"])){
573
+
574
+ foreach ($approvalUrlResponseArr["ScheduledPaymentSection"]["ScheduleItems"] as $key => $value) {
575
+ $dateOfChargeTemp = (string)$value["DateOfCharge"];
576
+ $dataOfCharge = substr($dateOfChargeTemp, 0, strpos($dateOfChargeTemp, "T"));
577
+ $date=date_create($dataOfCharge);
578
+
579
+ $schedulePayment .= '<tr>';
580
+ $schedulePayment .= '<td style="text-align: left;">'.$value["InstallmentNumber"].'.</td>';
581
+ $schedulePayment .= '<td>'.date_format($date,"m/d/Y").'</td>';
582
+ $schedulePayment .= '<td>'.$currencySymbol.$value["ChargeAmount"].'</td>';
583
+ $schedulePayment .= '<td>'.$currencySymbol.$value["RequiredAvailableCredit"].'</td>';
584
+ $schedulePayment .= '</tr>';
585
+ }
586
+ }
587
+ $html .= $schedulePayment;
588
+ $html .= '</tbody>';
589
+ $html .= '</table>';
590
+ $html .= '</div>';
591
+ $html .= '<div class="popup-footer" style="">';
592
+ $html .= '<div id="payment-schedule-close-btn" class="popup-btn" style="">';
593
+ $html .= '<div class="popup-btn-area" style=""><span id="complete-payment-schedule-close" class="popup-btn-icon" style="">Close</span></div>';
594
+ $html .= '</div>';
595
+ $html .= '</div>';
596
+ $html .= '</div>';
597
+ $html .= '</div>';
598
+ $html .= '<!-- End small inner popup -->';
599
+
600
+
601
+ $html .= '<div class="mainHeader">';
602
+ $html .= '<span class="closeapprovalpopup_btn" style="" onclick="closeApprovalPopup();"><img style="width:100%;" src="'. Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true ).'js/payitsimple/payitsimplepament/approval-popup-close.png"></span>';
603
+ $html .= '<table id="wiz-header" width="100%;">';
604
+ $html .= '<tbody>';
605
+ $html .= '<tr>';
606
+ $html .= '<td class="wiz-header-side wiz-header-left" style=""></td>';
607
+ $html .= '<td class="wiz-header-center" style="">';
608
+ $html .= '<div>TOTAL PURCHASE:</div>';
609
+ $html .= '<div class="currencySymbolIcon" style="">'.$currencySymbol.$totalAmount.'</div></td><td class="wiz-header-side wiz-header-right" style="">';
610
+ $html .= '</td>';
611
+ $html .= '</tr>';
612
+ $html .= '</tbody>';
613
+ $html .= '</table>';
614
+ $html .= '</div>';
615
+ $html .= '<div style="margin-top: auto;">';
616
+
617
+ $html .= '<div class="form-block" style="">';
618
+ $html .= '<div class="form-block-area" style="">';
619
+ $html .= '<div class="spacer15" style=""></div>';
620
+ $html .= '<div class="tableResponsive"><table class="tablePage2" style="" cellspacing="0" cellpadding="0">';
621
+ $html .= '<tbody>';
622
+
623
+ $planDataSection = '';
624
+ $planDataSectionHtml = '';
625
+ $planDataSection = $approvalUrlResponseArr["PlanDataSection"];
626
+ if(isset($approvalUrlResponseArr["PlanDataSection"])){
627
+ $planDataSectionHtml .= '<tr class="tablePage2TD" style="">';
628
+ $planDataSectionHtml .= '<td>'.$planDataSection["NumberOfInstallments"]["Text"].'</td>';
629
+ $planDataSectionHtml .= '<td class="text-right" style="">';
630
+ $planDataSectionHtml .= '<span>'.$planDataSection["NumberOfInstallments"]["NumOfInstallments"].'</span>';
631
+ $planDataSectionHtml .= '</td></tr>';
632
+
633
+ $planDataSectionHtml .= '<tr class="tablePage2TD" style="">';
634
+ $planDataSectionHtml .= '<td>'.$planDataSection["FirstInstallmentAmount"]["Text"].'</td>';
635
+ $planDataSectionHtml .= '<td class="text-right" style="">';
636
+ $planDataSectionHtml .= '<span>'.$currencySymbol.$planDataSection["FirstInstallmentAmount"]["Amount"].'</span>';
637
+ $planDataSectionHtml .= '</td></tr>';
638
+
639
+ $planDataSectionHtml .= '<tr class="tablePage2TD" style="">';
640
+ $planDataSectionHtml .= '<td>'.$planDataSection["SubsequentInstallmentAmount"]["Text"].'</td>';
641
+ $planDataSectionHtml .= '<td class="text-right">';
642
+ $planDataSectionHtml .= '<span>'.$currencySymbol.$planDataSection["SubsequentInstallmentAmount"]["Amount"].'</span>';
643
+ $planDataSectionHtml .= '</td></tr>';
644
+
645
+ $planDataSectionHtml .= '<tr class="tablePage2TD" style="">';
646
+ $planDataSectionHtml .= '<td>'.$planDataSection["RequiredAvailableCredit"]["Text"].'</td>';
647
+ $planDataSectionHtml .= '<td class="text-right" style="">';
648
+ $planDataSectionHtml .= '<span>'.$currencySymbol.$planDataSection["RequiredAvailableCredit"]["Amount"].'</span>';
649
+ $planDataSectionHtml .= '</td></tr>';
650
+
651
+ }
652
+
653
+ $html .= $planDataSectionHtml;
654
+ $html .= '</tbody>';
655
+ $html .= '</table></div>';
656
+ $html .= '<a id="payment-schedule-link" style="">See Complete Payment Schedule</a>';
657
+ $html .= '</div>';
658
+ $html .= '</div>';
659
+ $html .= '<div class="form-block right" style="">';
660
+ $html .= '<div class="form-block-area">';
661
+ $html .= '<div>';
662
+ $html .= '<div class="important_note_sec" style="">'.$approvalUrlResponseArr["ImportantNotesSection"]["ImportantNotesHeader"]["Text"].':</div>';
663
+ $html .= '<div class="pnlEula" style="">'.$approvalUrlResponseArr["ImportantNotesSection"]["ImportantNotesBody"]["Text"].'</div>';
664
+ $html .= '<div id="i_acknowledge_area"><input type="checkbox" id="i_acknowledge" class="i_acknowledge" name="i_acknowledge" value="" />';
665
+ $html .= '<label for="i_acknowledge" class="i_acknowledge_lbl">';
666
+ $html .= 'I acknowledge that I have read and agree to the <a href="#" id="i_acknowledge_content_show" > terms and conditions </a> </label><div style="display:none" class="i_ack_err"> Please select I acknowledge.</div></div>' ;
667
+
668
+
669
+
670
+ $html .= '</div>';
671
+ $html .= '</div>';
672
+ $html .= '</div>';
673
+ $html .= '</div>';
674
+ $html .= '<div class="iAgreeBtn" style=""><input id="iagree" type="button" onclick="paymentSave();" value="I agree" style=" "> </div>';
675
+ $html .= '<div class="termAndConditionBtn" style=""> <a href="'.$termsConditionsLink.'" target="_blank" style="">'.$termsConditionsText.'</a> | <a href="'.$servicesLink.'" style="" target="_blank">'.$servicesText.'</a>
676
+
677
+ </div>';
678
+
679
+ $html .= '</div>';
680
+
681
+
682
+
683
+
684
+ }
685
+
686
+ return $html;
687
+ }
688
+
689
+ public function getTermnConditionText(){
690
+ $str = '<p style="text-align: left;">1. &nbsp;Buyer, whose name appears below ("Buyer", "You", or "Your"), promises to pay the full amount of the Total Authorized Purchase Price in the number of installment payments set forth in the Recurring Installment Payment Authorization ("Authorization") to Seller ("Seller", "We" or "Us") by authorizing Seller to charge Buyer’s credit card in equal monthly installments as set forth in the Authorization (each an "Installment") each month until paid in full.</p>