Skip to content

Magento 2: Create order programmatically using carrier containing underscore (PostNL)

I am unable to create an order programmatically with the carrier PostNL. The carrier code is “tig_postnl” and the method “regular”. Normally I set the shipping address simply using:

$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('freeshipping_freeshipping');

(for full code please see example: https://webkul.com/blog/create-quote-and-order-programmatically-in-magento2/)

Magento explodes the method on the underscore into carrier “freeshipping” and method “freeshipping”. However, our carrier “tig_postnl” already contains an underscore which causes the carrier to being “tig” and method “postnl”.

$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('tig_postnl_regular');

As a result, Magento returns an error saying the shipping method for the quote has not been set.
Just to make sure, I verified the carrier and method by placing an order using the REST API. The API lets me split them and this works as expected (order & shipment placed succesfully):

URL: https://HOST/rest/V1/guest-carts/QUOTE_ID/shipping-information
BODY:
"addressInformation": {
    shippingAddress": {
        "sameAsBilling": 1,
        ...
    },
    "billingAddress": {
        ...
    },
    "shipping_method_code": "regular",
    "shipping_carrier_code": "tig_postnl"
}

It is probably not allowed/expected by Magento to use an underscore in the carrier name, but I cannot change this. A lot of other modules depend on this specific module “tig_postnl”, so I cannot simply change the carrier name.

Basic question: How I can create an order programmatically in a custom module, using PostNL as the shipping method?

Thanks for any thoughts in advance!