Woocommerce Orders API returning "woocommerce_rest_shop_order_exists"

69 Views Asked by At

I can't figure out how to get SITE B to accept the order from SITE A I essentially need SITE A to be a proxy of SITE B, sending all orders processed to site Bs orders API

using my current code, I get the response:

"woocommerce_rest_shop_order_exists"

The order IDs are not clashing since site B has set up a test environment for me to test with, so I can see all the orders and their ids, nothing is clashing. I have been asking chat GPT but I feel its time to ask real people

Here is the exact error response I am getting:

Array
(
    [headers] => WpOrg\Requests\Utility\CaseInsensitiveDictionary Object
        (
            [data:protected] => Array
                (
                    [date] => Sun, 18 Feb 2024 13:02:46 GMT
                    [server] => Apache
                    [x-robots-tag] => noindex
                    [link] => <REMOVED>; rel="https://api.w.org/"
                    [x-content-type-options] => nosniff
                    [access-control-expose-headers] => X-WP-Total, X-WP-TotalPages, Link
                    [access-control-allow-headers] => Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type
                    [allow] => GET, POST
                    [expires] => Wed, 11 Jan 1984 05:00:00 GMT
                    [cache-control] => no-cache, must-revalidate, max-age=0, no-store, private
                    [x-frame-options] => sameorigin
                    [x-xss-protection] => 1; mode=block
                    [referrer-policy] => same-origin
                    [strict-transport-security] => max-age=63072000; preload;
                    [upgrade] => h2,h2c
                    [content-type] => application/json; charset=UTF-8
                )

        )

    [body] => {"code":"woocommerce_rest_shop_order_exists","message":"Kan bestaande shop_order niet aanmaken.","data":{"status":400}}
    [response] => Array
        (
            [code] => 400
            [message] => Bad Request
        )

    [cookies] => Array
        (
        )

    [filename] =>
    [http_response] => WP_HTTP_Requests_Response Object
        (
            [response:protected] => WpOrg\Requests\Response Object
                (
                    [body] => {"code":"woocommerce_rest_shop_order_exists","message":"Kan bestaande shop_order niet aanmaken.","data":{"status":400}}
                    [raw] => HTTP/1.1 400 Bad Request
Date: Sun, 18 Feb 2024 13:02:46 GMT
Server: Apache
X-Robots-Tag: noindex
Link: <REMOVED>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages, Link
Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type
Allow: GET, POST
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0, no-store, private
X-Frame-Options: sameorigin
X-XSS-Protection: 1; mode=block
Referrer-Policy: same-origin
Strict-Transport-Security: max-age=63072000; preload;
Upgrade: h2,h2c
Connection: Upgrade, close
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{"code":"woocommerce_rest_shop_order_exists","message":"Kan bestaande shop_order niet aanmaken.","data":{"status":400}}
                    [headers] => WpOrg\Requests\Response\Headers Object
                        (
                            [data:protected] => Array
                                (
                                    [date] => Array
                                        (
                                            [0] => Sun, 18 Feb 2024 13:02:46 GMT
                                        )

                                    [server] => Array
                                        (
                                            [0] => Apache
                                        )

                                    [x-robots-tag] => Array
                                        (
                                            [0] => noindex
                                        )

                                    [link] => Array
                                        (
                                            [0] => <REMOVED>; rel="https://api.w.org/"
                                        )

                                    [x-content-type-options] => Array
                                        (
                                            [0] => nosniff
                                        )

                                    [access-control-expose-headers] => Array
                                        (
                                            [0] => X-WP-Total, X-WP-TotalPages, Link
                                        )

                                    [access-control-allow-headers] => Array
                                        (
                                            [0] => Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type
                                        )

                                    [allow] => Array
                                        (
                                            [0] => GET, POST
                                        )

                                    [expires] => Array
                                        (
                                            [0] => Wed, 11 Jan 1984 05:00:00 GMT
                                        )

                                    [cache-control] => Array
                                        (
                                            [0] => no-cache, must-revalidate, max-age=0, no-store, private
                                        )

                                    [x-frame-options] => Array
                                        (
                                            [0] => sameorigin
                                        )

                                    [x-xss-protection] => Array
                                        (
                                            [0] => 1; mode=block
                                        )

                                    [referrer-policy] => Array
                                        (
                                            [0] => same-origin
                                        )

                                    [strict-transport-security] => Array
                                        (
                                            [0] => max-age=63072000; preload;
                                        )

                                    [upgrade] => Array
                                        (
                                            [0] => h2,h2c
                                        )

                                    [content-type] => Array
                                        (
                                            [0] => application/json; charset=UTF-8
                                        )

                                )

                        )

                    [status_code] => 400
                    [protocol_version] => 1.1
                    [success] =>
                    [redirects] => 0
                    [url] => <REMOVED>
                    [history] => Array
                        (
                        )

                    [cookies] => WpOrg\Requests\Cookie\Jar Object
                        (
                            [cookies:protected] => Array
                                (
                                )

                        )

                )

            [filename:protected] =>
            [data] =>
            [headers] =>
            [status] =>
        )

)

