Онлайн заказ с вукомерс

Плагин для синхронизации ВуКоммерс и Фронтпад

Данный плагин позволяет получать данные в вашего магазина на вукомерс и отправлять их во фронтпад.

Код php

<?php
/* ====================================
 * Plugin Name: Синхронизация Frontpad и Woocommerce
 * Description: Плагин для синхронизации фронтпад с вукомерс
 * Author:      Allslava
 * Author URI:  https://allslava.ru/
 * Plugin URI:  https://allslava.ru/plagin-dlya-sinhronizacii-vukommers-i-frontpad/
 * Version: 1.10
 * ==================================== */

// Устанавливаем маску для ввода телефона на странице оформления
add_action('wp_enqueue_scripts', 'my_maskedinput');
function my_maskedinput() {
    if (is_checkout()) {
        wp_enqueue_script('maskedinput', '/wp-content/plugins/WoocommerceToFrontpad/jquery.maskedinput.js', array('jquery'));
        add_action( 'wp_footer', 'masked_script', 999);
    }
}
 function masked_script() {
    if ( wp_script_is( 'jquery', 'done' ) ) {
?>
    <script type="text/javascript">
        jQuery( function( $ ) {
            $("#billing_phone").mask("+7(999)999-99-99");
        });
    </script>
<?php
    }
}

/*
 * Отправка данных заказа во Frontpad
 */

add_action( 'woocommerce_thankyou', 'otpravka_zakaza_v_frontpad' );

