Search code examples
woocommercewoocommerce-rest-apiwoocommerce-subscriptions

Remove Subscription line items via API for items that no longer exist in WooCommerce Store


Background:

I have about 1000 subscriptions that I need to run through and delete line items. Woocommerce has somehow allowed us to delete products that are tied to subscriptions, meaning there are now up to 1000 subscriptions with products in them which no longer exist.

This creates many problems for the subscribers, such as not being able to manually renew, as they get errors for the products that do not exist. I can delete them manually, where I will click into a subscription and remove 10+ items 1 by 1 per subscription. This will take way too long manually.

What I’m trying to do:

I want to run through all the subscriptions 1 by 1, look through the line items, and remove any line items where the “parent_id” is 0.

What I have tried so far:

I’ve tried many variations of the JSON below (also both with and without the 'subscription' line), and this is where I am at currently.

See API info here

See line item info here

NOTE: I get no error messages, the request reponse is 200. But no items are removed...

curl -X PUT https://example.com/wp-json/wc/v3/subscriptions/{subscriptions_id} \
    -u consumer_key:consumer_secret \
    -H "Content-Type: application/json" \
    -d '{
       "subscription":{
          "line_items":[
             {
                "product_id":0,
                 "quantity":0
             }
          ]
       }
    }'

What I would like help with:

At the very least to know if I'm on the right track, or if what I'm trying to do is even possible. But ideally, to point me in the right direction, or help fix up my API request.

Thanks in advance!!

NOTE 2: I can't use AutomateWoo for this, as AutomateWoo requires the product to exist before you can select it / remove it.


Solution

  • Figured it out...

    So you need to refer to the line item by using 'id' and not 'product_id' if you want to remove it. Because the 'id' is never empty (even if the product doesn't exist), I had to build a complex automation using different API endpoints.

    You need to

    1. list all subscriptions
    2. have automation run through line items per subscription, only allowing ones with product_id = 0 to pass
    3. run the proper JSON to delete the line items referencing the 'id'

    {

    "line_items": [{
        "id": 18756,
        "quantity": 0
    }]
    

    }