Php 成功签出后获取订单数据

Php 成功签出后获取订单数据,php,wordpress,woocommerce,checkout,orders,Php,Wordpress,Woocommerce,Checkout,Orders,在WooCommerce中,我希望在客户成功签出后向API发送请求。它基本上是一个客户销售在线课程的网站(如) 当客户退房时,我想发送一个API请求并为该特定课程的用户注册。我试过好几种钩子,但都不管用 这是我正在使用的代码: add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1); function enroll_student($order_id) { echo $order_id;

在WooCommerce中,我希望在客户成功签出后向API发送请求。它基本上是一个客户销售在线课程的网站(如

当客户退房时,我想发送一个API请求并为该特定课程的用户注册。我试过好几种钩子,但都不管用

这是我正在使用的代码:

add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);

function enroll_student($order_id)
{
    echo $order_id;
    echo "Hooked";
}
我正在为一个插件编写这段代码,为了让它更简单,我目前正在使用货到付款的方法

谁能告诉我哪里出了问题,因为当我结账时,我看不到我正在打印的消息“hooked”,也看不到
$order\u id

它把我带到成功页面,并没有显示我正在打印的这两个东西

仅针对Woocommerce 3+更新2(增加了仅执行一次代码的限制)

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

该代码经过测试并正常工作

然后可以在
$order
对象上使用所有类方法

相关的:


您可以通过

   // Getting an instance of the order object

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

   //Loop through them, you can get all the relevant data:

    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];
    }

谢谢你的回答。我用Thankyou页面钩子检查了它,它显示了期望的结果,但是我可以在这个钩子中获得产品数据吗。我想在结帐后获得产品ID并将其传递给外部APIOne问题:如果用户刷新感谢页面,它将向发送另一个请求API@sanjeev更新了Woocommerce 3的代码,并添加了一个限制,仅允许此代码执行一次。问题2:如果管理员手动创建订单,则此代码不起作用。刚刚遇到了那个用例myself@LoicTheAztec只是觉得人们应该知道他们是否找到了这个!除了那个特殊的用例之外,您的解决方案对我来说非常有效。
add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {

    if ( ! $order_id )
        return;

    // Getting an instance of the order object
    $order = wc_get_order( $order_id );

    if($order->is_paid())
        $paid = 'yes';
    else
        $paid = 'no';

    // iterating through each order items (getting product ID and the product object) 
    // (work for simple and variable products)
    foreach ( $order->get_items() as $item_id => $item ) {

        if( $item['variation_id'] > 0 ){
            $product_id = $item['variation_id']; // variable product
        } else {
            $product_id = $item['product_id']; // simple product
        }

        // Get the product object
        $product = wc_get_product( $product_id );

    }

    // Ouptput some data
    echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
}
   // Getting an instance of the order object

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

   //Loop through them, you can get all the relevant data:

    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];
    }