付款前在结账页面获取订单ID

Get the order ID in checkout page before payment process

在 WooCommerce 中,我需要在 WooCoommerce 的结帐页面中 order ID在付款之前,创建订单时。

我查看了所有会话并试图找出订单何时在 order_awaiting_payment 会话中付款,但我在付款前需要它。
所以我想到了一个解决方案,即在加载结帐页面时下订单(实际上使其准备好付款)并在结帐真正完成时更新它。

如何在 WooCommerce 中付款前在结帐页面中获取订单 ID?

我想这有一些钩子,但我找不到它。

如果您只查看第 935 行的 class-wc-checkout.php 文件,您会看到有一个操作 woocommerce_checkout_order_processed$order_id 作为参数传递。

所以这应该适合你:

add_action('woocommerce_checkout_order_processed', 'wh_pre_paymentcall');

function wh_pre_paymentcall($order_id) {

    //create an order instance
    $order = wc_get_order($order_id);
    //$payment_method = $order->payment_method_title;
    //$status = $order->get_status();

    // write your custom logic over here.
}

代码进入您的活动子主题(或主题)的 functions.php 文件。或者在任何插件 php 文件中。

相关问题: (同时阅读评论)

希望对您有所帮助!

您可以使用挂钩在 woocommerce_checkout_order_processed 操作挂钩中的自定义函数。
从woocommerce 3.0+版本开始,这里是对应的核心代码位于process_checkout()函数中。

// Since WooCommerce version 3.0+
do_action( 'woocommerce_checkout_order_processed', $order_id, $posted_data, $order );

WooCommerce 3.0 及以下版本:

// Since WooCommerce version 2.1+ (before version 3.0+)
do_action( 'woocommerce_checkout_order_processed', $order_id, $this->posted );

根据您使用的 woocommerce 版本,有 2 种情况:

Since WooCommerce 3.0+ you can use 2 additional arguments in your hooked function and you will not need to create an instance of the order object as you get $order already as an argument.
You will be able also to access the posted data directly through $posted_data argument.

add_action('woocommerce_checkout_order_processed', 'action_checkout_order_processed', 10, 3);
function action_checkout_order_processed( $order_id, $posted_data, $order ) {
   // Do something
}

Since WooCommerce 2.1+ (Before WooCommerce 3.0), you have only the $order_id as argument, so you might be need to get an instance of $order object with wc_get_order() function:

add_action('woocommerce_checkout_order_processed', 'action_checkout_order_processed', 10, 1);
function action_checkout_order_processed( $order_id ) {
   // get an instance of the order object
   $order = wc_get_order( $order_id );

   // Do something
}

代码在您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

很遗憾,您无法访问结帐页面上的 order_id,因为尚未创建订单。虽然这是事实,但购物车数据暂时保存为 WooCommerce 调用的 'session'。如果您可以稍微调整一下,这可能会帮助您解决将信息传递给 iFrame 的问题。

您可以通过从 WC_session:

获取信息来做到这一点
$cart_data = WC()->session->get('cart');

完成后,您将能够使用 'product_id' :

等键索引访问 WooCommerce 存储的购物车数据层次结构
$cart_data[array_keys($cart_data)[0]]['product_id'];

这是有效购物车数据键的列表:

关键
product_id
variation_id
变体(数组)
数量
data_hash
line_tax_data(数组)
line_subtotal
line_subtotal_tax
line_total
line_tax