programing

WooCommerce 체크아웃 페이지의 카트 합계에 ajax를 사용한 사용자 지정 수수료 추가

anycallme 2023. 10. 28. 08:10

WooCommerce 체크아웃 페이지의 카트 합계에 ajax를 사용한 사용자 지정 수수료 추가

사용자가 배송 주소 선택 드롭다운을 변경하면 ajax를 사용하여 카트 총액에 동적으로 수수료를 추가합니다.값을 얻을 수는 있었지만 다른 상태를 선택하면 합계가 업데이트되지 않습니다.

나의 아약스 요청:

jQuery(document).ready(function () {
    jQuery('#shipping_state').change(function () {
        var data = {
            action: 'woocommerce_custom_fee',
            security: wc_checkout_params.update_order_review_nonce,
            add_order_fee: 'state',
            post_data: jQuery('form.checkout').serialize()
        };
        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
                var result = '';
                result = jQuery.parseJSON(code);
                if (result.result === 'success') {

                    jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });
        return false;
    });
})
And in functions.php

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
global $woocommerce;
$destsuburb = $woocommerce->customer->get_shipping_state();

/*Then I use $destsuburb as a variable to API and get a shipping cost returning $shipping_cost*/

$woocommerce->cart->add_fee('Shipping and Handling:', $shipping_cost);
}

국가에 따라 배송비가 달라지는데 add_fee()를 통해 프론트엔드 값이 변경되지 않습니다.

드디어 세션 변수를 이용하여 Ajax 값과 add_fee()를 저장하는 솔루션을 찾았습니다.

나의 아약스 요청:

jQuery(document).ready(function () {

    jQuery('#State').click(function () {
        if (jQuery('#ship-to-different-address-checkbox').is(':checked')) {
            var state = jQuery('#shipping_state').val();
            var post_code = jQuery('#shipping_postcode').val();
        } else {
            var state = jQuery('#billing_state').val();
            var post_code = jQuery('#billing_postcode').val();

        }
        console.log(state + post_code);
        var data = {
            action: 'woocommerce_apply_state',
            security: wc_checkout_params.apply_state_nonce,
            state: state,
            post_code: post_code
        };

        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
                console.log(code);
//                jQuery('.woocommerce-error, .woocommerce-message').remove();

                if (code === '0') {
//                    $form.before(code);
                    jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });

        return false;
    });

});

기능도 있고요.php

wp_enqueue_script('neemo_state', get_template_directory_uri() . '/js/state_test.js', array('jquery'));
wp_localize_script('neemo_state', 'wc_checkout_params', array('ajaxurl' => admin_url('admin-ajax.php')));

add_action('wp_ajax_woocommerce_apply_state', 'calculate', 10);
add_action('wp_ajax_nopriv_woocommerce_apply_state', 'calculate', 10);

function calculate() {
    if (isset($_POST['state'])) {
        global $woocommerce;
        $weight = WC()->cart->cart_contents_weight;
        $state = $_POST['state'];
        if ($state === "VIC") {
            $val = 1;
        } else {
            $val = 2;
        }
        session_start();
        $_SESSION['val'] = $val;
    }
}

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
    session_start();
    $extracost = $_SESSION['val'];
    WC()->cart->add_fee('Shipping & Handling:', $extracost);
}

저는 체크아웃 직전에 기부금을 받고 카트에 그 기부금을 수수료로 추가하는 코드를 작성해야 했습니다. 그리고 사용자가 지불하기 전에 기부금을 몇 번이든 변경할 수 있도록 유연성을 제공해야 했습니다.저는 아래 코드를 사용했는데 아주 잘 작동했습니다.기부금액과 기부나우 버튼 - <입력형="버튼" id="donateNowBtn" 값="DonateNow!"

작동중인 코드

add_action( 'wp_footer', 'woocommerce_click_donate_button', 80 );
function woocommerce_click_donate_button() {
    if (is_checkout()) {
    ?>
    <script type="text/javascript">
    jQuery( document ).ready(function( $ ) {
        $('#donateNowBtn').click(function(){
            jQuery('body').trigger('update_checkout');
        });
    });
    </script>
    <?php
    }
}


add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
        if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    if (isset($post_data['donation_amount'])) {
        $donation_amount = $post_data['donation_amount'] ;
        WC()->cart->add_fee( 'Donation Amount', $donation_amount );
    }

}

언급URL : https://stackoverflow.com/questions/30297049/woocommerce-add-a-custom-fee-using-ajax-to-cart-totals-on-checkout-page