Code phương thức thanh toán Wocommerce

Eric (kedochanh)
0
18/06/25
18/06/2025
//Add fee when select payment transfer(bacs)
add_action( 'woocommerce_cart_calculate_fees','ts_add_discount', 20, 1 );
function ts_add_discount( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
  
    if (is_user_logged_in()){
            
            // Mention the payment method e.g. cod, bacs, cheque or paypal
            $payment_method = 'payos';
            // The percentage to apply
            $percent = 2; // 2%
            $cart_total = $cart_object->subtotal_ex_tax;
    
            $chosen_payment_method = WC()->session->get('chosen_payment_method');  //Get the selected payment method
            if( $payment_method == $chosen_payment_method ){
        
                   $label_text = __( "PayPal Discount" );
        
                   // Calculating percentage
                   $discount = number_format(($cart_total / 100) * $percent, 2);
        
                   // Adding the discount
                   $cart_object->add_fee( $label_text, -$discount, false );
             }
     }
}
add_action( 'woocommerce_review_order_before_payment', 'ts_refresh_payment_method' );
function ts_refresh_payment_method(){
    // jQuery
    ?>
    <script type="text/javascript">
        (function($){
            $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script>
    <?php
}
// Enable BACS for orders below a certain total and add a fee to BACS
add_action('woocommerce_cart_calculate_fees', 'ts_add_checkout_fee_for_bacs');
function ts_add_checkout_fee_for_bacs() {
    if (!is_checkout()) {
        return;
    }
    $chosen_gateway = WC()->session->get('chosen_payment_method');
    if ($chosen_gateway === 'payos') {
        $order_total = WC()->cart->subtotal;
        $fee = $order_total > 200000 ? -5000 : 0;
        // Remove the fee if the order total is greater than 100
        if ($order_total < 200000) {
            foreach (WC()->cart->get_fees() as $fee_key => $fee) {
                if ($fee->name === 'Custom Fee') {
                    WC()->cart->remove_fee($fee_key);
                    break;
                }
            }
        }
        else {
            WC()->cart->add_fee('Custom Fee', $fee);
        }
    }
}
// Refresh checkout on payment method change
add_action('woocommerce_after_checkout_form', 'ts_refresh_checkout_on_payment_methods_change');
function ts_refresh_checkout_on_payment_methods_change() {
    wc_enqueue_js("
        $('form.checkout').on('change', 'input[name^=\'payment_method\']', function() {
            $('body').trigger('update_checkout');
        });
    ");
}
// BACS payment gateway description: Append custom select field
add_filter('woocommerce_gateway_description', 'ts_gateway_bacs_custom_fields', 20, 2);
function ts_gateway_bacs_custom_fields($description, $payment_id)
{
    if ('bacs' === $payment_id) {
        ob_start(); // Start buffering
        echo '<div class="bacs-fields" style="padding:10px 0;">';
        woocommerce_form_field('field_slug', array(
            'type'      => 'select',
            'label'     => __("Fill in this field", "woocommerce"),
            'class'     => array('form-row-wide'),
            'required'  => false,
            'options'   => array(
                ''          => __("Select something", "woocommerce"),
                'choice-1'  => __("via a Bank", "woocommerce"),
                'choice-2'  => __("via PayPal", "woocommerce"),
            ),
        ), '');
        echo '</div>';
        $description .= ob_get_clean(); // Append buffered content
    }
    return $description;
}
// Save custom BACS field to order meta
add_action('woocommerce_checkout_create_order', 'ts_save_bacs_custom_field', 10, 2);
function ts_save_bacs_custom_field($order, $data)
{
    if ($data['payment_method'] === 'bacs' && isset($_POST['field_slug'])) {
        $order->update_meta_data('_bacs_custom_field', sanitize_text_field($_POST['field_slug']));
    }
}
// Display and get the custom BACS field value in WooCommerce admin
add_action('woocommerce_admin_order_data_after_billing_address', 'ts_display_bacs_custom_field_in_admin', 10, 1);
function ts_display_bacs_custom_field_in_admin($order)
{
    if ($order->get_payment_method() === 'bacs' && ($value = $order->get_meta('_bacs_custom_field'))) {
        echo '<p><strong>' . __('Payment Additional Field:', 'woocommerce') . '</strong> ' . get_bacs_custom_field_value($value) . '</p>';
    }
}
// Helper function to get the actual value for the custom field
function ts_get_bacs_custom_field_value($field_slug)
{
    $options = array('choice-1' => __("via a Bank", "woocommerce"), 'choice-2' => __("via PayPal", "woocommerce"));
    return isset($options[$field_slug]) ? $options[$field_slug] : '';
}
//Restrict payment gateways based on taxonomy terms in WooCommerce checkout
add_filter( 'woocommerce_available_payment_gateways', 'filter_available_payment_gateways' );
function filter_available_payment_gateways( $available_gateways ) {
    // Only on checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() ) {
        // Here define your product categories
        $product_categories = array( 't-shirts', 'posters' ); // Can be term names, term slugs or term ids
        $taxonomy = 'product_cat'; // For WooCommerce product category terms (or 'product_tag' for WooCommerce product tag terms)

        $payment_method     = 'cheque'; // Here define your payment method id to be removed
        $hide_payment       = false;

        // Loop through cart items
        foreach ( WC()->cart->get_cart_contents() as $item ) {
            if ( ! has_term( $product_categories, $taxonomy, $item['product_id'] ) ) {
                $hide_payment = true;
            }
        }
        
        if ( $hide_payment ) {
            unset( $available_gateways[$payment_method] );
        }
    }
    return $available_gateways;
}
//Restrict Payment Methods based on Cart Total
add_filter( 'woocommerce_available_payment_gateways', 'rudr_turn_off_cod' );

function rudr_turn_off_cod( $available_gateways ) {
	
	if( is_admin() ) {
		return $available_gateways;
	}
	
	// STEP 1: Get order/cart total
	if( is_wc_endpoint_url( 'order-pay' ) ) { // Pay for order page
		
		$order_id = wc_get_order_id_by_order_key( $_GET[ 'key' ] );
		$order = wc_get_order( $order_id );
		$order_total = $order->get_total();
		
	} else { // Cart/Checkout page
		$order_total = WC()->cart->get_total();
	}
	
	// STEP 2: Disable payment gateway if order/cart total is more than 1000
	if ( $order_total > 1000 ) {
		unset( $available_gateways[ 'cod' ] ); // unset Cash on Delivery
	}

	return $available_gateways;

}
Tags :
Tags: ,