Shipping Cost Not Being Charged in WooCommerce Stripe Payment Gateway Plugin

I’m developing a custom Stripe Payment Gateway plugin for WooCommerce. Everything works fine except for the shipping cost, which is not being charged to the customer. I’m using the following code to add the shipping cost to the order:

` // Seleccionar método de envío automáticamente si no está seleccionado
if (!isset(WC()->session->get(‘chosen_shipping_methods’)[0])) {
$shipping_methods = WC()->session->get(‘shipping_for_package_0’)[‘rates’];
foreach ($shipping_methods as $key => $rate) {
if ($rate->method_id === ‘free_shipping’) {
WC()->session->set(‘chosen_shipping_methods’, array($rate->id));
break;
}
}
}

                    // Obtener el método de envío seleccionado y establecer el costo de envío
                    $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
                    if (!empty($chosen_shipping_methods)) {
                        $shipping_total = WC()->cart->get_shipping_total();
                        if ($shipping_total > 0) {
                            $order->set_shipping_total($shipping_total);
                            foreach ($order->get_shipping_methods() as $shipping_item) {
                                $shipping_item->set_cost($shipping_total);
                                $shipping_item->save();
                            }
                        }
                    }`

However, the shipping cost is not being added to the total order amount. I’ve also verified that the add_shipping() method is being called correctly. Can anyone help me figure out why the shipping cost is not being charged to the customer?

Additional Information:

I’m using a multivendor marketplace plugin for WooCommerce.
The plugin is in development, and I’m using the latest versions of WordPress and WooCommerce.
I’m also open to suggestions for improving the code or any best practices for handling shipping costs in a custom WooCommerce payment gateway plugin.