function otpravka_zakaza_v_frontpad( $order_id ) {
    $order         = wc_get_order( $order_id );
    $parol_api = 'Здесь ваш секретный ключ API Frontpad';
    $email         = $order->billing_email;
    $phone         = $order->billing_phone;
	
	$phone = str_replace(array('(',')', '-'),'',$phone); // Очищаем поле телефон от ненужных символов
    $shipping_type = $order->get_shipping_method();
    if ( $order->get_payment_method_title() == 'Оплата при получении' ) {
        $shipping_type = '';
    } else {
        $shipping_type = 947;
    }
    $shipping_cost = $order->get_total_shipping();

    // получение данных товара

    $items      = $order->get_items();
    $item_name  = array();
    $item_qty   = array();
    $item_price = array();
    $item_sku   = array();

    // установка полей адреса

    $user_id        = $order->user_id;
    $address_fields = array(
        'country',
        'title',
        'given_name',
        'surname',
        'street',
        'house',
        'pod',
        'et',
        'apart',
    );

    $order_details = array();
    foreach ( $order->get_meta_data() as $item ) {
        $order_details[ $item->jsonSerialize()['key'] ] = $item->jsonSerialize()['value'];
    }
    $address = array();
    if ( is_array( $address_fields ) ) {
        foreach ( $address_fields as $field ) {
            $address[ 'billing_' . $field ]  = get_user_meta( $user_id, 'billing_' . $field, true );
            $address[ 'shipping_' . $field ] = get_user_meta( $user_id, 'shipping_' . $field, true );
            $address[ 'billing_' . $field ]  = $order_details[ '_billing_' . $field ];
            $address[ 'shipping_' . $field ] = $order_details[ '_shipping_' . $field ];
        }
    }
    $address['pre_order'] = get_post_meta( $order_id, 'pre_order', true );

    foreach ( $items as $item_id => $item ) {

        $item_name[]          = $item['name'];
        $item_qty[]           = $item['qty'];
        $item_price[]         = $item['line_total'];
        $item_id              = $item['product_id'];
        $product              = new WC_Product( $item['product_id'] );
        $product_variation_id = $item['variation_id'];
        $product              = $order->get_product_from_item( $item );
        
        // Получение артикула
        $item_sku[] = $product->get_sku();

    }


    // сбор данных для отправки
    $data = array(
        'secret'   => $parol_api,
        'street'   => $address['billing_street'],
        'home'     => $address['billing_house'],
        'pod'      => $address['billing_pod'],
        'et'       => $address['billing_et'],
        'apart'    => $address['billing_apart'],
        'phone'    => $phone,
        'mail'     => $email,
        'descr'    => $order->get_customer_note(),
        'name'     => $address['billing_given_name'] . ' ' . $address['billing_surname'],
        'pay'      => $shipping_type,
        'datetime' => date( 'Y-m-d G:i:s', $order->get_date_created()->getOffsetTimestamp() ),
    );
    
    // если указан адрес доставки, берем данные оттуда, если нет, то из платежного адреса
    if ( $address['shipping_street'] != "" ) {
        $data['street'] = $address['shipping_street'];
    }
    if ( $address['shipping_house'] != "" ) {
        $data['home'] = $address['shipping_house'];
    }
    if ( $address['shipping_pod'] != "" ) {
        $data['pod'] = $address['shipping_pod'];
    }
    if ( $address['shipping_et'] != "" ) {
        $data['et'] = $address['shipping_et'];
    }
    if ( $address['shipping_apart'] != "" ) {
        $data['apart'] = $address['shipping_apart'];
    }
    if ( ( $address['shipping_given_name'] != "" ) && ( $address['shipping_surname'] != "" ) ) {
        $data['name'] = $address['shipping_given_name'] . ' ' . $address['shipping_surname'];
    }
    if ( $address['pre_order'] != '' ) {
        $data['datetime'] = date( 'Y-m-d G:i:s', strtotime( $address['pre_order'] ) );
    }
    foreach ( $order->get_items( 'shipping' ) as $item_id => $shipping_item_obj ) {
        $data['descr'] = $data['descr'] . ' Доставка: ' . $shipping_item_obj->get_method_title();
    }

    $query = '';
	
    // подготовка запроса
    foreach ( $data as $key => $value ) {
        $query .= "&" . $key . "=" . $value;
    }

    // содержимое заказа
    foreach ( $item_sku as $key => $value ) {
        $query .= "&product[" . $key . "]=" . $value . "";
        $query .= "&product_kol[" . $key . "]=" . $item_qty[ $key ] . "";
    }

    // отправка запроса API через cURL
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_URL, "https://app.frontpad.ru/api/index.php?new_order" );
    curl_setopt( $ch, CURLOPT_FAILONERROR, 1 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
    curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_HEADER, false );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $query );

    $response = curl_exec( $ch );

    curl_close( $ch );

    $response = json_decode( $response, true );

    if ( $response['result'] == 'success' ) {
        update_post_meta( $order_id, 'Frontpad Order ID', sanitize_text_field( $response['order_id'] ) );
        update_post_meta( $order_id, 'Frontpad Order Number', sanitize_text_field( $response['order_number'] ) );

    } else {
        switch ( $response['error'] ) {
            case 'cash_close' :
                echo 'Cмена закрыта';
                echo "<script>jQuery(document).ready(function ($) {
    var popup_id = 948;
    MasterPopups.open(popup_id);
    //Or using a jQuery selector
    $('.mpp-popup-' + popup_id).MasterPopups();
});
</script>";
                $order->update_status( 'failed' );
                break;
            case 'invalid_product_keys' :
                echo 'Неверный массив товаров';
                $order->update_status( 'failed' );
                break;
        }
    }

}

?>

Код JS

