PluginProbe
MakeCommerce for WooCommerce / 1.0
MakeCommerce for WooCommerce v1.0
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
← All changes | makecommerce.php +2081 -40 trunk1.0 View file →
@@ -1,46 +1,2087 @@
1 1 <?php
2 -/**
3 - * @link https://makecommerce.net/
4 - * @since 4.0.0
5 - * @package Makecommerce
6 - *
7 - * @wordpress-plugin
8 - * Plugin Name: MakeCommerce
9 - * Plugin URI: https://makecommerce.net/
10 - * Description: Adds MakeCommerce payment gateway and shipping methods to WooCommerce checkout
11 - * Version: 4.1.0
12 - * Author: Maksekeskus AS
13 - * Author URI: https://makecommerce.net/
14 - * License: GPL-2.0+
15 - * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
16 - * Text Domain: makecommerce
17 - * Domain Path: /languages
18 - * Requires Plugins: woocommerce
19 - * Requires at least: 6.8.1
20 - * Requires PHP: 8.1
21 - * WC requires at least: 9.9.3
22 - * WC tested up to: 11.0.1
23 - * WC HPOS compatibility: yes
24 - * WC Legacy Order Table Compatibility: yes
25 - */
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
6 + Author: Maksekeskus AS
7 + Author URI: https://MakeCommerce.net/
8 + Text Domain: wc_makecommerce_domain
9 +*/
26 10
27 -function mc_table_exists(string $table): bool {
28 - global $wpdb;
29 - $table_name = $wpdb->prefix . $table;
30 - return $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name;
11 +if ( ! defined( 'ABSPATH' ) ) {
12 + exit; // Exit if accessed directly.
31 13 }
32 14
15 +if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
33 16
34 -if (
35 - (
36 - get_option('mc_version') !== false ||
37 - get_option('wc_mc_version') !== false ||
38 - mc_table_exists('mc_banklinks')
39 - ) &&
40 - !filter_var(get_option('mc_shipping_plus'), FILTER_VALIDATE_BOOLEAN)
41 -) {
42 - require_once plugin_dir_path(__FILE__) . 'config.php';
43 -} else {
44 - require_once plugin_dir_path(__FILE__) . 'makecommerce/makecommerce.php';
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 + function __get_logo_html() {
1378 + return '<div class="makecommerce-info">'.
1379 + '<div class="makecommerce-logo">'.
1380 + '<a target="_blank" href="http://maksekeskus.ee"><img src="'. plugins_url('/images/makecommerce_logo_en.svg', __FILE__) .'" class="makecommerce-logo"></a>'.
1381 + '</div>'.
1382 + '<div class="makecommerce-links">'.
1383 + '<div class="makecommerce-link"><a target="_blank" href="https://merchant.maksekeskus.ee">Merchant Portal</a></div>'.
1384 + '<div class="makecommerce-link"><a target="_blank" href="https://makecommerce.net/">makecommerce.net</a></div>'.
1385 + '<div class="makecommerce-link"><a target="_blank" href="http://maksekeskus.ee">maksekeskus.ee</a></div>'.
1386 + '</div>'.
1387 + '</div>';
1388 + }
1389 + class WC_ParcelMachine_Shipping_Method_Omniva extends WC_ParcelMachine_Shipping_Method {
1390 + function __construct($instance_id = 0) {
1391 + $this->ext = 'Omniva';
1392 + $this->name_ext = 'Omniva';
1393 + parent::__construct();
1394 + }
1395 + function init_form_fields() {
1396 +
1397 + $this->form_fields = array(
1398 + 'logo' => array('type' => 'title', 'title' => __get_logo_html()),
1399 + 'generic' => array('type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
1400 + 'active' => array(
1401 + 'title' => __('Enable', 'wc_makecommerce_domain'),
1402 + 'type' => 'checkbox',
1403 + 'label' => __('enabled', 'wc_makecommerce_domain'),
1404 + 'default' => 'no',
1405 + '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'),
1406 + ),
1407 + 'price_ee' => array(
1408 + 'title' => __('Price EE', 'wc_makecommerce_domain'),
1409 + 'type' => 'text',
1410 + 'default' => '2.99'
1411 + ),
1412 + 'price_lv' => array(
1413 + 'title' => __('Price LV', 'wc_makecommerce_domain'),
1414 + 'type' => 'text',
1415 + 'default' => '7.99'
1416 + ),
1417 + 'price_lt' => array(
1418 + 'title' => __('Price LT', 'wc_makecommerce_domain'),
1419 + 'type' => 'text',
1420 + 'default' => '8.99'
1421 + ),
1422 + //'price_fi' => array(
1423 + // 'title' => __('Price FI', 'wc_makecommerce_domain'),
1424 + // 'type' => 'text',
1425 + // 'default' => '10.99'
1426 + //),
1427 + 'free_shipping_min_amount' => array(
1428 + 'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
1429 + 'type' => 'number',
1430 + 'default' => '0',
1431 + 'description' => '(0 means no free shipping)'
1432 + ),
1433 + 'maximum_weight' => array(
1434 + 'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
1435 + 'type' => 'text',
1436 + 'default' => '15'
1437 + ),
1438 + 'countries' => array(
1439 + 'title' => __('Specific Countries', 'wc_makecommerce_domain'),
1440 + 'type' => 'multiselect',
1441 + 'class' => 'wp-enhanced-select',
1442 + 'css' => 'width: 450px;',
1443 + 'default' => array('EE','LV','LT'),
1444 + 'options' => array('EE' => __('Estonia'), 'LV' => __('Latvia'), 'LT' => __('Lithuania')),
1445 + ),
1446 + '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')),
1447 + 'method_name' => array(
1448 + 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
1449 + 'type' => 'text',
1450 + 'default' => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
1451 + ),
1452 + 'prioritization' => array(
1453 + 'title' => __('Prioritize', 'wc_makecommerce_domain'),
1454 + 'type' => 'checkbox',
1455 + 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
1456 + 'default' => 'yes'
1457 + ),
1458 + 'short_office_names' => array(
1459 + 'title' => __('Short names', 'wc_makecommerce_domain'),
1460 + 'type' => 'checkbox',
1461 + 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
1462 + 'default' => 'no'
1463 + ),
1464 + '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'))),
1465 + 'service_user' => array(
1466 + 'title' => __('Omniva web services username', 'wc_makecommerce_domain'),
1467 + 'type' => 'text',
1468 + 'default' => ''
1469 + ),
1470 + 'service_password' => array(
1471 + 'title' => __('Omniva web services password', 'wc_makecommerce_domain'),
1472 + 'type' => 'text',
1473 + 'default' => ''
1474 + ),
1475 + 'return_address' => array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for Omniva shipments', 'wc_makecommerce_domain')),
1476 + 'shop_name' => array(
1477 + 'type' => 'text',
1478 + 'title' => __('Shop name', 'wc_makecommerce_domain'),
1479 + 'class' => 'input-text regular-input',
1480 + ),
1481 + 'shop_phone' => array(
1482 + 'type' => 'text',
1483 + 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1484 + 'class' => 'input-text regular-input',
1485 + ),
1486 + 'shop_email' => array(
1487 + 'type' => 'text',
1488 + 'title' => __('Shop email', 'wc_makecommerce_domain'),
1489 + 'class' => 'input-text regular-input',
1490 + ),
1491 + 'shop_postal_code' => array(
1492 + 'type' => 'text',
1493 + 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1494 + 'class' => 'input-text regular-input',
1495 + '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')
1496 + ),
1497 + );
1498 + }
1499 +
1500 + }
1501 + class WC_ParcelMachine_Shipping_Method_Smartpost extends WC_ParcelMachine_Shipping_Method {
1502 + function __construct() {
1503 + $this->ext = 'SmartPost';
1504 + $this->name_ext = 'SmartPOST';
1505 + parent::__construct();
1506 + }
1507 + function init_form_fields() {
1508 + global $woocommerce;
1509 +
1510 + $this->form_fields = array(
1511 + 'logo' => array('type' => 'title', 'title' => __get_logo_html()),
1512 + 'generic' => array( 'type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain')),
1513 + 'active' => array(
1514 + 'title' => __('Enable', 'wc_makecommerce_domain'),
1515 + 'type' => 'checkbox',
1516 + 'label' => __('enabled', 'wc_makecommerce_domain'),
1517 + 'default' => 'no',
1518 + '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'),
1519 + ),
1520 + 'price_ee' => array(
1521 + 'title' => __('Price EE', 'wc_makecommerce_domain'),
1522 + 'type' => 'text',
1523 + 'default' => '2.99'
1524 + ),
1525 + 'price_fi' => array(
1526 + 'title' => __('Price FI', 'wc_makecommerce_domain'),
1527 + 'type' => 'text',
1528 + 'default' => '10.99'
1529 + ),
1530 + 'free_shipping_min_amount' => array(
1531 + 'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
1532 + 'type' => 'number',
1533 + 'default' => '0',
1534 + 'description' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
1535 + ),
1536 + 'maximum_weight' => array(
1537 + 'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
1538 + 'type' => 'text',
1539 + 'default' => '15'
1540 + ),
1541 + 'countries' => array(
1542 + 'title' => __('Specific Countries', 'wc_makecommerce_domain'),
1543 + 'type' => 'multiselect',
1544 + 'class' => 'wp-enhanced-select',
1545 + 'css' => 'width: 450px;',
1546 + 'default' => array('EE','FI'),
1547 + 'options' => array('EE' => __('Estonia'), 'FI' => __('Finland')),
1548 + ),
1549 + 'look_and_feel' => array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on checkout page', 'wc_makecommerce_domain')),
1550 + 'method_name' => array(
1551 + 'title' => __('Method Title', 'wc_makecommerce_domain'),
1552 + 'type' => 'text',
1553 + 'default' => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
1554 + ),
1555 + 'prioritization' => array(
1556 + 'title' => __('Prioritize', 'wc_makecommerce_domain'),
1557 + 'type' => 'checkbox',
1558 + 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
1559 + 'default' => 'yes'
1560 + ),
1561 + 'short_office_names' => array(
1562 + 'title' => __('Short names', 'wc_makecommerce_domain'),
1563 + 'type' => 'checkbox',
1564 + 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
1565 + 'default' => 'no'
1566 + ),
1567 + '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'))),
1568 + 'service_user' => array(
1569 + 'title' => __('eteenindus.smartpost.ee username', 'wc_makecommerce_domain'),
1570 + 'type' => 'text',
1571 + 'default' => ''
1572 + ),
1573 + 'service_password' => array(
1574 + 'title' => __('eteenindus.smartpost.ee password', 'wc_makecommerce_domain'),
1575 + 'type' => 'text',
1576 + 'default' => ''
1577 + ),
1578 + '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')),
1579 + 'shop_name' => array(
1580 + 'type' => 'text',
1581 + 'title' => __('Shop name', 'wc_makecommerce_domain'),
1582 + 'class' => 'input-text regular-input',
1583 + ),
1584 + 'shop_phone' => array(
1585 + 'type' => 'text',
1586 + 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1587 + 'class' => 'input-text regular-input',
1588 + ),
1589 + 'shop_email' => array(
1590 + 'type' => 'text',
1591 + 'title' => __('Shop email', 'wc_makecommerce_domain'),
1592 + 'class' => 'input-text regular-input',
1593 + ),
1594 + /*'shop_postal_code' => array(
1595 + 'type' => 'text',
1596 + 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1597 + 'class' => 'input-text regular-input',
1598 + ),
1599 + */
1600 + );
1601 + }
1602 +
1603 + }
1604 + }
1605 + }
1606 + add_action('woocommerce_shipping_init', 'parcelmachine_add_method');
1607 +
1608 + function add_parcelmachine_shipping_method($methods) {
1609 + $methods[] = 'WC_ParcelMachine_Shipping_Method_Omniva';
1610 + $methods[] = 'WC_ParcelMachine_Shipping_Method_Smartpost';
1611 + return $methods;
1612 + }
1613 + add_filter('woocommerce_shipping_methods', 'add_parcelmachine_shipping_method');
1614 +
1615 + function mk_parcelmachine_add_assets() {
1616 + wp_enqueue_style('parcelmachine-css', plugin_dir_url(__FILE__).'/css/parcelmachine.css');
1617 + wp_enqueue_script('parcelmachine-js', plugin_dir_url(__FILE__).'/scripts/parcelmachine.js', array('jquery'));
1618 + }
1619 + add_action('wp_enqueue_scripts', 'mk_parcelmachine_add_assets');
1620 +
1621 + function mk_admin_plugin_settings_link($links) {
1622 + $settings_link = '<a href="admin.php?page=wc-settings&tab=api&section=mk_api">API '.__('Settings').'</a>';
1623 + array_unshift($links, $settings_link);
1624 + return $links;
1625 + }
1626 + $plugin = plugin_basename(__FILE__);
1627 + add_filter("plugin_action_links_$plugin", 'mk_admin_plugin_settings_link' );
1628 +
1629 + function mk_admin_add_settings($sections) {
1630 + $sections['mk_api'] = __('MakeCommerce API access', 'wc_makecommerce_domain');
1631 + return $sections;
1632 + }
1633 +
1634 + function mk_admin_all_settings($settings) {
1635 + global $current_section;
1636 + if ($current_section !== 'mk_api') {
1637 + return $settings;
1638 + }
1639 + return array(
1640 + array('type' => 'title', 'desc' => __get_logo_html()),
1641 + array(
1642 + 'type' => 'title',
1643 + 'title' => __('MakeCommerce API access credentials', 'wc_makecommerce_domain'),
1644 + 'desc' => sprintf(__('To use MakeCommerce/Maksekeskus services you need to enter API credentials below here <br/> <br/>'.
1645 + 'To further configure the Payment methods please go to <a href="%s">MakeCommerce Checkout Options</a><br>'.
1646 + 'To use also Ominva or Itella SmartPOST integration please configure these API accesses: <a href="%s">Omniva API access</a> | '.
1647 + '<a href="%s">SmartPOST API access</a><br/>','wc_makecommerce_domain'),
1648 + 'admin.php?page=wc-settings&tab=checkout&section=makecommerce',
1649 + 'admin.php?page=wc-settings&tab=-shipping&section=parcelmachine_omniva',
1650 + 'admin.php?page=wc-settings&tab=shipping&section=parcelmachine_smartpost'
1651 + ),
1652 + 'id' => 'mk_api_settings'
1653 + ),
1654 + array(
1655 + 'type' => 'select',
1656 + 'title' => __('Current environment', 'wc_makecommerce_domain'),
1657 + 'desc' => __('See more about <a href="https://maksekeskus.ee/en/for-developers/test-environment/">MakeCommerce Test environment</a>', 'wc_makecommerce_domain'),
1658 + 'default' => 'live',
1659 + 'options' => array(
1660 + 'live' => __('Live', 'wc_makecommerce_domain'),
1661 + 'test' => __('Test', 'wc_makecommerce_domain'),
1662 + ),
1663 + 'id' => 'mk_api_type'
1664 + ),
1665 + array(
1666 + 'id' => 'mk_shop_id',
1667 + 'type' => 'text',
1668 + 'title' => __('Shop ID (live)', 'wc_makecommerce_domain'),
1669 + 'desc' => __('Get it from <a href="https://merchant.maksekeskus.ee/api.html" target="_blank">Merchant Portal</a>','wc_makecommerce_domain'),
1670 + 'class' => 'input-text regular-input',
1671 + ),
1672 + array(
1673 + 'id' => 'mk_public_key',
1674 + 'type' => 'text',
1675 + 'title' => __('Public key (live)', 'wc_makecommerce_domain'),
1676 + 'class' => 'input-text regular-input',
1677 + ),
1678 + array(
1679 + 'id' => 'mk_private_key',
1680 + 'type' => 'text',
1681 + 'title' => __('Private key (live)', 'wc_makecommerce_domain'),
1682 + 'class' => 'input-text regular-input',
1683 + ),
1684 + array(
1685 + 'id' => 'mk_test_shop_id',
1686 + 'type' => 'text',
1687 + 'title' => __('Shop ID (test)', 'wc_makecommerce_domain'),
1688 + 'class' => 'input-text regular-input',
1689 + 'desc' => __('Get it from <a href="https://merchant-test.maksekeskus.ee/api.html" target="_blank">Merchant Portal Test</a>','wc_makecommerce_domain'),
1690 + ),
1691 + array(
1692 + 'id' => 'mk_test_public_key',
1693 + 'type' => 'text',
1694 + 'title' => __('Public key (test)', 'wc_makecommerce_domain'),
1695 + 'class' => 'input-text regular-input',
1696 + ),
1697 + array(
1698 + 'id' => 'mk_test_private_key',
1699 + 'type' => 'text',
1700 + 'title' => __('Private key (test)', 'wc_makecommerce_domain'),
1701 + 'class' => 'input-text regular-input',
1702 + ),
1703 + array('type' => 'sectionend', 'id' => 'mk_api_settings')
1704 + );
1705 + }
1706 +
1707 + function mk_admin_save_settings() {
1708 + // reload banklinks
1709 + global $current_section;
1710 + if ($current_section !== 'mk_api') {
1711 + return;
1712 + }
1713 + $wcmc = New woocommerce_makecommerce(true);
1714 + $wcmc->mc_banklinks_reload(true);
1715 + }
1716 +
1717 + add_action('woocommerce_get_sections_api', 'mk_admin_add_settings');
1718 + add_filter('woocommerce_get_settings_api', 'mk_admin_all_settings', 10, 2);
1719 + add_action('woocommerce_settings_saved', 'mk_admin_save_settings', 30, 0);
1720 +
1721 + function mk_admin_restrict_manage_posts() {
1722 + global $typenow;
1723 + if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
1724 + $selected_method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1725 + $methods = WC()->shipping->load_shipping_methods();
1726 + echo '<select name="_shipping_method" id="shipping_type" class="enhanced">';
1727 + echo '<option value="">'.__('-- filter by shipping method', 'wc_makecommerce_domain') . '</option>';
1728 + foreach ($methods as $method) {
1729 + echo '<option value="'.$method->id.'"'.($selected_method === $method->id ? ' selected="selected"' : '').'>'.$method->title.'</option>';
1730 + }
1731 + echo '</select>';
1732 + }
1733 + }
1734 + function mk_admin_shipping_filter($where, &$wp_query) {
1735 + global $pagenow, $wpdb;
1736 + $method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1737 + if (is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
1738 + $where .= $GLOBALS['wpdb']->prepare( ' AND ID
1739 + IN (
1740 + SELECT items.order_id
1741 + FROM '.$wpdb->prefix.'woocommerce_order_itemmeta meta, '.$wpdb->prefix.'woocommerce_order_items items
1742 + WHERE meta.order_item_id = items.order_item_id
1743 + AND meta.meta_key = "method_id"
1744 + AND meta.meta_value = %s
1745 + ) ', $method );
1746 + }
1747 + return $where;
1748 + }
1749 + add_filter('restrict_manage_posts', 'mk_admin_restrict_manage_posts');
1750 + add_filter('posts_where', 'mk_admin_shipping_filter', 10, 2);
1751 +
1752 + function mk_admin_bulk_actions() {
1753 + global $post_type;
1754 + if ('shop_order' === $post_type) {
1755 +?>
1756 + <script type="text/javascript">
1757 + jQuery(function() {
1758 + jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1759 + jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1760 + jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1761 + jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1762 + });
1763 + </script>
1764 +<?php
1765 + if (!empty($_REQUEST['mk_pdf'])) {
1766 +?>
1767 + <script type="text/javascript">
1768 + jQuery(function(){
1769 + window.open('<?php echo $_REQUEST['mk_pdf'] ?>', 'pdf');
1770 + });
1771 + </script>
1772 +<?php
1773 + }
1774 + }
1775 + }
1776 + function mk_admin_bulk_action_labels() {
1777 + $wp_list_table = _get_list_table('WP_Posts_List_Table');
1778 + $shipping_request = array('credentials' => array(), 'orders' => array());
1779 + $post_ids = array_map('absint', (array)$_REQUEST['post']);
1780 + mk_get_shipment_ids($post_ids);
1781 + }
1782 + function mk_admin_bulk_action_print() {
1783 + $wp_list_table = _get_list_table('WP_Posts_List_Table');
1784 + $shipping_request = array('credentials' => array(), 'orders' => array());
1785 + $post_ids = array_map('absint', (array)$_REQUEST['post']);
1786 + mk_get_labels($post_ids);
1787 + }
1788 + add_action('admin_footer', 'mk_admin_bulk_actions', 11);
1789 + add_action('admin_action_parcel_machine_labels', 'mk_admin_bulk_action_labels');
1790 + add_action('admin_action_parcel_machine_print_labels', 'mk_admin_bulk_action_print');
1791 +
1792 +
1793 +
1794 + function mk_admin_parcelmachine_order_meta($order) {
1795 + $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1796 + if (empty($machine_id)) return;
1797 + list($provider, $machine) = explode('||', $machine_id);
1798 + if (empty($machine)) return;
1799 + $machine = mk_get_machine($provider, (int)$machine);
1800 + if (!$machine) return;
1801 + echo '<p><strong>'.__('Parcel machine').':</strong><br/>' . $machine['name'] . '<br/><small>' . $machine['address'] . '</small></p>';
1802 + $shipment_id = get_post_meta($order->id, '_parcel_machine_shipment_id', true);
1803 + $shipment_id_error = get_post_meta($order->id, '_parcel_machine_error', true);
1804 + if ($shipment_id) {
1805 + echo '<p><strong>'.__('Parcel machine shipment ID').':</strong><br/>' . $shipment_id . '</small></p>';
1806 + }
1807 + if ($shipment_id_error) {
1808 + echo '<p><strong style="color: red;">'.__('Parcel machine shipment generation error').':</strong><br/>' . $shipment_id_error . '</small></p>';
1809 + }
1810 + }
1811 +
1812 + function mk_admin_render_shop_order_columns( $column ) {
1813 + global $post, $woocommerce, $the_order;
1814 + if (empty($the_order) || $the_order->id != $post->ID) {
1815 + $the_order = wc_get_order($post->ID);
1816 + }
1817 + if ($column === 'shipping_address') {
1818 + $machine = get_post_meta($the_order->id, '_parcel_machine', true);
1819 + $shipment_id = get_post_meta($the_order->id, '_parcel_machine_shipment_id', true);
1820 + $shipment_id_error = get_post_meta($the_order->id, '_parcel_machine_error', true);
1821 + if ($machine) {
1822 + if ($shipment_id) echo __('Package shipment_id:', 'wc_makecommerce_domain') . ' ' . $shipment_id;
1823 + else if ($shipment_id_error) echo '<span style="color: red;">'.__('Package shipment generation error:', 'wc_makecommerce_domain') . '</span><br/>' .$shipment_id_error;
1824 + else echo __('Shipment ID not generated for delivery', 'wc_makecommerce_domain');
1825 + }
1826 + }
1827 + }
1828 + function mk_add_email_customer_details_fields($fields, $sent_to_admin, $order) {
1829 + $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1830 + if (empty($machine_id)) return $fields;
1831 + list($provider, $machine) = explode('||', $machine_id);
1832 + if (empty($machine)) return $fields;
1833 + $machine = mk_get_machine($provider, (int)$machine);
1834 + if (!$machine) return $fields;
1835 + $fields[] = array('label' => __('Parcel machine'), 'value' => $machine['name'].' - '.$machine['address']);
1836 + return $fields;
1837 + }
1838 + function mk_add_order_customer_details_fields($order) {
1839 + $machine_id = get_post_meta($order->id, '_parcel_machine', true);
1840 + if (empty($machine_id)) return;
1841 + list($provider, $machine) = explode('||', $machine_id);
1842 + if (empty($machine)) return;
1843 + $machine = mk_get_machine($provider, (int)$machine);
1844 + if (!$machine) return;
1845 + echo '<tr>';
1846 + echo '<th>'.__('Parcel machine').'</th>';
1847 + echo '<td>'.$machine['name'].'<br/>'.$machine['address'].'</td>';
1848 + echo '</tr>';
1849 + }
1850 + function mk_admin_product_option_fields($fields) {
1851 + echo '<div class="options_group">';
1852 + woocommerce_wp_checkbox(
1853 + array(
1854 + 'id' => '_no_parcel_machine',
1855 + 'wrapper_class' => 'show_if_simple',
1856 + 'label' => __('Does not fit parcel machine', 'wc_makecommerce_domain'),
1857 + 'description' => __('When this is checked, parcel machine shipping option is not available for a cart with this product', 'wc_makecommerce_domain')
1858 + )
1859 + );
1860 + echo '</div>';
1861 + }
1862 + function mk_admin_product_fields_save($post_id) {
1863 + $no_parcel_machine = isset($_POST['_no_parcel_machine']) ? 'yes' : 'no';
1864 + update_post_meta($post_id, '_no_parcel_machine', $no_parcel_machine);
1865 + }
1866 +
1867 + add_action('woocommerce_product_options_shipping', 'mk_admin_product_option_fields');
1868 + add_action('woocommerce_process_product_meta', 'mk_admin_product_fields_save');
1869 + add_action('woocommerce_admin_order_data_after_shipping_address', 'mk_admin_parcelmachine_order_meta', 10, 1);
1870 + add_action('manage_shop_order_posts_custom_column', 'mk_admin_render_shop_order_columns', 3);
1871 + add_filter('woocommerce_email_customer_details_fields', 'mk_add_email_customer_details_fields', 10, 3 );
1872 + add_action('woocommerce_order_details_after_customer_details', 'mk_add_order_customer_details_fields');
1873 + add_action('woocommerce_order_status_processing', 'mk_get_shipment_ids');
1874 +
1875 +
1876 +
1877 + function mk_get_shipment_ids($post_ids) {
1878 + if (!is_array($post_ids)) {
1879 + $post_ids = array($post_ids);
1880 + }
1881 + parcelmachine_add_method();
1882 + $shipping_request = array('credentials' => array(), 'orders' => array());
1883 + foreach ($post_ids as $post_id) {
1884 + $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
1885 + if (!$parcel_machine) { continue; }
1886 + list($provider, $machine_id) = explode('||', $parcel_machine);
1887 + if (!$provider || !$machine_id) { continue; }
1888 + $provider_uc = mb_strtoupper($provider);
1889 + switch ($provider_uc) {
1890 + case "OMNIVA":
1891 + $transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
1892 + break;
1893 + case "SMARTPOST":
1894 + $transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
1895 + break;
1896 + default:
1897 + break 2;
1898 + }
1899 + if (empty($shipping_request['credentials'][$provider_uc])) {
1900 + $api_user = $transport_class->settings['service_user'];
1901 + $api_password = $transport_class->settings['service_password'];
1902 + if (!$api_user || !$api_password) {
1903 + add_action('admin_notices', 'mk_admin_error');
1904 + continue;
1905 + }
1906 + $shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
1907 + }
1908 + $order = wc_get_order($post_id);
1909 + $sender = array(
1910 + 'name' => $transport_class->settings['shop_name'],
1911 + 'phone' => $transport_class->settings['shop_phone'],
1912 + 'email' => $transport_class->settings['shop_email'],
1913 + 'postalCode' => $transport_class->settings['shop_postal_code']
1914 + );
1915 + $shipping_request['orders'][] = array(
1916 + 'carrier' => $provider_uc,
1917 + 'orderId' => $order->id,
1918 + 'destination' => array('destinationId' => $machine_id),
1919 + 'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
1920 + 'sender' => $sender
1921 + );
1922 + }
1923 + $shipping_request['credentials'] = array_values($shipping_request['credentials']);
1924 + if (empty($shipping_request['orders'])) {
1925 + return;
1926 + }
1927 + $MK = mk_get_api();
1928 + if (!$MK) {
1929 + return;
1930 + }
1931 + try {
1932 + $response = $MK->createShipments($shipping_request);
1933 + } catch (Exception $e) {
1934 + echo $e->getMessage();
1935 + exit();
1936 + }
1937 + foreach ($response as $order) {
1938 + if (!empty($order->orderId) && !empty($order->shipmentId)) {
1939 + update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->shipmentId));
1940 + } else if (!empty($order->orderId) && !empty($order->barCode)) {
1941 + update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->barCode));
1942 + } else if (!empty($order->orderId) && !empty($order->errorMessage)) {
1943 + update_post_meta((int)$order->orderId, '_parcel_machine_error', sanitize_text_field($order->errorMessage));
1944 + }
1945 + }
1946 + }
1947 +
1948 + function mk_get_labels($post_ids) {
1949 + if (!is_array($post_ids)) {
1950 + $post_ids = array($post_ids);
1951 + }
1952 + $sender = array(
1953 + 'name' => get_option('mk_shop_name', ''),
1954 + 'phone' => get_option('mk_shop_phone', ''),
1955 + 'email' => get_option('mk_shop_email', ''),
1956 + 'postalCode' => get_option('mk_shop_postal_code', '')
1957 + );
1958 + parcelmachine_add_method();
1959 + $shipping_request = array('credentials' => array(), 'orders' => array(), 'printFormat' => 'A4');
1960 + foreach ($post_ids as $post_id) {
1961 + $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
1962 + if (!$parcel_machine) { continue; }
1963 + list($provider, $machine_id) = explode('||', $parcel_machine);
1964 + if (!$provider || !$machine_id) { continue; }
1965 + $provider_uc = mb_strtoupper($provider);
1966 + if (empty($shipping_request['credentials'][$provider_uc])) {
1967 + switch ($provider_uc) {
1968 + case "OMNIVA":
1969 + $transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
1970 + break;
1971 + case "SMARTPOST":
1972 + $transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
1973 + break;
1974 + default:
1975 + break 2;
1976 + }
1977 + $api_user = $transport_class->settings['service_user'];
1978 + $api_password = $transport_class->settings['service_password'];
1979 + if (!$api_user || !$api_password) {
1980 + add_action('admin_notices', 'mk_admin_error');
1981 + continue;
1982 + }
1983 + $shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
1984 + }
1985 + $order = wc_get_order($post_id);
1986 + $shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
1987 + if (!$shipment_id) { continue; }
1988 + $shipping_request['orders'][] = array(
1989 + 'carrier' => $provider_uc,
1990 + 'orderId' => $order->id,
1991 + 'destination' => array('destinationId' => $machine_id),
1992 + 'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
1993 + 'sender' => $sender,
1994 + 'shipmentId' => $shipment_id
1995 + );
1996 + }
1997 + $shipping_request['credentials'] = array_values($shipping_request['credentials']);
1998 + if (empty($shipping_request['orders'])) {
1999 + return;
2000 + }
2001 + $MK = mk_get_api();
2002 + if (!$MK) {
2003 + return;
2004 + }
2005 + try {
2006 + $response = $MK->createLabels($shipping_request);
2007 + } catch (Exception $e) {
2008 + echo $e->getMessage();
2009 + exit();
2010 + }
2011 + if (empty($response->labelUrl)) {
2012 + return;
2013 + }
2014 + $sendback = add_query_arg(array('post_type' => 'shop_order', 'mk_pdf' => urlencode($response->labelUrl)), '');
2015 + wp_redirect(esc_url_raw($sendback));
2016 + exit();
2017 + }
2018 +
2019 +
2020 +
2021 + $MKAPI = false;
2022 + function mk_get_api() {
2023 + global $MKAPI;
2024 + if ($MKAPI) {
2025 + //return $MKAPI;
2026 + }
2027 + $mk_api_type = get_option('mk_api_type', false);
2028 + if (!$mk_api_type) {
2029 + return false;
2030 + }
2031 + $key_prefix = $mk_api_type.'_';
2032 + $mk_shop_id = get_option('mk_'.$key_prefix.'shop_id', '');
2033 + $mk_public_key = get_option('mk_'.$key_prefix.'public_key', '');
2034 + $mk_private_key = get_option('mk_'.$key_prefix.'private_key', '');
2035 + if (!$mk_shop_id || !$mk_public_key || !$mk_shop_id) {
2036 + return false;
2037 + }
2038 + $MKAPI = new Maksekeskus($mk_shop_id, $mk_public_key, $mk_private_key, $mk_api_type === 'live' ? false : true);
2039 + return $MKAPI;
2040 + }
2041 + function mk_get_machines($provider, $country = 'EE') {
2042 + $data = get_option('mk_machines_cache', false);
2043 + $data_expires = get_option('mk_machines_expires', false);
2044 + if (!$data || $data_expires < time()) {
2045 + $MK = mk_get_api();
2046 + $data = $MK->getDestinations(array('type' => 'APT'));
2047 + update_option('mk_machines_cache', $data);
2048 + update_option('mk_machines_expires', time()+3*60*60);
2049 + }
2050 +
2051 + $machines = array();
2052 + if (!$data || empty($data)) {
2053 + return array();
2054 + }
2055 + foreach ($data as $machine) {
2056 + if ($machine->country === $country && $machine->type === 'APT' && ($provider === '*' || strtolower($provider) === strtolower($machine->provider))) {
2057 + $machines[] = array(
2058 + 'provider' => strtolower($machine->provider),
2059 + 'id' => $machine->id,
2060 + 'name' => $machine->name,
2061 + 'city' => $machine->city,
2062 + 'address' => !empty($machine->address) ? $machine->address : '',
2063 + );
2064 + }
2065 + }
2066 + usort($machines, function($a, $b){
2067 + if ($a['city'] === $b['city']) {
2068 + return $a['name'] > $b['name'];
2069 + }
2070 + return $a['city'] > $b['city'];
2071 + });
2072 + return $machines;
2073 + }
2074 +
2075 + function mk_get_machine($provider, $id) {
2076 + $machines = mk_get_machines($provider);
2077 + foreach ($machines as $machine) {
2078 + if ($machine['provider'] === $provider && $machine['id'] === $id) {
2079 + return $machine;
2080 + }
2081 + }
2082 + return false;
2083 + }
2084 + function mk_admin_error() {
2085 + 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'));
2086 + }
45 2087 }
46 -