function `function process_stripe_token_outside() {
if ($_SERVER[“REQUEST_METHOD”] == “POST” && isset($_POST[‘stripe_token’])) {

                global $woocommerce;
        
                // Verificar si hay un pedido activo.
                $order_id = absint(WC()->session->get('order_awaiting_payment'));
                if (!$order_id) {
                    $order_id = absint(get_query_var('order-pay')) ?: absint(get_query_var('order-received'));
                }
                if (!$order_id) {
                    if (isset($_POST['order_id'])) {
                        $order_id = absint($_POST['order_id']);
                    } elseif (isset($_POST['woocommerce_checkout_update_totals'])) {
                        $order_id = absint($_POST['woocommerce_checkout_update_totals']);
                    }
                }
        
                // Si no hay un pedido activo, crear uno nuevo.
                if (!$order_id) {
                    $order_data = array(
                        'status' => 'pending',
                        'customer_id' => get_current_user_id(),
                        'created_via' => 'checkout',
                        'payment_method' => 'stripe',
                        'payment_method_title' => 'Stripe Payment Gateway',
                        'set_paid' => false,
                        'billing' => array(),
                        'shipping' => array(),
                        'line_items' => array(),
                        'shipping_lines' => array(),
                        'fee_lines' => array(),
                        'coupon_lines' => array(),
                        'customer_note' => '',
                        'customer_message' => '',
                        'date_created' => wc_string_to_timestamp(current_time('mysql')),
                        'date_modified' => wc_string_to_timestamp(current_time('mysql')),
                      

                    );
        
                    $order = wc_create_order($order_data);
                    $order_id = $order->get_id();
        
                    // Agregar los artículos del carrito al pedido.
                    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
                        $product = $cart_item['data'];
                        $quantity = $cart_item['quantity'];
                        $order->add_product($product, $quantity);
                    }
        
                    // Establecer las direcciones de facturación y envío del cliente.
                    $customer = new WC_Customer(get_current_user_id());
                    $billing_address = array(
                        'first_name' => $customer->get_billing_first_name(),
                        'last_name' => $customer->get_billing_last_name(),
                        'company' => $customer->get_billing_company(),
                        'address_1' => $customer->get_billing_address_1(),
                        'address_2' => $customer->get_billing_address_2(),
                        'city' => $customer->get_billing_city(),
                        'state' => $customer->get_billing_state(),
                        'postcode' => $customer->get_billing_postcode(),
                        'country' => $customer->get_billing_country(),
                        'email' => $customer->get_billing_email(),
                        'phone' => $customer->get_billing_phone(),
                    );
        
                    $shipping_address = array(
                        'first_name' => $customer->get_shipping_first_name(),
                        'last_name' => $customer->get_shipping_last_name(),
                        'company' => $customer->get_shipping_company(),
                        'address_1' => $customer->get_shipping_address_1(),
                        'address_2' => $customer->get_shipping_address_2(),
                        'city' => $customer->get_shipping_city(),
                        'state' => $customer->get_shipping_state(),
                        'postcode' => $customer->get_shipping_postcode(),
                        'country' => $customer->get_shipping_country(),
                    );
        
                    $order->set_address($billing_address, 'billing');
                    $order->set_address($shipping_address, 'shipping');
                } else {
                    $order = wc_get_order($order_id);
                }
        
               // Seleccionar método de envío automáticamente si no está seleccionado
                    if (!isset(WC()->session->get('chosen_shipping_methods')[0])) {
                        $shipping_methods = WC()->session->get('shipping_for_package_0')['rates'];
                        foreach ($shipping_methods as $key => $rate) {
                            if ($rate->method_id === 'free_shipping') {
                                WC()->session->set('chosen_shipping_methods', array($rate->id));
                                break;
                            }
                        }
                    }

                    // Obtener el método de envío seleccionado y establecer el costo de envío
                    $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
                    if (!empty($chosen_shipping_methods)) {
                        $shipping_total = WC()->cart->get_shipping_total();
                        if ($shipping_total > 0) {
                            $order->set_shipping_total($shipping_total);
                            foreach ($order->get_shipping_methods() as $shipping_item) {
                                $shipping_item->set_cost($shipping_total);
                                $shipping_item->save();
                            }
                        }
                    }
                                        
                // Calcular los totales y establecer el estado.
                $order->calculate_totals();
        
                // Para depuración
                error_log('Order ID: ' . $order_id);
                error_log('Stripe Token: ' . sanitize_text_field($_POST['stripe_token']));
        
                if ($order) {
                    $token = sanitize_text_field($_POST['stripe_token']);
        
                    try {
                        if (empty($token)) {
                            wc_add_notice('Invalid payment source.', 'error');
                            return;
                        }
        
                        // Obtener el nombre del producto y la cantidad
                        $items = $order->get_items();
                        $product_details = '';
                        foreach ($items as $item) {
                            $product_name = $item->get_name();
                            $product_quantity = $item->get_quantity();
                            $product_details .= $product_name . ' x ' . $product_quantity . ', ';
                        }
                        $product_details = rtrim($product_details, ', ');
        
                        $description = 'Order ' . $order->get_order_number() . ' - Products: ' . $product_details;
        
                        // Procesar el pago con Stripe
                        $stripe = new StripeClient($this->secret_key);
                        $charge = $stripe->charges->create([
                            'amount' => $order->get_total() * 100,
                            'currency' => strtolower(get_woocommerce_currency()),
                            'description' => $description,
                            'source' => $token,
                            'metadata' => [
                                'order_id' => $order_id
                            ],
                            'receipt_email' => $order->get_billing_email(),
                            'statement_descriptor' => 'Stripe Payment Gateway',
                            'capture' => true,
                       
                        ]);
        
                        if ($charge->status == 'succeeded') {
                            $order->payment_complete();
                            $order->reduce_order_stock();
                            $woocommerce->cart->empty_cart();
        
                            wp_redirect($order->get_checkout_order_received_url());
                            exit;
                        } else {
                            wc_add_notice('Payment failed: ' . $charge->failure_message, 'error');
                        }
                    } catch (Exception $e) {
                        wc_add_notice('Payment failed: ' . $e->getMessage(), 'error');
                    }
                } else {
                    wc_add_notice('Invalid order.', 'error');
                }
            }
        }`

New contributor

Descargas Full is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật