woocommerce hook when order payment status is changed

I want to send an API request when the admin changes the order status from pending to completed when cash on delivery is received. I can't use thank you page hook in this case. Actually, when the user buys a course using WordPress site I want to enroll him in a course in third party LMS "Canvas" using their API. This is the code:

// enroll student on buying course
add_action( 'woocommerce_order_status_completed', 'enroll_student', 10,1 );


function enroll_student( $order_id  ) {


$order = new WC_Order($order_id);
$user = get_current_user_id();
global $wpdb;
$canvas_user = $wpdb->get_var( 'SELECT canvas_id FROM wp_user_map where wp_id ='.$user);
foreach ( $order->get_items() as $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 );
}
$prod_id = $product->id;
global $wpdb;
$canvas_prod_id = $wpdb->get_var( 'SELECT canvas_id FROM wp_course_map where wp_id ='.$prod_id);
$url = "https://myurl/api/v1/courses/".$canvas_prod_id."/enrollments";
$token = 'mytoken';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' .$token ) );
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'enrollment[user_id]'=>$canvas_user,
    'enrollment[type]'=>'StudentEnrollment',

));
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
//echo $curlData;
//echo $name;
//echo $email;
//echo 'cur user:'.$user;
//echo 'cavas user id:'.$canvas_user;
//echo 'Prod id:'.$prod_id;
//echo 'canvas Prod id:'.$canvas_prod_id;

curl_close($curl);
}

This code works perfectly if I use thankyou page hook, but not with this hook : woocommerce_payment_complete_order_status or any other payment can some plz point me which hook can help me achieve this?

Upvotes: 2

Views: 2618

Answers (1)

There was an error in my logic, I was getting user Id of currently logged in user but I needed the user ID of user who ordered the product. Got that solved using the order ID object

Upvotes: 1

Related Questions