WooCommerce Rest API PHP Example – Error creating Order

How to create an Order using Woo Commerce Rest API

Take a look at this short snippet for WooCommerce Rest API example

On WooCommerce documentation for creating an Order you will see this PHP example

<?php
$data = [
    'payment_method' => 'bacs',
    'payment_method_title' => 'Direct Bank Transfer',
    'set_paid' => true,
    'billing' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US',
        'email' => 'john.doe@example.com',
        'phone' => '(555) 555-5555'
    ],
    'shipping' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'address_1' => '969 Market',
        'address_2' => '',
        'city' => 'San Francisco',
        'state' => 'CA',
        'postcode' => '94103',
        'country' => 'US'
    ],
    'line_items' => [
        [
            'product_id' => 93,
            'quantity' => 2
        ],
        [
            'product_id' => 22,
            'variation_id' => 23,
            'quantity' => 1
        ]
    ],
    'shipping_lines' => [
        [
            'method_id' => 'flat_rate',
            'method_title' => 'Flat Rate',
            'total' => 10
        ]
    ]
];

print_r($woocommerce->post('orders', $data));
?>

 

If you simply run the above example, you will come across an error similar to below

string(64) “Error: Invalid parameter(s): shipping_lines [rest_invalid_param]” object(Automattic\WooCommerce\HttpClient\Request)#5 (5) { [“url”:”Automattic\WooCommerce\HttpClient\Request”:private]=> string(295) “

This simply indicates that the example posted in the woocommerce documentation has a slight error.

If you take a look at the API details

The total for shipping line is of ‘String’ type and in the example it is supplied as a number value.

We simply surround the value with quotes to indicate a string value. This solves the issue.