Skip to content

Order Processing with REST API on MSI

Tomash Khamlai edited this page Jun 18, 2018 · 40 revisions

Order Processing with REST API on MSI

This is the simplest example of Order Processing that takes into account all the new features that are specific for Multi-Source Inventory. This step-by-step guide is written in the form of a tutorial.

Before you begin

Each step in this tutorial provides the following information:

Endpoint
This section lists the HTTP verb and full path to the endpoint. The basic structure of a REST call in Magento is
<HTTP verb> http://<host>/rest/<scope>/<endpoint>
where:

Element Description
HTTP verb One of GET, POST, PUT, or DELETE
host The hostname or IP address (and optionally, port) of the Magento installation.
scope Specifies which store the call affects. In this tutorial, this value is default.
endpoint The full URI (Uniform Resource Identifier) to the endpoint. These values always start with /V1. For example, /V1/orders/4.

HTTP headers
This section indicates which key/value pairs you must specify in the HTTP headers. All calls require one or more HTTP headers.

Payload
This section lists the information that is sent to Magento. All payload samples are valid and can be copied and pasted into your calls, but you might need to change the id values that Magento returns.

Response
This section lists the information that Magento sends to the REST client. These values are often referenced in other steps in the tutorial. The values Magento returns might be different than the values listed in the examples provided in this tutorial.

Complete cURL request sample This section contains the code that can be copied and pasted to UNIX-like console emulator (Bourne Shell for example) with cURL support. The information that should be modified by the user will be enclosed between angle brackets. Example:

endpoint="http://<host>/rest"
curl -X GET "$endpoint/V1/directory/countries" \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer $admin_token" | json_pp | grep -in -B3 -A3 "United States"

where:

  • endpoint is a temporary variable set to Bourne Shell environment. You have access to it only during this terminal session. It is not reachable in other tab or window or if the terminal is reopened.
  • <host> is the Magento Base URL
  • json_pp is the prettifier (only humans need it)
  • grep is used for search and highlighting information

Complete these prerequisites

Step 1. Get the admin token

Most REST calls to Magento require an authorization token. The token allows Magento to verify that the caller is authorized to access a system resource. To get a token, you must specify the user’s username and password in the payload.

By default, an admin token is valid for 4 hours. To change this value, log in to Admin and go to Configuration > Services > OAuth > Access Token Expiration.

See Token-based authentication for more information about authorization tokens.

Endpoint
POST http://<host>/rest/default/V1/integration/admin/token

Headers
Content-Type application/json
Authorization: Bearer <admin_token>

Payload
{ "username": "<admin username>", "password": "<admin password>" }

Response
Magento returns the admin’s access token.
5r8cvmpr11j6gmau8990rcj2qk7unh8i

This token must be specified in the authorization header of every call that requires admin permissions. This token is not displayed in Admin.

Complete cURL request sample

endpoint="http://<host>/rest"
username="<admin username>"
password="<admin password>"
admin_token=$(curl -X POST "$endpoint/V1/integration/admin/token" \
 -H "Content-Type: application/json" \
 -d '{"username":"'"$username"'","password":"'"$password"'"}') && echo $admin_token && admin_token=$(echo $admin_token | tr -d '"')

Step 2. Configure the store

If your Magento MSI was successfully deployed, it doesn't mean that now you can enjoy all the benefits of the Multi-Source Inventory functionality. By default, Magento MSI is configured to use Single Stock Mode. This configuration doesn't differ much from usual Magento Open Source. The most recognizable difference of Magento MSI in Single Stock Mode is Salable Quantity. The main goal of this tutorial is to show Magento MSI working with different Sources, Stocks and Sales Channels.

The Default store needs additional configuration to run the REST calls mentioned in this tutorial.

Create additional Source

The name, source_code, country_id, and postcode attributes are required.

Endpoint
POST http://<host>/rest/all/V1/inventory/sources

Headers
Content-Type application/json
Authorization: Bearer <admin_token>

Payload

{
   "source" : {
      "description" : " Source #17",
      "source_code" : "txspeqs",
      "phone" : "(555) 555-5555",
      "email" : "[email protected]",
      "postcode" : "77010",
      "longitude" : -95.383056,
      "enabled" : true,
      "contact_name" : "Ethan Carter",
      "latitude" : 29.762778,
      "region_id" : 57,
      "region" : "Texas",
      "name" : "Texas Sport Equipment Source #017",
      "country_id" : "US",
      "city" : "Houston"
   }
}

Response
Magento returns an empty array.
[]

Complete cURL request

