PluginProbe
MakeCommerce for WooCommerce / 1.0.1
MakeCommerce for WooCommerce v1.0.1
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.1, at makecommerce.php

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