I am building custom payment gateway which i need to handle the success response through ajax and mapped the transaction id with the order id. I am querying to get the last_order_id. Is this the correct way to get the order id or any issue will be arised if i use this way to get the order 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);
}
Updated
On a normal process you can see in WC_Checkout
Class on process_checkout()
method:
$order_id = $this->create_order( $posted_data ); // on line 1067
or in WC_Checkout
Class with create_order()
method:
$order_id = $order->save(); // on line 365
Which gives the Order ID
Now inside the process_checkout()
method you have:
if ( WC()->cart->needs_payment() ) {
$this->process_order_payment( $order_id, $posted_data['payment_method'] );
And if you look to process_order_payment()
method you will see:
// Store Order ID in session so it can be re-used after payment failure
WC()->session->set( 'order_awaiting_payment', $order_id );
which will store the order ID in Woocommerce sessions
So TO GET THE ORDER ID through AJAX (when it has been generated) you will use inside your Wordpress Ajax PHP function:
$order_id = WC()->session->get( 'order_awaiting_payment' );
And return it to jQuery.