File: /home/royaltuning/www/public/wp-content/plugins/webshippy/webshippy.php
<?php
/**
* Plugin Name: Webshippy Order Sync
* Plugin URI: http://webshippy.com
* Description: This plugin syncs all Woocommerce orders with the Webshippy Logistic System
* Version: 1.7.8
* Author: Webshippy Ltd.
* License: All rights reserved
*/
if (defined('WEBSHIPPY_ORDER_SYNC_VERSION') === false) {
define('WEBSHIPPY_ORDER_SYNC_VERSION', '1.7.8');
}
// MENU START
add_action('admin_menu', 'webshippy_plugin_menu');
// MENU ITEMS
function webshippy_plugin_menu()
{
add_menu_page(
'Webshippy',
'Webshippy',
'administrator',
'webshippy-settings',
'webshippy_plugin_settings_page',
'dashicons-admin-generic'
);
}
// SETTINGS ITEMS
add_action('admin_init', 'webshippy_plugin_settings');
function webshippy_plugin_settings()
{
register_setting('webshippy-plugin-settings-group', 'webshippy_secrect');
register_setting('webshippy-plugin-settings-group', 'wspy_sslskip');
register_setting('webshippy-plugin-settings-group', 'wspy_debug');
register_setting('webshippy-plugin-settings-group', 'webshippy_url');
register_setting('webshippy-plugin-settings-group', 'wspy_billing_name_swap');
}
/// SETTINGS PAGE START
function webshippy_plugin_settings_page()
{
load_plugin_textdomain('webshippy', false, dirname(plugin_basename(__FILE__)) . '/languages');
?>
<div class="wrap">
<h2><?php _e('Webshippy Fulfillments - General Settings', 'webshippy'); ?> (<?php _e('version:', 'webshippy'); ?> <?= WEBSHIPPY_ORDER_SYNC_VERSION ?>)</h2>
<form method="post" action="options.php">
<?php settings_fields('webshippy-plugin-settings-group'); ?>
<?php do_settings_sections('webshippy-plugin-settings-group'); ?>
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('Webshippy API Key', 'webshippy'); ?></th>
<td><input size="70" type="text" name="webshippy_secrect" placeholder="<?php _e('Webshippy API Key', 'webshippy'); ?>" value="<?php echo esc_attr(get_option('webshippy_secrect')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Server URL', 'webshippy'); ?></th>
<td><input size="70" placeholder="<?php _e('https://app.webshippy.com', 'webshippy'); ?>" value="<?php echo get_option('webshippy_url')?:'https://app.webshippy.com'; ?>" type="text" name="webshippy_url" /></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Ignore SSL certificate errors', 'webshippy'); ?></th>
<td><input <?php echo esc_attr(get_option('wspy_sslskip')) == 1 ? "checked" : ""; ?> type="checkbox" name="wspy_sslskip" value="1" /></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Enable Debug', 'webshippy'); ?></th>
<td><input <?php echo esc_attr(get_option('wspy_debug')) == 1 ? "checked" : ""; ?> type="checkbox" name="wspy_debug" value="1" /></td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Swap surname and firstname on the invoice', 'webshippy'); ?></th>
<td><input <?php echo esc_attr(get_option('wspy_billing_name_swap')) == 1 ? "checked" : ""; ?> type="checkbox" name="wspy_billing_name_swap" value="1" /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
add_action('woocommerce_order_status_pending', 'wspy_woocommerce_order_status_pending');
add_action('woocommerce_order_status_failed', 'wspy_woocommerce_order_status_failed');
add_action('woocommerce_order_status_on-hold', 'wspy_woocommerce_order_status_on_hold');
add_action('woocommerce_order_status_processing', 'wspy_woocommerce_order_status_processing');
add_action('woocommerce_order_status_completed', 'wspy_woocommerce_order_status_completed');
add_action('woocommerce_order_status_refunded', 'wspy_woocommerce_order_status_refunded');
add_action('woocommerce_order_status_cancelled', 'wspy_woocommerce_order_status_cancelled');
add_action('edit_post', 'wspy_edit_post', 10, 2);
add_action('updated_post_meta', 'wspy_updated_post_meta', 10, 4);
add_action('woocommerce_payment_complete', 'wspyPaymentCompleteAction');
function wspy_woocommerce_order_status_pending($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_pending');
}
function wspy_woocommerce_order_status_failed($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_failed');
}
function wspy_woocommerce_order_status_on_hold($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_on-hold');
}
function wspy_woocommerce_order_status_processing($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_processing');
}
function wspy_woocommerce_order_status_completed($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_completed');
}
function wspy_woocommerce_order_status_refunded($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_refunded');
}
function wspy_woocommerce_order_status_cancelled($postId)
{
wspySendOrder($postId, 'woocommerce_order_status_cancelled');
}
function wspy_edit_post($postId)
{
wspySendOrder($postId, 'edit_post');
}
/**
* @param int $metaId
* @param int $postId
* @param string $metKey
*/
function wspy_updated_post_meta($metaId, $postId, $metKey)
{
if ('_edit_lock' === $metKey) {
return;
}
wspySendOrder($postId, 'updated_post_meta');
}
/**
* Payment complete
*
* @param int $order_id
*/
function wspyPaymentCompleteAction($order_id)
{
wspySendOrder($order_id, 'woocommerce_payment_complete', 'payment_complete');
}
/**
* Get shipping method id
*
* @param \WC_Order $order
*
* @return string|null
*/
function wspyGetShippingMethodId($order)
{
// detect order shipping methods
$shipping_methods = $order->get_shipping_methods();
if (count($shipping_methods)) {
$shipping_method = array_shift($shipping_methods);
wspy_log_error_messages((string) $shipping_method, 'Shipping method: ', 'string');
$method_id = $shipping_method->get_method_id();
return stristr($method_id, ':', true) ?: $method_id;
}
}
/**
* Custom order process
*
* @param int $order_id
* @param null|string $method
* @param null|string('payment_complete')|mixed $status
*
* @return mixed
*/
function wspySendOrder($order_id, $method = null, $status = null)
{
if (is_null($order = wspyGetOrder($order_id))) {
return;
};
wspy_log_error_messages($order, $order_id . '-' . $method . '-' . $status, 'text');
// In case of local pickup will not send anything!
if (wspyGetShippingMethodId($order) === 'local_pickup') {
wspy_log_error_messages('Local_pickup shipping method', $order_id . '-' . $method . '-' . $status, 'text');
return;
}
// get status, if it's not payment_complete
if ($status !== 'payment_complete') {
$status = $order->get_status();
}
// check order status exceptions
switch ($status) {
case '':
case null: {
wspy_log_error_messages('No status', $order_id . '-' . $method . '-' . $status, 'text');
return;
}
// Teljesítve
case 'completed': {
wspy_log_error_messages('Completed status', $order_id . '-' . $method . '-' . $status, 'text');
return;
}
// Fizetésre vár
case 'pending':
case 'on-hold': {
if (
$order->get_payment_method() === 'cod'
or $order->get_payment_method() === 'stripe'
or $order->get_payment_method() === 'paypal'
or $order->get_payment_method() === 'paypal-ec'
or $order->get_payment_method() === 'paypal-braintree'
) {
wspy_log_error_messages('Peding with not valid payment method', $order_id . '-' . $method . '-' . $status, 'text');
return;
}
}
}
$data = array(
'method' => $method,
'webshippy_version' => WEBSHIPPY_ORDER_SYNC_VERSION,
'wp_version' => isset($wp_version) ? $wp_version : get_bloginfo('version'),
'woocommerce_version' => get_option('woocommerce_version'),
'woocommerce_db_version' => get_option('woocommerce_db_version'),
'webshippy_secrect' => esc_attr(get_option('webshippy_secrect')),
'order' => wspyGetOrderData($order, $status),
'lineitems' => wspyGetOrderDataLineItems($order),
'order|orig' => get_post($order_id),
);
wspy_log_error_messages($data, $order_id . '-' . $method . '-' . $status, 'json');
$url = (get_option('webshippy_url')?:'https://app.webshippy.com') . '/sync_orders_woocommerce.php';
wspy_log_error_messages('Send data to: ' . $url, $order_id . '-' . $method . '-' . $status, 'text');
$response = wp_remote_post($url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'sslverify' => (get_option('wspy_sslskip') == 0 ? false : true),
'blocking' => true,
'headers' => array(),
'body' => json_encode($data)
));
if (is_wp_error($response)) {
wspy_log_error_messages($response, $order_id . '-' . $method . '-' . $status, 'json');
}
}
/**
* @param WC_Order $order
* @param string $status
*
* @return array
*/
function wspyGetOrderData($order, $status)
{
$order_number = $order->get_order_number();
// set cod amount
$cod_amount = $order->get_payment_method() === 'cod' ? $order->get_total() : 0;
// payment complete status handling
if($order->get_payment_method()==="barion" AND ($status=="processing" OR $status=="payment_complete")) {
$payment_method="Bankkártya";
$payment_status = 'paid';
$paid = date('Y-m-d H:i:s');
$cod_amount=0;
}
elseif($order->get_payment_method()==="paylike" AND ($status=="processing" OR $status=="payment_complete")) {
$payment_method="Paylike";
$payment_status = 'paid';
$paid = date('Y-m-d H:i:s');
$cod_amount=0;
}
elseif($order->get_payment_method()==="ppcp-gateway" AND ($status=="processing" OR $status=="payment_complete")){
$payment_method="PayPal";
$payment_status = 'paid';
$paid = date('Y-m-d H:i:s');
$cod_amount=0;
}
elseif($order->get_payment_method()==="ppcp-credit-card-gateway" AND ($status=="processing" OR $status=="payment_complete")){
$payment_method="PayPal";
$payment_status = 'paid';
$paid = date('Y-m-d H:i:s');
$cod_amount=0;
}
else if ($status === 'payment_complete' ) {
$paid = date('Y-m-d H:i:s');
$payment_status = 'paid';
$cod_amount=0;
}
else {
$paid = '0000-00-00 00:00:00';
$payment_status = 'pending';
$payment_method=$order->get_payment_method();
}
$billing = $order->get_address('billing');
$shipping = $order->get_address('shipping');
$shipping_items = $order->get_items(array('shipping'));
$bstItem = array_shift($shipping_items);
$billing_shipping_title = $bstItem ? ($bstItem['name'] ?: '') : '';
$billing_shipping_vat = floatval($order->get_shipping_tax());
$billing_total_shipping = floatval($order->get_shipping_total())
+ $billing_shipping_vat;
if($order->payment_method==="cod") {
$billing_total_shipping = floatval($order->get_shipping_total())
+ $billing_shipping_vat + 490;
}else{
$billing_total_shipping = floatval($order->get_shipping_total())
+ $billing_shipping_vat;
}
if ($tmp = floatval($order->get_shipping_total())) {
$billing_shipping_vat = $billing_shipping_vat / $tmp;
}
// check for WS prio shipping method
$wc_selected_pont = wspyGetPackpoint($order, $shipping);
$countries = WC()->countries;
$shippingState = wspyGetState($countries->get_states($shipping['country']), $shipping['state']);
$billingState = wspyGetState($countries->get_states($billing['country']), $billing['state']);
return array(
'status' => $status,
//Wordpress post_id
'order_id' => $order->get_id(),
//Woocommerce order name
'order_name' => $order_number,
'created_at' => (string)$order->get_date_created(),
'imported_at' => date('Y-m-d H:i:s'),
'payment_status' => $payment_status,
'paid_at' => $paid,
'payment_gateway' => $payment_method,
'cod_amount' => $cod_amount,
'cod_currency' => $order->get_currency(),
// shipping
'shipping_address_name' => empty($wc_selected_pont)?($shipping['first_name'] . ' ' . $shipping['last_name']):($billing['first_name'] . ' ' . $billing['last_name']),
'shipping_address_company' => $shipping['company'],
'shipping_address_address1' => $shipping['address_1'],
'shipping_address_address2' => $shipping['address_2'],
'shipping_address_city' => $shipping['city'],
'shipping_address_country' => $shipping['country'],
'shipping_state_or_province_code' => $shippingState,
'shipping_address_zip' => $shipping['postcode'],
'shipping_address_phone' => $billing['phone'], /// TODO > !BILLING
'shipping_address_email' => $billing['email'], /// TODO > !BILLING
'shipping_note' => $order->get_customer_note(),
// billing address
'billing_address_name' => wspyGetBillingName($billing),
'billing_address_company' => $billing['company'],
'billing_address_address1' => $billing['address_1'],
'billing_address_address2' => $billing['address_2'],
'billing_address_city' => $billing['city'],
'billing_address_country' => $billing['country'],
'billing_state_or_province_code' => $billingState,
'billing_address_zip' => $billing['postcode'],
'billing_address_phone' => $billing['phone'],
// billing price
'billing_total_price' => $order->get_total(),
'billing_total_discounts' => $order->get_total_discount(),
'billing_total_shipping' => $billing_total_shipping,
'billing_shipping_title' => $billing_shipping_title,
'billing_shipping_vat' => $billing_shipping_vat,
'billing_tax_number' => wspyGetTaxNumber($order),
//
'wc_selected_pont' => $wc_selected_pont
);
}
/**
* @param \WC_Order $order
*
* @return array
*/
function wspyGetOrderDataLineItems($order)
{
$return = array();
$items = $order->get_items();
foreach ($items as $item) {
if (is_object($item) and method_exists($item, 'get_product_id')) {
$return[] = wspyGetOrderDataLineItemNew($item);
} else {
$return[] = wspyGetOrderDataLineItem((object)$item);
}
}
return $return;
}
/**
* @param $item
*
* @return array
*/
function wspyGetOrderDataLineItem($item)
{
$netUnit = $item->line_total / $item->qty;
$price = ($item->line_total + $item->line_tax) / $item->qty;
$variant_name = array();
if (isset($item->variation_id) && $item->variation_id) {
$product_sku = get_post_meta($item->variation_id, '_sku', true);
$variantId = $item->variation_id;
} else {
$product_sku = get_post_meta($item->product_id, '_sku', true);
$variantId = $item->product_id;
}
if (empty($product_sku)) {
$product_sku = get_post_meta($item->product_id, '_sku', true);
}
foreach ($item->item_meta_array as $meta) {
if (strpos($meta->key, '_') === 0) {
continue;
}
$variant_name[] = $meta->value;
}
return array(
'product_sku' => $product_sku,
'variant_id' => $item->product_id,
'product_name' => $item->name,
'variant_name' => implode(', ', $variant_name),
'price_net' => $netUnit,
'price' => number_format($price, 2, '.', ''),
'vat' => number_format($item->line_tax / $item->line_total, 2),
'required_quantity' => $item->qty,
'_yith_wcpb_bundle_data' => get_post_meta($variantId, '_yith_wcpb_bundle_data', true)
);
}
/**
* @param \WC_Order_Item_Product $item
*
* @return array
*/
function wspyGetOrderDataLineItemNew($item)
{
$productId = $item->get_product_id();
$product_name = get_post_field('post_title', $productId);
$quantity = $item->get_quantity();
$total = $item->get_total();
$netUnit = $item->get_total() / $quantity;
$total_tax = $item->get_total_tax();
$price = ($total + $total_tax) / $quantity;
$vat = $total == 0 ? 0 : $total_tax / $total;
if ($variantId = $item->get_variation_id()) {
$product_sku = get_post_meta($variantId, '_sku', true);
$product_name = get_post_field('post_title', $productId);
$variant_name = $item->get_name();
} else {
$product_sku = get_post_meta($productId, '_sku', true);
$variantId = $productId;
$variant_name = '';
}
return array(
'product_sku' => $product_sku,
'variant_id' => $variantId,
'product_name' => $product_name,
'variant_name' => $variant_name,
'price_net' => $netUnit,
'price' => number_format($price, 2, '.', ''),
'vat' => number_format($vat, 2),
'required_quantity' => $quantity,
'_yith_wcpb_bundle_data' => get_post_meta($variantId, '_yith_wcpb_bundle_data', true)
);
}
function wspy_log_error_messages($error, $source, $format = 'json')
{
if (esc_attr(get_option('wspy_debug')) != 1) return;
$logger = wc_get_logger();
$logger->debug(
$source . ' - ' . ($format == 'json' ? json_encode($error) : (string)$error),
array('source' => 'wc_webshippy')
);
}
function wspyGetPackpoint($order, $shipping)
{
$wc_selected_pont = get_post_meta($order->get_id(), 'wc_selected_pont', true);
// check for WS prio shipping method
if ($order->has_shipping_method('webshippy_2') || $order->has_shipping_method('webshippy_3')) {
return 'prio';
}
// check for Viszt Péter plugin
if ($vp = get_post_meta($order->get_id(), '_vp_woo_pont_provider', true)){
return sprintf("%s %s %s|%s|%s",
$shipping['postcode'],
$shipping['city'],
$shipping['address_1'],
$vp,
$order->get_meta('_vp_woo_pont_point_id')
);
}
if (($packeta = wspyGetPacketaPackPoint($order->get_id())) !== null) {
return $packeta;
}
return $wc_selected_pont;
}
function wspyGetBillingName($billing)
{
return esc_attr(get_option('wspy_billing_name_swap')) == 1
? $billing['last_name'] . ' ' . $billing['first_name']
: $billing['first_name'] . ' ' . $billing['last_name'];
}
function wspyGetPacketaPackpoint($order_id)
{
global $wpdb;
if (defined('PACKETERY_PLUGIN_DIR') === false) {
return null;
}
return $wpdb->get_var($wpdb->prepare("SELECT CONCAT(point_zip,' ',point_city,' ',point_street,'|PACKETA|',point_id) as point FROM " . $wpdb->get_blog_prefix() . "packetery_order WHERE id=%s;", $order_id));
}
/**
* @param int $postId
* @return WC_Order|null
*/
function wspyGetOrder($postId)
{
// In case of non shop order post type will not send anything!
if (in_array($post_type = get_post_field('post_type', $postId), ['shop_order', 'shop_order_placehold'])) {
// construct WC_Order.
return new WC_Order($postId);
}
wspy_log_error_messages('Not shop_order post_type', $postId . '-' . $post_type, 'text');
return null;
}
function wspyGetState($states, $key)
{
if (!is_array($states) || empty($key)) {
return null;
}
return $states[$key] ?? null;
}
function wspyGetTaxNumber($order)
{
if (function_exists('wc_eu_vat_get_vat_from_order')) {
return wc_eu_vat_get_vat_from_order($order);
}
$vatNumber = get_post_meta($order->get_id(), '_billing_tax_number', true) ?: '';
if (!empty ($vatNumber)) {
return $vatNumber;
}
return get_post_meta($order->get_id(), '_shipping_tax_number', true) ?: '';
}