Magento 2 Cart to Order programmatically

1 minute read

Due to errors in custom code, sometimes Magento fails to create an order. If the payment had been taken and confirmed in the payment gateway, it would be a waste to having to refund this payment, because the order is not showing up in the Magento admin. The order items are still in the database and the customer’s cart is still keeping the items.

This is what happened on my wife’s store recently, when a recent sales_order_save_after observer thrown an exception. The payment was taken, but there was no order in the Magento admin.

I’m showing a quick solution here to convert any cart in Magento 2 to an actual order. We will get an authentication token for the REST API using curl, then we will use the REST API to create an order.

To get the token, execute the following command, replacing the username and password to an existing admin user:

curl -X POST "https://my-magento-store.tld/index.php/rest/V1/integration/admin/token" \
     -H "Content-Type:application/json" \
     -d '{"username":"my username", "password":"my password"}'

This will return with a token and the console will display it. Put this token into the $access_token variable in the script below.

To get the $cartId, open the database, get the entity_id from the quote table, then run the following query:

SELECT masked_id
FROM quote_id_mask WHERE entity_id=4001;

Where 4001 was my entity_id from the quote table. The returned masked_id is your $cartId to use.


$access_token = "klljn51gnadeqo5vwgn3l4szz64avfnj";

$cartId = "HeSn74ZlTHGED1NH3LX7e6DrGemS"; // From quote_id_mask
$url = 'https://my-magento-store.tld/index.php/rest/V1/guest-carts/'. $cartId . '/order';

$body = json_encode([
   "paymentMethod" => [ 
       "method" => "checkmo"

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));

$result = curl_exec($ch);