/*
jQuery Masked Input Plugin
Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
Version: 1.4.1
*/
!function(factory) {
"function" == typeof define && define.amd ? define([ "jquery" ], factory) : factory("object" == typeof exports ? require("jquery") : jQuery);
}(function($) {
var caretTimeoutId, ua = navigator.userAgent, iPhone = /iphone/i.test(ua), chrome = /chrome/i.test(ua), android = /android/i.test(ua);
$.mask = {
definitions: {
"9": "[0-9]",
a: "[A-Za-z]",
"*": "[A-Za-z0-9]"
},
autoclear: !0,
dataName: "rawMaskFn",
placeholder: "_"
}, $.fn.extend({
caret: function(begin, end) {
var range;
if (0 !== this.length && !this.is(":hidden")) return "number" == typeof begin ? (end = "number" == typeof end ? end : begin, 
this.each(function() {
this.setSelectionRange ? this.setSelectionRange(begin, end) : this.createTextRange && (range = this.createTextRange(), 
range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin), 
range.select());
})) : (this[0].setSelectionRange ? (begin = this[0].selectionStart, end = this[0].selectionEnd) : document.selection && document.selection.createRange && (range = document.selection.createRange(), 
begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length), 
{
begin: begin,
end: end
});
},
unmask: function() {
return this.trigger("unmask");
},
mask: function(mask, settings) {
var input, defs, tests, partialPosition, firstNonMaskPos, lastRequiredNonMaskPos, len, oldVal;
if (!mask && this.length > 0) {
input = $(this[0]);
var fn = input.data($.mask.dataName);
return fn ? fn() : void 0;
}
return settings = $.extend({
autoclear: $.mask.autoclear,
placeholder: $.mask.placeholder,
completed: null
}, settings), defs = $.mask.definitions, tests = [], partialPosition = len = mask.length, 
firstNonMaskPos = null, $.each(mask.split(""), function(i, c) {
"?" == c ? (len--, partialPosition = i) : defs[c] ? (tests.push(new RegExp(defs[c])), 
null === firstNonMaskPos && (firstNonMaskPos = tests.length - 1), partialPosition > i && (lastRequiredNonMaskPos = tests.length - 1)) : tests.push(null);
}), this.trigger("unmask").each(function() {
function tryFireCompleted() {
if (settings.completed) {
for (var i = firstNonMaskPos; lastRequiredNonMaskPos >= i; i++) if (tests[i] && buffer[i] === getPlaceholder(i)) return;
settings.completed.call(input);
}
}
function getPlaceholder(i) {
return settings.placeholder.charAt(i < settings.placeholder.length ? i : 0);
}
function seekNext(pos) {
for (;++pos < len && !tests[pos]; ) ;
return pos;
}
function seekPrev(pos) {
for (;--pos >= 0 && !tests[pos]; ) ;
return pos;
}
function shiftL(begin, end) {
var i, j;
if (!(0 > begin)) {
for (i = begin, j = seekNext(end); len > i; i++) if (tests[i]) {
if (!(len > j && tests[i].test(buffer[j]))) break;
buffer[i] = buffer[j], buffer[j] = getPlaceholder(j), j = seekNext(j);
}
writeBuffer(), input.caret(Math.max(firstNonMaskPos, begin));
}
}
function shiftR(pos) {
var i, c, j, t;
for (i = pos, c = getPlaceholder(pos); len > i; i++) if (tests[i]) {
if (j = seekNext(i), t = buffer[i], buffer[i] = c, !(len > j && tests[j].test(t))) break;
c = t;
}
}
function androidInputEvent() {
var curVal = input.val(), pos = input.caret();
if (oldVal && oldVal.length && oldVal.length > curVal.length) {
for (checkVal(!0); pos.begin > 0 && !tests[pos.begin - 1]; ) pos.begin--;
if (0 === pos.begin) for (;pos.begin < firstNonMaskPos && !tests[pos.begin]; ) pos.begin++;
input.caret(pos.begin, pos.begin);
} else {
for (checkVal(!0); pos.begin < len && !tests[pos.begin]; ) pos.begin++;
input.caret(pos.begin, pos.begin);
}
tryFireCompleted();
}
function blurEvent() {
checkVal(), input.val() != focusText && input.change();
}
function keydownEvent(e) {
if (!input.prop("readonly")) {
var pos, begin, end, k = e.which || e.keyCode;
oldVal = input.val(), 8 === k || 46 === k || iPhone && 127 === k ? (pos = input.caret(), 
begin = pos.begin, end = pos.end, end - begin === 0 && (begin = 46 !== k ? seekPrev(begin) : end = seekNext(begin - 1), 
end = 46 === k ? seekNext(end) : end), clearBuffer(begin, end), shiftL(begin, end - 1), 
e.preventDefault()) : 13 === k ? blurEvent.call(this, e) : 27 === k && (input.val(focusText), 
input.caret(0, checkVal()), e.preventDefault());
}
}
function keypressEvent(e) {
if (!input.prop("readonly")) {
var p, c, next, k = e.which || e.keyCode, pos = input.caret();
if (!(e.ctrlKey || e.altKey || e.metaKey || 32 > k) && k && 13 !== k) {
if (pos.end - pos.begin !== 0 && (clearBuffer(pos.begin, pos.end), shiftL(pos.begin, pos.end - 1)), 
p = seekNext(pos.begin - 1), len > p && (c = String.fromCharCode(k), tests[p].test(c))) {
if (shiftR(p), buffer[p] = c, writeBuffer(), next = seekNext(p), android) {
var proxy = function() {
$.proxy($.fn.caret, input, next)();
};
setTimeout(proxy, 0);
} else input.caret(next);
pos.begin <= lastRequiredNonMaskPos && tryFireCompleted();
}
e.preventDefault();
}
}
}
function clearBuffer(start, end) {
var i;
for (i = start; end > i && len > i; i++) tests[i] && (buffer[i] = getPlaceholder(i));
}
function writeBuffer() {
input.val(buffer.join(""));
}
function checkVal(allow) {
var i, c, pos, test = input.val(), lastMatch = -1;
for (i = 0, pos = 0; len > i; i++) if (tests[i]) {
for (buffer[i] = getPlaceholder(i); pos++ < test.length; ) if (c = test.charAt(pos - 1), 
tests[i].test(c)) {
buffer[i] = c, lastMatch = i;
break;
}
if (pos > test.length) {
clearBuffer(i + 1, len);
break;
}
} else buffer[i] === test.charAt(pos) && pos++, partialPosition > i && (lastMatch = i);
return allow ? writeBuffer() : partialPosition > lastMatch + 1 ? settings.autoclear || buffer.join("") === defaultBuffer ? (input.val() && input.val(""), 
clearBuffer(0, len)) : writeBuffer() : (writeBuffer(), input.val(input.val().substring(0, lastMatch + 1))), 
partialPosition ? i : firstNonMaskPos;
}
var input = $(this), buffer = $.map(mask.split(""), function(c, i) {
return "?" != c ? defs[c] ? getPlaceholder(i) : c : void 0;
}), defaultBuffer = buffer.join(""), focusText = input.val();
input.data($.mask.dataName, function() {
return $.map(buffer, function(c, i) {
return tests[i] && c != getPlaceholder(i) ? c : null;
}).join("");
}), input.one("unmask", function() {
input.off(".mask").removeData($.mask.dataName);
}).on("focus.mask", function() {
if (!input.prop("readonly")) {
clearTimeout(caretTimeoutId);
var pos;
focusText = input.val(), pos = checkVal(), caretTimeoutId = setTimeout(function() {
input.get(0) === document.activeElement && (writeBuffer(), pos == mask.replace("?", "").length ? input.caret(0, pos) : input.caret(pos));
}, 10);
}
}).on("blur.mask", blurEvent).on("keydown.mask", keydownEvent).on("keypress.mask", keypressEvent).on("input.mask paste.mask", function() {
input.prop("readonly") || setTimeout(function() {
var pos = checkVal(!0);
input.caret(pos), tryFireCompleted();
}, 0);
}), chrome && android && input.off("input.mask").on("input.mask", androidInputEvent), 
checkVal();
});
}
});
});

Скачать плагин

Оставьте комментарий

Ваш адрес email не будет опубликован.