I am writing a script where when an order is made on site A, it sends it to Site B's woocommerce orders api for them to deal with, package, and ship.

here is my current code, I apologise for the mess, this error has been getting to me:

function send_order_to_another_site($order_id) {
    
//SITE B API DATA
    $site_url = 'SITE B URL';
    $consumer_key = 'SITE B KEY';
    $consumer_secret = 'SITE B SECRET';

// Get site As newly submitted order and store order ID
    $order = wc_get_order($order_id);
    $order_id = $order->get_id();
    
//SITE A API INFO
    $ck = 'SITE A KEY';
    $cs = 'SITE A SECRET';
    $store_url = SITE A URL';
    
// fetch highest order number from SITE B and add 1
    $url = $store_url . '/wp-json/wc/v3/orders?consumer_key=' . $consumer_key . '&consumer_secret=' . $consumer_secret . '&per_page=1&orderby=id&order=desc';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    $response = curl_exec($ch);
    if ($response === false) {
        echo 'Error: ' . curl_error($ch);
        exit;
    }
    curl_close($ch);
    $order_data = json_decode($response, true);
    if (empty($order_data)) {
        echo 'No orders found.';
        exit;
    }
    $newOrderNum = $order_data[0]['number']+1;

// Fetch New Order object from SITE A
    $url = $store_url . '/wp-json/wc/v3/orders/' . $order_id . '?consumer_key=SITEAKEY&consumer_secret=SITEASECRET';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',));
    $response = curl_exec($ch);
    if ($response === false) {
        echo 'Error: ' . curl_error($ch);
        mail("MY EMAIL","ORDER FAIL",print_r(curl_error($ch),true));
        exit;
    }
    $order_data1 = json_decode($response, true);
    if (isset($order_data1['code'])) {
        echo 'Failed to retrieve order. Error code: ' . $order_data1['code'];
        mail("MY EMAIL","ORDER FAIL",print_r($order_data1['code'],true));
        exit;
    } else {
// Order retrieved successfully
// Change all occurrences of Order id for the new order ID of site B
        $order_data1['id']=$newOrderNum;
        $order_data1['number']=$newOrderNum;
        $original_string = $order_data1['payment_url'];
        $string_to_replace = $order_id.'';
        $replacement_string = $newOrderNum.'';
        $order_data1['payment_url'] = str_replace($string_to_replace, $replacement_string, $original_string);

        foreach($order_data1['links']['self'] as &$link){
            if(isset($link['href'])){
                $original_string = $link['href'];
                $string_to_replace = $order_id.'';
                $replacement_string = $newOrderNum.'';
                $link['href'] = str_replace($string_to_replace, $replacement_string, $original_string);
            }
        }
        
        foreach($order_data1['meta_data'] as &$mdat){
            if(isset($mdat['key']))
            {
                if($mdat['key']=="_wcpdf_invoice_number_data"){
                    if(isset($mdat['value'])){
                        $mdat['value']['order_id']=$newOrderNum;
                    }
                }
            }
        }
        foreach ($order_data1['line_items'] as &$item) {
            if($item['parent_name']==null){
                $item['parent_name']="";
            }
            foreach ($item['meta_data'] as &$mdata) {
                if (isset($mdata['display_value'])) {
                    $mdata['display_value'] = "";
                }
            }
        }
        unset($mdata);
    unset($mdat);
        unset($item);
        $newData = json_encode($order_data1);
    }
    curl_close($ch);

    // Set request arguments
    $args = array(
        'method' => 'POST',
        'headers' => array(
            'Authorization' => 'Basic ' . base64_encode($consumer_key . ':' . $consumer_secret),
            'Content-Type' => 'application/json'
        ),
        'body' => $newData
    );
    
    // Make the request
    $response = wp_remote_post($site_url . '/wp-json/wc/v3/orders', $args);
    $resp = print_r($response, true);
    mail("MY EMAIL", "responseData", $resp, "");
    // Check for errors
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        mail("MY EMAIL", "Error", $error_message, "");
        echo "Error: $error_message";
    } else {
        // Order created successfully
        $order = json_decode(wp_remote_retrieve_body($response), true);
        $ordDeet = print_r($order,true);
        mail("MY EMAIL", "Success", $ordDeet, "");
        echo "Order created successfully. Order ID: " . $order['id'];
    }
}

