Magento 2 API: Add Products to Cart & Checkout Place Order
This guide explains how to use Magento 2 APIs to add products to a cart and place an order programmatically. It includes example requests, responses, and payloads.
For more details, visit the official Magento 2 API Documentation.
Step 1: Create a Customer Token
Authenticate the user to retrieve a customer token for further API calls.
Request
POST /rest/V1/integration/customer/token
Headers:
- Content-Type: application/json
Body:
{ "username": "[email protected]", "password": "customer_password" }
Response
{ "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1..." }
Step 2: Create a Cart
Create a new cart (quote) for the customer using the customer token.
Request
POST /rest/V1/carts/mine
Headers:
- Authorization: Bearer {customer_token}
- Content-Type: application/json
Response
1234 // Cart ID
Step 3: Add a Product to the Cart
Add a product to the cart by specifying the product details and the cart ID.
Request
POST /rest/V1/carts/mine/items
Headers:
- Authorization: Bearer {customer_token}
- Content-Type: application/json
Body:
{ "cartItem": { "sku": "product-sku", "qty": 1, "quote_id": "1234" } }
Response
{ "item_id": 1, "sku": "product-sku", "qty": 1, "name": "Product Name", "price": 100, "quote_id": "1234" }
Step 4: Set Shipping Information
Provide shipping address and carrier information for the cart.
Request
POST /rest/V1/carts/mine/shipping-information
Headers:
- Authorization: Bearer {customer_token}
- Content-Type: application/json
Body:
{ "addressInformation": { "shipping_address": { "region": "California", "region_id": 12, "country_id": "US", "street": ["123 Main St"], "telephone": "1234567890", "postcode": "90001", "city": "Los Angeles", "firstname": "John", "lastname": "Doe", "email": "[email protected]" }, "billing_address": { "region": "California", "region_id": 12, "country_id": "US", "street": ["123 Main St"], "telephone": "1234567890", "postcode": "90001", "city": "Los Angeles", "firstname": "John", "lastname": "Doe", "email": "[email protected]" }, "shipping_carrier_code": "flatrate", "shipping_method_code": "flatrate" } }
Response
{ "payment_methods": [ { "code": "checkmo", "title": "Check / Money order" } ] }
Step 5: Place the Order
Finalize the order by providing payment method details.
Request
POST /rest/V1/carts/mine/payment-information
Headers:
- Authorization: Bearer {customer_token}
- Content-Type: application/json
Body:
{ "paymentMethod": { "method": "checkmo" }, "billing_address": { "region": "California", "region_id": 12, "country_id": "US", "street": ["123 Main St"], "telephone": "1234567890", "postcode": "90001", "city": "Los Angeles", "firstname": "John", "lastname": "Doe", "email": "[email protected]" } }
Response
{ "order_id": 1001 }
Conclusion
Using the Magento 2 REST APIs outlined above, you can programmatically add products to the cart and complete the checkout process. For additional details, visit the Magento 2 API Documentation.