prefix . $mkDbTable;
$charset = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $tableName (
id mediumint(9) NOT NULL AUTO_INCREMENT,
type varchar(10) NOT NULL,
country char(2) NOT NULL,
name varchar(25) NOT NULL,
url varchar(250) NOT NULL,
UNIQUE KEY id (id)
) $charset;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'mc_install' );
if (!class_exists('wc_makecommerce_domain')) {
require_once('includes/Api.php');
}
function woocommerce_payment_makecommerce_init() {
load_plugin_textdomain('wc_makecommerce_domain', false, dirname(plugin_basename(__FILE__)) . '/');
class woocommerce_makecommerce extends WC_Payment_Gateway {
const MC_CANCELLED = 'CANCELLED';
const MC_COMPLETED = 'COMPLETED';
const MC_DEPOSITED = 'DEPOSITED';
const MC_PART_REFUNDED = 'PART_REFUNDED';
const MC_REFUNDED = 'REFUNDED';
const module_name = 'MakeCommerce';
const api_url = 'https://api.maksekeskus.ee/v1/';
const gateway_url = 'https://payment.maksekeskus.ee/pay/1/signed.html';
const gateway_url_static = 'https://payment.maksekeskus.ee/checkout/dist/';
const fo_url = 'https://merchant.maksekeskus.ee/';
const test_api_url = 'https://api-test.maksekeskus.ee/v1/';
const test_gateway_url = 'https://payment-test.maksekeskus.ee/pay/1/signed.html';
const test_gateway_url_static = 'https://payment-test.maksekeskus.ee/checkout/dist/';
const test_fo_url = 'https://merchant-test.maksekeskus.ee/';
const billing_descriptor_dba = '';
const currencies_allowed = 'EUR';
const module_homepage_url = 'https://maksekeskus.ee/en/integration-modules/makecommerce-woocommerce-payment-plugin/';
const testenv_homepage_url = 'http://maksekeskus.ee/en/for-developers/test-environment/';
public $id = 'makecommerce';
public $version = '1.1';
public $return_url;
public $return_url_cancel;
public $return_url_cc;
protected $_shop_id;
protected $_api_key_secret;
protected $_api_key_public;
protected $_gateway_url_static;
protected $_banklinks = array();
protected $_banklinks_grouped;
protected $_cards = array();
protected $_api;
protected $_init;
public function __construct($init = false) {
$this->_init = $init;
$this->return_url = site_url('/?makecommerce_return=1');
$this->return_url_cancel = site_url('/?makecommerce_return=1');
$this->return_url_cc = site_url('/?makecommerce_return=2');
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
$this->initBanklinks();
$this->title = $this->settings['ui_widget_title'];
if (defined('ICL_LANGUAGE_CODE') && !empty($this->settings['ui_widget_title_'.ICL_LANGUAGE_CODE])) {
$this->title = $this->settings['ui_widget_title_'.ICL_LANGUAGE_CODE];
}
$this->method_title = 'MakeCommerce';
$this->description = true;
$this->_api = mk_get_api();
if (!$this->_api && $this->_init) {
add_action( 'admin_notices', array(&$this, 'makecommerce_api_info_missing') );
}
if(get_option('mk_api_type', false) == 'live') {
$this->_gateway_url_static = self::gateway_url_static;
} elseif (get_option('mk_api_type', false) == 'test') {
$this->_gateway_url_static = self::test_gateway_url_static;
}
$this->supports = array(
'products',
'refunds',
);
add_filter('query_vars', array(&$this, 'makecommerce_return_trigger'));
add_action('template_redirect', array(&$this, 'makecommerce_return_trigger_check'));
add_action( 'wp_ajax_makecommerce_pay_token', array(&$this, 'makecommerce_pay_token') );
add_action( 'wp_ajax_nopriv_makecommerce_pay_token', array(&$this, 'makecommerce_pay_token') );
if($this->_init == false) {
add_action('woocommerce_update_options_payment_gateways', array(&$this, 'process_admin_options'));
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array(&$this, 'process_admin_options'));
add_action('woocommerce_receipt_' . $this->id, array(&$this, 'receipt_page'));
add_action('woocommerce_admin_order_data_after_order_details', array(&$this, 'admin_order_page'), 10, 1);
wp_enqueue_script('jquery');
wp_enqueue_style('makecommerce', plugins_url('/css/makecommerce.css', __FILE__), array(), $this->version);
}
if(is_admin()) {
add_action( 'wp_ajax_mc_banklinks_reload', array(&$this, 'mc_banklinks_reload') );
}
}
function makecommerce_api_info_missing() {
?>
form_fields = array();
$this->form_fields['header'] = array(
'type' => 'mc_header',
);
$this->form_fields['active'] = array(
'title' => __('Enable/Disable', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('Enable MakeCommerce payments', 'wc_makecommerce_domain'),
'default' => 'no'
);
$this->form_fields['api_title'] = array(
'title' => __('MakeCommerce API', 'wc_makecommerce_domain'),
'description' => sprintf(__('Go to API settings to fill in the credentials', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api§ion=mk_api')),
'type' => 'title',
);
$this->form_fields['ui_title'] = array(
'title' => ' '.__('User Interface', 'wc_makecommerce_domain'),
'type' => 'title',
'class' => 'ui-identifier',
);
$this->form_fields['ui_open_by_default'] = array(
'title' => __('Set as default selection', 'wc_makecommerce_domain'),
'label' => __('MakeCommerce payments widget will be selected by default', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'default' => 'yes',
'class' => 'ui-identifier',
);
$this->form_fields['ui_mode'] = array(
'title' => __('Display MC payment channels as', 'wc_makecommerce_domain'),
'type' => 'mc_hidden',
'default' => 'widget',
'options' => array(
'inline' => __('List', 'wc_makecommerce_domain'),
'widget' => __('Grouped to widget', 'wc_makecommerce_domain'),
),
'class' => 'ui-identifier',
);
if (empty($languages)) {
$this->form_fields['ui_widget_title'] = array(
'title' => __('Payments widget title', 'wc_makecommerce_domain'),
'type' => 'text',
'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'),
'default' => __('Pay with bank-links or credit card', 'wc_makecommerce_domain'),
'class' => 'ui-identifier',
);
} else {
foreach ($languages as $language_code => $language) {
$language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
$this->form_fields['ui_widget_title_'.$language_code] = array(
'title' => __('Payments widget title', 'wc_makecommerce_domain').sprintf(' (%s)', $language_code),
'type' => 'text',
'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'),
'default' => __('Pay with bank-links or credit card', 'wc_makecommerce_domain'),
'class' => 'ui-identifier',
);
}
}
$this->form_fields['ui_inline_uselogo'] = array(
'title' => __('MC payment channels display style', 'wc_makecommerce_domain'),
'type' => 'select',
'default' => 'logo',
'options' => array(
'logo' => __('Logo', 'wc_makecommerce_domain'),
'text_logo' => __('Text & logo', 'wc_makecommerce_domain'),
'text' => __('Text', 'wc_makecommerce_domain'),
),
'class' => 'ui-identifier',
);
$this->form_fields['ui_widget_logosize'] = array(
'title' => __('Size of payment channel logos', 'wc_makecommerce_domain'),
'type' => 'select',
'default' => 'medium',
'options' => array(
'small' => __('Small', 'wc_makecommerce_domain'),
'medium' => __('Medium', 'wc_makecommerce_domain'),
'large' => __('Large', 'wc_makecommerce_domain')
),
'class' => 'ui-identifier',
);
$this->form_fields['ui_widget_groupcountries'] = array(
'title' => __('Group bank-links by countries', 'wc_makecommerce_domain'),
'type' => 'mc_hidden',
'default' => 'no',
'class' => 'ui-identifier',
);
$this->form_fields['ui_widget_countryselector'] = array(
'title' => __('Country selector style', 'wc_makecommerce_domain'),
'type' => 'mc_hidden',
'default' => 'flag',
'options' => array(
'flag' => __('Flag', 'wc_makecommerce_domain'),
'dropdown' => __('Dropdown', 'wc_makecommerce_domain'),
),
'class' => 'ui-identifier',
);
$this->form_fields['ui_widget_groupcc'] = array(
'title' => __('Group credit card into separate widget', 'wc_makecommerce_domain'),
'type' => 'mc_hidden',
'default' => 'no',
'class' => 'ui-identifier',
);
$this->form_fields['ui_chorder'] = array(
'title' => __('Define custom order of payment channels', 'wc_makecommerce_domain'),
'type' => 'text',
'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'),
'class' => 'ui-identifier',
);
$this->form_fields['ui_javascript'] = array(
'type' => 'ui_javascript',
);
$this->form_fields['cc_title'] = array(
'title' => ' '.__('Credit Card Settings', 'wc_makecommerce_domain'),
'type' => 'title',
);
$this->form_fields['cc_pass_cust_data'] = array(
'title' => __('Prefill Credit Card form with customer data', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'default' => 'yes',
'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'),
);
$this->form_fields['cc_shop_name'] = array(
'title' => __('Shop name on credit card payment', 'wc_makecommerce_domain'),
'type' => 'text',
'desc_tip' => __('This will appear on buyer\'s credit card transaction', 'wc_makecommerce_domain'),
);
$this->form_fields['cc_cart_reference_string'] = array(
'title' => __('Order reference on credit card payment', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => 'Order %s',
'desc_tip' => __('This will appear on buyer\'s credit card transaction where "%s" is the order number', 'wc_makecommerce_domain'),
);
$this->form_fields['adv_title'] = array(
'title' => ' '.__('Advanced Settings', 'wc_makecommerce_domain'),
'type' => 'title',
);
$this->form_fields['reload_links'] = array(
'type' => 'mc_banklinks_reload',
'title' => __('Update payment methods', 'wc_makecommerce_domain'),
'description' => __('Update', 'wc_makecommerce_domain'),
'desc_tip' => __('This will update shop configuration from MakeCommerce servers.', 'wc_makecommerce_domain'),
);
}
public function generate_mc_hidden_html( $key, $data ) {
$field_key = $this->get_field_key($key);
ob_start();
?>
get_field_key( $key );
$defaults = array(
'title' => '',
'disabled' => false,
'class' => '',
'css' => '',
'placeholder' => '',
'type' => 'text',
'desc_tip' => false,
'description' => '',
'custom_attributes' => array()
);
$data = wp_parse_args( $data, $defaults );
ob_start();
?>
get_tooltip_html( $data ); ?>
get_custom_attribute_html( $data ); ?> />
prefix . $mkDbTable;
$wpdb->query('TRUNCATE TABLE '.$tableName);
$request_params = array(
'environment' => json_encode(array(
'platform' => 'wordpress '.$wp_version,
'module' => $this->id.' '.$this->version,
)),
);
if (!$this->_api) {
return false;
}
try {
$methods = $this->_api->getShopConfig($request_params)->payment_methods;
} catch (Exception $e) {
error_log(print_r($e, 1));
return false;
}
if(isset($methods->banklinks)) {
foreach($methods->banklinks as $method) {
$wpdb->insert($tableName, array('type' => 'banklink', 'country' => $method->country, 'name' => $method->name, 'url' => $method->url));
}
$updated = true;
}
if(isset($methods->cards)) {
foreach($methods->cards as $method) {
$wpdb->insert($tableName, array('type' => 'card', 'name' => $method->name));
}
$updated = true;
}
if ($updated) {
update_option( 'mc_banklinks_api_type', get_option('mk_api_type', false) );
}
if ($force) {
$this->initBankLinks();
return $updated;
}
if($updated) {
wp_send_json(array('success' => 1, 'data' => __('Update successfully completed!', 'wc_makecommerce_domain')));
exit;
}
wp_send_json(array('success' => 0, 'data' => __('There was an error with your update. Please try again.', 'wc_makecommerce_domain')));
exit;
}
die();
}
protected function _getWooCommerce() {
global $woocommerce;
return $woocommerce;
}
function is_valid_for_use() {
return true;
}
public function is_available() {
if ($this->settings['active'] == "yes") {
return true;
}
}
function payment_fields() {
if($this->settings['ui_mode'] == 'inline') {
?>
_banklinks as $method): ?>
country).' - '.ucfirst($method->name); ?>
_cards as $method): ?>
name); ?>
settings['ui_open_by_default'] == 'yes') {
?>
_getWooCommerce()->customer) {
$customerCountry = strtolower($this->_getWooCommerce()->customer->get_shipping_country());
if(array_key_exists($customerCountry, $this->_banklinks_grouped)) {
return $customerCountry;
}
}
$localeToCountry = array(
'et' => 'ee',
'lv' => 'lv',
'lt' => 'lt',
'fi' => 'fi',
);
if(array_key_exists(get_locale(), $localeToCountry)) {
return $localeToCountry[get_locale()];
}
return key($this->_banklinks_grouped);
}
private function initBanklinks() {
global $wpdb;
global $mkDbTable;
$this->_banklinks = array();
$tableName = $wpdb->prefix . $mkDbTable;
$methods = $wpdb->get_results('SELECT * FROM '.$tableName);
if(count($methods)) {
if(is_admin() && $this->_init == true && get_option( 'mc_banklinks_api_type' ) != get_option('mk_api_type', false)) {
//add_action( 'admin_notices', array(&$this, 'makecommerce_banklinks_list_type_notice') );
}
$banklinks = array();
$banklinks_grouped = array();
$cards = array();
foreach($methods as $method) {
if($method->type == 'banklink') {
$banklinks[] = $banklinks_grouped[$method->country][] = $method;
} elseif($method->type == 'card') {
$cards[] = $method;
}
}
usort($banklinks, array($this, 'orderBanklinks'));
foreach($banklinks_grouped as &$country) {
usort($country, array($this, 'orderBanklinks'));
}
$this->_banklinks = $banklinks;
$this->_banklinks_grouped = $banklinks_grouped;
$this->_cards = $cards;
remove_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
} elseif(is_admin() && $this->_init == true) {
add_action('admin_notices', array(&$this, 'makecommerce_banklinks_list_empty'), 30);
}
}
private function orderBanklinks($a, $b) {
$order = array_map('trim', explode(",", $this->settings['ui_chorder']));
$posA = array_search($a->name, $order);
$posB = array_search($b->name, $order);
if($posA === $posB) return $a->id > $b->id ? 1 : -1;
if($posA === FALSE) return 1;
if($posB === FALSE) return -1;
return $posA > $posB ? 1 : -1;
}
protected function getImageUrl($methodName) {
$imageUrlPath = 'https://static.maksekeskus.ee/img/channel/lnd/';
return $imageUrlPath.$methodName.'.png';
}
public function validate_fields() {
$selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
if (!$selected) {
wc_add_notice(__('Please select suitable payment option!', 'wc_makecommerce_domain'), 'error');
} else {
$this->_getWooCommerce()->session->makecommerce_preselected_method = $selected;
}
return true;
}
function process_payment($orderId) {
$order = new WC_Order($orderId);
$selected = isset($_POST['PRESELECTED_METHOD_' . $this->id]) ? sanitize_text_field($_POST['PRESELECTED_METHOD_' . $this->id]) : false;
if(!empty($selected)) {
update_post_meta($order->id, '_makecommerce_preselected_method', $selected);
if(substr($selected, 0, 5) == 'card_') {
$request_body = array(
'transaction' => array(
'amount' => round($order->order_total, 2),
'currency' => $order->get_order_currency(),
'reference' => $order->id,
'transaction_url' => array(
'return_url' => array(
'url' => $this->return_url_cc,
'method' => 'POST',
),
'cancel_url' => array(
'url' => $this->return_url_cc,
'method' => 'POST',
),
'notification_url' => array(
'url' => $this->return_url_cc,
'method' => 'POST',
),
),
),
'customer' => array(
'ip' => $_SERVER['REMOTE_ADDR'],
'country' => strtolower($order->billing_country),
'locale' => strtolower(substr(get_locale(), 0, 2)),
),
);
$transaction = $this->_api->createTransaction($request_body);
if(isset($transaction->id)) {
update_post_meta($order->id, '_makecommerce_cc_transaction_id', $transaction->id);
return array(
'result' => 'success',
'redirect' => $this->_getOrderConfirmationUrl($order),
);
}
wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
return array(
'result' => 'failure',
);
} else {
$redirectUrl = $this->_getRedirectUrl($selected);
if($redirectUrl) {
$request_body = array(
'transaction' => array(
'amount' => round($order->order_total, 2),
'currency' => $order->get_order_currency(),
'reference' => $order->id,
'transaction_url' => array(
'return_url' => array(
'url' => $this->return_url,
'method' => 'POST',
),
'cancel_url' => array(
'url' => $this->return_url,
'method' => 'POST',
),
'notification_url' => array(
'url' => $this->return_url,
'method' => 'POST',
),
),
),
'customer' => array(
'ip' => $_SERVER['REMOTE_ADDR'],
'country' => strtolower($order->billing_country),
'locale' => strtolower(substr(get_locale(), 0, 2)),
)
);
$transaction = $this->_api->createTransaction($request_body);
if(isset($transaction->id)) {
return array(
'result' => 'success',
'redirect' => $redirectUrl.$transaction->id,
);
}
}
wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
return array(
'result' => 'failure',
);
}
}
wc_add_notice(__('An error occured when trying to process payment!', 'wc_makecommerce_domain'), 'error');
return array(
'result' => 'failure',
);
}
protected function _getRedirectUrl($selected) {
foreach($this->_banklinks as $method) {
if($selected == $method->country.'_'.$method->name)
return $method->url;
}
return false;
}
protected function _getOrderConfirmationUrl($order) {
//$url = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
$url = site_url('?makecommerce_card_pay=1&order_id='.$order->id.'&lang='.(defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : strtolower(substr(get_locale(), 0, 2))));
return $url;
}
function receipt_page($orderId) {
echo '' . __('Thank you for the order, please click on the button to start the payment.', 'wc_makecommerce_domain') . '
';
$order = new WC_Order($orderId);
if(substr(get_post_meta($orderId, '_makecommerce_preselected_method', true), 0, 5) == 'card_' && $order->get_status() == 'pending') {
echo $this->generateCardForm($order);
}
}
function generateCardForm($order) {
$scriptSrc = htmlspecialchars($this->_gateway_url_static.'checkout.js');
$transactionId = get_post_meta($order->id, '_makecommerce_cc_transaction_id', true);
$idReference = $order->id;
$jsParams = array(
'key' => $this->_api->getPublishableKey(),
'transaction' => $transactionId,
'selector' => '#submit_banklinkmakecommerce_payment_form',
'amount' => round($order->order_total, 2),
'locale' => !empty($_GET['lang']) ? $_GET['lang'] : (defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : strtolower(substr(get_locale(), 0, 2))),
'open-on-load' => 'true',
'client-name' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) ($order->billing_first_name . ' ' . $order->billing_last_name) : ''),
'email' => ($this->settings['cc_pass_cust_data'] == 'yes' ? (string) $order->billing_email : ''),
'name' => $this->settings['cc_shop_name'],
'description' => (string)sprintf($this->settings['cc_cart_reference_string'], (string) $idReference),
'completed' => 'makecommerce_cc_complete',
'currency' => 'EUR',
);
?>
$value) {
$result[] = 'data-' . htmlspecialchars($key) . '=' . '"' . htmlspecialchars($value) . '"';
}
return implode(' ', $result);
}
function makecommerce_return_trigger($vars) {
$vars[] = 'makecommerce_return';
$vars[] = 'makecommerce_card_pay';
return $vars;
}
function makecommerce_return_trigger_check() {
if(intval(get_query_var('makecommerce_return')) == 1) {
$returnUrl = home_url();
$request = stripslashes_deep($_POST);
if($this->_api->verifySignature($request)) {
$data = $this->_api->extractRequestData($request);
$order = new WC_Order($data['reference']);
switch($data['status']) {
case self::MC_CANCELLED:
$order->update_status( 'cancelled' );
wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
break;
case self::MC_COMPLETED:
if($this->validate_completed_payment($order, $data)) {
$orderNote = array();
$orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data['transaction'];
$orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
$order->add_order_note(implode("\r\n", $orderNote));
$order->payment_complete($data['transaction']);
$order->update_status( 'processing' );
try {
@ob_start();
$this->receipt_page($order->id);
@ob_end_clean();
$returnUrl = $this->get_return_url($order);
} catch (Exception $ex) {
@ob_end_clean();
}
} else {
$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
}
break;
}
//exit;
}
wp_redirect($returnUrl);
exit;
} elseif(intval(get_query_var('makecommerce_return')) == 2) {
$returnUrl = home_url();
if(isset($_POST['paymentToken']) && isset($_POST['transaction'])) {
$token = $_POST['paymentToken'];
$transaction = $_POST['transaction'];
}
if(isset($_POST['json'])) {
$data = json_decode(stripslashes($_POST['json']), true);
$token = $data['token']['id'];
$transaction = $data['transaction']['id'];
}
if(!empty($token) && !empty($transaction)) {
global $wpdb;
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.'"'))) {
$request_body = array(
'token' => $token,
);
$data = $this->_api->createPayment(get_post_meta($order->id, '_makecommerce_cc_transaction_id', true), $request_body);
switch($data->status) {
case self::MC_CANCELLED:
$order->update_status( 'cancelled' );
wc_add_notice(__('Payment transaction cancelled', 'wc_makecommerce_domain'), 'error');
$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
break;
case self::MC_DEPOSITED:
if($this->validate_completed_payment($order, $data)) {
$orderNote = array();
$orderNote[] = __('Transaction ID', 'wc_makecommerce_domain') . ': ' . $data->transaction->id;
$orderNote[] = __('Payment option', 'wc_makecommerce_domain') . ': ' . get_post_meta($order->id, '_makecommerce_preselected_method', true);
$order->add_order_note(implode("\r\n", $orderNote));
$order->payment_complete($data->transaction->id);
$order->update_status( 'processing' );
try {
@ob_start();
$this->receipt_page($order->id);
@ob_end_clean();
$returnUrl = $this->get_return_url($order);
} catch (Exception $ex) {
@ob_end_clean();
}
} else {
$returnUrl = $this->_getWooCommerce()->cart->get_cart_url();
}
break;
}
}
}
wp_redirect($returnUrl);
exit;
}
if(intval(get_query_var('makecommerce_card_pay')) == 1) {
if(isset($_GET['order_id'])) {
if($order = New WC_Order($_GET['order_id'])) {
New woocommerce_makecommerce(false);
get_header();
?>
receipt_page($order->id); ?>
add_order_note(__('Payment error, missing transaction id', 'wc_makecommerce_domain'));
wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain'), 'error');
return false;
}
if($data['amount'] != round($order->order_total, 2)) {
$order->add_order_note(sprintf(__('Payment error, incorrect amount captured: %s', 'wc_makecommerce_domain'), $data['amount'].' '.$data['currency']));
wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect amount captured', 'wc_makecommerce_domain'), 'error');
return false;
}
if($data['currency'] != $order->get_order_currency()) {
$order->add_order_note(sprintf(__('Payment error, incorrect currency captured: %s', 'wc_makecommerce_domain'), $data['currency']));
wc_add_notice(__('Error verifying transaction', 'wc_makecommerce_domain').', '.__('Incorrect currency captured', 'wc_makecommerce_domain'), 'error');
return false;
}
return true;
}
function admin_order_page($order) {
//
}
public function process_refund($order_id, $amount = null, $comment = '') {
if ($this->_api) {
try {
$order = new WC_Order($order_id);
$transactionId = $order->get_transaction_id();
if($response = $this->_api->createRefund($transactionId, array('amount' => $amount, 'comment' => ($comment ? : 'refund')))) {
if($status = (string)$response->transaction->status) {
switch($status) {
case self::MC_REFUNDED:
$order->add_order_note(sprintf(__('Refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
return true;
break;
case self::MC_PART_REFUNDED:
$order->add_order_note(sprintf(__('Partial refund completed for amount %s', 'wc_makecommerce_domain'), $amount));
return true;
break;
}
}
}
return false;
} catch (Exception $e) {
return new WP_Error('makecommerce_refund_error', $e->getMessage());
}
return false;
}
return false;
}
protected function getCountryName($slug) {
switch($slug) {
case 'ee': return __('Estonia', 'wc_makecommerce_domain'); break;
case 'lv': return __('Latvia', 'wc_makecommerce_domain'); break;
case 'lt': return __('Lithuania', 'wc_makecommerce_domain'); break;
case 'fi': return __('Finland', 'wc_makecommerce_domain'); break;
}
return $slug;
}
}
New woocommerce_makecommerce(true);
}
function woocommerce_payment_makecommerce_add($methods) {
$methods[] = 'woocommerce_makecommerce';
return $methods;
}
add_action('plugins_loaded', 'woocommerce_payment_makecommerce_init');
add_action('woocommerce_payment_gateways', 'woocommerce_payment_makecommerce_add');
function clear_wc_shipping_rates_cache(){
$packages = WC()->cart->get_shipping_packages();
foreach ($packages as $key => $value) {
$shipping_session = "shipping_for_package_$key";
unset(WC()->session->$shipping_session);
}
}
add_filter('woocommerce_checkout_update_order_review', 'clear_wc_shipping_rates_cache');
// Parcel machine specific stuff
function parcelmachine_add_method() {
// Delete all the wc_ship transient scum, you aren’t wanted around here, move along.
// Same as being in shipping debug mode
global $wpdb;
$transients = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_wc_ship%'");
if (count($transients)) {
foreach ($transients as $tr) {
$hash = substr($tr, 11);
delete_transient($hash);
}
}
$transient_value = get_transient('shipping-transient-version');
WC_Cache_Helper::delete_version_transients( $transient_value );
if (WC()->session) {
WC()->session->set('shipping_for_package', '');
}
if ( ! class_exists( 'WC_ParcelMachine_Shipping_Method' ) ) {
class WC_ParcelMachine_Shipping_Method extends WC_Shipping_Method {
function __construct($instance_id = 0) {
if (!$this->ext) {
throw new Exception('Do not call this class directly!');
}
$this->id = 'parcelmachine_' . mb_strtolower($this->ext);
$this->instance_id = $instance_id;
$this->method_title = $this->name_ext . __(' Parcel Machine by MC', 'wc_makecommerce_domain');
$this->init();
}
function init() {
$this->init_form_fields();
$this->init_settings();
$this->enable = $this->settings['active'];
$this->title = $this->settings['method_name'];
if (defined('ICL_LANGUAGE_CODE') && !empty($this->settings['method_name_'.ICL_LANGUAGE_CODE])) {
$this->title = $this->settings['method_name_'.ICL_LANGUAGE_CODE];
}
$this->availability = 'specific';
$this->countries = $this->settings['countries'];
$this->prioritization = $this->settings['prioritization'];
$this->free_shipping_min_amount = $this->settings['free_shipping_min_amount'];
$this->maximum_weight = (double)$this->settings['maximum_weight'];
$this->short_office_names = $this->settings['short_office_names'];
$this->order_country = 'unknown';
add_action('woocommerce_update_options_shipping_' . $this->id, array(&$this, 'process_admin_options'));
add_filter('woocommerce_review_order_after_shipping' , array(&$this, 'add_parcelmachine_checkout_fields'));
add_action('woocommerce_checkout_process', array(&$this, 'check_parcelmachine_checkout_fields'));
add_action('woocommerce_checkout_update_order_meta', array(&$this, 'add_parcelmachine_order_meta'));
add_filter('woocommerce_order_shipping_to_display_shipped_via', array(&$his, 'add_admin_parcelmachine_via_field'));
}
function calculate_shipping($package = array()) {
$price = $this->settings['price_'.strtolower($package['destination']['country'])];
if ($this->free_shipping_min_amount && $package['contents_cost'] >= $this->free_shipping_min_amount) {
$price = 0;
}
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => $price,
'calc_tax' => 'per_order',
);
$this->add_rate( $rate );
}
function calculate_weight($package) {
$weight = 0;
foreach ($package['contents'] as $line) {
$weight += $line['data']->get_weight();
}
return $weight;
}
function fits_parcel_machine($package) {
foreach ($package['contents'] as $line) {
if (get_post_meta($line['product_id'], '_no_parcel_machine', true) === 'yes') {
return false;
}
}
return true;
}
function is_available($package) {
if (!$this->fits_parcel_machine($package)) {
return false;
}
$package_weight = $this->calculate_weight($package);
if ($package_weight >= $this->maximum_weight) {
return false;
}
$is_available = $this->enable === 'yes';
if (!$is_available) {
return false;
}
if (is_array($this->countries) && !in_array($package['destination']['country'], $this->countries)) {
$is_available = false;
}
$this->order_country = $package['destination']['country'];
return apply_filters('woocommerce_shipping_' . $this->id . '_is_available', $is_available, $package);
}
function mk_get_machines() {
$machines = mk_get_machines($this->ext, $this->order_country);
if ($this->prioritization === 'yes') {
usort($machines, function($a, $b) {
$sortorder = array(
'tallinn', 'tartu', 'narva', 'pärnu', 'viljandi', 'kohtla-järve', 'rakvere', 'maardu', 'sillamäe', 'kuressaare',
'helsinki', 'espoo', 'tampere', 'vantaa', 'oulu', 'turku', 'jüväskülä', 'lahti', 'kuopio', 'kouvola',
'riga', 'daugavpils', 'liepaja', 'jelgava', 'jurmala', 'ventspils', 'rezekne', 'valmiera', 'jekabpils',
'vilnius', 'kaunas', 'klaipeda', 'siauliai', 'panevezys', 'alytus', 'mariampole', 'mazeikiai', 'jonava', 'utena'
);
$acity = mb_strtolower($a['city']);
$bcity = mb_strtolower($b['city']);
if (!$acity) { $acity = 'xxxxxxx'; }
if (!$bcity) { $bcity = 'xxxxxxx'; }
$aidx = array_search($acity, $sortorder);
$bidx = array_search($bcity, $sortorder);
if ($aidx !== false) {
$acity = str_pad($aidx, 4, "0", STR_PAD_LEFT) . '-' . $acity;
}
if ($bidx !== false) {
$bcity = str_pad($bidx, 4, "0", STR_PAD_LEFT) . '-' . $bcity;
}
$acity .= '-' . mb_strtolower($a['name']);
$bcity .= '-' . mb_strtolower($b['name']);
return $acity < $bcity ? -1 : 1;
});
}
return $machines;
}
function add_parcelmachine_checkout_fields($checkout) {
$this->order_country = WC()->customer->get_shipping_country();
echo '' . $this->title . ' ';
echo '';
$options = array();
$machines = $this->mk_get_machines();
echo '';
echo '';
$pcity = false;
foreach ($machines as $machine) {
$city = strtolower($machine['city']);
if ($city !== $pcity) {
if ($pcity) echo '';
echo '';
}
$mname = $machine['name'];
if ($this->short_office_names !== 'yes') $mname .= ' - ' . $machine['city'] . ', ' . $machine['address'];
echo ''.$mname.' ';
$pcity = $city;
}
if ($pcity) echo ' ';
echo ' ';
echo '
';
echo ' ';
}
function check_parcelmachine_checkout_fields() {
$shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
if ($shipping_method === $this->id && empty($_POST[$shipping_method])) {
wc_add_notice(__('Parcel machine is a required field.'), 'error');
}
}
function add_parcelmachine_order_meta($order_id) {
$shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
if (!empty($shipping_method[0])) { $shipping_method = $shipping_method[0]; }
if ($shipping_method === $this->id && !empty($_POST[$this->id])) {
update_post_meta($order_id, '_parcel_machine', sanitize_text_field($_POST[$this->id]));
}
}
function add_admin_parcelmachine_via_field($order) {
error_log('Via');
error_log(print_r($order, 1));
}
}
class WC_ParcelMachine_Shipping_Method_Omniva extends WC_ParcelMachine_Shipping_Method {
function __construct($instance_id = 0) {
$this->ext = 'Omniva';
$this->name_ext = 'Omniva';
parent::__construct();
}
function init_form_fields() {
$this->form_fields = array();
$this->form_fields['logo'] = array('type' => 'title', 'title' => __get_logo_html());
$this->form_fields['generic'] = array('type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'));
$this->form_fields['active'] = array(
'title' => __('Enable', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('enabled', 'wc_makecommerce_domain'),
'default' => 'no',
'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'),
);
$this->form_fields['price_ee'] = array(
'title' => __('Price EE', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '2.99'
);
$this->form_fields['price_lv'] = array(
'title' => __('Price LV', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '7.99'
);
$this->form_fields['price_lt'] = array(
'title' => __('Price LT', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '8.99'
);
$this->form_fields['free_shipping_min_amount'] = array(
'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
'type' => 'number',
'default' => '0',
'description' => '(0 means no free shipping)'
);
$this->form_fields['maximum_weight'] = array(
'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '15'
);
$this->form_fields['countries'] = array(
'title' => __('Specific Countries', 'wc_makecommerce_domain'),
'type' => 'multiselect',
'class' => 'wp-enhanced-select',
'css' => 'width: 450px;',
'default' => array('EE','LV','LT'),
'options' => array('EE' => __('Estonia'), 'LV' => __('Latvia'), 'LT' => __('Lithuania')),
);
$this->form_fields['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'));
$languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
if (empty($languages)) {
$this->form_fields['method_name'] = array(
'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
);
} else {
foreach ($languages as $language_code => $language) {
$language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
$this->form_fields['method_name_'.$language_code] = array(
'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', $language_code),
'type' => 'text',
'default' => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
);
}
}
$this->form_fields['prioritization'] = array(
'title' => __('Prioritize', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
'default' => 'yes'
);
$this->form_fields['short_office_names'] = array(
'title' => __('Short names', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
'default' => 'no'
);
$this->form_fields['api_access'] = array( 'type' => 'title', 'title' => ' '.__('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. Please set your Omniva web servises account credentials below here. (see more on MakeCommerce plugin page . Don\'t forget to enable also MC API keys !)', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api§ion=mk_api')));
$this->form_fields['service_user'] = array(
'title' => __('Omniva web services username', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => ''
);
$this->form_fields['service_password'] = array(
'title' => __('Omniva web services password', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => ''
);
$this->form_fields['return_address'] = array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for Omniva shipments', 'wc_makecommerce_domain'));
$this->form_fields['shop_name'] = array(
'type' => 'text',
'title' => __('Shop name', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
);
$this->form_fields['shop_phone'] = array(
'type' => 'text',
'title' => __('Shop phone', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
);
$this->form_fields['shop_email'] = array(
'type' => 'text',
'title' => __('Shop email', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
);
$this->form_fields['shop_postal_code'] = array(
'type' => 'text',
'title' => __('Shop postal code', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
'description' => __('Put here zip-code of the Parcel Terminal you use for returns, see: List of Omniva Terminals ', 'wc_makecommerce_domain')
);
}
}
class WC_ParcelMachine_Shipping_Method_Smartpost extends WC_ParcelMachine_Shipping_Method {
function __construct() {
$this->ext = 'SmartPost';
$this->name_ext = 'SmartPOST';
parent::__construct();
}
function init_form_fields() {
global $woocommerce;
$this->form_fields = array();
$this->form_fields['logo'] = array('type' => 'title', 'title' => __get_logo_html());
$this->form_fields['generic'] = array( 'type' => 'title', 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'));
$this->form_fields['active'] = array(
'title' => __('Enable', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('enabled', 'wc_makecommerce_domain'),
'default' => 'no',
'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'),
);
$this->form_fields['price_ee'] = array(
'title' => __('Price EE', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '2.99'
);
$this->form_fields['price_fi'] = array(
'title' => __('Price FI', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '10.99'
);
$this->form_fields['free_shipping_min_amount'] = array(
'title' => __('Minimum amount for free shipping', 'wc_makecommerce_domain'),
'type' => 'number',
'default' => '0',
'description' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
);
$this->form_fields['maximum_weight'] = array(
'title' => __('Maximum weight allowed for shipping', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => '15'
);
$this->form_fields['countries'] = array(
'title' => __('Specific Countries', 'wc_makecommerce_domain'),
'type' => 'multiselect',
'class' => 'wp-enhanced-select',
'css' => 'width: 450px;',
'default' => array('EE','FI'),
'options' => array('EE' => __('Estonia'), 'FI' => __('Finland')),
);
$this->form_fields['look_and_feel'] = array( 'type' => 'title', 'title' => __('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on checkout page', 'wc_makecommerce_domain'));
$languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
if (empty($languages)) {
$this->form_fields['method_name'] = array(
'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
);
} else {
foreach ($languages as $language_code => $language) {
$language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
$this->form_fields['method_name_'.$language_code] = array(
'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', $language_code),
'type' => 'text',
'default' => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
);
}
}
$this->form_fields['prioritization'] = array(
'title' => __('Prioritize', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
'default' => 'yes'
);
$this->form_fields['short_office_names'] = array(
'title' => __('Short names', 'wc_makecommerce_domain'),
'type' => 'checkbox',
'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
'default' => 'no'
);
$this->form_fields['api_access'] = array( 'type' => 'title', 'title' => ' '.__('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. Please set your smartpost.ee account credentials below here. (See more on MakeCommerce plugin page . Don\'t forget to enable also MC API keys !)', 'wc_makecommerce_domain'), admin_url('admin.php?page=wc-settings&tab=api§ion=mk_api')));
$this->form_fields['service_user'] = array(
'title' => __('eteenindus.smartpost.ee username', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => ''
);
$this->form_fields['service_password'] = array(
'title' => __('eteenindus.smartpost.ee password', 'wc_makecommerce_domain'),
'type' => 'text',
'default' => ''
);
$this->form_fields['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'));
$this->form_fields['shop_name'] = array(
'type' => 'text',
'title' => __('Shop name', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
);
$this->form_fields['shop_phone'] = array(
'type' => 'text',
'title' => __('Shop phone', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
);
$this->form_fields['shop_email'] = array(
'type' => 'text',
'title' => __('Shop email', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
);
}
}
}
}
add_action('woocommerce_shipping_init', 'parcelmachine_add_method');
function add_parcelmachine_shipping_method($methods) {
$methods[] = 'WC_ParcelMachine_Shipping_Method_Omniva';
$methods[] = 'WC_ParcelMachine_Shipping_Method_Smartpost';
return $methods;
}
add_filter('woocommerce_shipping_methods', 'add_parcelmachine_shipping_method');
function mk_parcelmachine_add_assets() {
wp_enqueue_style('parcelmachine-css', plugin_dir_url(__FILE__).'/css/parcelmachine.css');
wp_enqueue_script('parcelmachine-js', plugin_dir_url(__FILE__).'/scripts/parcelmachine.js', array('jquery'));
}
add_action('wp_enqueue_scripts', 'mk_parcelmachine_add_assets');
function mk_admin_plugin_settings_link($links) {
$settings_link = 'API '.__('Settings').' ';
array_unshift($links, $settings_link);
return $links;
}
$plugin = plugin_basename(__FILE__);
add_filter("plugin_action_links_$plugin", 'mk_admin_plugin_settings_link' );
function mk_admin_add_settings($sections) {
$sections['mk_api'] = __('MakeCommerce API access', 'wc_makecommerce_domain');
return $sections;
}
function mk_admin_all_settings($settings) {
global $current_section;
if ($current_section !== 'mk_api') {
return $settings;
}
return array(
array('type' => 'title', 'desc' => __get_logo_html()),
array(
'type' => 'title',
'title' => __('MakeCommerce API access credentials', 'wc_makecommerce_domain'),
'desc' => sprintf(__('To use MakeCommerce/Maksekeskus services you need to enter API credentials below here '.
'To further configure the Payment methods please go to MakeCommerce Checkout Options '.
'To use also Ominva or Itella SmartPOST integration please configure these API accesses: Omniva API access | '.
'SmartPOST API access ','wc_makecommerce_domain'),
'admin.php?page=wc-settings&tab=checkout§ion=makecommerce',
'admin.php?page=wc-settings&tab=-shipping§ion=parcelmachine_omniva',
'admin.php?page=wc-settings&tab=shipping§ion=parcelmachine_smartpost'
),
'id' => 'mk_api_settings'
),
array(
'type' => 'select',
'title' => __('Current environment', 'wc_makecommerce_domain'),
'desc' => __('See more about MakeCommerce Test environment ', 'wc_makecommerce_domain'),
'default' => 'live',
'options' => array(
'live' => __('Live', 'wc_makecommerce_domain'),
'test' => __('Test', 'wc_makecommerce_domain'),
),
'id' => 'mk_api_type'
),
array(
'id' => 'mk_shop_id',
'type' => 'text',
'title' => __('Shop ID (live)', 'wc_makecommerce_domain'),
'desc' => __('Get it from Merchant Portal ','wc_makecommerce_domain'),
'class' => 'input-text regular-input',
),
array(
'id' => 'mk_private_key',
'type' => 'text',
'title' => __('Secret key (live)', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
),
array(
'id' => 'mk_public_key',
'type' => 'text',
'title' => __('Publishable key (live)', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
),
array(
'id' => 'mk_test_shop_id',
'type' => 'text',
'title' => __('Shop ID (test)', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
'desc' => __('Get it from Merchant Portal Test ','wc_makecommerce_domain'),
),
array(
'id' => 'mk_test_private_key',
'type' => 'text',
'title' => __('Secret key (test)', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
),
array(
'id' => 'mk_test_public_key',
'type' => 'text',
'title' => __('Publishable key (test)', 'wc_makecommerce_domain'),
'class' => 'input-text regular-input',
),
array('type' => 'sectionend', 'id' => 'mk_api_settings')
);
}
function mk_admin_save_settings() {
// reload banklinks
global $current_section;
if ($current_section !== 'mk_api') {
return;
}
$wcmc = New woocommerce_makecommerce(true);
$wcmc->mc_banklinks_reload(true);
}
function __get_logo_html() {
return ''.
'
'.
'
'.
'
'.
'
'.
'
';
}
add_action('woocommerce_get_sections_api', 'mk_admin_add_settings');
add_filter('woocommerce_get_settings_api', 'mk_admin_all_settings', 10, 2);
add_action('woocommerce_settings_saved', 'mk_admin_save_settings', 30, 0);
function mk_admin_restrict_manage_posts() {
global $typenow;
if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
$selected_method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
$methods = WC()->shipping->load_shipping_methods();
echo '';
echo ''.__('-- filter by shipping method', 'wc_makecommerce_domain') . ' ';
foreach ($methods as $method) {
echo 'id ? ' selected="selected"' : '').'>'.$method->title.' ';
}
echo ' ';
}
}
function mk_admin_shipping_filter($where, &$wp_query) {
global $pagenow, $wpdb;
$method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
if (is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
$where .= $GLOBALS['wpdb']->prepare( ' AND ID
IN (
SELECT items.order_id
FROM '.$wpdb->prefix.'woocommerce_order_itemmeta meta, '.$wpdb->prefix.'woocommerce_order_items items
WHERE meta.order_item_id = items.order_item_id
AND meta.meta_key = "method_id"
AND meta.meta_value = %s
) ', $method );
}
return $where;
}
add_filter('restrict_manage_posts', 'mk_admin_restrict_manage_posts');
add_filter('posts_where', 'mk_admin_shipping_filter', 10, 2);
function mk_admin_bulk_actions() {
global $post_type;
if ('shop_order' === $post_type) {
?>
array(), 'orders' => array());
$post_ids = array_map('absint', (array)$_REQUEST['post']);
mk_get_shipment_ids($post_ids);
}
function mk_admin_bulk_action_print() {
$wp_list_table = _get_list_table('WP_Posts_List_Table');
$shipping_request = array('credentials' => array(), 'orders' => array());
$post_ids = array_map('absint', (array)$_REQUEST['post']);
mk_get_labels($post_ids);
}
add_action('admin_footer', 'mk_admin_bulk_actions', 11);
add_action('admin_action_parcel_machine_labels', 'mk_admin_bulk_action_labels');
add_action('admin_action_parcel_machine_print_labels', 'mk_admin_bulk_action_print');
function mk_admin_parcelmachine_order_meta($order) {
$machine_id = get_post_meta($order->id, '_parcel_machine', true);
if (empty($machine_id)) return;
list($provider, $machine) = explode('||', $machine_id);
if (empty($machine)) return;
$machine = mk_get_machine($provider, (int)$machine);
if (!$machine) return;
echo ''.__('Parcel machine').': ' . $machine['name'] . '' . $machine['address'] . '
';
$shipment_id = get_post_meta($order->id, '_parcel_machine_shipment_id', true);
$shipment_id_error = get_post_meta($order->id, '_parcel_machine_error', true);
if ($shipment_id) {
echo ''.__('Parcel machine shipment ID').': ' . $shipment_id . '
';
}
if ($shipment_id_error) {
echo ''.__('Parcel machine shipment generation error').': ' . $shipment_id_error . '
';
}
}
function mk_admin_render_shop_order_columns( $column ) {
global $post, $woocommerce, $the_order;
if (empty($the_order) || $the_order->id != $post->ID) {
$the_order = wc_get_order($post->ID);
}
if ($column === 'shipping_address') {
$machine = get_post_meta($the_order->id, '_parcel_machine', true);
$shipment_id = get_post_meta($the_order->id, '_parcel_machine_shipment_id', true);
$shipment_id_error = get_post_meta($the_order->id, '_parcel_machine_error', true);
if ($machine) {
if ($shipment_id) echo __('Package shipment_id:', 'wc_makecommerce_domain') . ' ' . $shipment_id;
else if ($shipment_id_error) echo ''.__('Package shipment generation error:', 'wc_makecommerce_domain') . ' ' .$shipment_id_error;
else echo __('Shipment ID not generated for delivery', 'wc_makecommerce_domain');
}
}
}
function mk_add_email_customer_details_fields($fields, $sent_to_admin, $order) {
$machine_id = get_post_meta($order->id, '_parcel_machine', true);
if (empty($machine_id)) return $fields;
list($provider, $machine) = explode('||', $machine_id);
if (empty($machine)) return $fields;
$machine = mk_get_machine($provider, (int)$machine);
if (!$machine) return $fields;
$fields[] = array('label' => __('Parcel machine'), 'value' => $machine['name'].' - '.$machine['address']);
return $fields;
}
function mk_add_order_customer_details_fields($order) {
$machine_id = get_post_meta($order->id, '_parcel_machine', true);
if (empty($machine_id)) return;
list($provider, $machine) = explode('||', $machine_id);
if (empty($machine)) return;
$machine = mk_get_machine($provider, (int)$machine);
if (!$machine) return;
echo '';
echo ''.__('Parcel machine').' ';
echo ''.$machine['name'].' '.$machine['address'].' ';
echo ' ';
}
function mk_admin_product_option_fields($fields) {
echo '';
woocommerce_wp_checkbox(
array(
'id' => '_no_parcel_machine',
'wrapper_class' => 'show_if_simple',
'label' => __('Does not fit parcel machine', 'wc_makecommerce_domain'),
'description' => __('When this is checked, parcel machine shipping option is not available for a cart with this product', 'wc_makecommerce_domain')
)
);
echo '
';
}
function mk_admin_product_fields_save($post_id) {
$no_parcel_machine = isset($_POST['_no_parcel_machine']) ? 'yes' : 'no';
update_post_meta($post_id, '_no_parcel_machine', $no_parcel_machine);
}
add_action('woocommerce_product_options_shipping', 'mk_admin_product_option_fields');
add_action('woocommerce_process_product_meta', 'mk_admin_product_fields_save');
add_action('woocommerce_admin_order_data_after_shipping_address', 'mk_admin_parcelmachine_order_meta', 10, 1);
add_action('manage_shop_order_posts_custom_column', 'mk_admin_render_shop_order_columns', 3);
add_filter('woocommerce_email_customer_details_fields', 'mk_add_email_customer_details_fields', 10, 3 );
add_action('woocommerce_order_details_after_customer_details', 'mk_add_order_customer_details_fields');
add_action('woocommerce_order_status_processing', 'mk_get_shipment_ids');
function mk_get_shipment_ids($post_ids) {
if (!is_array($post_ids)) {
$post_ids = array($post_ids);
}
parcelmachine_add_method();
$shipping_request = array('credentials' => array(), 'orders' => array());
foreach ($post_ids as $post_id) {
$parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
if (!$parcel_machine) { continue; }
list($provider, $machine_id) = explode('||', $parcel_machine);
if (!$provider || !$machine_id) { continue; }
$provider_uc = mb_strtoupper($provider);
switch ($provider_uc) {
case "OMNIVA":
$transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
break;
case "SMARTPOST":
$transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
break;
default:
break 2;
}
if (empty($shipping_request['credentials'][$provider_uc])) {
$api_user = $transport_class->settings['service_user'];
$api_password = $transport_class->settings['service_password'];
if (!$api_user || !$api_password) {
add_action('admin_notices', 'mk_admin_error');
continue;
}
$shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
}
$order = wc_get_order($post_id);
$sender = array(
'name' => $transport_class->settings['shop_name'],
'phone' => $transport_class->settings['shop_phone'],
'email' => $transport_class->settings['shop_email'],
'postalCode' => $transport_class->settings['shop_postal_code']
);
$shipping_request['orders'][] = array(
'carrier' => $provider_uc,
'orderId' => $order->id,
'destination' => array('destinationId' => $machine_id),
'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
'sender' => $sender
);
}
$shipping_request['credentials'] = array_values($shipping_request['credentials']);
if (empty($shipping_request['orders'])) {
return;
}
$MK = mk_get_api();
if (!$MK) {
return;
}
try {
$response = $MK->createShipments($shipping_request);
} catch (Exception $e) {
echo $e->getMessage();
exit();
}
foreach ($response as $order) {
if (!empty($order->orderId) && !empty($order->shipmentId)) {
update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->shipmentId));
} else if (!empty($order->orderId) && !empty($order->barCode)) {
update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->barCode));
} else if (!empty($order->orderId) && !empty($order->errorMessage)) {
update_post_meta((int)$order->orderId, '_parcel_machine_error', sanitize_text_field($order->errorMessage));
}
}
}
function mk_get_labels($post_ids) {
if (!is_array($post_ids)) {
$post_ids = array($post_ids);
}
$sender = array(
'name' => get_option('mk_shop_name', ''),
'phone' => get_option('mk_shop_phone', ''),
'email' => get_option('mk_shop_email', ''),
'postalCode' => get_option('mk_shop_postal_code', '')
);
parcelmachine_add_method();
$shipping_request = array('credentials' => array(), 'orders' => array(), 'printFormat' => 'A4');
foreach ($post_ids as $post_id) {
$parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
if (!$parcel_machine) { continue; }
list($provider, $machine_id) = explode('||', $parcel_machine);
if (!$provider || !$machine_id) { continue; }
$provider_uc = mb_strtoupper($provider);
if (empty($shipping_request['credentials'][$provider_uc])) {
switch ($provider_uc) {
case "OMNIVA":
$transport_class = new WC_ParcelMachine_Shipping_Method_Omniva();
break;
case "SMARTPOST":
$transport_class = new WC_ParcelMachine_Shipping_Method_Smartpost();
break;
default:
break 2;
}
$api_user = $transport_class->settings['service_user'];
$api_password = $transport_class->settings['service_password'];
if (!$api_user || !$api_password) {
add_action('admin_notices', 'mk_admin_error');
continue;
}
$shipping_request['credentials'][$provider_uc] = array('carrier' => $provider_uc, 'username' => $api_user, 'password' => $api_password);
}
$order = wc_get_order($post_id);
$shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
if (!$shipment_id) { continue; }
$shipping_request['orders'][] = array(
'carrier' => $provider_uc,
'orderId' => $order->id,
'destination' => array('destinationId' => $machine_id),
'recipient' => array('name' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'phone' => $order->billing_phone, 'email' => $order->billing_email),
'sender' => $sender,
'shipmentId' => $shipment_id
);
}
$shipping_request['credentials'] = array_values($shipping_request['credentials']);
if (empty($shipping_request['orders'])) {
return;
}
$MK = mk_get_api();
if (!$MK) {
return;
}
try {
$response = $MK->createLabels($shipping_request);
} catch (Exception $e) {
echo $e->getMessage();
exit();
}
if (empty($response->labelUrl)) {
return;
}
$sendback = add_query_arg(array('post_type' => 'shop_order', 'mk_pdf' => urlencode($response->labelUrl)), '');
wp_redirect(esc_url_raw($sendback));
exit();
}
$MKAPI = false;
function mk_get_api() {
global $MKAPI;
if ($MKAPI) {
//return $MKAPI;
}
$mk_api_type = get_option('mk_api_type', false);
if (!$mk_api_type) {
return false;
}
if ($mk_api_type !== 'live') {
$key_prefix = $mk_api_type.'_';
} else {
$key_prefix = '';
}
$mk_shop_id = get_option('mk_'.$key_prefix.'shop_id', '');
$mk_public_key = get_option('mk_'.$key_prefix.'public_key', '');
$mk_private_key = get_option('mk_'.$key_prefix.'private_key', '');
if (!$mk_shop_id || !$mk_public_key || !$mk_shop_id) {
return false;
}
$MKAPI = new Maksekeskus($mk_shop_id, $mk_public_key, $mk_private_key, $mk_api_type === 'live' ? false : true);
return $MKAPI;
}
function mk_get_machines($provider, $country = 'EE') {
$data = get_option('mk_machines_cache', false);
$data_expires = get_option('mk_machines_expires', false);
if (!$data || $data_expires < time()) {
$MK = mk_get_api();
$data = $MK->getDestinations(array('type' => 'APT'));
update_option('mk_machines_cache', $data);
update_option('mk_machines_expires', time()+3*60*60);
}
$machines = array();
if (!$data || empty($data)) {
return array();
}
foreach ($data as $machine) {
if ($machine->country === $country && $machine->type === 'APT' && ($provider === '*' || strtolower($provider) === strtolower($machine->provider))) {
$machines[] = array(
'provider' => strtolower($machine->provider),
'id' => $machine->id,
'name' => $machine->name,
'city' => $machine->city,
'address' => !empty($machine->address) ? $machine->address : '',
);
}
}
usort($machines, function($a, $b){
if ($a['city'] === $b['city']) {
return $a['name'] > $b['name'];
}
return $a['city'] > $b['city'];
});
return $machines;
}
function mk_get_machine($provider, $id) {
$machines = mk_get_machines($provider);
foreach ($machines as $machine) {
if ($machine['provider'] === $provider && $machine['id'] === $id) {
return $machine;
}
}
return false;
}
function mk_admin_error() {
printf( '', 'notice notice-error', __('Please check that you have configured correctly MakeCommerce API accesses', 'wc_makecommerce_domain'));
}
}