3

Is it possible to get the Subscription id from the Woocommerce order id with the API of WooCommerce? I'm using PHP and with this I can get all the order data, but not subscription id:

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => "https://www.example.com/wp-json/wc/v3/orders/".$orderId,
    CURLOPT_USERPWD => 'code:code',
    CURLOPT_HTTPHEADER => array(
         "accept: application/json"
    )
]);
$woocommerceOrder = curl_exec($curl);
mujuonly
  • 11,370
  • 5
  • 45
  • 75

2 Answers2

2
add_filter( 'woocommerce_api_order_response', 'add_woo_field_order_api_response', 20, 4 );

function add_woo_field_order_api_response( $order_data, $order, $fields, $server ) {

    // Get the subscription id
    $subscriptions_ids  = wcs_get_subscriptions_for_order( $order->get_id(), array( 'order_type' => 'any' ) );
    // We get all related subscriptions for this order
    foreach ( $subscriptions_ids as $subscription_id => $subscription_obj )
        if ( $subscription_obj->order->id == $order_id )
            break; // Stop the loop
    $order_data[ 'subscription_id' ] = $subscription_id;
    return $order_data;
}

Add this code snippet in your server active theme function.php. Then the order API response will contain the subscription_id

mujuonly
  • 11,370
  • 5
  • 45
  • 75
  • I've tried this code, but in https://www.example.com/wp-json/wc/v3/orders/".$orderId endopoint I don't see any element subscription_id – Damiano Fontana Apr 28 '21 at 14:24
  • @DamianoFontana Check if the code gets executed when the request is triggered. – mujuonly Apr 28 '21 at 14:47
  • I've tried to add a test parameter, but I can't see it in the endpoint response... function add_woo_field_order_api_response( $order_data, $order, $fields, $server ) { $order_data['test-parameter'] = "Test test test"; – Damiano Fontana Apr 28 '21 at 14:54
  • https://dominykasgel.com/modify-woocommerce-api-orders-response/ – mujuonly Apr 28 '21 at 15:02
  • Should I use prefix_wc_rest_prepare_order_object instead add_woo_field_order_api_response? – Damiano Fontana Apr 28 '21 at 16:43
1

I've solved with this code in my functions.php file in Wordpress:

function prefix_wc_rest_prepare_order_object($response, $object, $request){
    // Get the subscription id
    $subscriptions_ids = wcs_get_subscriptions_for_order($object->get_id(), array('order_type' => 'any'));
    // We get all related subscriptions for this order
    foreach($subscriptions_ids as $subscription_id => $subscription_obj){
        if($subscription_obj->order->id == $object->get_id()){
            break; // Stop the loop
        }
    }
    $response->data['subscription_id'] = $subscription_id;
    return $response;
}
add_filter('woocommerce_rest_prepare_shop_order_object', 'prefix_wc_rest_prepare_order_object', 10, 3);

Thanks to mujuonly for the reference and for the initial snippet.