PluginProbe
MakeCommerce for WooCommerce / 1.0.2
MakeCommerce for WooCommerce v1.0.2
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.2, at makecommerce.php

2,093 lines 84.8 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.2
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 return false;
499 }
500 if(isset($methods->banklinks)) {
501 foreach($methods->banklinks as $method) {
502 $wpdb->insert($tableName, array('type' => 'banklink', 'country' => $method->country, 'name' => $method->name, 'url' => $method->url));
503 }
504 $updated = true;
505 }
506
507 if(isset($methods->cards)) {
508 foreach($methods->cards as $method) {
509 $wpdb->insert($tableName, array('type' => 'card', 'name' => $method->name));
510 }
511 $updated = true;
512 }
513 if ($updated) {
514 update_option( 'mc_banklinks_api_type', get_option('mk_api_type', false) );
515 }
516 if ($force) {
517 $this->initBankLinks();
518 return $updated;
519 }
520
521 if($updated) {
522 wp_send_json(array('success' => 1, 'data' => __('Update successfully completed!', 'wc_makecommerce_domain')));
523 exit;
524 }
525
526 wp_send_json(array('success' => 0, 'data' => __('There was an error with your update. Please try again.', 'wc_makecommerce_domain')));
527 exit;
528 }
529 die();
530 }
531
532 protected function _getWooCommerce() {
533 global $woocommerce;
534 return $woocommerce;
535 }
536
537 function is_valid_for_use() {
538 return true;
539 }
540
541 public function is_available() {
542 if ($this->settings['active'] == "yes") {
543 return true;
544 }
545 }
546
547 function payment_fields() {
548
549 if($this->settings['ui_mode'] == 'inline') {
550
551 ?>
552 <ul class="makecommerce-picker">
553 <?php foreach($this->_banklinks as $method): ?>
554 <li class="makecommerce-picker-method">
555 <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; ?>"/>
556 <label for="makecommerce_method_picker_<?php echo $method->country.'_'.$method->name; ?>">
557 <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>
558 <?php if(in_array($this->settings['ui_inline_uselogo'], array('logo', 'text_logo'))) : ?>
559 <div><img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" /></div>
560 <?php endif; ?>
561 </label>
562 </li>
563 <?php endforeach; ?>
564 <?php foreach($this->_cards as $method): ?>
565 <li class="makecommerce-picker-method">
566 <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; ?>"/>
567 <label for="makecommerce_method_picker_<?php echo 'card_'.$method->name; ?>">
568 <span class="makecommerce-method-title"><?php if(in_array($this->settings['ui_inline_uselogo'], array('text', 'text_logo'))) { echo ucfirst($method->name); } ?></span>
569 <?php if(in_array($this->settings['ui_inline_uselogo'], array('logo', 'text_logo'))) : ?>
570 <div><img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" /></div>
571 <?php endif; ?>
572 </label>
573 </li>
574 <?php endforeach; ?>
575 </ul>
576 <?php
577
578 } else {
579 ?>
580 <select id="<?php echo $this->id; ?>" name="PRESELECTED_METHOD_<?php echo $this->id; ?>">
581 <option value=""></option>
582 <?php foreach($this->_banklinks as $method): ?>
583 <option value="<?php echo $method->country.'_'.$method->name; ?>"><?php echo strtoupper($method->country).' - '.ucfirst($method->name); ?></option>
584 <?php endforeach; ?>
585 <?php foreach($this->_cards as $method): ?>
586 <option value="card_<?php echo $method->name; ?>"><?php echo ucfirst($method->name); ?></option>
587 <?php endforeach; ?>
588 </select>
589 <ul class="makecommerce-picker">
590 <?php
591
592 if($this->_banklinks) {
593 $defaultCountry = $this->getDefaultCountry();
594 ?>
595 <?php if(empty($this->settings['ui_widget_groupcountries']) || $this->settings['ui_widget_groupcountries'] == 'no') : ?>
596 <div class="makecommerce_country_picker_countries">
597 <?php foreach(array_keys($this->_banklinks_grouped) as $country): ?>
598 <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 } ?>
599 <?php endforeach; ?>
600 <?php if($this->settings['ui_widget_countryselector'] == 'dropdown') : ?>
601 <select name="makecommerce_country_picker_select">
602 <?php foreach(array_keys($this->_banklinks_grouped) as $country): ?>
603 <option value="<?php echo $country; ?>" <?php if($defaultCountry == $country) echo 'selected="selected" '; ?>><?php echo $this->getCountryName($country); ?></option>
604 <?php endforeach; ?>
605 <option value="card" style="display:none;"></option>
606 </select>
607 <?php endif; ?>
608 </div>
609 <?php endif; ?>
610 <?php foreach($this->_banklinks_grouped as $country => $methods): ?>
611 <li class="makecommerce-picker-country">
612 <?php if($this->settings['ui_widget_groupcountries'] == 'yes') : ?>
613 <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>
614 <?php endif; ?>
615 <div class="makecommerce_country_picker_methods" id="makecommerce_country_picker_methods_<?php echo $country; ?>">
616 <?php foreach($methods as $method): ?>
617 <div class="makecommerce-banklink-picker" banklink_id="<?php echo $method->country.'_'.$method->name; ?>">
618 <img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
619 </div>
620 <?php endforeach; ?>
621 <?php if($this->_cards && $this->settings['ui_widget_groupcc'] == 'no') : ?>
622 <div class="breaker"></div>
623 <?php foreach($this->_cards as $method): ?>
624 <div class="makecommerce-banklink-picker" banklink_id="card_<?php echo $method->name; ?>">
625 <img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
626 </div>
627 <?php endforeach; ?>
628 <?php endif; ?>
629 </div>
630 </li>
631 <?php endforeach; ?>
632 <?php if($this->_cards && $this->settings['ui_widget_groupcc'] == 'yes') : ?>
633 <li class="makecommerce-picker-country">
634 <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>
635 <div class="makecommerce_country_picker_methods" id="makecommerce_country_picker_methods_card">
636 <?php foreach($this->_cards as $method): ?>
637 <div class="makecommerce-banklink-picker" banklink_id="card_<?php echo $method->name; ?>">
638 <img src="<?php echo $this->getImageUrl($method->name); ?>" title="<?php echo ucfirst($method->name); ?>" />
639 </div>
640 <?php endforeach; ?>
641 </div>
642 </li>
643 <?php endif; ?>
644 <?php
645 }
646 ?>
647 </ul>
648 <script type="text/javascript">
649 var makecommerceId = '<?php echo $this->id; ?>';
650 var selectedCountry = jQuery('input[name=makecommerce_country_picker]:checked').val();
651
652 var logosize = '<?php echo $this->settings['ui_widget_logosize']; ?>';
653 jQuery('div.makecommerce_country_picker_methods').addClass('logosize-'+logosize);
654
655 <?php if(count($this->_banklinks_grouped) == 1): ?>
656 jQuery('div.makecommerce_country_picker_methods').show();
657 jQuery('div.makecommerce_country_picker_countries').hide();
658 jQuery('li.makecommerce-picker-country > input, li.makecommerce-picker-country > label').hide();
659 <?php else: ?>
660 makecommercePick();
661
662 jQuery('body').on('change', 'select[name=makecommerce_country_picker_select]', function() {
663 selectedCountry = jQuery(this).val();
664 jQuery('input[name=makecommerce_country_picker]').removeAttr('checked');
665 makecommercePick();
666 });
667 jQuery('body').on('change', 'input[name=makecommerce_country_picker]', function() {
668 selectedCountry = jQuery(this).val();
669 jQuery('select[name=makecommerce_country_picker_select]').val(selectedCountry);
670 makecommercePick();
671 });
672
673 function makecommercePick() {
674 jQuery('select#'+makecommerceId).val('');
675 jQuery('div.makecommerce-banklink-picker').removeClass('selected');
676 jQuery('label.makecommerce_country_picker_label').removeClass('selected');
677
678 jQuery('div.makecommerce_country_picker_methods').hide();
679 jQuery('div#makecommerce_country_picker_methods_' + selectedCountry).show();
680 jQuery('label[for=makecommerce_country_picker_' + selectedCountry + ']').addClass('selected');
681 }
682 <?php endif; ?>
683
684 jQuery('div.makecommerce-banklink-picker').on('click', function() {
685 var banklink_id = jQuery(this).attr('banklink_id');
686 jQuery('select#'+makecommerceId).val(banklink_id);
687
688 jQuery('div.makecommerce-banklink-picker').removeClass('selected');
689 jQuery(this).addClass('selected');
690 });
691 </script>
692 <?php
693 }
694
695 if($this->settings['ui_open_by_default'] == 'yes') {
696 ?>
697 <script type="text/javascript">
698 jQuery('input#payment_method_<?php echo $this->id; ?>').trigger('click');
699 </script>
700 <?php
701 }
702 }
703
704 private function getDefaultCountry() {
705 if ($this->_getWooCommerce()->customer) {
706 $customerCountry = strtolower($this->_getWooCommerce()->customer->get_shipping_country());
707 if(array_key_exists($customerCountry, $this->_banklinks_grouped)) {
708 return $customerCountry;
709 }
710 }
711
712 $localeToCountry = array(
713 'et' => 'ee',
714 'lv' => 'lv',
715 'lt' => 'lt',
716 'fi' => 'fi',
717 );
718 if(array_key_exists(get_locale(), $localeToCountry)) {
719 return $localeToCountry[get_locale()];
720 }
721
722 return key($this->_banklinks_grouped);
723 }
724
725 private function initBanklinks() {
726 global $wpdb;
727 global $mkDbTable;
728 $this->_banklinks = array();
729
730 $tableName = $wpdb->prefix . $mkDbTable;
731 $methods = $wpdb->get_results('SELECT * FROM '.$tableName);
732
733 if(count($methods)) {
734 if(is_admin() && $this->_init == true && get_option( 'mc_banklinks_api_type' ) != get_option('mk_api_type', false)) {
735 //add_action( 'admin_notices', array(&$this, 'makecommerce_banklinks_list_type_notice') );
736 }
737 $banklinks = array();
738 $banklinks_grouped = array();
739 $cards = array();
740 foreach($methods as $method) {
741 if($method->type == 'banklink') {
742 $banklinks[] = $banklinks_grouped[$method->country][] = $method;
743 } elseif($method->type == 'card') {
744 $cards[] = $method;
745 }
746 }
747
748 usort($banklinks, array($this, 'orderBanklinks'));
749 foreach($banklinks_grouped as &$country) {
750 usort($country, array($this, 'orderBanklinks'));
751 }
752
753 $this->_banklinks = $banklinks;
754 $this->_banklinks_grouped = $banklinks_grouped;
755 $this->_cards = $cards;
756 remove_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
757 } elseif(is_admin() && $this->_init == true) {
758 add_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
759 }
760 }
761
762 private function orderBanklinks($a, $b) {
763 $order = array_map('trim', explode(",", $this->settings['ui_chorder']));
764
765 $posA = array_search($a->name, $order);
766 $posB = array_search($b->name, $order);
767
768 if($posA === $posB) return 0;
769 if($posA === FALSE) return 1;
770 if($posB === FALSE) return -1;
771
772 return $posA > $posB ? 1 : -1;
773 }
774
775 protected function getImageUrl($methodName) {
776 $imageUrlPath = 'https://static.maksekeskus.ee/img/channel/lnd/';
777
778 return $imageUrlPath.$methodName.'.png';
779 }
780
781 public function validate_fields() {
782 $selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
783
784 if (!$selected) {
785 wc_add_notice(__('Please select suitable payment option!', 'wc_makecommerce_domain'), 'error');
786 } else {
787 $this->_getWooCommerce()->session->makecommerce_preselected_method = $selected;
788 }
789
790 return true;
791 }
792
793 function process_payment($orderId) {
794
795 $order = new WC_Order($orderId);
796
797 $selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
798
799 if(!empty($selected)) {
800
801 update_post_meta($order->id, '_makecommerce_preselected_method', $selected);
802
803 if(substr($selected, 0, 5) == 'card_') {
804
805 $request_body = array(
806 'transaction' => array(
807 'amount' => round($order->order_total, 2),
808 'currency' => $order->get_order_currency(),
809 'reference' => $order->id,
810 'transaction_url' => array(
811 'return_url' => array(
812 'url' => $this->return_url_cc,
813 'method' => 'POST',
814 ),
815 'cancel_url' => array(
816 'url' => $this->return_url_cc,
817 'method' => 'POST',
818 ),
819 'notification_url' => array(
820 'url' => $this->return_url_cc,
821 'method' => 'POST',
822 ),
823 ),
824 ),
825 'customer' => array(
826 'ip' => $_SERVER['REMOTE_ADDR'],
827 'country' => strtolower($order->billing_country),
828 'locale' => strtolower(substr(get_locale(), 0, 2)),
829 ),
830 );
831 $transaction = $this->_api->createTransaction($request_body);
832
833 if(isset($transaction->id)) {
834 update_post_meta($order->id, '_makecommerce_cc_transaction_id', $transaction->id);
835 return array(
836 'result' => 'success',
837 'redirect' => $this->_getOrderConfirmationUrl($order),
838 );
839 }
840
841 wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
842 return array(
843 'result' => 'failure',
844 );
845
846 } else {
847
848 $redirectUrl = $this->_getRedirectUrl($selected);
849
850 if($redirectUrl) {
851 $request_body = array(
852 'transaction' => array(
853 'amount' => round($order->order_total, 2),
854 'currency' => $order->get_order_currency(),
855 'reference' => $order->id,
856 'transaction_url' => array(
857 'return_url' => array(
858 'url' => $this->return_url,
859 'method' => 'POST',
860 ),
861 'cancel_url' => array(
862 'url' => $this->return_url,
863 'method' => 'POST',
864 ),
865 'notification_url' => array(
866 'url' => $this->return_url,
867 'method' => 'POST',
868 ),
869 ),
870 ),
871 'customer' => array(
872 'ip' => $_SERVER['REMOTE_ADDR'],
873 'country' => strtolower($order->billing_country),
874 'locale' => strtolower(substr(get_locale(), 0, 2)),
875 )
876 );
877 $transaction = $this->_api->createTransaction($request_body);
878
879 if(isset($transaction->id)) {
880 return array(
881 'result' => 'success',
882 'redirect' => $redirectUrl.$transaction->id,
883 );
884 }
885 }
886
887 wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
888 return array(
889 'result' => 'failure',
890 );
891
892 }
893
894 }
895
896 wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
897 return array(
898 'result' => 'failure',
899 );
900 }
901
902 protected function _getRedirectUrl($selected) {
903 foreach($this->_banklinks as $method) {
904 if($selected == $method->country.'_'.$method->name)
905 return $method->url;
906 }
907
908 return false;
909 }
910
911 protected function _getOrderConfirmationUrl($order) {
912 //$url = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
913 $url = site_url('?makecommerce_card_pay=1&order_id='.$order->id);
914 return $url;
915 }
916
917 function receipt_page($orderId) {
918 echo '<p>' . __('Thank you for the order, please click on the button to start the payment.', 'wc_makecommerce_domain') . '</p>';
919
920 $order = new WC_Order($orderId);
921 if(substr(get_post_meta($orderId, '_makecommerce_preselected_method', true), 0, 5) == 'card_' && $order->get_status() == 'pending') {
922 echo $this->generateCardForm($order);
923 }
924 }
925
926 function generateCardForm($order) {
927 $scriptSrc = htmlspecialchars($this->_gateway_url_static.'checkout.js');
928 $transactionId = get_post_meta($order->id, '_makecommerce_cc_transaction_id', true);
929 $idReference = $order->id;
930 $jsParams = array(
931 'key' => $this->_api->getPublishableKey(),
932 'transaction' => $transactionId,
933 'selector' => '#submit_banklinkmakecommerce_payment_form',
934 'amount' => round($order->order_total, 2),
935 'locale' => strtolower(substr(get_locale(), 0, 2)),
936 'open-on-load' => 'true',
937 'client-name' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) ($order->billing_first_name . ' ' . $order->billing_last_name) : ''),
938 'email' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) $order->billing_email : ''),
939 'name' => $this->settings['cc_shop_name'],
940 'description' => (string)sprintf($this->settings['cc_cart_reference_string'], (string) $idReference),
941 'completed' => 'makecommerce_cc_complete',
942 'currency' => 'EUR',
943 );
944 ?>
945 <script type="text/javascript">
946 function makecommerce_cc_complete(data) {
947 if(data.paymentToken) {
948 jQuery('div.mc-processing-message').show();
949
950 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>');
951 for(var key in data) {
952 submitform.append('<input type="hidden" name="'+key+'" value="'+data[key]+'" />');
953 }
954 jQuery('body').append(submitform);
955 submitform.submit();
956 }
957 }
958 </script>
959 <form id="cc_form">
960 <input type="submit" class="button-alt" id="submit_banklinkmakecommerce_payment_form" value="<?php echo __('Pay', 'wc_makecommerce_domain'); ?>" />
961 <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>
962 <script type="text/javascript" src="<?php echo $scriptSrc; ?>" <?php echo $this->_toHtmlAttributes($jsParams); ?>></script>
963 </form>
964 <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>
965 <?php
966 }
967
968 protected function _toHtmlAttributes($input) {
969 $result = array();
970 foreach ($input as $key => $value) {
971 $result[] = 'data-' . htmlspecialchars($key) . '=' . '"' . htmlspecialchars($value) . '"';
972 }
973 return implode(' ', $result);
974 }
975
976 function makecommerce_return_trigger($vars) {
977 $vars[] = 'makecommerce_return';
978 $vars[] = 'makecommerce_card_pay';
979 return $vars;
980 }
981
982 function makecommerce_return_trigger_check() {
983 if(intval(get_query_var('makecommerce_return')) == 1) {
984
985 $returnUrl = home_url();
986
987 $request = stripslashes_deep($_POST);
988 if($this->_api->verifySignature($request)) {
989 $data = $this->_api->extractRequestData($request);
990 $order = new WC_Order($data['reference']);
991
992 switch($data['status']) {
993 case self::MC_CANCELLED:
994 $order->update_status( 'cancelled' );
995 wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
996 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
997 break;
998 case self::MC_COMPLETED:
999 if($this->validate_completed_payment($order, $data)) {
1000 $orderNote = array();
1001 $orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data['transaction'];
1002 $orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
1003
1004 $order->add_order_note(implode("\r\n", $orderNote));
1005
1006 $order->payment_complete($data['transaction']);
1007 $order->update_status( 'processing' );
1008
1009 try {
1010 @ob_start();
1011 $this->receipt_page($order->id);
1012 @ob_end_clean();
1013
1014 $returnUrl = $this->get_return_url($order);
1015 } catch (Exception $ex) {
1016 @ob_end_clean();
1017 }
1018 } else {
1019 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
1020 }
1021 break;
1022 }
1023
1024 //exit;
1025 }
1026 wp_redirect($returnUrl);
1027 exit;
1028
1029 } elseif(intval(get_query_var('makecommerce_return')) == 2) {
1030
1031 $returnUrl = home_url();
1032
1033 if(isset($_POST['paymentToken']) && isset($_POST['transaction'])) {
1034 $token = $_POST['paymentToken'];
1035 $transaction = $_POST['transaction'];
1036 }
1037
1038 if(isset($_POST['json'])) {
1039 $data = json_decode(stripslashes($_POST['json']), true);
1040 $token = $data['token']['id'];
1041 $transaction = $data['transaction']['id'];
1042 }
1043
1044 if(!empty($token) && !empty($transaction)) {
1045 global $wpdb;
1046 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.'"'))) {
1047 $request_body = array(
1048 'token' => $token,
1049 );
1050 $data = $this->_api->createPayment(get_post_meta($order->id, '_makecommerce_cc_transaction_id', true), $request_body);
1051 switch($data->status) {
1052 case self::MC_CANCELLED:
1053 $order->update_status( 'cancelled' );
1054 wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
1055 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
1056 break;
1057 case self::MC_DEPOSITED:
1058 if($this->validate_completed_payment($order, $data)) {
1059 $orderNote = array();
1060 $orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data->transaction->id;
1061 $orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
1062
1063 $order->add_order_note(implode("\r\n", $orderNote));
1064
1065 $order->payment_complete($data->transaction->id);
1066 $order->update_status( 'processing' );
1067
1068 try {
1069 @ob_start();
1070 $this->receipt_page($order->id);
1071 @ob_end_clean();
1072
1073 $returnUrl = $this->get_return_url($order);
1074 } catch (Exception $ex) {
1075 @ob_end_clean();
1076 }
1077 } else {
1078 $returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
1079 }
1080 break;
1081 }
1082 }
1083 }
1084
1085 wp_redirect($returnUrl);
1086 exit;
1087 }
1088
1089 if(intval(get_query_var('makecommerce_card_pay')) == 1) {
1090 if(isset($_GET['order_id'])) {
1091 if($order = New WC_Order($_GET['order_id'])) {
1092 New woocommerce_makecommerce(false);
1093 get_header();
1094 ?>
1095 <div id="primary" class="content-area">
1096 <?php $this->receipt_page($order->id); ?>
1097 </div>
1098 <?php
1099 get_sidebar();
1100 get_footer();
1101
1102 exit;
1103 }
1104 }
1105 }
1106 }
1107
1108 private function validate_completed_payment($order, $data) {
1109
1110 if(is_object($data)) {
1111 $data = json_decode(json_encode($data), true);
1112 }
1113
1114 if(empty($data['transaction'])) {
1115 $order->add_order_note(__('Payment error, missing transaction id', 'wc_makecommerce_domain'));
1116 wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain'), 'error');
1117 return false;
1118 }
1119 if($data['amount'] != round($order->order_total, 2)) {
1120 $order->add_order_note(sprintf(__('Payment error, incorrect amount captured: %s', 'wc_makecommerce_domain'), $data['amount'].' '.$data['currency']));
1121 wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect amount captured', 'wc_makecommerce_domain'), 'error');
1122 return false;
1123 }
1124 if($data['currency'] != $order->get_order_currency()) {
1125 $order->add_order_note(sprintf(__('Payment error, incorrect currency captured: %s', 'wc_makecommerce_domain'), $data['currency']));
1126 wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect currency captured', 'wc_makecommerce_domain'), 'error');
1127 return false;
1128 }
1129
1130 return true;
1131 }
1132
1133 function admin_order_page($order) {
1134 //
1135 }
1136
1137 public function process_refund($order_id, $amount = null, $comment = '') {
1138 if ($this->_api) {
1139 try {
1140 $order = new WC_Order($order_id);
1141 $transactionId = $order->get_transaction_id();
1142
1143 if($response = $this->_api->createRefund($transactionId, array('amount' => $amount, 'comment' => ($comment ? : 'refund')))) {
1144 if($status = (string)$response->transaction->status) {
1145 switch($status) {
1146 case self::MC_REFUNDED:
1147 $order->add_order_note(sprintf(__('Refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
1148 return true;
1149 break;
1150 case self::MC_PART_REFUNDED:
1151 $order->add_order_note(sprintf(__('Partial refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
1152 return true;
1153 break;
1154 }
1155 }
1156 }
1157 return false;
1158
1159 } catch (Exception $e) {
1160 return new WP_Error('makecommerce_refund_error', $e->getMessage());
1161 }
1162
1163 return false;
1164 }
1165 return false;
1166 }
1167
1168 protected function getCountryName($slug) {
1169 switch($slug) {
1170 case 'ee': return __('Estonia', 'wc_makecommerce_domain'); break;
1171 case 'lv': return __('Latvia', 'wc_makecommerce_domain'); break;
1172 case 'lt': return __('Lithuania', 'wc_makecommerce_domain'); break;
1173 case 'fi': return __('Finland', 'wc_makecommerce_domain'); break;
1174 }
1175 return $slug;
1176 }
1177
1178 }
1179
1180 New woocommerce_makecommerce(true);
1181
1182 }
1183
1184 function woocommerce_payment_makecommerce_add($methods) {
1185 $methods[] = 'woocommerce_makecommerce';
1186 return $methods;
1187 }
1188
1189 add_action('plugins_loaded', 'woocommerce_payment_makecommerce_init');
1190 add_action('woocommerce_payment_gateways', 'woocommerce_payment_makecommerce_add');
1191
1192 function clear_wc_shipping_rates_cache(){
1193 $packages = WC()->cart->get_shipping_packages();
1194 foreach ($packages as $key => $value) {
1195 $shipping_session = "shipping_for_package_$key";
1196 unset(WC()->session->$shipping_session);
1197 }
1198 }
1199 add_filter('woocommerce_checkout_update_order_review', 'clear_wc_shipping_rates_cache');
1200
1201 // Parcel machine specific stuff
1202 function parcelmachine_add_method() {
1203
1204 // Delete all the wc_ship transient scum, you aren’t wanted around here, move along.
1205 // Same as being in shipping debug mode
1206 global $wpdb;
1207 $transients = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_wc_ship%'");
1208 if (count($transients)) {
1209 foreach ($transients as $tr) {
1210 $hash = substr($tr, 11);
1211 delete_transient($hash);
1212 }
1213 }
1214 $transient_value = get_transient('shipping-transient-version');
1215 WC_Cache_Helper::delete_version_transients( $transient_value );
1216 if (WC()->session) {
1217 WC()->session->set('shipping_for_package', '');
1218 }
1219
1220 if ( ! class_exists( 'WC_ParcelMachine_Shipping_Method' ) ) {
1221
1222 class WC_ParcelMachine_Shipping_Method extends WC_Shipping_Method {
1223
1224
1225 function __construct($instance_id = 0) {
1226 if (!$this->ext) {
1227 throw new Exception('Do not call this class directly!');
1228 }
1229 $this->id = 'parcelmachine_' . mb_strtolower($this->ext);
1230 $this->instance_id = $instance_id;
1231 $this->method_title = $this->name_ext . __(' Parcel Machine by MC', 'wc_makecommerce_domain');
1232 $this->init();
1233 }
1234
1235 function init() {
1236 $this->init_form_fields();
1237 $this->init_settings();
1238
1239 $this->enable = $this->settings['active'];
1240 $this->title = $this->settings['method_name'];
1241 $this->availability = 'specific';
1242 $this->countries = $this->settings['countries'];
1243 $this->prioritization = $this->settings['prioritization'];
1244 $this->free_shipping_min_amount = $this->settings['free_shipping_min_amount'];
1245 $this->maximum_weight = (double)$this->settings['maximum_weight'];
1246 $this->short_office_names = $this->settings['short_office_names'];
1247 $this->order_country = 'unknown';
1248 add_action('woocommerce_update_options_shipping_' . $this->id, array(&$this, 'process_admin_options'));
1249 add_filter('woocommerce_review_order_after_shipping' , array(&$this, 'add_parcelmachine_checkout_fields'));
1250 add_action('woocommerce_checkout_process', array(&$this, 'check_parcelmachine_checkout_fields'));
1251 add_action('woocommerce_checkout_update_order_meta', array(&$this, 'add_parcelmachine_order_meta'));
1252 add_filter('woocommerce_order_shipping_to_display_shipped_via', array(&$his, 'add_admin_parcelmachine_via_field'));
1253 }
1254
1255 function calculate_shipping($package = array()) {
1256
1257 $price = $this->settings['price_'.strtolower($package['destination']['country'])];
1258 if ($this->free_shipping_min_amount && $package['contents_cost'] >= $this->free_shipping_min_amount) {
1259 $price = 0;
1260 }
1261 $rate = array(
1262 'id' => $this->id,
1263 'label' => $this->title,
1264 'cost' => $price,
1265 'calc_tax' => 'per_order',
1266 );
1267 $this->add_rate( $rate );
1268 }
1269
1270 function calculate_weight($package) {
1271 $weight = 0;
1272 foreach ($package['contents'] as $line) {
1273 $weight += $line['data']->get_weight();
1274 }
1275 return $weight;
1276 }
1277 function fits_parcel_machine($package) {
1278 foreach ($package['contents'] as $line) {
1279 if (get_post_meta($line['product_id'], '_no_parcel_machine', true) === 'yes') {
1280 return false;
1281 }
1282 }
1283 return true;
1284 }
1285
1286
1287 function is_available($package) {
1288 if (!$this->fits_parcel_machine($package)) {
1289 return false;
1290 }
1291 $package_weight = $this->calculate_weight($package);
1292 if ($package_weight >= $this->maximum_weight) {
1293 return false;
1294 }
1295 $is_available = $this->enable === 'yes';
1296 if (!$is_available) {
1297 return false;
1298 }
1299 if (is_array($this->countries) && !in_array($package['destination']['country'], $this->countries)) {
1300 $is_available = false;
1301 }
1302 $this->order_country = $package['destination']['country'];
1303 return apply_filters('woocommerce_shipping_' . $this->id . '_is_available', $is_available, $package);
1304 }
1305
1306 function mk_get_machines() {
1307 $machines = mk_get_machines($this->ext, $this->order_country);
1308 if ($this->prioritization === 'yes') {
1309 usort($machines, function($a, $b) {
1310 $sortorder = array(
1311 'tallinn', 'tartu', 'narva', 'pärnu', 'viljandi', 'kohtla-järve', 'rakvere', 'maardu', 'sillamäe', 'kuressaare',
1312 'helsinki', 'espoo', 'tampere', 'vantaa', 'oulu', 'turku', 'jüväskülä', 'lahti', 'kuopio', 'kouvola',
1313 'riga', 'daugavpils', 'liepaja', 'jelgava', 'jurmala', 'ventspils', 'rezekne', 'valmiera', 'jekabpils',
1314 'vilnius', 'kaunas', 'klaipeda', 'siauliai', 'panevezys', 'alytus', 'mariampole', 'mazeikiai', 'jonava', 'utena'
1315 );
1316 $acity = mb_strtolower($a['city']);
1317 $bcity = mb_strtolower($b['city']);
1318 if (!$acity) { $acity = 'xxxxxxx'; }
1319 if (!$bcity) { $bcity = 'xxxxxxx'; }
1320 $aidx = array_search($acity, $sortorder);
1321 $bidx = array_search($bcity, $sortorder);
1322 if ($aidx !== false) {
1323 $acity = str_pad($aidx, 4, "0", STR_PAD_LEFT) . '-' . $acity;
1324 }
1325 if ($bidx !== false) {
1326 $bcity = str_pad($bidx, 4, "0", STR_PAD_LEFT) . '-' . $bcity;
1327 }
1328 $acity .= '-' . mb_strtolower($a['name']);
1329 $bcity .= '-' . mb_strtolower($b['name']);
1330 return $acity < $bcity ? -1 : 1;
1331 });
1332 }
1333 return $machines;
1334 }
1335
1336 function add_parcelmachine_checkout_fields($checkout) {
1337 $this->order_country = WC()->customer->get_shipping_country();
1338 echo '<tr style="display: none;" class="parcel_machine_checkout" id="parcel_machine_checkout_parcelmachine_'.mb_strtolower($this->ext).'"><th>' . $this->title . '</th>';
1339 echo '<td>';
1340 $options = array();
1341 $machines = $this->mk_get_machines();
1342 echo '<p class="form-row" id="'.esc_attr($this->id).'_field">';
1343 echo '<select class="select" name="'.esc_attr($this->id).'" id="'.esc_attr($this->id).'">';
1344 $pcity = false;
1345 foreach ($machines as $machine) {
1346 $city = strtolower($machine['city']);
1347 if ($city !== $pcity) {
1348 if ($pcity) echo '</optgroup>';
1349 echo '<optgroup label="'.$machine['city'].'">';
1350 }
1351 $mname = $machine['name'];
1352 if ($this->short_office_names !== 'yes') $mname .= ' - ' . $machine['city'] . ', ' . $machine['address'];
1353 echo '<option value="'.esc_attr($machine['provider'].'||'.$machine['id']).'">'.$mname.'</option>';
1354 $pcity = $city;
1355 }
1356 if ($pcity) echo '</optgroup>';
1357 echo '</select>';
1358 echo '</p>';
1359 echo '</td></tr>';
1360 }
1361
1362 function check_parcelmachine_checkout_fields() {
1363 $shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
1364 if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
1365 if ($shipping_method === $this->id && empty($_POST['parcel_machine_itella'])) {
1366 wc_add_notice(__('<strong>Parcel machine</strong> is a required field.'), 'error');
1367 }
1368 }
1369 function add_parcelmachine_order_meta($order_id) {
1370 $shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
1371 if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
1372 if ($shipping_method === $this->id && !empty($_POST[$this->id])) {
1373 update_post_meta($order_id, '_parcel_machine', sanitize_text_field($_POST[$this->id]));
1374 }
1375 }
1376 function add_admin_parcelmachine_via_field($order) {
1377 error_log('Via');
1378 error_log(print_r($order, 1));
1379 }
1380 }
1381 class WC_ParcelMachine_Shipping_Method_Omniva extends WC_ParcelMachine_Shipping_Method {
1382 function __construct($instance_id = 0) {
1383 $this->ext = 'Omniva';
1384 $this->name_ext = 'Omniva';
1385 parent::__construct();
1386 }
1387 function init_form_fields() {
1388
1389 $this->form_fields = array(
1390 'logo' => array('type' => 'title', 'title' => __get_logo_html()),
1391 'generic' => array('type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
1392 'active' => array(
1393 'title' => __('Enable', 'wc_makecommerce_domain'),
1394 'type' => 'checkbox',
1395 'label' => __('enabled', 'wc_makecommerce_domain'),
1396 'default' => 'no',
1397 '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'),
1398 ),
1399 'price_ee' => array(
1400 'title' => __('Price EE', 'wc_makecommerce_domain'),
1401 'type' => 'text',
1402 'default' => '2.99'
1403 ),
1404 'price_lv' => array(
1405 'title' => __('Price LV', 'wc_makecommerce_domain'),
1406 'type' => 'text',
1407 'default' => '7.99'
1408 ),
1409 'price_lt' => array(
1410 'title' => __('Price LT', 'wc_makecommerce_domain'),
1411 'type' => 'text',
1412 'default' => '8.99'
1413 ),
1414 //'price_fi' => array(
1415 // 'title' => __('Price FI', 'wc_makecommerce_domain'),
1416 // 'type' => 'text',
1417 // 'default' => '10.99'
1418 //),
1419 'free_shipping_min_amount' => array(
1420 'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
1421 'type' => 'number',
1422 'default' => '0',
1423 'description' => '(0 means no free shipping)'
1424 ),
1425 'maximum_weight' => array(
1426 'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
1427 'type' => 'text',
1428 'default' => '15'
1429 ),
1430 'countries' => array(
1431 'title' => __('Specific Countries', 'wc_makecommerce_domain'),
1432 'type' => 'multiselect',
1433 'class' => 'wp-enhanced-select',
1434 'css' => 'width: 450px;',
1435 'default' => array('EE','LV','LT'),
1436 'options' => array('EE' => __('Estonia'), 'LV' => __('Latvia'), 'LT' => __('Lithuania')),
1437 ),
1438 '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')),
1439 'method_name' => array(
1440 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
1441 'type' => 'text',
1442 'default' => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
1443 ),
1444 'prioritization' => array(
1445 'title' => __('Prioritize', 'wc_makecommerce_domain'),
1446 'type' => 'checkbox',
1447 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
1448 'default' => 'yes'
1449 ),
1450 'short_office_names' => array(
1451 'title' => __('Short names', 'wc_makecommerce_domain'),
1452 'type' => 'checkbox',
1453 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
1454 'default' => 'no'
1455 ),
1456 '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'))),
1457 'service_user' => array(
1458 'title' => __('Omniva web services username', 'wc_makecommerce_domain'),
1459 'type' => 'text',
1460 'default' => ''
1461 ),
1462 'service_password' => array(
1463 'title' => __('Omniva web services password', 'wc_makecommerce_domain'),
1464 'type' => 'text',
1465 'default' => ''
1466 ),
1467 'return_address' => array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for Omniva shipments', 'wc_makecommerce_domain')),
1468 'shop_name' => array(
1469 'type' => 'text',
1470 'title' => __('Shop name', 'wc_makecommerce_domain'),
1471 'class' => 'input-text regular-input',
1472 ),
1473 'shop_phone' => array(
1474 'type' => 'text',
1475 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1476 'class' => 'input-text regular-input',
1477 ),
1478 'shop_email' => array(
1479 'type' => 'text',
1480 'title' => __('Shop email', 'wc_makecommerce_domain'),
1481 'class' => 'input-text regular-input',
1482 ),
1483 'shop_postal_code' => array(
1484 'type' => 'text',
1485 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1486 'class' => 'input-text regular-input',
1487 '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')
1488 ),
1489 );
1490 }
1491
1492 }
1493 class WC_ParcelMachine_Shipping_Method_Smartpost extends WC_ParcelMachine_Shipping_Method {
1494 function __construct() {
1495 $this->ext = 'SmartPost';
1496 $this->name_ext = 'SmartPOST';
1497 parent::__construct();
1498 }
1499 function init_form_fields() {
1500 global $woocommerce;
1501
1502 $this->form_fields = array(
1503 'logo' => array('type' => 'title', 'title' => __get_logo_html()),
1504 'generic' => array( 'type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
1505 'active' => array(
1506 'title' => __('Enable', 'wc_makecommerce_domain'),
1507 'type' => 'checkbox',
1508 'label' => __('enabled', 'wc_makecommerce_domain'),
1509 'default' => 'no',
1510 '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'),
1511 ),
1512 'price_ee' => array(
1513 'title' => __('Price EE', 'wc_makecommerce_domain'),
1514 'type' => 'text',
1515 'default' => '2.99'
1516 ),
1517 'price_fi' => array(
1518 'title' => __('Price FI', 'wc_makecommerce_domain'),
1519 'type' => 'text',
1520 'default' => '10.99'
1521 ),
1522 'free_shipping_min_amount' => array(
1523 'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
1524 'type' => 'number',
1525 'default' => '0',
1526 'description' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
1527 ),
1528 'maximum_weight' => array(
1529 'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
1530 'type' => 'text',
1531 'default' => '15'
1532 ),
1533 'countries' => array(
1534 'title' => __('Specific Countries', 'wc_makecommerce_domain'),
1535 'type' => 'multiselect',
1536 'class' => 'wp-enhanced-select',
1537 'css' => 'width: 450px;',
1538 'default' => array('EE','FI'),
1539 'options' => array('EE' => __('Estonia'), 'FI' => __('Finland')),
1540 ),
1541 'look_and_feel' => array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on checkout page', 'wc_makecommerce_domain')),
1542 'method_name' => array(
1543 'title' => __('Method Title', 'wc_makecommerce_domain'),
1544 'type' => 'text',
1545 'default' => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
1546 ),
1547 'prioritization' => array(
1548 'title' => __('Prioritize', 'wc_makecommerce_domain'),
1549 'type' => 'checkbox',
1550 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
1551 'default' => 'yes'
1552 ),
1553 'short_office_names' => array(
1554 'title' => __('Short names', 'wc_makecommerce_domain'),
1555 'type' => 'checkbox',
1556 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
1557 'default' => 'no'
1558 ),
1559 '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'))),
1560 'service_user' => array(
1561 'title' => __('eteenindus.smartpost.ee username', 'wc_makecommerce_domain'),
1562 'type' => 'text',
1563 'default' => ''
1564 ),
1565 'service_password' => array(
1566 'title' => __('eteenindus.smartpost.ee password', 'wc_makecommerce_domain'),
1567 'type' => 'text',
1568 'default' => ''
1569 ),
1570 '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')),
1571 'shop_name' => array(
1572 'type' => 'text',
1573 'title' => __('Shop name', 'wc_makecommerce_domain'),
1574 'class' => 'input-text regular-input',
1575 ),
1576 'shop_phone' => array(
1577 'type' => 'text',
1578 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1579 'class' => 'input-text regular-input',
1580 ),
1581 'shop_email' => array(
1582 'type' => 'text',
1583 'title' => __('Shop email', 'wc_makecommerce_domain'),
1584 'class' => 'input-text regular-input',
1585 ),
1586 /*'shop_postal_code' => array(
1587 'type' => 'text',
1588 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1589 'class' => 'input-text regular-input',
1590 ),
1591 */
1592 );
1593 }
1594
1595 }
1596 }
1597 }
1598 add_action('woocommerce_shipping_init', 'parcelmachine_add_method');
1599
1600 function add_parcelmachine_shipping_method($methods) {
1601 $methods[] = 'WC_ParcelMachine_Shipping_Method_Omniva';
1602 $methods[] = 'WC_ParcelMachine_Shipping_Method_Smartpost';
1603 return $methods;
1604 }
1605 add_filter('woocommerce_shipping_methods', 'add_parcelmachine_shipping_method');
1606
1607 function mk_parcelmachine_add_assets() {
1608 wp_enqueue_style('parcelmachine-css', plugin_dir_url(__FILE__).'/css/parcelmachine.css');
1609 wp_enqueue_script('parcelmachine-js', plugin_dir_url(__FILE__).'/scripts/parcelmachine.js', array('jquery'));
1610 }
1611 add_action('wp_enqueue_scripts', 'mk_parcelmachine_add_assets');
1612
1613 function mk_admin_plugin_settings_link($links) {
1614 $settings_link = '<a href="admin.php?page=wc-settings&tab=api&section=mk_api">API '.__('Settings').'</a>';
1615 array_unshift($links, $settings_link);
1616 return $links;
1617 }
1618 $plugin = plugin_basename(__FILE__);
1619 add_filter("plugin_action_links_$plugin", 'mk_admin_plugin_settings_link' );
1620
1621 function mk_admin_add_settings($sections) {
1622 $sections['mk_api'] = __('MakeCommerce API access', 'wc_makecommerce_domain');
1623 return $sections;
1624 }
1625
1626 function mk_admin_all_settings($settings) {
1627 global $current_section;
1628 if ($current_section !== 'mk_api') {
1629 return $settings;
1630 }
1631 return array(
1632 array('type' => 'title', 'desc' => __get_logo_html()),
1633 array(
1634 'type' => 'title',
1635 'title' => __('MakeCommerce API access credentials', 'wc_makecommerce_domain'),
1636 'desc' => sprintf(__('To use MakeCommerce/Maksekeskus services you need to enter API credentials below here <br/> <br/>'.
1637 'To further configure the Payment methods please go to <a href="%s">MakeCommerce Checkout Options</a><br>'.
1638 'To use also Ominva or Itella SmartPOST integration please configure these API accesses: <a href="%s">Omniva API access</a> | '.
1639 '<a href="%s">SmartPOST API access</a><br/>','wc_makecommerce_domain'),
1640 'admin.php?page=wc-settings&tab=checkout&section=makecommerce',
1641 'admin.php?page=wc-settings&tab=-shipping&section=parcelmachine_omniva',
1642 'admin.php?page=wc-settings&tab=shipping&section=parcelmachine_smartpost'
1643 ),
1644 'id' => 'mk_api_settings'
1645 ),
1646 array(
1647 'type' => 'select',
1648 'title' => __('Current environment', 'wc_makecommerce_domain'),
1649 'desc' => __('See more about <a href="https://maksekeskus.ee/en/for-developers/test-environment/">MakeCommerce Test environment</a>', 'wc_makecommerce_domain'),
1650 'default' => 'live',
1651 'options' => array(
1652 'live' => __('Live', 'wc_makecommerce_domain'),
1653 'test' => __('Test', 'wc_makecommerce_domain'),
1654 ),
1655 'id' => 'mk_api_type'
1656 ),
1657 array(
1658 'id' => 'mk_shop_id',
1659 'type' => 'text',
1660 'title' => __('Shop ID (live)', 'wc_makecommerce_domain'),
1661 'desc' => __('Get it from <a href="https://merchant.maksekeskus.ee/api.html" target="_blank">Merchant Portal</a>','wc_makecommerce_domain'),
1662 'class' => 'input-text regular-input',
1663 ),
1664 array(
1665 'id' => 'mk_public_key',
1666 'type' => 'text',
1667 'title' => __('Public key (live)', 'wc_makecommerce_domain'),
1668 'class' => 'input-text regular-input',
1669 ),
1670 array(
1671 'id' => 'mk_private_key',
1672 'type' => 'text',
1673 'title' => __('Private key (live)', 'wc_makecommerce_domain'),
1674 'class' => 'input-text regular-input',
1675 ),
1676 array(
1677 'id' => 'mk_test_shop_id',
1678 'type' => 'text',
1679 'title' => __('Shop ID (test)', 'wc_makecommerce_domain'),
1680 'class' => 'input-text regular-input',
1681 'desc' => __('Get it from <a href="https://merchant-test.maksekeskus.ee/api.html" target="_blank">Merchant Portal Test</a>','wc_makecommerce_domain'),
1682 ),
1683 array(
1684 'id' => 'mk_test_public_key',
1685 'type' => 'text',
1686 'title' => __('Public key (test)', 'wc_makecommerce_domain'),
1687 'class' => 'input-text regular-input',
1688 ),
1689 array(
1690 'id' => 'mk_test_private_key',
1691 'type' => 'text',
1692 'title' => __('Private key (test)', 'wc_makecommerce_domain'),
1693 'class' => 'input-text regular-input',
1694 ),
1695 array('type' => 'sectionend', 'id' => 'mk_api_settings')
1696 );
1697 }
1698
1699 function mk_admin_save_settings() {
1700 // reload banklinks
1701 global $current_section;
1702 if ($current_section !== 'mk_api') {
1703 return;
1704 }
1705 $wcmc = New woocommerce_makecommerce(true);
1706 $wcmc->mc_banklinks_reload(true);
1707 }
1708
1709 function __get_logo_html() {
1710 return '<div class="makecommerce-info">'.
1711 '<div class="makecommerce-logo">'.
1712 '<a target="_blank" href="http://maksekeskus.ee"><img src="'. plugins_url('/images/makecommerce_logo_en.svg', __FILE__) .'" class="makecommerce-logo"></a>'.
1713 '</div>'.
1714 '<div class="makecommerce-links">'.
1715 '<div class="makecommerce-link"><a target="_blank" href="https://merchant.maksekeskus.ee">Merchant Portal</a></div>'.
1716 '<div class="makecommerce-link"><a target="_blank" href="https://makecommerce.net/">makecommerce.net</a></div>'.
1717 '<div class="makecommerce-link"><a target="_blank" href="http://maksekeskus.ee">maksekeskus.ee</a></div>'.
1718 '</div>'.
1719 '</div>';
1720 }
1721
1722 add_action('woocommerce_get_sections_api', 'mk_admin_add_settings');
1723 add_filter('woocommerce_get_settings_api', 'mk_admin_all_settings', 10, 2);
1724 add_action('woocommerce_settings_saved', 'mk_admin_save_settings', 30, 0);
1725
1726 function mk_admin_restrict_manage_posts() {
1727 global $typenow;
1728 if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
1729 $selected_method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1730 $methods = WC()->shipping->load_shipping_methods();
1731 echo '<select name="_shipping_method" id="shipping_type" class="enhanced">';
1732 echo '<option value="">'.__('-- filter by shipping method', 'wc_makecommerce_domain') . '</option>';
1733 foreach ($methods as $method) {
1734 echo '<option value="'.$method->id.'"'.($selected_method === $method->id ? ' selected="selected"' : '').'>'.$method->title.'</option>';
1735 }
1736 echo '</select>';
1737 }
1738 }
1739 function mk_admin_shipping_filter($where, &$wp_query) {
1740 global $pagenow, $wpdb;
1741 $method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1742 if (is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
1743 $where .= $GLOBALS['wpdb']->prepare( ' AND ID
1744 IN (
1745 SELECT items.order_id
1746 FROM '.$wpdb->prefix.'woocommerce_order_itemmeta meta, '.$wpdb->prefix.'woocommerce_order_items items
1747 WHERE meta.order_item_id = items.order_item_id
1748 AND meta.meta_key = "method_id"
1749 AND meta.meta_value = %s
1750 ) ', $method );
1751 }
1752 return $where;
1753 }
1754 add_filter('restrict_manage_posts', 'mk_admin_restrict_manage_posts');
1755 add_filter('posts_where', 'mk_admin_shipping_filter', 10, 2);
1756
1757 function mk_admin_bulk_actions() {
1758 global $post_type;
1759 if ('shop_order' === $post_type) {
1760 ?>
1761 <script type="text/javascript">
1762 jQuery(function() {
1763 jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1764 jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1765 jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1766 jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1767 });
1768 </script>
1769 <?php
1770 if (!empty($_REQUEST['mk_pdf'])) {
1771 ?>
1772 <script type="text/javascript">
1773 jQuery(function(){
1774 window.open('<?php echo $_REQUEST['mk_pdf'] ?>', 'pdf');
1775 });
1776 </script>
1777 <?php
1778 }
1779 }
1780 }
1781 function mk_admin_bulk_action_labels() {
1782 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1783 $shipping_request = array('credentials' => array(), 'orders' => array());
1784 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1785 mk_get_shipment_ids($post_ids);
1786 }
1787 function mk_admin_bulk_action_print() {
1788 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1789 $shipping_request = array('credentials' => array(), 'orders' => array());
1790 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1791 mk_get_labels($post_ids);
1792 }
1793 add_action('admin_footer', 'mk_admin_bulk_actions', 11);
1794 add_action('admin_action_parcel_machine_labels', 'mk_admin_bulk_action_labels');
1795 add_action('admin_action_parcel_machine_print_labels', 'mk_admin_bulk_action_print');
1796
1797
1798
1799 function mk_admin_parcelmachine_order_meta($order) {
1800 $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1801 if (empty($machine_id)) return;
1802 list($provider, $machine) = explode('||', $machine_id);
1803 if (empty($machine)) return;
1804 $machine = mk_get_machine($provider, (int)$machine);
1805 if (!$machine) return;
1806 echo '<p><strong>'.__('Parcel machine').':</strong><br/>' . $machine['name'] . '<br/><small>' . $machine['address'] . '</small></p>';
1807 $shipment_id = get_post_meta($order->id, '_parcel_machine_shipment_id', true);
1808 $shipment_id_error = get_post_meta($order->id, '_parcel_machine_error', true);
1809 if ($shipment_id) {
1810 echo '<p><strong>'.__('Parcel machine shipment ID').':</strong><br/>' . $shipment_id . '</small></p>';
1811 }
1812 if ($shipment_id_error) {
1813 echo '<p><strong style="color: red;">'.__('Parcel machine shipment generation error').':</strong><br/>' . $shipment_id_error . '</small></p>';
1814 }
1815 }
1816
1817 function mk_admin_render_shop_order_columns( $column ) {
1818 global $post, $woocommerce, $the_order;
1819 if (empty($the_order) || $the_order->id != $post->ID) {
1820 $the_order = wc_get_order($post->ID);
1821 }
1822 if ($column === 'shipping_address') {
1823 $machine = get_post_meta($the_order->id, '_parcel_machine', true);
1824 $shipment_id = get_post_meta($the_order->id, '_parcel_machine_shipment_id', true);
1825 $shipment_id_error = get_post_meta($the_order->id, '_parcel_machine_error', true);
1826 if ($machine) {
1827 if ($shipment_id) echo __('Package shipment_id:', 'wc_makecommerce_domain') . ' ' . $shipment_id;
1828 else if ($shipment_id_error) echo '<span style="color: red;">'.__('Package shipment generation error:', 'wc_makecommerce_domain') . '</span><br/>' .$shipment_id_error;
1829 else echo __('Shipment ID not generated for delivery', 'wc_makecommerce_domain');
1830 }
1831 }
1832 }
1833 function mk_add_email_customer_details_fields($fields, $sent_to_admin, $order) {
1834 $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1835 if (empty($machine_id)) return $fields;
1836 list($provider, $machine) = explode('||', $machine_id);
1837 if (empty($machine)) return $fields;
1838 $machine = mk_get_machine($provider, (int)$machine);
1839 if (!$machine) return $fields;
1840 $fields[] = array('label' => __('Parcel machine'), 'value' => $machine['name'].' - '.$machine['address']);
1841 return $fields;
1842 }
1843 function mk_add_order_customer_details_fields($order) {
1844 $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1845 if (empty($machine_id)) return;
1846 list($provider, $machine) = explode('||', $machine_id);
1847 if (empty($machine)) return;
1848 $machine = mk_get_machine($provider, (int)$machine);
1849 if (!$machine) return;
1850 echo '<tr>';
1851 echo '<th>'.__('Parcel machine').'</th>';
1852 echo '<td>'.$machine['name'].'<br/>'.$machine['address'].'</td>';
1853 echo '</tr>';
1854 }
1855 function mk_admin_product_option_fields($fields) {
1856 echo '<div class="options_group">';
1857 woocommerce_wp_checkbox(
1858 array(
1859 'id' => '_no_parcel_machine',
1860 'wrapper_class' => 'show_if_simple',
1861 'label' => __('Does not fit parcel machine', 'wc_makecommerce_domain'),
1862 'description' => __('When this is checked, parcel machine shipping option is not available for a cart with this product', 'wc_makecommerce_domain')
1863 )
1864 );
1865 echo '</div>';
1866 }
1867 function mk_admin_product_fields_save($post_id) {
1868 $no_parcel_machine = isset($_POST['_no_parcel_machine']) ? 'yes' : 'no';
1869 update_post_meta($post_id, '_no_parcel_machine', $no_parcel_machine);
1870 }
1871
1872 add_action('woocommerce_product_options_shipping', 'mk_admin_product_option_fields');
1873 add_action('woocommerce_process_product_meta', 'mk_admin_product_fields_save');
1874 add_action('woocommerce_admin_order_data_after_shipping_address', 'mk_admin_parcelmachine_order_meta', 10, 1);
1875 add_action('manage_shop_order_posts_custom_column', 'mk_admin_render_shop_order_columns', 3);
1876 add_filter('woocommerce_email_customer_details_fields', 'mk_add_email_customer_details_fields', 10, 3 );
1877 add_action('woocommerce_order_details_after_customer_details', 'mk_add_order_customer_details_fields');
1878 add_action('woocommerce_order_status_processing', 'mk_get_shipment_ids');
1879
1880
1881
1882 function mk_get_shipment_ids($post_ids) {
1883 if (!is_array($post_ids)) {
1884 $post_ids = array($post_ids);
1885 }
1886 parcelmachine_add_method();
1887 $shipping_request = array('credentials' => array(), 'orders' => array());
1888 foreach ($post_ids as $post_id) {
1889 $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
1890 if (!$parcel_machine) { continue; }
1891 list($provider, $machine_id) = explode('||', $parcel_machine);
1892 if (!$provider || !$machine_id) { continue; }
1893 $provider_uc = mb_strtoupper($provider);
1894 switch ($provider_uc) {
1895 case "OMNIVA":
1896 $transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
1897 break;
1898 case "SMARTPOST":
1899 $transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
1900 break;
1901 default:
1902 break 2;
1903 }
1904 if (empty($shipping_request['credentials'][$provider_uc])) {
1905 $api_user = $transport_class->settings['service_user'];
1906 $api_password = $transport_class->settings['service_password'];
1907 if (!$api_user || !$api_password) {
1908 add_action('admin_notices', 'mk_admin_error');
1909 continue;
1910 }
1911 $shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
1912 }
1913 $order = wc_get_order($post_id);
1914 $sender = array(
1915 'name' => $transport_class->settings['shop_name'],
1916 'phone' => $transport_class->settings['shop_phone'],
1917 'email' => $transport_class->settings['shop_email'],
1918 'postalCode' => $transport_class->settings['shop_postal_code']
1919 );
1920 $shipping_request['orders'][] = array(
1921 'carrier' => $provider_uc,
1922 'orderId' => $order->id,
1923 'destination' => array('destinationId' => $machine_id),
1924 'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
1925 'sender' => $sender
1926 );
1927 }
1928 $shipping_request['credentials'] = array_values($shipping_request['credentials']);
1929 if (empty($shipping_request['orders'])) {
1930 return;
1931 }
1932 $MK = mk_get_api();
1933 if (!$MK) {
1934 return;
1935 }
1936 try {
1937 $response = $MK->createShipments($shipping_request);
1938 } catch (Exception $e) {
1939 echo $e->getMessage();
1940 exit();
1941 }
1942 foreach ($response as $order) {
1943 if (!empty($order->orderId) && !empty($order->shipmentId)) {
1944 update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->shipmentId));
1945 } else if (!empty($order->orderId) && !empty($order->barCode)) {
1946 update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->barCode));
1947 } else if (!empty($order->orderId) && !empty($order->errorMessage)) {
1948 update_post_meta((int)$order->orderId, '_parcel_machine_error', sanitize_text_field($order->errorMessage));
1949 }
1950 }
1951 }
1952
1953 function mk_get_labels($post_ids) {
1954 if (!is_array($post_ids)) {
1955 $post_ids = array($post_ids);
1956 }
1957 $sender = array(
1958 'name' => get_option('mk_shop_name', ''),
1959 'phone' => get_option('mk_shop_phone', ''),
1960 'email' => get_option('mk_shop_email', ''),
1961 'postalCode' => get_option('mk_shop_postal_code', '')
1962 );
1963 parcelmachine_add_method();
1964 $shipping_request = array('credentials' => array(), 'orders' => array(), 'printFormat' => 'A4');
1965 foreach ($post_ids as $post_id) {
1966 $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
1967 if (!$parcel_machine) { continue; }
1968 list($provider, $machine_id) = explode('||', $parcel_machine);
1969 if (!$provider || !$machine_id) { continue; }
1970 $provider_uc = mb_strtoupper($provider);
1971 if (empty($shipping_request['credentials'][$provider_uc])) {
1972 switch ($provider_uc) {
1973 case "OMNIVA":
1974 $transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
1975 break;
1976 case "SMARTPOST":
1977 $transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
1978 break;
1979 default:
1980 break 2;
1981 }
1982 $api_user = $transport_class->settings['service_user'];
1983 $api_password = $transport_class->settings['service_password'];
1984 if (!$api_user || !$api_password) {
1985 add_action('admin_notices', 'mk_admin_error');
1986 continue;
1987 }
1988 $shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
1989 }
1990 $order = wc_get_order($post_id);
1991 $shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
1992 if (!$shipment_id) { continue; }
1993 $shipping_request['orders'][] = array(
1994 'carrier' => $provider_uc,
1995 'orderId' => $order->id,
1996 'destination' => array('destinationId' => $machine_id),
1997 'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
1998 'sender' => $sender,
1999 'shipmentId' => $shipment_id
2000 );
2001 }
2002 $shipping_request['credentials'] = array_values($shipping_request['credentials']);
2003 if (empty($shipping_request['orders'])) {
2004 return;
2005 }
2006 $MK = mk_get_api();
2007 if (!$MK) {
2008 return;
2009 }
2010 try {
2011 $response = $MK->createLabels($shipping_request);
2012 } catch (Exception $e) {
2013 echo $e->getMessage();
2014 exit();
2015 }
2016 if (empty($response->labelUrl)) {
2017 return;
2018 }
2019 $sendback = add_query_arg(array('post_type' => 'shop_order', 'mk_pdf' => urlencode($response->labelUrl)), '');
2020 wp_redirect(esc_url_raw($sendback));
2021 exit();
2022 }
2023
2024
2025
2026 $MKAPI = false;
2027 function mk_get_api() {
2028 global $MKAPI;
2029 if ($MKAPI) {
2030 //return $MKAPI;
2031 }
2032 $mk_api_type = get_option('mk_api_type', false);
2033 if (!$mk_api_type) {
2034 return false;
2035 }
2036 $key_prefix = $mk_api_type.'_';
2037 $mk_shop_id = get_option('mk_'.$key_prefix.'shop_id', '');
2038 $mk_public_key = get_option('mk_'.$key_prefix.'public_key', '');
2039 $mk_private_key = get_option('mk_'.$key_prefix.'private_key', '');
2040 if (!$mk_shop_id || !$mk_public_key || !$mk_shop_id) {
2041 return false;
2042 }
2043 $MKAPI = new Maksekeskus($mk_shop_id, $mk_public_key, $mk_private_key, $mk_api_type === 'live' ? false : true);
2044 return $MKAPI;
2045 }
2046 function mk_get_machines($provider, $country = 'EE') {
2047 $data = get_option('mk_machines_cache', false);
2048 $data_expires = get_option('mk_machines_expires', false);
2049 if (!$data || $data_expires < time()) {
2050 $MK = mk_get_api();
2051 $data = $MK->getDestinations(array('type' => 'APT'));
2052 update_option('mk_machines_cache', $data);
2053 update_option('mk_machines_expires', time()+3*60*60);
2054 }
2055
2056 $machines = array();
2057 if (!$data || empty($data)) {
2058 return array();
2059 }
2060 foreach ($data as $machine) {
2061 if ($machine->country === $country && $machine->type === 'APT' && ($provider === '*' || strtolower($provider) === strtolower($machine->provider))) {
2062 $machines[] = array(
2063 'provider' => strtolower($machine->provider),
2064 'id' => $machine->id,
2065 'name' => $machine->name,
2066 'city' => $machine->city,
2067 'address' => !empty($machine->address) ? $machine->address : '',
2068 );
2069 }
2070 }
2071 usort($machines, function($a, $b){
2072 if ($a['city'] === $b['city']) {
2073 return $a['name'] > $b['name'];
2074 }
2075 return $a['city'] > $b['city'];
2076 });
2077 return $machines;
2078 }
2079
2080 function mk_get_machine($provider, $id) {
2081 $machines = mk_get_machines($provider);
2082 foreach ($machines as $machine) {
2083 if ($machine['provider'] === $provider && $machine['id'] === $id) {
2084 return $machine;
2085 }
2086 }
2087 return false;
2088 }
2089 function mk_admin_error() {
2090 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'));
2091 }
2092 }
2093