PluginProbe
MakeCommerce for WooCommerce / 1.0.3
MakeCommerce for WooCommerce v1.0.3
4.1.0 4.0.8 trunk 1.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.2.0 2.2.1 2.2.2 All 96 releases
makecommerce / makecommerce.php

makecommerce.php in MakeCommerce for WooCommerce 1.0.3, at makecommerce.php

2,098 lines 84.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: MakeCommerce for WooCommerce
4 Description: Adds MakeCommerce payment gateway and Itella/Omniva parcel machine shipping methods to Woocommerce checkout
5 Version: 1.0.3
6 Author: Maksekeskus AS
7 Author URI: https://MakeCommerce.net/
8 Text Domain: wc_makecommerce_domain
9 */
10
11 if ( ! defined( 'ABSPATH' ) ) {
12 exit; // Exit if accessed directly.
13 }
14
15 if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
16
17 global $mkDbTable;
18 $mkDbTable = 'mc_banklinks';
19
20 function mc_install() {
21 global $wpdb;
22 global $mkDbTable;
23
24 $tableName = $wpdb->prefix . $mkDbTable;
25
26 $charset = $wpdb->get_charset_collate();
27
28 $sql = "CREATE TABLE $tableName (
29 id mediumint(9) NOT NULL AUTO_INCREMENT,
30 type varchar(10) NOT NULL,
31 country char(2) NOT NULL,
32 name varchar(25) NOT NULL,
33 url varchar(250) NOT NULL,
34 UNIQUE KEY id (id)
35 ) $charset;";
36
37 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
38 dbDelta( $sql );
39 }
40
41 register_activation_hook( __FILE__, 'mc_install' );
42
43 if (!class_exists('wc_makecommerce_domain')) {
44 require_once('includes/Api.php');
45 }
46
47 function woocommerce_payment_makecommerce_init() {
48 load_plugin_textdomain('wc_makecommerce_domain', false, dirname(plugin_basename(__FILE__)) . '/');
49
50
51 class woocommerce_makecommerce extends WC_Payment_Gateway {
52
53 const MC_CANCELLED = 'CANCELLED';
54 const MC_COMPLETED = 'COMPLETED';
55 const MC_DEPOSITED = 'DEPOSITED';
56
57 const MC_PART_REFUNDED = 'PART_REFUNDED';
58 const MC_REFUNDED = 'REFUNDED';
59
60 const module_name = 'MakeCommerce';
61 const api_url = 'https://api.maksekeskus.ee/v1/';
62 const gateway_url = 'https://payment.maksekeskus.ee/pay/1/signed.html';
63 const gateway_url_static = 'https://payment.maksekeskus.ee/checkout/dist/';
64 const fo_url = 'https://merchant.maksekeskus.ee/';
65 const test_api_url = 'https://api-test.maksekeskus.ee/v1/';
66 const test_gateway_url = 'https://payment-test.maksekeskus.ee/pay/1/signed.html';
67 const test_gateway_url_static = 'https://payment-test.maksekeskus.ee/checkout/dist/';
68 const test_fo_url = 'https://merchant-test.maksekeskus.ee/';
69 const billing_descriptor_dba = '';
70 const currencies_allowed = 'EUR';
71 const module_homepage_url = 'https://maksekeskus.ee/en/integration-modules/makecommerce-woocommerce-payment-plugin/';
72 const testenv_homepage_url = 'http://maksekeskus.ee/en/for-developers/test-environment/';
73
74 public $id = 'makecommerce';
75 public $version = '1.1';
76
77 public $return_url;
78 public $return_url_cancel;
79
80 public $return_url_cc;
81
82 protected $_shop_id;
83 protected $_api_key_secret;
84 protected $_api_key_public;
85
86 protected $_gateway_url_static;
87
88 protected $_banklinks = array();
89 protected $_banklinks_grouped;
90 protected $_cards = array();
91
92 protected $_api;
93
94 protected $_init;
95
96 public function __construct($init = false) {
97
98 $this->_init = $init;
99
100 $this->return_url = site_url('/?makecommerce_return=1');
101 $this->return_url_cancel = site_url('/?makecommerce_return=1');
102
103 $this->return_url_cc = site_url('/?makecommerce_return=2');
104
105 // Load the form fields.
106 $this->init_form_fields();
107
108 // Load the settings.
109 $this->init_settings();
110
111 $this->initBanklinks();
112
113 $this->title = $this->settings['ui_widget_title'];
114 $this->method_title = 'MakeCommerce';
115 $this->description = true;
116
117 $this->_api = mk_get_api();
118 if (!$this->_api && $this->_init) {
119 add_action( 'admin_notices', array(&$this, 'makecommerce_api_info_missing') );
120 }
121
122 if(get_option('mk_api_type', false) == 'live') {
123 $this->_gateway_url_static = self::gateway_url_static;
124 } elseif (get_option('mk_api_type', false) == 'test') {
125 $this->_gateway_url_static = self::test_gateway_url_static;
126 }
127
128 $this->supports = array(
129 'products',
130 'refunds',
131 );
132
133 add_filter('query_vars', array(&$this, 'makecommerce_return_trigger'));
134 add_action('template_redirect', array(&$this, 'makecommerce_return_trigger_check'));
135
136 add_action( 'wp_ajax_makecommerce_pay_token', array(&$this, 'makecommerce_pay_token') );
137 add_action( 'wp_ajax_nopriv_makecommerce_pay_token', array(&$this, 'makecommerce_pay_token') );
138
139 if($this->_init == false) {
140 add_action('woocommerce_update_options_payment_gateways', array(&$this, 'process_admin_options'));
141 add_action('woocommerce_update_options_payment_gateways_' . $this->id, array(&$this, 'process_admin_options'));
142
143 add_action('woocommerce_receipt_' . $this->id, array(&$this, 'receipt_page'));
144 add_action('woocommerce_admin_order_data_after_order_details', array(&$this, 'admin_order_page'), 10, 1);
145
146 wp_enqueue_script('jquery');
147 wp_enqueue_style('makecommerce', plugins_url('/css/makecommerce.css', __FILE__), array(), $this->version);
148 }
149
150 if(is_admin()) {
151 add_action( 'wp_ajax_mc_banklinks_reload', array(&$this, 'mc_banklinks_reload') );
152 }
153 }
154
155 function makecommerce_api_info_missing() {
156 ?>
157 <div class="notice notice-error is-dismissible">
158 <p>
159 <?php echo __('You have not entered the Shop ID and keys for the MakeCommerce payment module. The module will not work without them.', 'wc_makecommerce_domain'); ?>
160 <a href="<?php echo admin_url('admin.php?page=wc-settings&tab=api&section=mk_api'); ?>"><?php echo __('Click here to enter them', 'wc_makecommerce_domain'); ?></a>
161 </p>
162 </div>
163 <?php
164 }
165
166 function makecommerce_banklinks_list_empty() {
167 ?>
168 <div class="notice notice-error is-dismissible">
169 <p>
170 <?php echo __('The payment methods list for MakeCommerce payment module is empty.', 'wc_makecommerce_domain'); ?>
171 <a href="<?php echo admin_url('admin.php?page=wc-settings&tab=checkout&section=makecommerce'); ?>"><?php echo __('Go to the settings to update them', 'wc_makecommerce_domain'); ?></a>
172 </p>
173 </div>
174 <?php
175 }
176
177 function makecommerce_banklinks_list_type_notice() {
178 ?>
179 <div class="notice notice-error is-dismissible">
180 <p>
181 <?php echo __('You have changed the environment for MakeCommerce payment module. The payment methods list has been loaded for a different environment.', 'wc_makecommerce_domain'); ?>
182 <a href="<?php echo admin_url('admin.php?page=wc-settings&tab=checkout&section=makecommerce'); ?>"><?php echo __('Go to the settings to update them', 'wc_makecommerce_domain'); ?></a>
183 </p>
184 </div>
185 <?php
186 }
187
188 /**
189 * Initialise Gateway Settings Form Fields
190 */
191 function init_form_fields() {
192
193 $this->form_fields = array(
194 'header' => array(
195 'type' => 'mc_header',
196 ),
197 'active' => array(
198 'title' => __('Enable/Disable', 'wc_makecommerce_domain'),
199 'type' => 'checkbox',
200 'label' => __('Enable MakeCommerce payments', 'wc_makecommerce_domain'),
201 'default' => 'no'
202 ),
203 'api_title' => array(
204 'title' => __('MakeCommerce API', 'wc_makecommerce_domain'),
205 'description' => sprintf(__('Go to <a href="%s">API settings</a> to fill in the credentials', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api&section=mk_api')),
206 'type' => 'title',
207 ),
208 'ui_title' => array(
209 'title' => '<br>'.__('User Interface', 'wc_makecommerce_domain'),
210 'type' => 'title',
211 'class' => 'ui-identifier',
212 ),
213 'ui_open_by_default' => array(
214 'title' => __('Set as default selection', 'wc_makecommerce_domain'),
215 'label' => __('MakeCommerce payments widget will be selected by default', 'wc_makecommerce_domain'),
216 'type' => 'checkbox',
217 'default' => 'yes',
218 'class' => 'ui-identifier',
219 ),
220 'ui_mode' => array(
221 'title' => __('Display MC payment channels as', 'wc_makecommerce_domain'),
222 'type' => 'mc_hidden',
223 'default' => 'widget',
224 'options' => array(
225 'inline' => __('List', 'wc_makecommerce_domain'),
226 'widget' => __('Grouped to widget', 'wc_makecommerce_domain'),
227 ),
228 'class' => 'ui-identifier',
229 ),
230 'ui_widget_title' => array(
231 'title' => __('MC payments widget title', 'wc_makecommerce_domain'),
232 'type' => 'text',
233 'desc_tip' => __("Appropriate title may depend on the configuration you have made, i.e. 'pay with bank-link or credit card', 'pay with bank-links' or 'payment methods'", 'wc_makecommerce_domain'),
234 'default' => __('Pay with bank-links or credit card', 'wc_makecommerce_domain'),
235 'class' => 'ui-identifier',
236 ),
237 'ui_inline_uselogo' => array(
238 'title' => __('MC payment channels display style', 'wc_makecommerce_domain'),
239 'type' => 'select',
240 'default' => 'logo',
241 'options' => array(
242 'logo' => __('Logo', 'wc_makecommerce_domain'),
243 'text_logo' => __('Text & logo', 'wc_makecommerce_domain'),
244 'text' => __('Text', 'wc_makecommerce_domain'),
245 ),
246 'class' => 'ui-identifier',
247 ),
248 'ui_widget_logosize' => array(
249 'title' => __('Size of payment channel logos', 'wc_makecommerce_domain'),
250 'type' => 'select',
251 'default' => 'medium',
252 'options' => array(
253 'small' => __('Small', 'wc_makecommerce_domain'),
254 'medium' => __('Medium', 'wc_makecommerce_domain'),
255 'large' => __('Large', 'wc_makecommerce_domain')
256 ),
257 'class' => 'ui-identifier',
258 ),
259 'ui_widget_groupcountries' => array(
260 'title' => __('Group bank-links by countries', 'wc_makecommerce_domain'),
261 'type' => 'mc_hidden',
262 'default' => 'no',
263 'class' => 'ui-identifier',
264 ),
265 'ui_widget_countryselector' => array(
266 'title' => __('Country selector style', 'wc_makecommerce_domain'),
267 'type' => 'mc_hidden',
268 'default' => 'flag',
269 'options' => array(
270 'flag' => __('Flag', 'wc_makecommerce_domain'),
271 'dropdown' => __('Dropdown', 'wc_makecommerce_domain'),
272 ),
273 'class' => 'ui-identifier',
274 ),
275 'ui_widget_groupcc' => array(
276 'title' => __('Group credit card into separate widget', 'wc_makecommerce_domain'),
277 'type' => 'mc_hidden',
278 'default' => 'no',
279 'class' => 'ui-identifier',
280 ),
281 'ui_chorder' => array(
282 'title' => __('Define custom order of payment channels', 'wc_makecommerce_domain'),
283 'type' => 'text',
284 'desc_tip' => __('If you want to change default order, put here comma separated list of channels. i,e, - seb,lhv,swedbank. see more on the module home page (link above)', 'wc_makecommerce_domain'),
285 'class' => 'ui-identifier',
286 ),
287 'ui_javascript' => array(
288 'type' => 'ui_javascript',
289 ),
290 'cc_title' => array(
291 'title' => '<br>'.__('Credit Card Settings', 'wc_makecommerce_domain'),
292 'type' => 'title',
293 ),
294 'cc_pass_cust_data' => array(
295 'title' => __('Prefill Credit Card form with customer data', 'wc_makecommerce_domain'),
296 'type' => 'checkbox',
297 'default' => 'yes',
298 'desc_tip' => __('It will pass user Name and e-mail address to the Credit Card dialog to make the form filling easier', 'wc_makecommerce_domain'),
299 ),
300 'cc_shop_name' => array(
301 'title' => __('Shop name on credit card payment', 'wc_makecommerce_domain'),
302 'type' => 'text',
303 'desc_tip' => __('This will appear on buyer\'s credit card transaction', 'wc_makecommerce_domain'),
304 ),
305 'cc_cart_reference_string' => array(
306 'title' => __('Order reference on credit card payment', 'wc_makecommerce_domain'),
307 'type' => 'text',
308 'default' => 'Order %s',
309 'desc_tip' => __('This will appear on buyer\'s credit card transaction where "%s" is the order number', 'wc_makecommerce_domain'),
310 ),
311 'adv_title' => array(
312 'title' => '<br>'.__('Advanced Settings', 'wc_makecommerce_domain'),
313 'type' => 'title',
314 ),
315 'reload_links' => array(
316 'type' => 'mc_banklinks_reload',
317 'title' => __('Update payment methods', 'wc_makecommerce_domain'),
318 'description' => __('Update', 'wc_makecommerce_domain'),
319 'desc_tip' => __('This will update shop configuration from MakeCommerce servers.', 'wc_makecommerce_domain'),
320 ),
321 );
322 }
323
324 public function generate_mc_hidden_html( $key, $data ) {
325 $field_key = $this->get_field_key($key);
326 ob_start();
327 ?>
328 <tr style="display: none;">
329 <td colspan="2">
330 <input type="hidden" name="<?php echo $field_key; ?>" value="<?php echo $data['default']; ?>" />
331 </td>
332 </tr>
333 <?php
334 return ob_get_clean();
335 }
336
337 public function generate_mc_banklinks_reload_html( $key, $data ) {
338
339 $field = $this->get_field_key( $key );
340 $defaults = array(
341 'title' => '',
342 'disabled' => false,
343 'class' => '',
344 'css' => '',
345 'placeholder' => '',
346 'type' => 'text',
347 'desc_tip' => false,
348 'description' => '',
349 'custom_attributes' => array()
350 );
351
352 $data = wp_parse_args( $data, $defaults );
353
354 ob_start();
355 ?>
356 <tr valign="top">
357 <th scope="row" class="titledesc">
358 <label for="<?php echo esc_attr( $field ); ?>"><?php echo wp_kses_post( $data['title'] ); ?></label>
359 <?php echo $this->get_tooltip_html( $data ); ?>
360 </th>
361 <td class="forminp">
362 <fieldset>
363 <legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
364 <input id="mc_banklinks_reload" class="button <?php echo esc_attr( $data['class'] ); ?>" type="button" name="<?php echo esc_attr( $field ); ?>" id="<?php echo esc_attr( $field ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" value="<?php echo esc_attr( $data['description'] ); ?>" placeholder="<?php echo esc_attr( $data['placeholder'] ); ?>" <?php disabled( $data['disabled'], true ); ?> <?php echo $this->get_custom_attribute_html( $data ); ?> />
365 <script type="text/javascript">
366 jQuery('input#mc_banklinks_reload').on('click', function() {
367 init_mc_loading();
368 jQuery.ajax({
369 url: '<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php',
370 type: 'POST',
371 data: 'action=mc_banklinks_reload',
372 success: function (output) {
373 if(output.data) {
374 alert(output.data);
375 } else {
376 alert('<?php echo __('There was an error with your update. Please try again.', 'wc_makecommerce_domain'); ?>');
377 }
378 },
379 complete: function() { stop_mc_loading(); }
380 });
381 });
382
383 function init_mc_loading() {
384 jQuery('input#mc_banklinks_reload').attr('disabled', 'disabled');
385 }
386
387 function stop_mc_loading() {
388 jQuery('input#mc_banklinks_reload').removeAttr('disabled');
389 }
390 </script>
391 </fieldset>
392 </td>
393 </tr>
394 <?php
395
396 return ob_get_clean();
397 }
398
399 public function generate_ui_javascript_html( $key, $data ) {
400 ?>
401 <script type="text/javascript">
402 jQuery(document).ready(function($) {
403
404 var api_type = $('#woocommerce_<?php echo $this->id; ?>_api_type');
405
406 var ui_inline_uselogo_row = $('#woocommerce_<?php echo $this->id; ?>_ui_inline_uselogo').closest('tr');
407 var ui_widget_title_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_title').closest('tr');
408 var ui_widget_logosize_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_logosize').closest('tr');
409 var ui_widget_countryselector_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_countryselector').closest('tr');
410 var ui_widget_groupcountries_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcountries').closest('tr');
411 var ui_widget_groupcc_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcc').closest('tr');
412 var ui_widget_groupcc_title_row = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcc_title').closest('tr');
413
414 var ui_mode = $('#woocommerce_<?php echo $this->id; ?>_ui_mode');
415 var ui_widget_groupcountries = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcountries');
416 var ui_widget_groupcc = $('#woocommerce_<?php echo $this->id; ?>_ui_widget_groupcc');
417
418 parseVisibility();
419 function parseVisibility() {
420 $('.ui-identifier').closest('tr').show();
421
422 if(api_type.val() == 'live') {
423 $('.mc-test-link').hide();
424 $('.api-test').closest('tr').hide();
425 } else {
426 $('.mc-test-link').show();
427 $('.api-live').closest('tr').hide();
428 }
429
430 if(ui_mode.val() == 'inline') {
431 ui_widget_title_row.hide();
432 ui_widget_logosize_row.hide();
433 ui_widget_countryselector_row.hide();
434 ui_widget_groupcountries_row.hide();
435 ui_widget_groupcc_row.hide();
436 ui_widget_groupcc_title_row.hide();
437 } else {
438 ui_inline_uselogo_row.hide();
439
440 if(ui_widget_groupcountries.prop('checked')) {
441 ui_widget_countryselector_row.hide();
442 }
443 if(!ui_widget_groupcc.prop('checked')) {
444 ui_widget_groupcc_title_row.hide();
445 }
446 }
447 }
448
449 api_type.on('change', parseVisibility);
450 ui_mode.on('change', parseVisibility);
451 ui_widget_groupcountries.on('change', parseVisibility);
452 ui_widget_groupcc.on('change', parseVisibility);
453
454 });
455 </script>
456 <?php
457 }
458
459 public function generate_mc_header_html( $key, $data ) {
460 ?>
461 <div class="makecommerce-info">
462 <div class="makecommerce-logo">
463 <a target="_blank" href="http://makecommerce.net"><img src="<?php echo plugins_url('/images/makecommerce_logo_en.svg', __FILE__); ?>" class="makecommerce-logo"></a>
464 </div>
465 <div class="makecommerce-links">
466 <div class="makecommerce-link"><a target="_blank" href="https://merchant.maksekeskus.ee">Merchant Portal</a></div>
467 <div class="makecommerce-link"><a target="_blank" href="https://makecommerce.net/">makecommerce.net</a></div>
468 <div class="makecommerce-link"><a target="_blank" href="http://maksekeskus.ee">maksekeskus.ee</a></div>
469 </div>
470 </div>
471 <?php
472 }
473
474 public function mc_banklinks_reload($force = false) {
475 if ($force || (defined('DOING_AJAX') && DOING_AJAX)) {
476
477 global $wpdb;
478 global $mkDbTable;
479 global $wp_version;
480
481 $tableName = $wpdb->prefix . $mkDbTable;
482 $wpdb->query('TRUNCATE TABLE '.$tableName);
483
484 $request_params = array(
485 'environment' => json_encode(array(
486 'platform' => 'wordpress '.$wp_version,
487 'module' => $this->id.' '.$this->version,
488 )),
489 );
490
491 if (!$this->_api) {
492 return false;
493 }
494
495 try {
496 $methods = $this->_api->getShopConfig($request_params)->paymentMethods;
497 } catch (Exception $e) {
498 error_log(print_r($e, 1));
499 return false;
500 }
501 if(isset($methods->banklinks)) {
502 foreach($methods->banklinks as $method) {
503 $wpdb->insert($tableName, array('type' => 'banklink', 'country' => $method->country, 'name' => $method->name, 'url' => $method->url));
504 }
505 $updated = true;
506 }
507
508 if(isset($methods->cards)) {
509 foreach($methods->cards as $method) {
510 $wpdb->insert($tableName, array('type' => 'card', 'name' => $method->name));
511 }
512 $updated = true;
513 }
514 if ($updated) {
515 update_option( 'mc_banklinks_api_type', get_option('mk_api_type', false) );
516 }
517 if ($force) {
518 $this->initBankLinks();
519 return $updated;
520 }
521
522 if($updated) {
523 wp_send_json(array('success' => 1, 'data' => __('Update successfully completed!', 'wc_makecommerce_domain')));
524 exit;
525 }
526
527 wp_send_json(array('success' => 0, 'data' => __('There was an error with your update. Please try again.', 'wc_makecommerce_domain')));
528 exit;
529 }
530 die();
531 }
532
533 protected function _getWooCommerce() {
534 global $woocommerce;
535 return $woocommerce;
536 }
537
538 function is_valid_for_use() {
539 return true;
540 }
541
542 public function is_available() {
543 if ($this->settings['active'] == "yes") {
544 return true;
545 }
546 }
547
548 function payment_fields() {
549
550 if($this->settings['ui_mode'] == 'inline') {
551
552 ?>
553 <ul class="makecommerce-picker">
554 <?php foreach($this->_banklinks as $method): ?>
555 <li class="makecommerce-picker-method">
556 <input type="radio" id="makecommerce_method_picker_<?php echo $method->country.'_'.$method->name; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>" value="<?php echo $method->country.'_'.$method->name; ?>"/>
557 <label for="makecommerce_method_picker_<?php echo $method->country.'_'.$method->name; ?>">
558 <span class="makecommerce-method-title"><?php if(in_array($this->settings['ui_inline_uselogo'], array('text', 'text_logo'))) { echo ucfirst($method->name); if(count($this->_banklinks_grouped) > 1) { echo ' ('.$this->getCountryName($method->country).')'; } } ?></span>
559 <?php if(in_array($this->settings['ui_inline_uselogo'], array('logo', 'text_logo'))) : ?>
560 <div><img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" /></div>
561 <?php endif; ?>
562 </label>
563 </li>
564 <?php endforeach; ?>
565 <?php foreach($this->_cards as $method): ?>
566 <li class="makecommerce-picker-method">
567 <input type="radio" id="makecommerce_method_picker_<?php echo 'card_'.$method->name; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>" value="<?php echo 'card_'.$method->name; ?>"/>
568 <label for="makecommerce_method_picker_<?php echo 'card_'.$method->name; ?>">
569 <span class="makecommerce-method-title"><?php if(in_array($this->settings['ui_inline_uselogo'], array('text', 'text_logo'))) { echo ucfirst($method->name); } ?></span>
570 <?php if(in_array($this->settings['ui_inline_uselogo'], array('logo', 'text_logo'))) : ?>
571 <div><img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" /></div>
572 <?php endif; ?>
573 </label>
574 </li>
575 <?php endforeach; ?>
576 </ul>
577 <?php
578
579 } else {
580 ?>
581 <select id="<?php echo $this->id; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>">
582 <option value=""></option>
583 <?php foreach($this->_banklinks as $method): ?>
584 <option value="<?php echo $method->country.'_'.$method->name; ?>"><?php echo strtoupper($method->country).' - '.ucfirst($method->name); ?></option>
585 <?php endforeach; ?>
586 <?php foreach($this->_cards as $method): ?>
587 <option value="card_<?php echo $method->name; ?>"><?php echo ucfirst($method->name); ?></option>
588 <?php endforeach; ?>
589 </select>
590 <ul class="makecommerce-picker">
591 <?php
592
593 if($this->_banklinks) {
594 $defaultCountry = $this->getDefaultCountry();
595 ?>
596 <?php if(empty($this->settings['ui_widget_groupcountries']) || $this->settings['ui_widget_groupcountries'] == 'no') : ?>
597 <div class="makecommerce_country_picker_countries">
598 <?php foreach(array_keys($this->_banklinks_grouped) as $country): ?>
599 <input style="display: none;" type="radio" id="makecommerce_country_picker_<?php echo $country; ?>" name="makecommerce_country_picker" value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'checked="checked" '; ?>/><?php if($this->settings['ui_widget_countryselector'] == 'flag') { ?><label for="makecommerce_country_picker_<?php echo $country; ?>" class="makecommerce_country_picker_label" style="background-image: url(<?php echo plugins_url('/images/'.$country.'32.png', __FILE__); ?>);"></label><?php } ?>
600 <?php endforeach; ?>
601 <?php if($this->settings['ui_widget_countryselector'] == 'dropdown') : ?>
602 <select name="makecommerce_country_picker_select">
603 <?php foreach(array_keys($this->_banklinks_grouped) as $country): ?>
604 <option value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'selected="selected" '; ?>><?php echo $this->getCountryName($country); ?></option>
605 <?php endforeach; ?>
606 <option value="card" style="display:none;"></option>
607 </select>
608 <?php endif; ?>
609 </div>
610 <?php endif; ?>
611 <?php foreach($this->_banklinks_grouped as $country => $methods): ?>
612 <li class="makecommerce-picker-country">
613 <?php if($this->settings['ui_widget_groupcountries'] == 'yes') : ?>
614 <input type="radio" id="makecommerce_country_picker_<?php echo $country; ?>" name="makecommerce_country_picker" value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'checked="checked" '; ?>/><label for="makecommerce_country_picker_<?php echo $country; ?>"><img src="<?php echo plugins_url('/images/'.$country.'32.png', __FILE__); ?>" /></label>
615 <?php endif; ?>
616 <div class="makecommerce_country_picker_methods" id="makecommerce_country_picker_methods_<?php echo $country; ?>">
617 <?php foreach($methods as $method): ?>
618 <div class="makecommerce-banklink-picker" banklink_id="<?php echo $method->country.'_'.$method->name; ?>">
619 <img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
620 </div>
621 <?php endforeach; ?>
622 <?php if($this->_cards && $this->settings['ui_widget_groupcc'] == 'no') : ?>
623 <div class="breaker"></div>
624 <?php foreach($this->_cards as $method): ?>
625 <div class="makecommerce-banklink-picker" banklink_id="card_<?php echo $method->name; ?>">
626 <img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
627 </div>
628 <?php endforeach; ?>
629 <?php endif; ?>
630 </div>
631 </li>
632 <?php endforeach; ?>
633 <?php if($this->_cards && $this->settings['ui_widget_groupcc'] == 'yes') : ?>
634 <li class="makecommerce-picker-country">
635 <input type="radio" id="makecommerce_country_picker_card" name="makecommerce_country_picker" value="card"/><label for="makecommerce_country_picker_card"><?php echo $this->settings['ui_widget_groupcc_title']; ?></label>
636 <div class="makecommerce_country_picker_methods" id="makecommerce_country_picker_methods_card">
637 <?php foreach($this->_cards as $method): ?>
638 <div class="makecommerce-banklink-picker" banklink_id="card_<?php echo $method->name; ?>">
639 <img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
640 </div>
641 <?php endforeach; ?>
642 </div>
643 </li>
644 <?php endif; ?>
645 <?php
646 }
647 ?>
648 </ul>
649 <script type="text/javascript">
650 var makecommerceId = '<?php echo $this->id; ?>';
651 var selectedCountry = jQuery('input[name=makecommerce_country_picker]:checked').val();
652
653 var logosize = '<?php echo $this->settings['ui_widget_logosize']; ?>';
654 jQuery('div.makecommerce_country_picker_methods').addClass('logosize-'+logosize);
655
656 <?php if(count($this->_banklinks_grouped) == 1): ?>
657 jQuery('div.makecommerce_country_picker_methods').show();
658 jQuery('div.makecommerce_country_picker_countries').hide();
659 jQuery('li.makecommerce-picker-country > input, li.makecommerce-picker-country > label').hide();
660 <?php else: ?>
661 makecommercePick();
662
663 jQuery('body').on('change', 'select[name=makecommerce_country_picker_select]', function() {
664 selectedCountry = jQuery(this).val();
665 jQuery('input[name=makecommerce_country_picker]').removeAttr('checked');
666 makecommercePick();
667 });
668 jQuery('body').on('change', 'input[name=makecommerce_country_picker]', function() {
669 selectedCountry = jQuery(this).val();
670 jQuery('select[name=makecommerce_country_picker_select]').val(selectedCountry);
671 makecommercePick();
672 });
673
674 function makecommercePick() {
675 jQuery('select#'+makecommerceId).val('');
676 jQuery('div.makecommerce-banklink-picker').removeClass('selected');
677 jQuery('label.makecommerce_country_picker_label').removeClass('selected');
678
679 jQuery('div.makecommerce_country_picker_methods').hide();
680 jQuery('div#makecommerce_country_picker_methods_' + selectedCountry).show();
681 jQuery('label[for=makecommerce_country_picker_' + selectedCountry + ']').addClass('selected');
682 }
683 <?php endif; ?>
684
685 jQuery('div.makecommerce-banklink-picker').on('click', function() {
686 var banklink_id = jQuery(this).attr('banklink_id');
687 jQuery('select#'+makecommerceId).val(banklink_id);
688
689 jQuery('div.makecommerce-banklink-picker').removeClass('selected');
690 jQuery(this).addClass('selected');
691 });
692 </script>
693 <?php
694 }
695
696 if($this->settings['ui_open_by_default'] == 'yes') {
697 ?>
698 <script type="text/javascript">
699 jQuery('input#payment_method_<?php echo $this->id; ?>').trigger('click');
700 </script>
701 <?php
702 }
703 }
704
705 private function getDefaultCountry() {
706 if ($this->_getWooCommerce()->customer) {
707 $customerCountry = strtolower($this->_getWooCommerce()->customer->get_shipping_country());
708 if(array_key_exists($customerCountry, $this->_banklinks_grouped)) {
709 return $customerCountry;
710 }
711 }
712
713 $localeToCountry = array(
714 'et' => 'ee',
715 'lv' => 'lv',
716 'lt' => 'lt',
717 'fi' => 'fi',
718 );
719 if(array_key_exists(get_locale(), $localeToCountry)) {
720 return $localeToCountry[get_locale()];
721 }
722
723 return key($this->_banklinks_grouped);
724 }
725
726 private function initBanklinks() {
727 global $wpdb;
728 global $mkDbTable;
729 $this->_banklinks = array();
730
731 $tableName = $wpdb->prefix . $mkDbTable;
732 $methods = $wpdb->get_results('SELECT * FROM '.$tableName);
733
734 if(count($methods)) {
735 if(is_admin() && $this->_init == true && get_option( 'mc_banklinks_api_type' ) != get_option('mk_api_type', false)) {
736 //add_action( 'admin_notices', array(&$this, 'makecommerce_banklinks_list_type_notice') );
737 }
738 $banklinks = array();
739 $banklinks_grouped = array();
740 $cards = array();
741 foreach($methods as $method) {
742 if($method->type == 'banklink') {
743 $banklinks[] = $banklinks_grouped[$method->country][] = $method;
744 } elseif($method->type == 'card') {
745 $cards[] = $method;
746 }
747 }
748
749 usort($banklinks, array($this, 'orderBanklinks'));
750 foreach($banklinks_grouped as &$country) {
751 usort($country, array($this, 'orderBanklinks'));
752 }
753
754 $this->_banklinks = $banklinks;
755 $this->_banklinks_grouped = $banklinks_grouped;
756 $this->_cards = $cards;
757 remove_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
758 } elseif(is_admin() && $this->_init == true) {
759 add_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
760 }
761 }
762
763 private function orderBanklinks($a, $b) {
764 $order = array_map('trim', explode(",", $this->settings['ui_chorder']));
765
766 $posA = array_search($a->name, $order);
767 $posB = array_search($b->name, $order);
768
769 if($posA === $posB) return 0;
770 if($posA === FALSE) return 1;
771 if($posB === FALSE) return -1;
772
773 return $posA > $posB ? 1 : -1;
774 }
775
776 protected function getImageUrl($methodName) {
777 $imageUrlPath = 'https://static.maksekeskus.ee/img/channel/lnd/';
778
779 return $imageUrlPath.$methodName.'.png';
780 }
781
782 public function validate_fields() {
783 $selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
784
785 if (!$selected) {
786 wc_add_notice(__('Please select suitable payment option!', 'wc_makecommerce_domain'), 'error');
787 } else {
788 $this->_getWooCommerce()->session->makecommerce_preselected_method = $selected;
789 }
790
791 return true;
792 }
793
794 function process_payment($orderId) {
795
796 $order = new WC_Order($orderId);
797
798 $selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
799
800 if(!empty($selected)) {
801
802 update_post_meta($order->id, '_makecommerce_preselected_method', $selected);
803
804 if(substr($selected, 0, 5) == 'card_') {
805
806 $request_body = array(
807 'transaction' => array(
808 'amount' => round($order->order_total, 2),
809 'currency' => $order->get_order_currency(),
810 'reference' => $order->id,
811 'transaction_url' => array(
812 'return_url' => array(
813 'url' => $this->return_url_cc,
814 'method' => 'POST',
815 ),
816 'cancel_url' => array(
817 'url' => $this->return_url_cc,
818 'method' => 'POST',
819 ),
820 'notification_url' => array(
821 'url' => $this->return_url_cc,
822 'method' => 'POST',
823 ),
824 ),
825 ),
826 'customer' => array(
827 'ip' => $_SERVER['REMOTE_ADDR'],
828 'country' => strtolower($order->billing_country),
829 'locale' => strtolower(substr(get_locale(), 0, 2)),
830 ),
831 );
832 $transaction = $this->_api->createTransaction($request_body);
833
834 if(isset($transaction->id)) {
835 update_post_meta($order->id, '_makecommerce_cc_transaction_id', $transaction->id);
836 return array(
837 'result' => 'success',
838 'redirect' => $this->_getOrderConfirmationUrl($order),
839 );
840 }
841
842 wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
843 return array(
844 'result' => 'failure',
845 );
846
847 } else {
848
849 $redirectUrl = $this->_getRedirectUrl($selected);
850
851 if($redirectUrl) {
852 $request_body = array(
853 'transaction' => array(
854 'amount' => round($order->order_total, 2),
855 'currency' => $order->get_order_currency(),
856 'reference' => $order->id,
857 'transaction_url' => array(
858 'return_url' => array(
859 'url' => $this->return_url,
860 'method' => 'POST',
861 ),
862 'cancel_url' => array(
863 'url' => $this->return_url,
864 'method' => 'POST',
865 ),
866 'notification_url' => array(
867 'url' => $this->return_url,
868 'method' => 'POST',
869 ),
870 ),
871 ),
872 'customer' => array(
873 'ip' => $_SERVER['REMOTE_ADDR'],
874 'country' => strtolower($order->billing_country),
875 'locale' => strtolower(substr(get_locale(), 0, 2)),
876 )
877 );
878 $transaction = $this->_api->createTransaction($request_body);
879
880 if(isset($transaction->id)) {
881 return array(
882 'result' => 'success',
883 'redirect' => $redirectUrl.$transaction->id,
884 );
885 }
886 }
887
888 wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
889 return array(
890 'result' => 'failure',
891 );
892
893 }
894
895 }
896
897 wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
898 return array(
899 'result' => 'failure',
900 );
901 }
902
903 protected function _getRedirectUrl($selected) {
904 foreach($this->_banklinks as $method) {
905 if($selected == $method->country.'_'.$method->name)
906 return $method->url;
907 }
908
909 return false;
910 }
911
912 protected function _getOrderConfirmationUrl($order) {
913 //$url = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
914 $url = site_url('?makecommerce_card_pay=1&order_id='.$order->id);
915 return $url;
916 }
917
918 function receipt_page($orderId) {
919 echo '<p>' . __('Thank you for the order, please click on the button to start the payment.', 'wc_makecommerce_domain') . '</p>';
920
921 $order = new WC_Order($orderId);
922 if(substr(get_post_meta($orderId, '_makecommerce_preselected_method', true), 0, 5) == 'card_' && $order->get_status() == 'pending') {
923 echo $this->generateCardForm($order);
924 }
925 }
926
927 function generateCardForm($order) {
928 $scriptSrc = htmlspecialchars($this->_gateway_url_static.'checkout.js');
929 $transactionId = get_post_meta($order->id, '_makecommerce_cc_transaction_id', true);
930 $idReference = $order->id;
931 $jsParams = array(
932 'key' => $this->_api->getPublishableKey(),
933 'transaction' => $transactionId,
934 'selector' => '#submit_banklinkmakecommerce_payment_form',
935 'amount' => round($order->order_total, 2),
936 'locale' => strtolower(substr(get_locale(), 0, 2)),
937 'open-on-load' => 'true',
938 'client-name' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) ($order->billing_first_name . ' ' . $order->billing_last_name) : ''),
939 'email' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) $order->billing_email : ''),
940 'name' => $this->settings['cc_shop_name'],
941 'description' => (string)sprintf($this->settings['cc_cart_reference_string'], (string) $idReference),
942 'completed' => 'makecommerce_cc_complete',
943 'currency' => 'EUR',
944 );
945 ?>
946 <script type="text/javascript">
947 function makecommerce_cc_complete(data) {
948 if(data.paymentToken) {
949 jQuery('div.mc-processing-message').show();
950
951 var submitform = jQuery('<form action="<?php echo $this->return_url_cc; ?>" method="POST" style="display: none;"><input type="submit"/><input type="hidden" name="transaction" value="<?php echo $transactionId; ?>" /></form>');
952 for(var key in data) {
953 submitform.append('<input type="hidden" name="'+key+'" value="'+data[key]+'" />');
954 }
955 jQuery('body').append(submitform);
956 submitform.submit();
957 }
958 }
959 </script>
960 <form id="cc_form">
961 <input type="submit" class="button-alt" id="submit_banklinkmakecommerce_payment_form" value="<?php echo __('Pay', 'wc_makecommerce_domain'); ?>" />
962 <a class="button cancel" href="<?php echo esc_url($order->get_cancel_order_url()); ?>"><?php echo __('Cancel order &amp; restore cart', 'wc_makecommerce_domain'); ?></a>
963 <script type="text/javascript" src="<?php echo $scriptSrc; ?>" <?php echo $this->_toHtmlAttributes($jsParams); ?>></script>
964 </form>
965 <div class="mc-processing-message"><img src="<?php echo plugins_url('/images/loading.png', __FILE__); ?>"/> <?php echo __('Please wait, processing payment...', 'wc_makecommerce_domain'); ?></div>
966 <?php
967 }
968
969 protected function _toHtmlAttributes($input) {
970 $result = array();
971 foreach ($input as $key => $value) {
972 $result[] = 'data-' . htmlspecialchars($key) . '=' . '"' . htmlspecialchars($value) . '"';
973 }
974 return implode(' ', $result);
975 }
976
977 function makecommerce_return_trigger($vars) {
978 $vars[] = 'makecommerce_return';
979 $vars[] = 'makecommerce_card_pay';
980 return $vars;
981 }
982
983 function makecommerce_return_trigger_check() {
984 if(intval(get_query_var('makecommerce_return')) == 1) {
985
986 $returnUrl = home_url();
987
988 $request = stripslashes_deep($_POST);
989 if($this->_api->verifySignature($request)) {
990 $data = $this->_api->extractRequestData($request);
991 $order = new WC_Order($data['reference']);
992
993 switch($data['status']) {
994 case self::MC_CANCELLED:
995 $order->update_status( 'cancelled' );
996 wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
997 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
998 break;
999 case self::MC_COMPLETED:
1000 if($this->validate_completed_payment($order, $data)) {
1001 $orderNote = array();
1002 $orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data['transaction'];
1003 $orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
1004
1005 $order->add_order_note(implode("\r\n", $orderNote));
1006
1007 $order->payment_complete($data['transaction']);
1008 $order->update_status( 'processing' );
1009
1010 try {
1011 @ob_start();
1012 $this->receipt_page($order->id);
1013 @ob_end_clean();
1014
1015 $returnUrl = $this->get_return_url($order);
1016 } catch (Exception $ex) {
1017 @ob_end_clean();
1018 }
1019 } else {
1020 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
1021 }
1022 break;
1023 }
1024
1025 //exit;
1026 }
1027 wp_redirect($returnUrl);
1028 exit;
1029
1030 } elseif(intval(get_query_var('makecommerce_return')) == 2) {
1031
1032 $returnUrl = home_url();
1033
1034 if(isset($_POST['paymentToken']) && isset($_POST['transaction'])) {
1035 $token = $_POST['paymentToken'];
1036 $transaction = $_POST['transaction'];
1037 }
1038
1039 if(isset($_POST['json'])) {
1040 $data = json_decode(stripslashes($_POST['json']), true);
1041 $token = $data['token']['id'];
1042 $transaction = $data['transaction']['id'];
1043 }
1044
1045 if(!empty($token) && !empty($transaction)) {
1046 global $wpdb;
1047 if($order = New WC_Order($wpdb->get_var('SELECT post_id from '.$wpdb->postmeta.' where meta_key = "_makecommerce_cc_transaction_id" AND meta_value = "'.$transaction.'"'))) {
1048 $request_body = array(
1049 'token' => $token,
1050 );
1051 $data = $this->_api->createPayment(get_post_meta($order->id, '_makecommerce_cc_transaction_id', true), $request_body);
1052 switch($data->status) {
1053 case self::MC_CANCELLED:
1054 $order->update_status( 'cancelled' );
1055 wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
1056 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
1057 break;
1058 case self::MC_DEPOSITED:
1059 if($this->validate_completed_payment($order, $data)) {
1060 $orderNote = array();
1061 $orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data->transaction->id;
1062 $orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
1063
1064 $order->add_order_note(implode("\r\n", $orderNote));
1065
1066 $order->payment_complete($data->transaction->id);
1067 $order->update_status( 'processing' );
1068
1069 try {
1070 @ob_start();
1071 $this->receipt_page($order->id);
1072 @ob_end_clean();
1073
1074 $returnUrl = $this->get_return_url($order);
1075 } catch (Exception $ex) {
1076 @ob_end_clean();
1077 }
1078 } else {
1079 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
1080 }
1081 break;
1082 }
1083 }
1084 }
1085
1086 wp_redirect($returnUrl);
1087 exit;
1088 }
1089
1090 if(intval(get_query_var('makecommerce_card_pay')) == 1) {
1091 if(isset($_GET['order_id'])) {
1092 if($order = New WC_Order($_GET['order_id'])) {
1093 New woocommerce_makecommerce(false);
1094 get_header();
1095 ?>
1096 <div id="primary" class="content-area">
1097 <?php $this->receipt_page($order->id); ?>
1098 </div>
1099 <?php
1100 get_sidebar();
1101 get_footer();
1102
1103 exit;
1104 }
1105 }
1106 }
1107 }
1108
1109 private function validate_completed_payment($order, $data) {
1110
1111 if(is_object($data)) {
1112 $data = json_decode(json_encode($data), true);
1113 }
1114
1115 if(empty($data['transaction'])) {
1116 $order->add_order_note(__('Payment error, missing transaction id', 'wc_makecommerce_domain'));
1117 wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain'), 'error');
1118 return false;
1119 }
1120 if($data['amount'] != round($order->order_total, 2)) {
1121 $order->add_order_note(sprintf(__('Payment error, incorrect amount captured: %s', 'wc_makecommerce_domain'), $data['amount'].' '.$data['currency']));
1122 wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect amount captured', 'wc_makecommerce_domain'), 'error');
1123 return false;
1124 }
1125 if($data['currency'] != $order->get_order_currency()) {
1126 $order->add_order_note(sprintf(__('Payment error, incorrect currency captured: %s', 'wc_makecommerce_domain'), $data['currency']));
1127 wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect currency captured', 'wc_makecommerce_domain'), 'error');
1128 return false;
1129 }
1130
1131 return true;
1132 }
1133
1134 function admin_order_page($order) {
1135 //
1136 }
1137
1138 public function process_refund($order_id, $amount = null, $comment = '') {
1139 if ($this->_api) {
1140 try {
1141 $order = new WC_Order($order_id);
1142 $transactionId = $order->get_transaction_id();
1143
1144 if($response = $this->_api->createRefund($transactionId, array('amount' => $amount, 'comment' => ($comment ? : 'refund')))) {
1145 if($status = (string)$response->transaction->status) {
1146 switch($status) {
1147 case self::MC_REFUNDED:
1148 $order->add_order_note(sprintf(__('Refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
1149 return true;
1150 break;
1151 case self::MC_PART_REFUNDED:
1152 $order->add_order_note(sprintf(__('Partial refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
1153 return true;
1154 break;
1155 }
1156 }
1157 }
1158 return false;
1159
1160 } catch (Exception $e) {
1161 return new WP_Error('makecommerce_refund_error', $e->getMessage());
1162 }
1163
1164 return false;
1165 }
1166 return false;
1167 }
1168
1169 protected function getCountryName($slug) {
1170 switch($slug) {
1171 case 'ee': return __('Estonia', 'wc_makecommerce_domain'); break;
1172 case 'lv': return __('Latvia', 'wc_makecommerce_domain'); break;
1173 case 'lt': return __('Lithuania', 'wc_makecommerce_domain'); break;
1174 case 'fi': return __('Finland', 'wc_makecommerce_domain'); break;
1175 }
1176 return $slug;
1177 }
1178
1179 }
1180
1181 New woocommerce_makecommerce(true);
1182
1183 }
1184
1185 function woocommerce_payment_makecommerce_add($methods) {
1186 $methods[] = 'woocommerce_makecommerce';
1187 return $methods;
1188 }
1189
1190 add_action('plugins_loaded', 'woocommerce_payment_makecommerce_init');
1191 add_action('woocommerce_payment_gateways', 'woocommerce_payment_makecommerce_add');
1192
1193 function clear_wc_shipping_rates_cache(){
1194 $packages = WC()->cart->get_shipping_packages();
1195 foreach ($packages as $key => $value) {
1196 $shipping_session = "shipping_for_package_$key";
1197 unset(WC()->session->$shipping_session);
1198 }
1199 }
1200 add_filter('woocommerce_checkout_update_order_review', 'clear_wc_shipping_rates_cache');
1201
1202 // Parcel machine specific stuff
1203 function parcelmachine_add_method() {
1204
1205 // Delete all the wc_ship transient scum, you aren’t wanted around here, move along.
1206 // Same as being in shipping debug mode
1207 global $wpdb;
1208 $transients = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_wc_ship%'");
1209 if (count($transients)) {
1210 foreach ($transients as $tr) {
1211 $hash = substr($tr, 11);
1212 delete_transient($hash);
1213 }
1214 }
1215 $transient_value = get_transient('shipping-transient-version');
1216 WC_Cache_Helper::delete_version_transients( $transient_value );
1217 if (WC()->session) {
1218 WC()->session->set('shipping_for_package', '');
1219 }
1220
1221 if ( ! class_exists( 'WC_ParcelMachine_Shipping_Method' ) ) {
1222
1223 class WC_ParcelMachine_Shipping_Method extends WC_Shipping_Method {
1224
1225
1226 function __construct($instance_id = 0) {
1227 if (!$this->ext) {
1228 throw new Exception('Do not call this class directly!');
1229 }
1230 $this->id = 'parcelmachine_' . mb_strtolower($this->ext);
1231 $this->instance_id = $instance_id;
1232 $this->method_title = $this->name_ext . __(' Parcel Machine by MC', 'wc_makecommerce_domain');
1233 $this->init();
1234 }
1235
1236 function init() {
1237 $this->init_form_fields();
1238 $this->init_settings();
1239
1240 $this->enable = $this->settings['active'];
1241 $this->title = $this->settings['method_name'];
1242 $this->availability = 'specific';
1243 $this->countries = $this->settings['countries'];
1244 $this->prioritization = $this->settings['prioritization'];
1245 $this->free_shipping_min_amount = $this->settings['free_shipping_min_amount'];
1246 $this->maximum_weight = (double)$this->settings['maximum_weight'];
1247 $this->short_office_names = $this->settings['short_office_names'];
1248 $this->order_country = 'unknown';
1249 add_action('woocommerce_update_options_shipping_' . $this->id, array(&$this, 'process_admin_options'));
1250 add_filter('woocommerce_review_order_after_shipping' , array(&$this, 'add_parcelmachine_checkout_fields'));
1251 add_action('woocommerce_checkout_process', array(&$this, 'check_parcelmachine_checkout_fields'));
1252 add_action('woocommerce_checkout_update_order_meta', array(&$this, 'add_parcelmachine_order_meta'));
1253 add_filter('woocommerce_order_shipping_to_display_shipped_via', array(&$his, 'add_admin_parcelmachine_via_field'));
1254 }
1255
1256 function calculate_shipping($package = array()) {
1257
1258 $price = $this->settings['price_'.strtolower($package['destination']['country'])];
1259 if ($this->free_shipping_min_amount && $package['contents_cost'] >= $this->free_shipping_min_amount) {
1260 $price = 0;
1261 }
1262 $rate = array(
1263 'id' => $this->id,
1264 'label' => $this->title,
1265 'cost' => $price,
1266 'calc_tax' => 'per_order',
1267 );
1268 $this->add_rate( $rate );
1269 }
1270
1271 function calculate_weight($package) {
1272 $weight = 0;
1273 foreach ($package['contents'] as $line) {
1274 $weight += $line['data']->get_weight();
1275 }
1276 return $weight;
1277 }
1278 function fits_parcel_machine($package) {
1279 foreach ($package['contents'] as $line) {
1280 if (get_post_meta($line['product_id'], '_no_parcel_machine', true) === 'yes') {
1281 return false;
1282 }
1283 }
1284 return true;
1285 }
1286
1287
1288 function is_available($package) {
1289 if (!$this->fits_parcel_machine($package)) {
1290 return false;
1291 }
1292 $package_weight = $this->calculate_weight($package);
1293 if ($package_weight >= $this->maximum_weight) {
1294 return false;
1295 }
1296 $is_available = $this->enable === 'yes';
1297 if (!$is_available) {
1298 return false;
1299 }
1300 if (is_array($this->countries) && !in_array($package['destination']['country'], $this->countries)) {
1301 $is_available = false;
1302 }
1303 $this->order_country = $package['destination']['country'];
1304 return apply_filters('woocommerce_shipping_' . $this->id . '_is_available', $is_available, $package);
1305 }
1306
1307 function mk_get_machines() {
1308 $machines = mk_get_machines($this->ext, $this->order_country);
1309 if ($this->prioritization === 'yes') {
1310 usort($machines, function($a, $b) {
1311 $sortorder = array(
1312 'tallinn', 'tartu', 'narva', 'pärnu', 'viljandi', 'kohtla-järve', 'rakvere', 'maardu', 'sillamäe', 'kuressaare',
1313 'helsinki', 'espoo', 'tampere', 'vantaa', 'oulu', 'turku', 'jüväskülä', 'lahti', 'kuopio', 'kouvola',
1314 'riga', 'daugavpils', 'liepaja', 'jelgava', 'jurmala', 'ventspils', 'rezekne', 'valmiera', 'jekabpils',
1315 'vilnius', 'kaunas', 'klaipeda', 'siauliai', 'panevezys', 'alytus', 'mariampole', 'mazeikiai', 'jonava', 'utena'
1316 );
1317 $acity = mb_strtolower($a['city']);
1318 $bcity = mb_strtolower($b['city']);
1319 if (!$acity) { $acity = 'xxxxxxx'; }
1320 if (!$bcity) { $bcity = 'xxxxxxx'; }
1321 $aidx = array_search($acity, $sortorder);
1322 $bidx = array_search($bcity, $sortorder);
1323 if ($aidx !== false) {
1324 $acity = str_pad($aidx, 4, "0", STR_PAD_LEFT) . '-' . $acity;
1325 }
1326 if ($bidx !== false) {
1327 $bcity = str_pad($bidx, 4, "0", STR_PAD_LEFT) . '-' . $bcity;
1328 }
1329 $acity .= '-' . mb_strtolower($a['name']);
1330 $bcity .= '-' . mb_strtolower($b['name']);
1331 return $acity < $bcity ? -1 : 1;
1332 });
1333 }
1334 return $machines;
1335 }
1336
1337 function add_parcelmachine_checkout_fields($checkout) {
1338 $this->order_country = WC()->customer->get_shipping_country();
1339 echo '<tr style="display: none;" class="parcel_machine_checkout" id="parcel_machine_checkout_parcelmachine_'.mb_strtolower($this->ext).'"><th>' . $this->title . '</th>';
1340 echo '<td>';
1341 $options = array();
1342 $machines = $this->mk_get_machines();
1343 echo '<p class="form-row" id="'.esc_attr($this->id).'_field">';
1344 echo '<select class="select" name="'.esc_attr($this->id).'" id="'.esc_attr($this->id).'">';
1345 $pcity = false;
1346 foreach ($machines as $machine) {
1347 $city = strtolower($machine['city']);
1348 if ($city !== $pcity) {
1349 if ($pcity) echo '</optgroup>';
1350 echo '<optgroup label="'.$machine['city'].'">';
1351 }
1352 $mname = $machine['name'];
1353 if ($this->short_office_names !== 'yes') $mname .= ' - ' . $machine['city'] . ', ' . $machine['address'];
1354 echo '<option value="'.esc_attr($machine['provider'].'||'.$machine['id']).'">'.$mname.'</option>';
1355 $pcity = $city;
1356 }
1357 if ($pcity) echo '</optgroup>';
1358 echo '</select>';
1359 echo '</p>';
1360 echo '</td></tr>';
1361 }
1362
1363 function check_parcelmachine_checkout_fields() {
1364 $shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
1365 if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
1366 if ($shipping_method === $this->id && empty($_POST['parcel_machine_itella'])) {
1367 wc_add_notice(__('<strong>Parcel machine</strong> is a required field.'), 'error');
1368 }
1369 }
1370 function add_parcelmachine_order_meta($order_id) {
1371 $shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
1372 if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
1373 if ($shipping_method === $this->id && !empty($_POST[$this->id])) {
1374 update_post_meta($order_id, '_parcel_machine', sanitize_text_field($_POST[$this->id]));
1375 }
1376 }
1377 function add_admin_parcelmachine_via_field($order) {
1378 error_log('Via');
1379 error_log(print_r($order, 1));
1380 }
1381 }
1382 class WC_ParcelMachine_Shipping_Method_Omniva extends WC_ParcelMachine_Shipping_Method {
1383 function __construct($instance_id = 0) {
1384 $this->ext = 'Omniva';
1385 $this->name_ext = 'Omniva';
1386 parent::__construct();
1387 }
1388 function init_form_fields() {
1389
1390 $this->form_fields = array(
1391 'logo' => array('type' => 'title', 'title' => __get_logo_html()),
1392 'generic' => array('type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
1393 'active' => array(
1394 'title' => __('Enable', 'wc_makecommerce_domain'),
1395 'type' => 'checkbox',
1396 'label' => __('enabled', 'wc_makecommerce_domain'),
1397 'default' => 'no',
1398 'description' => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options', 'wc_makecommerce_domain'),
1399 ),
1400 'price_ee' => array(
1401 'title' => __('Price EE', 'wc_makecommerce_domain'),
1402 'type' => 'text',
1403 'default' => '2.99'
1404 ),
1405 'price_lv' => array(
1406 'title' => __('Price LV', 'wc_makecommerce_domain'),
1407 'type' => 'text',
1408 'default' => '7.99'
1409 ),
1410 'price_lt' => array(
1411 'title' => __('Price LT', 'wc_makecommerce_domain'),
1412 'type' => 'text',
1413 'default' => '8.99'
1414 ),
1415 //'price_fi' => array(
1416 // 'title' => __('Price FI', 'wc_makecommerce_domain'),
1417 // 'type' => 'text',
1418 // 'default' => '10.99'
1419 //),
1420 'free_shipping_min_amount' => array(
1421 'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
1422 'type' => 'number',
1423 'default' => '0',
1424 'description' => '(0 means no free shipping)'
1425 ),
1426 'maximum_weight' => array(
1427 'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
1428 'type' => 'text',
1429 'default' => '15'
1430 ),
1431 'countries' => array(
1432 'title' => __('Specific Countries', 'wc_makecommerce_domain'),
1433 'type' => 'multiselect',
1434 'class' => 'wp-enhanced-select',
1435 'css' => 'width: 450px;',
1436 'default' => array('EE','LV','LT'),
1437 'options' => array('EE' => __('Estonia'), 'LV' => __('Latvia'), 'LT' => __('Lithuania')),
1438 ),
1439 'look_and_feel' => array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on check-out page', 'wc_makecommerce_domain')),
1440 'method_name' => array(
1441 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
1442 'type' => 'text',
1443 'default' => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
1444 ),
1445 'prioritization' => array(
1446 'title' => __('Prioritize', 'wc_makecommerce_domain'),
1447 'type' => 'checkbox',
1448 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
1449 'default' => 'yes'
1450 ),
1451 'short_office_names' => array(
1452 'title' => __('Short names', 'wc_makecommerce_domain'),
1453 'type' => 'checkbox',
1454 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
1455 'default' => 'no'
1456 ),
1457 'api_access' => array( 'type' => 'title', 'title' => '<br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into Omniva system and print the out the package labels right here, at the shop orders view. <br> Please set your Omniva web servises account credentials below here. <br>(see more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>. Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api&section=mk_api'))),
1458 'service_user' => array(
1459 'title' => __('Omniva web services username', 'wc_makecommerce_domain'),
1460 'type' => 'text',
1461 'default' => ''
1462 ),
1463 'service_password' => array(
1464 'title' => __('Omniva web services password', 'wc_makecommerce_domain'),
1465 'type' => 'text',
1466 'default' => ''
1467 ),
1468 'return_address' => array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for Omniva shipments', 'wc_makecommerce_domain')),
1469 'shop_name' => array(
1470 'type' => 'text',
1471 'title' => __('Shop name', 'wc_makecommerce_domain'),
1472 'class' => 'input-text regular-input',
1473 ),
1474 'shop_phone' => array(
1475 'type' => 'text',
1476 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1477 'class' => 'input-text regular-input',
1478 ),
1479 'shop_email' => array(
1480 'type' => 'text',
1481 'title' => __('Shop email', 'wc_makecommerce_domain'),
1482 'class' => 'input-text regular-input',
1483 ),
1484 'shop_postal_code' => array(
1485 'type' => 'text',
1486 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1487 'class' => 'input-text regular-input',
1488 'description' => __('Put here zip-code of the Parcel Terminal you use for returns, see: <a href="https://www.omniva.ee/era/kaart/asukohad">List of Omniva Terminals</a>', 'wc_makecommerce_domain')
1489 ),
1490 );
1491 }
1492
1493 }
1494 class WC_ParcelMachine_Shipping_Method_Smartpost extends WC_ParcelMachine_Shipping_Method {
1495 function __construct() {
1496 $this->ext = 'SmartPost';
1497 $this->name_ext = 'SmartPOST';
1498 parent::__construct();
1499 }
1500 function init_form_fields() {
1501 global $woocommerce;
1502
1503 $this->form_fields = array(
1504 'logo' => array('type' => 'title', 'title' => __get_logo_html()),
1505 'generic' => array( 'type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
1506 'active' => array(
1507 'title' => __('Enable', 'wc_makecommerce_domain'),
1508 'type' => 'checkbox',
1509 'label' => __('enabled', 'wc_makecommerce_domain'),
1510 'default' => 'no',
1511 'description' => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options', 'wc_makecommerce_domain'),
1512 ),
1513 'price_ee' => array(
1514 'title' => __('Price EE', 'wc_makecommerce_domain'),
1515 'type' => 'text',
1516 'default' => '2.99'
1517 ),
1518 'price_fi' => array(
1519 'title' => __('Price FI', 'wc_makecommerce_domain'),
1520 'type' => 'text',
1521 'default' => '10.99'
1522 ),
1523 'free_shipping_min_amount' => array(
1524 'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
1525 'type' => 'number',
1526 'default' => '0',
1527 'description' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
1528 ),
1529 'maximum_weight' => array(
1530 'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
1531 'type' => 'text',
1532 'default' => '15'
1533 ),
1534 'countries' => array(
1535 'title' => __('Specific Countries', 'wc_makecommerce_domain'),
1536 'type' => 'multiselect',
1537 'class' => 'wp-enhanced-select',
1538 'css' => 'width: 450px;',
1539 'default' => array('EE','FI'),
1540 'options' => array('EE' => __('Estonia'), 'FI' => __('Finland')),
1541 ),
1542 'look_and_feel' => array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on checkout page', 'wc_makecommerce_domain')),
1543 'method_name' => array(
1544 'title' => __('Method Title', 'wc_makecommerce_domain'),
1545 'type' => 'text',
1546 'default' => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
1547 ),
1548 'prioritization' => array(
1549 'title' => __('Prioritize', 'wc_makecommerce_domain'),
1550 'type' => 'checkbox',
1551 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
1552 'default' => 'yes'
1553 ),
1554 'short_office_names' => array(
1555 'title' => __('Short names', 'wc_makecommerce_domain'),
1556 'type' => 'checkbox',
1557 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
1558 'default' => 'no'
1559 ),
1560 'api_access' => array( 'type' => 'title', 'title' => '<br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into smartpost.ee system and print the out the package labels right here, at the shop orders view. <br> Please set your smartpost.ee account credentials below here. <br>(See more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>. Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api&section=mk_api'))),
1561 'service_user' => array(
1562 'title' => __('eteenindus.smartpost.ee username', 'wc_makecommerce_domain'),
1563 'type' => 'text',
1564 'default' => ''
1565 ),
1566 'service_password' => array(
1567 'title' => __('eteenindus.smartpost.ee password', 'wc_makecommerce_domain'),
1568 'type' => 'text',
1569 'default' => ''
1570 ),
1571 'return_address' => array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for SmartPOST shipments (used on parcel labels)', 'wc_makecommerce_domain')),
1572 'shop_name' => array(
1573 'type' => 'text',
1574 'title' => __('Shop name', 'wc_makecommerce_domain'),
1575 'class' => 'input-text regular-input',
1576 ),
1577 'shop_phone' => array(
1578 'type' => 'text',
1579 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1580 'class' => 'input-text regular-input',
1581 ),
1582 'shop_email' => array(
1583 'type' => 'text',
1584 'title' => __('Shop email', 'wc_makecommerce_domain'),
1585 'class' => 'input-text regular-input',
1586 ),
1587 /*'shop_postal_code' => array(
1588 'type' => 'text',
1589 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1590 'class' => 'input-text regular-input',
1591 ),
1592 */
1593 );
1594 }
1595
1596 }
1597 }
1598 }
1599 add_action('woocommerce_shipping_init', 'parcelmachine_add_method');
1600
1601 function add_parcelmachine_shipping_method($methods) {
1602 $methods[] = 'WC_ParcelMachine_Shipping_Method_Omniva';
1603 $methods[] = 'WC_ParcelMachine_Shipping_Method_Smartpost';
1604 return $methods;
1605 }
1606 add_filter('woocommerce_shipping_methods', 'add_parcelmachine_shipping_method');
1607
1608 function mk_parcelmachine_add_assets() {
1609 wp_enqueue_style('parcelmachine-css', plugin_dir_url(__FILE__).'/css/parcelmachine.css');
1610 wp_enqueue_script('parcelmachine-js', plugin_dir_url(__FILE__).'/scripts/parcelmachine.js', array('jquery'));
1611 }
1612 add_action('wp_enqueue_scripts', 'mk_parcelmachine_add_assets');
1613
1614 function mk_admin_plugin_settings_link($links) {
1615 $settings_link = '<a href="admin.php?page=wc-settings&tab=api&section=mk_api">API '.__('Settings').'</a>';
1616 array_unshift($links, $settings_link);
1617 return $links;
1618 }
1619 $plugin = plugin_basename(__FILE__);
1620 add_filter("plugin_action_links_$plugin", 'mk_admin_plugin_settings_link' );
1621
1622 function mk_admin_add_settings($sections) {
1623 $sections['mk_api'] = __('MakeCommerce API access', 'wc_makecommerce_domain');
1624 return $sections;
1625 }
1626
1627 function mk_admin_all_settings($settings) {
1628 global $current_section;
1629 if ($current_section !== 'mk_api') {
1630 return $settings;
1631 }
1632 return array(
1633 array('type' => 'title', 'desc' => __get_logo_html()),
1634 array(
1635 'type' => 'title',
1636 'title' => __('MakeCommerce API access credentials', 'wc_makecommerce_domain'),
1637 'desc' => sprintf(__('To use MakeCommerce/Maksekeskus services you need to enter API credentials below here <br/> <br/>'.
1638 'To further configure the Payment methods please go to <a href="%s">MakeCommerce Checkout Options</a><br>'.
1639 'To use also Ominva or Itella SmartPOST integration please configure these API accesses: <a href="%s">Omniva API access</a> | '.
1640 '<a href="%s">SmartPOST API access</a><br/>','wc_makecommerce_domain'),
1641 'admin.php?page=wc-settings&tab=checkout&section=makecommerce',
1642 'admin.php?page=wc-settings&tab=-shipping&section=parcelmachine_omniva',
1643 'admin.php?page=wc-settings&tab=shipping&section=parcelmachine_smartpost'
1644 ),
1645 'id' => 'mk_api_settings'
1646 ),
1647 array(
1648 'type' => 'select',
1649 'title' => __('Current environment', 'wc_makecommerce_domain'),
1650 'desc' => __('See more about <a href="https://maksekeskus.ee/en/for-developers/test-environment/">MakeCommerce Test environment</a>', 'wc_makecommerce_domain'),
1651 'default' => 'live',
1652 'options' => array(
1653 'live' => __('Live', 'wc_makecommerce_domain'),
1654 'test' => __('Test', 'wc_makecommerce_domain'),
1655 ),
1656 'id' => 'mk_api_type'
1657 ),
1658 array(
1659 'id' => 'mk_shop_id',
1660 'type' => 'text',
1661 'title' => __('Shop ID (live)', 'wc_makecommerce_domain'),
1662 'desc' => __('Get it from <a href="https://merchant.maksekeskus.ee/api.html" target="_blank">Merchant Portal</a>','wc_makecommerce_domain'),
1663 'class' => 'input-text regular-input',
1664 ),
1665 array(
1666 'id' => 'mk_public_key',
1667 'type' => 'text',
1668 'title' => __('Public key (live)', 'wc_makecommerce_domain'),
1669 'class' => 'input-text regular-input',
1670 ),
1671 array(
1672 'id' => 'mk_private_key',
1673 'type' => 'text',
1674 'title' => __('Private key (live)', 'wc_makecommerce_domain'),
1675 'class' => 'input-text regular-input',
1676 ),
1677 array(
1678 'id' => 'mk_test_shop_id',
1679 'type' => 'text',
1680 'title' => __('Shop ID (test)', 'wc_makecommerce_domain'),
1681 'class' => 'input-text regular-input',
1682 'desc' => __('Get it from <a href="https://merchant-test.maksekeskus.ee/api.html" target="_blank">Merchant Portal Test</a>','wc_makecommerce_domain'),
1683 ),
1684 array(
1685 'id' => 'mk_test_public_key',
1686 'type' => 'text',
1687 'title' => __('Public key (test)', 'wc_makecommerce_domain'),
1688 'class' => 'input-text regular-input',
1689 ),
1690 array(
1691 'id' => 'mk_test_private_key',
1692 'type' => 'text',
1693 'title' => __('Private key (test)', 'wc_makecommerce_domain'),
1694 'class' => 'input-text regular-input',
1695 ),
1696 array('type' => 'sectionend', 'id' => 'mk_api_settings')
1697 );
1698 }
1699
1700 function mk_admin_save_settings() {
1701 // reload banklinks
1702 global $current_section;
1703 if ($current_section !== 'mk_api') {
1704 return;
1705 }
1706 $wcmc = New woocommerce_makecommerce(true);
1707 $wcmc->mc_banklinks_reload(true);
1708 }
1709
1710 function __get_logo_html() {
1711 return '<div class="makecommerce-info">'.
1712 '<div class="makecommerce-logo">'.
1713 '<a target="_blank" href="http://maksekeskus.ee"><img src="'. plugins_url('/images/makecommerce_logo_en.svg', __FILE__) .'" class="makecommerce-logo"></a>'.
1714 '</div>'.
1715 '<div class="makecommerce-links">'.
1716 '<div class="makecommerce-link"><a target="_blank" href="https://merchant.maksekeskus.ee">Merchant Portal</a></div>'.
1717 '<div class="makecommerce-link"><a target="_blank" href="https://makecommerce.net/">makecommerce.net</a></div>'.
1718 '<div class="makecommerce-link"><a target="_blank" href="http://maksekeskus.ee">maksekeskus.ee</a></div>'.
1719 '</div>'.
1720 '</div>';
1721 }
1722
1723 add_action('woocommerce_get_sections_api', 'mk_admin_add_settings');
1724 add_filter('woocommerce_get_settings_api', 'mk_admin_all_settings', 10, 2);
1725 add_action('woocommerce_settings_saved', 'mk_admin_save_settings', 30, 0);
1726
1727 function mk_admin_restrict_manage_posts() {
1728 global $typenow;
1729 if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
1730 $selected_method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1731 $methods = WC()->shipping->load_shipping_methods();
1732 echo '<select name="_shipping_method" id="shipping_type" class="enhanced">';
1733 echo '<option value="">'.__('-- filter by shipping method', 'wc_makecommerce_domain') . '</option>';
1734 foreach ($methods as $method) {
1735 echo '<option value="'.$method->id.'"'.($selected_method === $method->id ? ' selected="selected"' : '').'>'.$method->title.'</option>';
1736 }
1737 echo '</select>';
1738 }
1739 }
1740 function mk_admin_shipping_filter($where, &$wp_query) {
1741 global $pagenow, $wpdb;
1742 $method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1743 if (is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
1744 $where .= $GLOBALS['wpdb']->prepare( ' AND ID
1745 IN (
1746 SELECT items.order_id
1747 FROM '.$wpdb->prefix.'woocommerce_order_itemmeta meta, '.$wpdb->prefix.'woocommerce_order_items items
1748 WHERE meta.order_item_id = items.order_item_id
1749 AND meta.meta_key = "method_id"
1750 AND meta.meta_value = %s
1751 ) ', $method );
1752 }
1753 return $where;
1754 }
1755 add_filter('restrict_manage_posts', 'mk_admin_restrict_manage_posts');
1756 add_filter('posts_where', 'mk_admin_shipping_filter', 10, 2);
1757
1758 function mk_admin_bulk_actions() {
1759 global $post_type;
1760 if ('shop_order' === $post_type) {
1761 ?>
1762 <script type="text/javascript">
1763 jQuery(function() {
1764 jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1765 jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1766 jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1767 jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1768 });
1769 </script>
1770 <?php
1771 if (!empty($_REQUEST['mk_pdf'])) {
1772 ?>
1773 <script type="text/javascript">
1774 jQuery(function(){
1775 window.open('<?php echo $_REQUEST['mk_pdf'] ?>', 'pdf');
1776 });
1777 </script>
1778 <?php
1779 }
1780 }
1781 }
1782 function mk_admin_bulk_action_labels() {
1783 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1784 $shipping_request = array('credentials' => array(), 'orders' => array());
1785 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1786 mk_get_shipment_ids($post_ids);
1787 }
1788 function mk_admin_bulk_action_print() {
1789 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1790 $shipping_request = array('credentials' => array(), 'orders' => array());
1791 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1792 mk_get_labels($post_ids);
1793 }
1794 add_action('admin_footer', 'mk_admin_bulk_actions', 11);
1795 add_action('admin_action_parcel_machine_labels', 'mk_admin_bulk_action_labels');
1796 add_action('admin_action_parcel_machine_print_labels', 'mk_admin_bulk_action_print');
1797
1798
1799
1800 function mk_admin_parcelmachine_order_meta($order) {
1801 $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1802 if (empty($machine_id)) return;
1803 list($provider, $machine) = explode('||', $machine_id);
1804 if (empty($machine)) return;
1805 $machine = mk_get_machine($provider, (int)$machine);
1806 if (!$machine) return;
1807 echo '<p><strong>'.__('Parcel machine').':</strong><br/>' . $machine['name'] . '<br/><small>' . $machine['address'] . '</small></p>';
1808 $shipment_id = get_post_meta($order->id, '_parcel_machine_shipment_id', true);
1809 $shipment_id_error = get_post_meta($order->id, '_parcel_machine_error', true);
1810 if ($shipment_id) {
1811 echo '<p><strong>'.__('Parcel machine shipment ID').':</strong><br/>' . $shipment_id . '</small></p>';
1812 }
1813 if ($shipment_id_error) {
1814 echo '<p><strong style="color: red;">'.__('Parcel machine shipment generation error').':</strong><br/>' . $shipment_id_error . '</small></p>';
1815 }
1816 }
1817
1818 function mk_admin_render_shop_order_columns( $column ) {
1819 global $post, $woocommerce, $the_order;
1820 if (empty($the_order) || $the_order->id != $post->ID) {
1821 $the_order = wc_get_order($post->ID);
1822 }
1823 if ($column === 'shipping_address') {
1824 $machine = get_post_meta($the_order->id, '_parcel_machine', true);
1825 $shipment_id = get_post_meta($the_order->id, '_parcel_machine_shipment_id', true);
1826 $shipment_id_error = get_post_meta($the_order->id, '_parcel_machine_error', true);
1827 if ($machine) {
1828 if ($shipment_id) echo __('Package shipment_id:', 'wc_makecommerce_domain') . ' ' . $shipment_id;
1829 else if ($shipment_id_error) echo '<span style="color: red;">'.__('Package shipment generation error:', 'wc_makecommerce_domain') . '</span><br/>' .$shipment_id_error;
1830 else echo __('Shipment ID not generated for delivery', 'wc_makecommerce_domain');
1831 }
1832 }
1833 }
1834 function mk_add_email_customer_details_fields($fields, $sent_to_admin, $order) {
1835 $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1836 if (empty($machine_id)) return $fields;
1837 list($provider, $machine) = explode('||', $machine_id);
1838 if (empty($machine)) return $fields;
1839 $machine = mk_get_machine($provider, (int)$machine);
1840 if (!$machine) return $fields;
1841 $fields[] = array('label' => __('Parcel machine'), 'value' => $machine['name'].' - '.$machine['address']);
1842 return $fields;
1843 }
1844 function mk_add_order_customer_details_fields($order) {
1845 $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1846 if (empty($machine_id)) return;
1847 list($provider, $machine) = explode('||', $machine_id);
1848 if (empty($machine)) return;
1849 $machine = mk_get_machine($provider, (int)$machine);
1850 if (!$machine) return;
1851 echo '<tr>';
1852 echo '<th>'.__('Parcel machine').'</th>';
1853 echo '<td>'.$machine['name'].'<br/>'.$machine['address'].'</td>';
1854 echo '</tr>';
1855 }
1856 function mk_admin_product_option_fields($fields) {
1857 echo '<div class="options_group">';
1858 woocommerce_wp_checkbox(
1859 array(
1860 'id' => '_no_parcel_machine',
1861 'wrapper_class' => 'show_if_simple',
1862 'label' => __('Does not fit parcel machine', 'wc_makecommerce_domain'),
1863 'description' => __('When this is checked, parcel machine shipping option is not available for a cart with this product', 'wc_makecommerce_domain')
1864 )
1865 );
1866 echo '</div>';
1867 }
1868 function mk_admin_product_fields_save($post_id) {
1869 $no_parcel_machine = isset($_POST['_no_parcel_machine']) ? 'yes' : 'no';
1870 update_post_meta($post_id, '_no_parcel_machine', $no_parcel_machine);
1871 }
1872
1873 add_action('woocommerce_product_options_shipping', 'mk_admin_product_option_fields');
1874 add_action('woocommerce_process_product_meta', 'mk_admin_product_fields_save');
1875 add_action('woocommerce_admin_order_data_after_shipping_address', 'mk_admin_parcelmachine_order_meta', 10, 1);
1876 add_action('manage_shop_order_posts_custom_column', 'mk_admin_render_shop_order_columns', 3);
1877 add_filter('woocommerce_email_customer_details_fields', 'mk_add_email_customer_details_fields', 10, 3 );
1878 add_action('woocommerce_order_details_after_customer_details', 'mk_add_order_customer_details_fields');
1879 add_action('woocommerce_order_status_processing', 'mk_get_shipment_ids');
1880
1881
1882
1883 function mk_get_shipment_ids($post_ids) {
1884 if (!is_array($post_ids)) {
1885 $post_ids = array($post_ids);
1886 }
1887 parcelmachine_add_method();
1888 $shipping_request = array('credentials' => array(), 'orders' => array());
1889 foreach ($post_ids as $post_id) {
1890 $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
1891 if (!$parcel_machine) { continue; }
1892 list($provider, $machine_id) = explode('||', $parcel_machine);
1893 if (!$provider || !$machine_id) { continue; }
1894 $provider_uc = mb_strtoupper($provider);
1895 switch ($provider_uc) {
1896 case "OMNIVA":
1897 $transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
1898 break;
1899 case "SMARTPOST":
1900 $transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
1901 break;
1902 default:
1903 break 2;
1904 }
1905 if (empty($shipping_request['credentials'][$provider_uc])) {
1906 $api_user = $transport_class->settings['service_user'];
1907 $api_password = $transport_class->settings['service_password'];
1908 if (!$api_user || !$api_password) {
1909 add_action('admin_notices', 'mk_admin_error');
1910 continue;
1911 }
1912 $shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
1913 }
1914 $order = wc_get_order($post_id);
1915 $sender = array(
1916 'name' => $transport_class->settings['shop_name'],
1917 'phone' => $transport_class->settings['shop_phone'],
1918 'email' => $transport_class->settings['shop_email'],
1919 'postalCode' => $transport_class->settings['shop_postal_code']
1920 );
1921 $shipping_request['orders'][] = array(
1922 'carrier' => $provider_uc,
1923 'orderId' => $order->id,
1924 'destination' => array('destinationId' => $machine_id),
1925 'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
1926 'sender' => $sender
1927 );
1928 }
1929 $shipping_request['credentials'] = array_values($shipping_request['credentials']);
1930 if (empty($shipping_request['orders'])) {
1931 return;
1932 }
1933 $MK = mk_get_api();
1934 if (!$MK) {
1935 return;
1936 }
1937 try {
1938 $response = $MK->createShipments($shipping_request);
1939 } catch (Exception $e) {
1940 echo $e->getMessage();
1941 exit();
1942 }
1943 foreach ($response as $order) {
1944 if (!empty($order->orderId) && !empty($order->shipmentId)) {
1945 update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->shipmentId));
1946 } else if (!empty($order->orderId) && !empty($order->barCode)) {
1947 update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->barCode));
1948 } else if (!empty($order->orderId) && !empty($order->errorMessage)) {
1949 update_post_meta((int)$order->orderId, '_parcel_machine_error', sanitize_text_field($order->errorMessage));
1950 }
1951 }
1952 }
1953
1954 function mk_get_labels($post_ids) {
1955 if (!is_array($post_ids)) {
1956 $post_ids = array($post_ids);
1957 }
1958 $sender = array(
1959 'name' => get_option('mk_shop_name', ''),
1960 'phone' => get_option('mk_shop_phone', ''),
1961 'email' => get_option('mk_shop_email', ''),
1962 'postalCode' => get_option('mk_shop_postal_code', '')
1963 );
1964 parcelmachine_add_method();
1965 $shipping_request = array('credentials' => array(), 'orders' => array(), 'printFormat' => 'A4');
1966 foreach ($post_ids as $post_id) {
1967 $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
1968 if (!$parcel_machine) { continue; }
1969 list($provider, $machine_id) = explode('||', $parcel_machine);
1970 if (!$provider || !$machine_id) { continue; }
1971 $provider_uc = mb_strtoupper($provider);
1972 if (empty($shipping_request['credentials'][$provider_uc])) {
1973 switch ($provider_uc) {
1974 case "OMNIVA":
1975 $transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
1976 break;
1977 case "SMARTPOST":
1978 $transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
1979 break;
1980 default:
1981 break 2;
1982 }
1983 $api_user = $transport_class->settings['service_user'];
1984 $api_password = $transport_class->settings['service_password'];
1985 if (!$api_user || !$api_password) {
1986 add_action('admin_notices', 'mk_admin_error');
1987 continue;
1988 }
1989 $shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
1990 }
1991 $order = wc_get_order($post_id);
1992 $shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
1993 if (!$shipment_id) { continue; }
1994 $shipping_request['orders'][] = array(
1995 'carrier' => $provider_uc,
1996 'orderId' => $order->id,
1997 'destination' => array('destinationId' => $machine_id),
1998 'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
1999 'sender' => $sender,
2000 'shipmentId' => $shipment_id
2001 );
2002 }
2003 $shipping_request['credentials'] = array_values($shipping_request['credentials']);
2004 if (empty($shipping_request['orders'])) {
2005 return;
2006 }
2007 $MK = mk_get_api();
2008 if (!$MK) {
2009 return;
2010 }
2011 try {
2012 $response = $MK->createLabels($shipping_request);
2013 } catch (Exception $e) {
2014 echo $e->getMessage();
2015 exit();
2016 }
2017 if (empty($response->labelUrl)) {
2018 return;
2019 }
2020 $sendback = add_query_arg(array('post_type' => 'shop_order', 'mk_pdf' => urlencode($response->labelUrl)), '');
2021 wp_redirect(esc_url_raw($sendback));
2022 exit();
2023 }
2024
2025
2026
2027 $MKAPI = false;
2028 function mk_get_api() {
2029 global $MKAPI;
2030 if ($MKAPI) {
2031 //return $MKAPI;
2032 }
2033 $mk_api_type = get_option('mk_api_type', false);
2034 if (!$mk_api_type) {
2035 return false;
2036 }
2037 if ($mk_api_type !== 'live') {
2038 $key_prefix = $mk_api_type.'_';
2039 } else {
2040 $key_prefix = '';
2041 }
2042 $mk_shop_id = get_option('mk_'.$key_prefix.'shop_id', '');
2043 $mk_public_key = get_option('mk_'.$key_prefix.'public_key', '');
2044 $mk_private_key = get_option('mk_'.$key_prefix.'private_key', '');
2045 if (!$mk_shop_id || !$mk_public_key || !$mk_shop_id) {
2046 return false;
2047 }
2048 $MKAPI = new Maksekeskus($mk_shop_id, $mk_public_key, $mk_private_key, $mk_api_type === 'live' ? false : true);
2049 return $MKAPI;
2050 }
2051 function mk_get_machines($provider, $country = 'EE') {
2052 $data = get_option('mk_machines_cache', false);
2053 $data_expires = get_option('mk_machines_expires', false);
2054 if (!$data || $data_expires < time()) {
2055 $MK = mk_get_api();
2056 $data = $MK->getDestinations(array('type' => 'APT'));
2057 update_option('mk_machines_cache', $data);
2058 update_option('mk_machines_expires', time()+3*60*60);
2059 }
2060
2061 $machines = array();
2062 if (!$data || empty($data)) {
2063 return array();
2064 }
2065 foreach ($data as $machine) {
2066 if ($machine->country === $country && $machine->type === 'APT' && ($provider === '*' || strtolower($provider) === strtolower($machine->provider))) {
2067 $machines[] = array(
2068 'provider' => strtolower($machine->provider),
2069 'id' => $machine->id,
2070 'name' => $machine->name,
2071 'city' => $machine->city,
2072 'address' => !empty($machine->address) ? $machine->address : '',
2073 );
2074 }
2075 }
2076 usort($machines, function($a, $b){
2077 if ($a['city'] === $b['city']) {
2078 return $a['name'] > $b['name'];
2079 }
2080 return $a['city'] > $b['city'];
2081 });
2082 return $machines;
2083 }
2084
2085 function mk_get_machine($provider, $id) {
2086 $machines = mk_get_machines($provider);
2087 foreach ($machines as $machine) {
2088 if ($machine['provider'] === $provider && $machine['id'] === $id) {
2089 return $machine;
2090 }
2091 }
2092 return false;
2093 }
2094 function mk_admin_error() {
2095 printf( '<div class="%1$s"><p>%2$s</p></div>', 'notice notice-error', __('Please check that you have configured correctly MakeCommerce API accesses', 'wc_makecommerce_domain'));
2096 }
2097 }
2098