在Woocommerce中的自定义支付网关上获取并传递订单ID

时间:2019-02-01 14:40:59

标签: php wordpress woocommerce payment-gateway orders

我正在构建自定义支付网关,我需要通过ajax处理成功响应,并将交易ID映射到订单ID。我正在查询以获取last_order_id。这是获取订单ID的正确方法,还是如果我使用这种方式获取订单ID会出现任何问题。

<script>
    jQuery.ajax({
        type : "POST",                                          
        url: 'http://example.com/?wc-api=callback',
// .........
</script>

function callback(){
    // handle the response here 
}


function get_last_order_id(){
    global $wpdb;
    $statuses = array_keys(wc_get_order_statuses());
    $statuses = implode( "','", $statuses );

    // Getting last Order ID (max value)
    $results = $wpdb->get_col( "
        SELECT MAX(ID) FROM {$wpdb->prefix}posts
        WHERE post_type LIKE 'shop_order'
        AND post_status IN ('$statuses')
    " );
    return reset($results);
}

1 个答案:

答案 0 :(得分:0)

已更新

正常过程中,您可以在WC_Checkout Classprocess_checkout()方法中看到

$order_id = $this->create_order( $posted_data ); // on line 1067

或在WC_Checkout Class中使用create_order()方法:

$order_id = $order->save(); // on line 365

哪个给出订单ID

现在在process_checkout()方法中,您可以:

if ( WC()->cart->needs_payment() ) {
    $this->process_order_payment( $order_id, $posted_data['payment_method'] );

如果您查看process_order_payment() method,将会看到:

// Store Order ID in session so it can be re-used after payment failure
WC()->session->set( 'order_awaiting_payment', $order_id );

将在Woocommerce会话中存储订单ID

  

因此,要通过AJAX 获取订单ID (生成时),您将在Wordpress Ajax PHP函数内部使用:

$order_id = WC()->session->get( 'order_awaiting_payment' );
     

并将其返回给jQuery。

相关问题