source_code_2="txspeqs" && curl -X POST "$endpoint/V1/inventory/sources" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $admin_token" \
-d '{"source":{"source_code":"'"$source_code_2"'","name":"Texas Sport Equipment Source #017","email":"[email protected]","contact_name":"Ethan Carter","enabled":true,"description":" Source #17","latitude":29.762778,"longitude":-95.383056,"country_id":"US","region_id":57,"region":"Texas","city":"Houston","postcode":"77010","phone":"(555) 555-5555"}}'

You can also Create a Source from Admin.

Create additional Stock

Endpoint
POST http://<host>/rest/all/V1/inventory/stocks

Headers
Content-Type application/json
Authorization: Bearer <admin_token>

Payload

{
   "stock" : {
      "name" : "Stock 2"
   }
}

Response
Magento returns the stock_id, which is an integer: 2

Complete cURL request

stock_name_2="Stock 2" && stock_id_2=$(curl -X POST "$endpoint/all/V1/inventory/stocks" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $admin_token" \
-d '{"stock":{"name":"'"$stock_name_2"'"}}') && echo $stock_id_2

Assign Source to Stock

To assign a source to a stock, you must specify a source_code, stock_id, and priority. The priority value indicates where the stock ranks in the list of stocks that can be used for fulfilling orders.

Endpoint
POST http://<host>/rest/all/V1/inventory/stock-source-links

Headers
Content-Type application/json
Authorization: Bearer <admin_token>

Payload

{
   "links" : [
      {
         "source_code" : "txspeqs",
         "stock_id" : "2",
         "priority" : 1
      }
   ]
}

Response
Magento returns empty array.
[]

Complete cURL request

curl -X POST "$endpoint/all/V1/inventory/stock-source-links" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $admin_token" \
-d '{"links":[{"stock_id": "'"$stock_id_2"'","source_code":"'"$source_code_2"'","priority":1}]}'

Reindex and flush cache

After you have assigned a source to stock, use the following command to perform a full reindex and flush the cache.

php bin/magento indexer:reindex && php bin/magento cache:flush

Create another Website

The purpose of this step is to demonstrate the meaning of Sales Channels.
Unfortunately, we can not create a Website using Web API so if you haven't created an additional website then go ahead and create one. Later we will show you how to turn things back and work with only one website. Log in to Admin and select Stores > Settings > All Stores and click Create Website button. Also, create Store and Store View.

Verify this step To follow this tutorial check that you have the same codes website, store and storeview as in the table below.

Web Site Store Store View
Main Website (Code: base) Main Website Store (Code: main_website_store) Default Store View (Code: default)
Test Website (Code: additional) Test Website Store (Code: test_website_store) Test Store View (Code: test)

Make Test Website to be the Sales Channel for Stock 2.

Endpoint
PUT http://<host>/rest/all/V1/inventory/stocks/2

Headers
Content-Type application/json
Authorization: Bearer <admin_token>

Payload

{
  "stock": {
    "stock_id": 2,
    "name": "Stock 2",
    "extension_attributes": {
      "sales_channels": [
        {
          "type": "website",
          "code": "test"
        }
      ]
    }
  }
}

Response

Complete cURL request

curl -X PUT "$endpoint/all/V1/inventory/stocks/$stock_id_2" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $admin_token" \
-d '{"stock":{"stock_id":"'"$stock_id_2"'","name":"'"$stock_name_2"'","extension_attributes":{"sales_channels":[{"type":"website","code":"test"}]}}}'

Set the payment method

Payment type Configuration name Enabled by default?
Check/Money Order checkmo Yes
Bank Transfer Payment banktransfer No
Cash on Delivery cashondelivery No
Purchase Order purchaseorder No
Zero Subtotal Checkout free No

Magento default configuration is not configured to handle credit card payments out from the box. If you want to change which offline payments (or any other online payment method) are configured as a payment method, log in to Admin and select Stores > Configuration > Sales > Payment Methods. Then enable the payment method and click Save.

Configure supported shipping methods (optional)

Shipping type Configuration name Enabled by default?
Flat rate flatrate Yes
Table rate tablerate Yes
Free shipping freeshipping No

If you want to change which offline shipping methods are available, select Stores > Configuration > Sales > Shipping Methods in Admin. Enable or disable the shipping methods as desired, then click Save. Upon clicking Save, a notification message states that the cache needs to be refreshed. Click the Cache Management link to refresh the cache.

Step 3. Create a customer

In this step, we assume that you started our tutorial with fresh Magento installation, otherwise you should check whether you have the same store_id and website_idas we have or replace with your values in the payload. Endpoint
POST http://<host>/rest/test/V1/customers

Headers
Content-Type application/json
Authorization: Bearer <admin_token>

Payload

{
   "customer" : {
      "store_id" : 2,
      "website_id" : 2,
      "lastname" : "Doe",
      "firstname" : "Jane",
      "email" : "[email protected]",
      "addresses" : [
         {
            "defaultBilling" : true,
            "defaultShipping" : true,
            "firstname" : "Jane",
            "lastname" : "Doe",
            "region" : {
               "regionCode" : "NY",
               "regionId" : 43,
               "region" : "New York"
            },
            "countryId" : "US",
            "postcode" : "10755",
            "city" : "Purchase",
            "street" : [
               "123 Oak Ave"
            ],
            "telephone" : "512-555-1111"
         }
      ]
   },
   "password" : "Password1"
}

Response
Magento assigned this user id value of 1.

Complete cURL request

store_id=2 && website_id=2 && store_view_code="test" && curl -X POST $endpoint/$store_view_code/V1/customers \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $admin_token" \
-d '{"customer":{"store_id":2,"website_id":2,"lastname":"Doe","firstname":"Jane","email":"[email protected]","addresses":[{"defaultBilling":true,"defaultShipping":true,"firstname":"Jane","lastname":"Doe","region":{"regionCode":"NY","regionId":43,"region":"New York"},"countryId":"US","postcode":"10755","city":"Purchase","street":["123 Oak Ave"],"telephone":"512-555-1111"}]},"password":"Password1"}' | json_pp

Step 4. Get the customer token

To get a customer token, you must specify the user’s username and password in the payload.

Endpoint
POST http://<host>/rest/default/V1/integration/customer/token

Headers
Content-Type application/json

Payload

{
"username": "[email protected]",
"password": "Password1"
}

Response
Magento returns the customer's access token.
8mu1d2tm0pqojd2vp7fy0mpa3uqv5p2q

Complete cURL request sample

customer_token=$(curl -X POST "$endpoint/$store_view_code/V1/integration/customer/token" \
 -H "Content-Type: application/json" \
 -d '{"username":"[email protected]","password":"Password1"}') && echo $customer_token $ && customer_token=$(echo $customer_token | tr -d '"')

Step 5. Create a quote

Endpoint
POST http://<host>/rest/default/V1/carts/mine

Headers
Content-Type application/json Authorization Bearer <customer token>

Payload
None

Response The response is the 1

Complete cURL request sample

curl -X POST "$endpoint/default/V1/carts/mine" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $customer_token"

Step 6. Add items to the cart

This article shows how to add a simple product, a configurable product, a downloadable product and a virtual product to the cart. Magento MSI has no full support for bundle product and grouped product until these issues are not resolved:
#458
#459
There are also some known bugs with products of this type in Multi-Stock Mode when products are assigned to non-default stock.

Add a simple product to a cart

To add a simple product to a cart, you must provide SKU, the quantity, and the quote ID, which was generated when the cart was created. But first, you need to have the product in the inventory. If you already have one then copy and modify payload to fulfil the requirements otherwise we assume that you followed these instructions to Create a simple product with REST API on MSI. The following example adds a Simple Product MSM 1 to the cart.

Add a configurable product to a cart

To add a configurable product to a cart, you must provide SKU, the quantity, ..., and the quote ID, which was generated when the cart was created. But first, you need to have the product in the inventory. If you already have one then copy and modify payload to fulfil the requirements otherwise we assume that you followed these instructions to Create a configurable product with REST API on MSI. The following example adds a Configurable Product MSM 1 to the cart.

Add a downloadable product to a cart

To add a downloadable product to a cart, you must provide SKU, ..., and the quote ID, which was generated when the cart was created. But first, you need to have the product in the inventory. If you already have one then copy and modify payload to fulfil the requirements otherwise we assume that you followed these instructions to Create a downloadable product with REST API on MSI. The following example adds a Downloadable Product MSM 1 to the cart.

Add a virtual product to a cart

To add a virtual product to a cart, you must provide SKU, ..., and the quote ID, which was generated when the cart was created. But first, you need to have the product in the inventory. If you already have one then copy and modify payload to fulfil the requirements otherwise we assume that you followed these instructions to Create a virtual product with REST API on MSI. The following example adds a Virtual Product MSM 1 to the cart.

Step 7. Prepare for checkout

Step 8. Create an order

Step 9. Create an invoice

Step 10. Create a shipment

Step 11. Issue a partial refund

MSI Documentation:

  1. Technical Vision. Catalog Inventory
  2. Installation Guide
  3. List of Inventory APIs and their legacy analogs
  4. MSI Roadmap
  5. Known Issues in Order Lifecycle
  6. MSI User Guide
  7. DevDocs Documentation
  8. User Stories
  9. User Scenarios:
  10. Technical Designs:
  11. Admin UI
  12. MFTF Extension Tests
  13. Weekly MSI Demos
  14. Tutorials
Clone this wiki locally