Descargas Full
Descargas Full

Reputation: 1

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:

// Automatically select shipping method if not selected
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;
        }
    }
}

// Get the selected shipping method and set the shipping cost
$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:

  1. I'm using a multivendor marketplace plugin for WooCommerce.
  2. The plugin is in development, and I'm using the latest versions of WordPress and WooCommerce.
  3. 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 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');
        }
    }
}

Upvotes: 0

Views: 61

Answers (0)

Related Questions