This is the JSON data for the object I am sending:

{
    "id": 11402,
    "parent_id": 0,
    "status": "processing",
    "currency": "EUR",
    "version": "8.6.0",
    "prices_include_tax": false,
    "date_created": "2024-02-18T12:55:28",
    "date_modified": "2024-02-18T12:55:44",
    "discount_total": "0.00",
    "discount_tax": "0.00",
    "shipping_total": "5.95",
    "shipping_tax": "0.00",
    "cart_tax": "0.00",
    "total": "19.90",
    "total_tax": "0.00",
    "customer_id": 7,
    "order_key": "wc_order_RJdTCaxIsyefI",
    "billing": {
        "first_name": "MYNAME",
        "last_name": "MYSURNAME",
        "company": "",
        "address_1": "Torensteeg 1-Torensteeg",
        "address_2": "",
        "city": "Amsterdam",
        "state": "",
        "postcode": "1012 TH",
        "country": "NL",
        "email": "MYEMAIL",
        "phone": "07984394843"
    },
    "shipping": {
        "first_name": "MYNAME",
        "last_name": "MYSURNAME",
        "company": "",
        "address_1": "Torensteeg 1-Torensteeg",
        "address_2": "",
        "city": "Amsterdam",
        "state": "",
        "postcode": "1012 TH",
        "country": "NL",
        "phone": "",
        "naarwie": "",
        "adreskeuze": "priveadres",
        "ziekenhuis": "",
        "afdeling": "",
        "verdieping": "",
        "kamer": ""
    },
    "payment_method": "mollie_wc_gateway_ideal",
    "payment_method_title": "iDEAL",
    "transaction_id": "ord_1.9akoml",
    "customer_ip_address": "",
    "customer_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "created_via": "checkout",
    "customer_note": "",
    "date_completed": null,
    "date_paid": "2024-02-18T12:55:38",
    "cart_hash": "397825dfcb209da19183750323e5cfc3",
    "number": "11402",
    "meta_data": [
        {
            "id": 2181,
            "key": "adreskeuze",
            "value": "priveadres"
        },
        {
            "id": 2168,
            "key": "is_vat_exempt",
            "value": "no"
        },
        {
            "id": 2174,
            "key": "jckwds_date",
            "value": "19\/02\/2024"
        },
        {
            "id": 2175,
            "key": "jckwds_date_ymd",
            "value": "20240219"
        },
        {
            "id": 2176,
            "key": "jckwds_shipping_method",
            "value": "flat_rate:1"
        },
        {
            "id": 2177,
            "key": "jckwds_timeslot",
            "value": "08:00 - 17:00"
        },
        {
            "id": 2178,
            "key": "jckwds_timeslot_id",
            "value": "0|0.00"
        },
        {
            "id": 2171,
            "key": "jckwds_timestamp",
            "value": "1708326000"
        },
        {
            "id": 2162,
            "key": "_billing_house_number",
            "value": "1"
        },
        {
            "id": 2163,
            "key": "_billing_house_number_suffix",
            "value": "Torensteeg"
        },
        {
            "id": 2164,
            "key": "_billing_street_name",
            "value": "Torensteeg"
        },
        {
            "id": 2173,
            "key": "_iconic_wds_is_next_day",
            "value": "1"
        },
        {
            "id": 2172,
            "key": "_iconic_wds_is_same_day",
            "value": ""
        },
        {
            "id": 2196,
            "key": "_mollie_customer_id",
            "value": "cst_FHbnGvvSNq"
        },
        {
            "id": 2193,
            "key": "_mollie_order_id",
            "value": "ord_1.9akoml"
        },
        {
            "id": 2205,
            "key": "_mollie_paid_and_processed",
            "value": "1"
        },
        {
            "id": 2194,
            "key": "_mollie_payment_id",
            "value": "tr_bh3fYpRHqi"
        },
        {
            "id": 2197,
            "key": "_mollie_payment_instructions",
            "value": "Payment completed by <strong>T. TEST<\/strong> (IBAN (last 4 digits): 4588, BIC: NNBANL2G)"
        },
        {
            "id": 2195,
            "key": "_mollie_payment_mode",
            "value": "test"
        },
        {
            "id": 2165,
            "key": "_shipping_house_number",
            "value": "1"
        },
        {
            "id": 2166,
            "key": "_shipping_house_number_suffix",
            "value": "Torensteeg"
        },
        {
            "id": 2167,
            "key": "_shipping_street_name",
            "value": "Torensteeg"
        },
        {
            "id": 2180,
            "key": "_thwcfe_disabled_fields",
            "value": "shipping_company,ziekenhuis,afdeling,verdieping,kamer"
        },
        {
            "id": 2179,
            "key": "_thwcfe_ship_to_billing",
            "value": "0"
        },
        {
            "id": 2200,
            "key": "_wcpdf_invoice_creation_trigger",
            "value": "email_attachment"
        },
        {
            "id": 2201,
            "key": "_wcpdf_invoice_date",
            "value": "1708257328"
        },
        {
            "id": 2202,
            "key": "_wcpdf_invoice_date_formatted",
            "value": "202

4-02-18 12:55:28"
        },
        {
            "id": 2199,
            "key": "_wcpdf_invoice_display_date",
            "value": "order_date"
        },
        {
            "id": 2203,
            "key": "_wcpdf_invoice_number",
            "value": "50"
        },
        {
            "id": 2204,
            "key": "_wcpdf_invoice_number_data",
            "value": {
                "number": 50,
                "formatted_number": "50",
                "prefix": "",
                "suffix": "",
                "document_type": "invoice",
                "order_id": 11402,
                "padding": ""
            }
        },
        {
            "id": 2198,
            "key": "_wcpdf_invoice_settings",
            "value": {
                "display_shipping_address": "always",
                "display_email": "1",
                "display_phone": "1",
                "display_customer_notes": "1",
                "display_date": "order_date",
                "due_date": "",
                "display_number": "invoice_number",
                "header_logo": "",
                "header_logo_height": "1cm",
                "vat_number": {
                    "default": ""
                },
                "coc_number": {
                    "default": "67599389"
                },
                "shop_name": {
                    "default": "SITEAURL.nl"
                },
                "shop_address": {
                    "default": "Nieuwe Langeweg 123\r\n3194 DC Hoogvliet"
                },
                "footer": {
                    "default": ""
                },
                "extra_1": {
                    "default": ""
                },
                "extra_2": {
                    "default": ""
                },
                "extra_3": {
                    "default": ""
                }
            }
        },
        {
            "id": 2192,
            "key": "_wc_order_attribution_device_type",
            "value": "Desktop"
        },
        {
            "id": 2183,
            "key": "_wc_order_attribution_referrer",
            "value": "https:\/\/www.mollie.com\/"
        },
        {
            "id": 2190,
            "key": "_wc_order_attribution_session_count",
            "value": "4"
        },
        {
            "id": 2187,
            "key": "_wc_order_attribution_session_entry",
            "value": "https:\/\/www.SITEAURL.nl\/afrekenen\/order-received\/11400\/?key=wc_order_ry9J7sDPtetxJ&utm_nooverride=1"
        },
        {
            "id": 2189,
            "key": "_wc_order_attribution_session_pages",
            "value": "4"
        },
        {
            "id": 2188,
            "key": "_wc_order_attribution_session_start_time",
            "value": "2024-02-16 20:23:53"
        },
        {
            "id": 2182,
            "key": "_wc_order_attribution_source_type",
            "value": "referral"
        },
        {
            "id": 2191,
            "key": "_wc_order_attribution_user_agent",
            "value": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/121.0.0.0 Safari\/537.36"
        },
        {
            "id": 2186,
            "key": "_wc_order_attribution_utm_content",
            "value": "\/"
        },
        {
            "id": 2185,
            "key": "_wc_order_attribution_utm_medium",
            "value": "referral"
        },
        {
            "id": 2184,
            "key": "_wc_order_attribution_utm_source",
            "value": "mollie.com"
        }
    ],
    "line_items": [
        {
            "id": 112,
            "name": "baby boy",
            "product_id": 10221,
            "variation_id": 0,
            "quantity": 1,
            "tax_class": "",
            "subtotal": "13.95",
            "subtotal_tax": "0.00",
            "total": "13.95",
            "total_tax": "0.00",
            "taxes": [],
            "meta_data": [
                {
                    "id": 1060,
                    "key": "_tmdata",
                    "value": [
                        {
                            "tmcp_post_fields": {
                                "tmcp_select_0": ""
                            },
                            "product_id": 10221,
                            "per_product_pricing": true,
                            "cpf_product_price": "13.95",
                            "variation_id": false,
                            "form_prefix": "",
                            "tc_added_in_currency": "EUR",
                            "tc_default_currency": "EUR"
                        }
                    ],
                    "display_key": "_tmdata",
                    "display_value": [
                        {
                            "tmcp_post_fields": {
                                "tmcp_select_0": ""
                            },
                            "product_id": 10221,
                            "per_product_pricing": true,
                            "cpf_product_price": "13.95",
                            "variation_id": false,
                            "form_prefix": "",
                            "tc_added_in_currency": "EUR",
                            "tc_default_currency": "EUR"
                        }
                    ]
                },
                {
                    "id": 1061,
                    "key": "_tmpost_data",
                    "value": [
                        {
                            "tm-epo-counter": "1",
                            "tcaddtocart": "10221",
                            "tmcp_select_0": "",
                            "cpf_product_price": "13.95",
                            "tc_form_prefix": "",
                            "quantity": "1",
                            "wd-add-to-cart": "10221"
                        }
                    ],
                    "display_key": "_tmpost_data",
                    "display_value": [
                        {
                            "tm-epo-counter": "1",
                            "tcaddtocart": "10221",
                            "tmcp_select_0": "",
                            "cpf_product_price": "13.95",
                            "tc_form_prefix": "",
                            "quantity": "1",
                            "wd-add-to-cart": "10221"
                        }
                    ]
                },
                {
                    "id": 1062,
                    "key": "_alg_ean",
                    "value": "071444879996",
                    "display_key": "EAN",
                    "display_value": "071444879996"
                },
                {
                    "id": 1069,
                    "key": "_reduced_stock",
                    "value": "1",
                    "display_key": "_reduced_stock",
                    "display_value": "1"
                }
            ],
            "sku": "16affd24bacf",
            "price": 13.95,
            "image": {
                "id": "9963",
                "src": "https:\/\/www.SITEAURL.nl\/wp-content\/uploads\/2023\/12\/geboorte-1.png"
            },
            "parent_name": null
        }
    ],
    "tax_lines": [],
    "shipping_lines": [


        {
            "id": 113,
            "method_title": "Verzendkosten",
            "method_id": "flat_rate",
            "instance_id": "1",
            "total": "5.95",
            "total_tax": "0.00",
            "taxes": [],
            "meta_data": [
                {
                    "id": 1068,
                    "key": "Artikelen",
                    "value": "baby boy &times; 1",
                    "display_key": "Artikelen",
                    "display_value": "baby boy &times; 1"
                }
            ]
        }
    ],
    "fee_lines": [],
    "coupon_lines": [],
    "refunds": [],
    "payment_url": "https:\/\/www.SITEAURL.nl\/afrekenen\/order-pay\/11402\/?pay_for_order=true&key=wc_order_RJdTCaxIsyefI",
    "is_editable": false,
    "needs_payment": false,
    "needs_processing": true,
    "date_created_gmt": "2024-02-18T11:55:28",
    "date_modified_gmt": "2024-02-18T11:55:44",
    "date_completed_gmt": null,
    "date_paid_gmt": "2024-02-18T11:55:38",
    "iconic_delivery_meta": {
        "date": "19\/02\/2024",
        "time": "08:00 - 17:00",
        "timeslot_id": "0|0.00",
        "timestamp": "1708326000",
        "ymd": "20240219",
        "override_rules": "",
        "shipping_method": "flat_rate:1"
    },
    "currency_symbol": "\u20ac",
    "_links": {
        "self": [
            {
                "href": "https:\/\/www.SITEAURL.nl\/wp-json\/wc\/v3\/orders\/11402"
            }
        ],
        "collection": [
            {
                "href": "https:\/\/www.SITEAURL.nl\/wp-json\/wc\/v3\/orders"
            }
        ],
        "customer": [
            {
                "href": "https:\/\/www.SITEAURL.nl\/wp-json\/wc\/v3\/customers\/7"
            }
        ]
    }
}
0

There are 0 best solutions below