Magento 2 Get Product Total, Subtotal, Coupon, Tax Details Via REST API

Often when we create an application, we have to get all the data of the customers via cart totals API so that we can successfully make the payment to the customer by counting the total at checkout correctly.

In this post, I will tell you how to get the total of customer's cart items how you can get all data through Magento rest api.

First of all, you add the item to the cart, after that you will get the details of all the products added to that cart through the endpoint given below.

Now you will not see subtotals, coupons discounts, tax details, etc in the cart details. For this, we have to follow other Rest API.

 

Step 1: Get Cart Items Details Via Cart Totals API

Method: GET

Endpoint:

https://wishusucess.com/rest/V1/carts/mine/

Payload: Not required

customer Cart products in Magento 2 Api

Response:

{

"id": 133,

"created_at": "2021-12-06 12:37:31",

"updated_at": "2021-12-08 08:57:31",

"is_active": true,

"is_virtual": false,

"items": [

{

"item_id": 283,

"sku": "test-product-3",

"qty": 1,

"name": "test-product-3",

"price": 3,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/1/_/1_1_2.png"

}

},

{

"item_id": 284,

"sku": "test-product-4",

"qty": 1,

"name": "test-product-4",

"price": 5,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/1/_/1_5.jpg"

}

},

{

"item_id": 285,

"sku": "Chilli Happy 10gm",

"qty": 2,

"name": "Indus Happy Hybrid Chilli seeds 10gm + 10gm - Offer Buy 1 Get 1",

"price": 900,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/2/_/2_7.jpg"

}

},

{

"item_id": 290,

"sku": "Kalichakra – Metarhizium anisopliae",

"qty": 3,

"name": "Kalichakra – Metarhizium anisopliae (Wettable Powder) BioInsecticide (IPL)",

"price": 200,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/k/a/kalichakra_ipl_455x455.jpg"

}

}

],

"items_count": 4,

"items_qty": 7,

"customer": {

"id": 58,

"group_id": 1,

"default_billing": "35",

"default_shipping": "35",

"created_at": "2021-11-29 06:44:25",

"updated_at": "2021-12-06 11:36:53",

"created_in": "Default Store View",

"email": "test@test.test",

"firstname": "Test 11",

"lastname": "Test",

"store_id": 1,

"website_id": 1,

"addresses": [

{

"id": 35,

"customer_id": 58,

"region": {

"region_code": "UP",

"region": "Uttar Pradesh",

"region_id": 566

},

"region_id": 566,

"country_id": "IN",

"street": [

"H-21",

"First Floor",

"Sector 63"

],

"company": "Wishusucess.com ",

"telephone": "+91987654321",

"postcode": "201301",

"city": "Noida",

"firstname": "Test 11",

"lastname": "Test",

"default_shipping": true,

"default_billing": true

}

],

"disable_auto_group_change": 0,

"extension_attributes": {

"is_subscribed": false

},

"custom_attributes": [

{

"attribute_code": "device_token",

"value": "caXHLarRSmqWWq8pXPRJfR:APA91bFYIxmFVF-ouwEKvmIMVV04dXki2o2LOh5ysG9Hk7BA05VqSV491i83LafAFSmCOhVAC8ZRcJVXSH_NNNdOGunSQHIHRSl0rbIbWDypCvLvxLCZZnu74s3dHwaABiIqtXGE9wB2"

},

{

"attribute_code": "is_approved",

"value": "approved"

}

]

},

"billing_address": {

"id": 495,

"region": "Uttar Pradesh",

"region_id": 566,

"region_code": "UP",

"country_id": "IN",

"street": [

"H-21",

"null - First Floor"

],

"telephone": "+9187787888",

"postcode": "201301",

"city": "Noida",

"firstname": "Test 11",

"lastname": "Test",

"customer_id": 58,

"email": "test@test.test",

"same_as_billing": 1,

"save_in_address_book": 0

},

"orig_order_id": 0,

"currency": {

"global_currency_code": "USD",

"base_currency_code": "USD",

"store_currency_code": "USD",

"quote_currency_code": "USD",

"store_to_base_rate": 0,

"store_to_quote_rate": 0,

"base_to_global_rate": 1,

"base_to_quote_rate": 1

},

"customer_is_guest": false,

"customer_note_notify": true,

"customer_tax_class_id": 3,

"store_id": 1,

"extension_attributes": {

"shipping_assignments": [

{

"shipping": {

"address": {

"id": 496,

"region": "Uttar Pradesh",

"region_id": 566,

"region_code": "UP",

"country_id": "IN",

"street": [

"H-21",

"null - First Floor"

],

"telephone": "+9198878898",

"postcode": "201301",

"city": "Noida",

"firstname": "Test 11",

"lastname": "Test",

"customer_id": 58,

"email": "test@test.test",

"same_as_billing": 1,

"save_in_address_book": 0

},

"method": "freeshipping_freeshipping"

},

"items": [

{

"item_id": 283,

"sku": "test-product-3",

"qty": 1,

"name": "test-product-3",

"price": 3,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/1/_/1_1_2.png"

}

},

{

"item_id": 284,

"sku": "test-product-4",

"qty": 1,

"name": "test-product-4",

"price": 5,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/1/_/1_5.jpg"

}

},

{

"item_id": 285,

"sku": "Chilli Happy 10gm",

"qty": 2,

"name": "Indus Happy Hybrid Chilli seeds 10gm + 10gm - Offer Buy 1 Get 1",

"price": 900,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/2/_/2_7.jpg"

}

},

{

"item_id": 290,

"sku": "Kalichakra – Metarhizium anisopliae",

"qty": 3,

"name": "Kalichakra – Metarhizium anisopliae (Wettable Powder) BioInsecticide (IPL)",

"price": 200,

"product_type": "simple",

"quote_id": "133",

"extension_attributes": {

"image": "/k/a/kalichakra_ipl_455x455.jpg"

}

}

]

}

]

}

}

 

Read more: How to Get Image URL in Customer Cart Using RESTb API

Step 2: Magento 2 Cart Totals API

Now, here you have to hit the following endpoint in order to get the total, subtotals, grand totals, discount amount, shipping details, tax detail, etc. via rest API.

Method: GET

Endpoint:

https://wishusucess.com/rest/V1/carts/mine/totals

Payload: Not required

Get Cart Totals APIResponse:

{

"grand_total": 2408,

"base_grand_total": 2408,

"subtotal": 2408,

"base_subtotal": 2408,

"discount_amount": 0,

"base_discount_amount": 0,

"subtotal_with_discount": 2408,

"base_subtotal_with_discount": 2408,

"shipping_amount": 0,

"base_shipping_amount": 0,

"shipping_discount_amount": 0,

"base_shipping_discount_amount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"weee_tax_applied_amount": null,

"shipping_tax_amount": 0,

"base_shipping_tax_amount": 0,

"subtotal_incl_tax": 2408,

"shipping_incl_tax": 0,

"base_shipping_incl_tax": 0,

"base_currency_code": "USD",

"quote_currency_code": "USD",

"items_qty": 7,

"items": [

{

"item_id": 283,

"price": 3,

"base_price": 3,

"qty": 1,

"row_total": 3,

"base_row_total": 3,

"row_total_with_discount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"tax_percent": 0,

"discount_amount": 0,

"base_discount_amount": 0,

"discount_percent": 0,

"price_incl_tax": 3,

"base_price_incl_tax": 3,

"row_total_incl_tax": 3,

"base_row_total_incl_tax": 3,

"options": "[]",

"weee_tax_applied_amount": null,

"weee_tax_applied": null,

"name": "test-product-3"

},

{

"item_id": 284,

"price": 5,

"base_price": 5,

"qty": 1,

"row_total": 5,

"base_row_total": 5,

"row_total_with_discount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"tax_percent": 0,

"discount_amount": 0,

"base_discount_amount": 0,

"discount_percent": 0,

"price_incl_tax": 5,

"base_price_incl_tax": 5,

"row_total_incl_tax": 5,

"base_row_total_incl_tax": 5,

"options": "[]",

"weee_tax_applied_amount": null,

"weee_tax_applied": null,

"name": "test-product-4"

},

{

"item_id": 285,

"price": 900,

"base_price": 900,

"qty": 2,

"row_total": 1800,

"base_row_total": 1800,

"row_total_with_discount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"tax_percent": 0,

"discount_amount": 0,

"base_discount_amount": 0,

"discount_percent": 0,

"price_incl_tax": 900,

"base_price_incl_tax": 900,

"row_total_incl_tax": 1800,

"base_row_total_incl_tax": 1800,

"options": "[]",

"weee_tax_applied_amount": null,

"weee_tax_applied": null,

"name": "Indus Happy Hybrid Chilli seeds 10gm + 10gm - Offer Buy 1 Get 1"

},

{

"item_id": 290,

"price": 200,

"base_price": 200,

"qty": 3,

"row_total": 600,

"base_row_total": 600,

"row_total_with_discount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"tax_percent": 0,

"discount_amount": 0,

"base_discount_amount": 0,

"discount_percent": 0,

"price_incl_tax": 200,

"base_price_incl_tax": 200,

"row_total_incl_tax": 600,

"base_row_total_incl_tax": 600,

"options": "[]",

"weee_tax_applied_amount": null,

"weee_tax_applied": null,

"name": "Kalichakra – Metarhizium anisopliae (Wettable Powder) BioInsecticide (IPL)"

}

],

"total_segments": [

{

"code": "subtotal",

"title": "Subtotal",

"value": 2408

},

{

"code": "shipping",

"title": "Shipping & Handling (Free Shipping - Free)",

"value": 0

},

{

"code": "tax",

"title": "Tax",

"value": 0,

"extension_attributes": {

"tax_grandtotal_details": []

}

},

{

"code": "grand_total",

"title": "Grand Total",

"value": 2408,

"area": "footer"

}

]

}
Similar Posts:

 

As a Magento 2 developer, while creating your store, you have to get much information through APIs such as shopping cart item, subtotal, grand total, billing and shipping address, etc., and all we can be get through the above endpoints.

 

Conclusion of Cart Totals API

By following the above steps you can get detailed data on the cart items of a customer such as subtotal, grand total, and billing & shipping address. Here are four approaches:

  • Get items information of your carts.
  • Get items quantity in the cart and the total products in the cart.
  • Get items total price and grand total price in customer cart.
  • Get the billing and shipping addresses of the customer.

Wishusucess GitHub

Search REST API: How to Find Product in Magento 2 Using REST API

If you also want to provide a product search facility to your customer for your mobile application, then for this the Magento Rest API is being explained in detail below.

I hope this post will be helpful in making the search facility better and more relevant while connecting your Magento store to the mobile application.

How to search products details and their other information with image details are given with the search endpoint.

There is two default endpoint for searching products in Magento 2 store:

  • GET V1/search
  • GET V1/products

Through GET V1/search endpoint, both the registered customers and guest customers can search the product on Magento's store, for that they do not need any admin authentication.

Through the GET V1/products endpoint, we can search the whole store but we need an authentication token to verify the request.

This endpoint has direct access to product data.

 

Read more: List of all Search REST API

 

Search By Name From a Category Magento 2 REST API

As you can see in the below image below that we have searched the product from one category on the basis of name and the detail found is only data from one category.

Method: GET

Endpoint: 

http://wishusucess.com/rest/all/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name&searchCriteria[filter_groups][0][filters][0][value]=%NEMATOFREE%25&searchCriteria[filter_groups][0][filters][0][condition_type]=like&searchCriteria[filter_groups][0][filters][1][field]=name&searchCriteria[filter_groups][0][filters][1][value]=%25Parachute%25&searchCriteria[filter_groups][0][filters][1][condition_type]=like

Payload: Not required

Search REST API Magento 2

 

Search Product By SKU Using REST API

We can also search the store's data on the basis of SKU, for that you can use the below-given method along with payload and endpoint, you will get the product on the basis of SKU search.

Method: GET

Endpoint:

https://wishusucess.com/rest/all/V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=test-product-4&searchCriteria[filter_groups][0][filters][1][field]=sku&searchCriteria[filter_groups][0][filters][1][value]=test-product-3&searchCriteria[filter_groups][0][filters][2][field]=sku&searchCriteria[filter_groups][0][filters][2][value]=test-product-1

Payload: Not required

search product by sku REST API

 

In the above image, you can see the params details, I have given the sku "test-product-1" and we have received all data that belong to the similar sku.

 

Read more:

Payment Method: How to Configure Payment Methods in Magento 2

 

Get Product By Price API Endpoint

Method: GET

Endpoint:

https://wishusucess.com/rest/all/V1/products?searchCriteria[filter_groups][1][filters][0][field]=price&searchCriteria[filter_groups][1][filters][0][value]=10&searchCriteria[filter_groups][1][filters][0][condition_type]=from&searchCriteria[filter_groups][2][filters][0][field]=price&searchCriteria[filter_groups][2][filters][0][value]=100&searchCriteria[filter_groups][2][filters][0][condition_type]=to

Payload: Not required

search by price rest api Magento 2

Here, If you want to search products on the basis of price, then we have to give the price range, the range we can decide from x to y.

 

Similar Post:

Payment Gateways: List of Best Online Payment Method Option in 2022

Payment API: How to Make Payment Through REST API in Magento 2

Payment API: How to Make Payment Through REST API in Magento 2

Nowadays, the mobile application has huge demand so providing the payment option by using mobile needs API to get the details and make payment done.

In this method, you can use the payments Magento 2 REST API to get the details and securely accept mobile payments through the mobile.

Magento 2 has many default payment methods so it depends on the customer-owner how they are going to give the customer experience. You can choose to make enable or disable that payment method.

The use of the PayPal payment method using REST API in Magento 2 can accept credit cards, debit cards to make payments done.

Magento Payment API

Cash On Delivery Payment API Configuration

If you are looking for the cash on delivery method option in Magento 2 then you can enable this payment method from

Admin > Stores > Configuration > Sales > Payment Method

You will see the COD option to enable and disable under other payment methods and set Enabled to Yes.

You can also set payment applicability countries.

 

Read more: How to Add Product in Cart Using REST API in Magento 2

Magento 2 Cash on Delivery REST API

This method allows the business owner to accept payment through the cash on delivery (COD) method from specific countries. Here you can also configure with minimum and maximum order total limits using COD REST API.

Method: GET

Endpoint:

https://wishusucess.com/rest/V1/carts/mine/payment-information

Payload: Not RequiredPayment Method Options in Magento 2Response:

{

"payment_methods": [

{

"code": "checkmo",

"title": "Check / Money order"

},

{

"code": "cashondelivery",

"title": "Cash On Delivery"

},

{

"code": "purchaseorder",

"title": "Purchase Order"

},

{

"code": "razorpay",

"title": "Razorpay"

}

],

"totals": {

"grand_total": 125,

"base_grand_total": 125,

"subtotal": 120,

"base_subtotal": 120,

"discount_amount": 0,

"base_discount_amount": 0,

"subtotal_with_discount": 120,

"base_subtotal_with_discount": 120,

"shipping_amount": 5,

"base_shipping_amount": 5,

"shipping_discount_amount": 0,

"base_shipping_discount_amount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"weee_tax_applied_amount": null,

"shipping_tax_amount": 0,

"base_shipping_tax_amount": 0,

"subtotal_incl_tax": 120,

"shipping_incl_tax": 5,

"base_shipping_incl_tax": 5,

"base_currency_code": "USD",

"quote_currency_code": "USD",

"items_qty": 1,

"items": [

{

"item_id": 289,

"price": 120,

"base_price": 120,

"qty": 1,

"row_total": 120,

"base_row_total": 120,

"row_total_with_discount": 0,

"tax_amount": 0,

"base_tax_amount": 0,

"tax_percent": 0,

"discount_amount": 0,

"base_discount_amount": 0,

"discount_percent": 0,

"price_incl_tax": 120,

"base_price_incl_tax": 120,

"row_total_incl_tax": 120,

"base_row_total_incl_tax": 120,

"options": "[]",

"weee_tax_applied_amount": null,

"weee_tax_applied": null,

"name": "SANJEEVNI®/SANJEEVNI+ Trichoderma wrap Biofungicide (IPL)"

}

],

"total_segments": [

{

"code": "subtotal",

"title": "Subtotal",

"value": 120

},

{

"code": "shipping",

"title": "Shipping & Handling (Flat Rate - Fixed)",

"value": 5

},

{

"code": "tax",

"title": "Tax",

"value": 0,

"extension_attributes": {

"tax_grandtotal_details": []

}

},

{

"code": "grand_total",

"title": "Grand Total",

"value": 125,

"area": "footer"

}

]

}

}

 

Step 2: Make Payment With COD REST API

Now, we got all the available payment methods in Magento 2 websites through the REST API so, In order to complete this payment, we have to send the payment method and the billing address along with it.

Method: POST

Endpoint:

https://wishusucess.com/rest/V1/carts/mine/payment-information

Payload:

{

"paymentMethod": {

"method": "cashondelivery"

},

"billing_address": {

"email": "cs.hemantsinghsparx@gmail.com",

"region": "Uttar Pradesh",

"region_id": 566,

"region_code": "UP",

"country_id": "IN",

"street": ["Noida, Noida"],

"postcode": "201301",

"city": "Noida",

"telephone": "7992293862",

"firstname": "Hemant",

"lastname": "Singh"

}

}

Payment Cash on Delivery

Response: 79

Now we will get the order confirmation response.

 

Other Posts:

Razorpay Payment: Step By Step Guide to Integrate Payment Method

Product Order Payload: How To Order Product Using Magento 2 REST API

Product Order Payload: How To Order Product Using Magento 2 REST API

In this Magento2 article, I am going to explain order flow using Rest API. Here, I am going to show you each step of the Magento 2 product order payload and their endpoint in detail.

It is mostly used for making mobile applications.

When we create a generic android mobile app time it is used to access and communicate data from the Magento 2 website and also used to implement basic features for any kind of mobile application using the Magento shopping framework.

Today there are so many options available to make payment in Magento, whether it is PayPal or Razorpay, or any other payment method when we want to pay it through rest API in the mobile application then usually we face the problem of transaction id or payment id. So this article will help you while Magento 2 payment gateway interaction in a Mobile application using REST API.

 

Step 1: Generate Customer Access Token

In the first step we need to generate the customer access token then only we can move to the next step to add a cart to a customer account.

In the POST request enter your store URL along with this endpoint.

Method: POST

Endpoint: www.wishusucess.com/rest/V1/integration/customer/token

Payload:

{  
"username": "cs.hemantsingh@gmail.com", 
"password": "Addddmin@#123" 
}

customer token creation api

Step 2: Create a Cart - Product Order Payload

Now, in the second step we will create a cart by using Magento 2 REST API, So in order to add items in the cart using rest API will contain the customer’s authorization token in the authorization header.

Method: POST

Endpoint:

https://wishusucess.com/rest/default/V1/carts/mine

Scope: default store view

Headers:

  • Content-Type: application/json
  • Authorization: Bearer n785dukrtbh4dhhuqfvc4aaito60ju1f

add to cart api

 


How to Get Quote ID in Magento 2 REST API

We can get the Quote ID by using rest/default/V1/carts/mine endpoint with the POST method.

Note: Now we have the response and the response quoteId is 119.

How to Check Product Availability?

We can check product availability by using the following rest API in Magento 2.

https://wishusucess.com/rest/default/V1/inventory/get-product-salable-quantity/SKU/2

Now we have ensured by checking the salable quantity that we have enough quantity of products in stock so we can order the potential order.


 

Step 3: Add Products to Cart Using REST API

So, in the third step, we can add products to the cart by using the following details.

Method: POST

Endpoint: 

https://www.wishusucess.com/rest/default/V1/carts/mine/items

Headers:

  • Content-Type: application/json
  • Authorization: Bearer <customer_token>

Payload:

{
"cartItem": {
"sku": "test-product-2",
"qty": 2,
"quote_id": "3"
}
}

rest api for add to cart using quote id

Read More: Add To Cart REST API for All Type of Products

 

Step 4: Get All Payment Information Using API

So, in the fourth step, we can check the list of available payment information to make payment done using API.

Method: GET

Endpoint: 

https://wishusucess.com/rest/V1/carts/mine/payment-information

Headers:

  • Content-Type: application/json
  • Authorization: Bearer <customer_token>

Payload:

  • Not Required

Product Order Payload

So now using the above Magento 2 REST API we can get all available payment methods in Magento 2.

 

Step 5: Save Payment Information and Order

In this step, we will use the post method to save the information and send the payment method type to complete the payment. Then only orders will be created by Magento 2 REST API. After successful order creation customer will receive the response of order confirmation.

Endpoint:

https://wishusucess.com/rest/V1/carts/mine/payment-information

Headers:

  • Content-Type application/json
  • Authorization Bearer ikdvclhbdr8a13473hyf3vdxq9m7ouh2

Payload:

{
"paymentMethod": {
"method": "cashondelivery"
},
"billing_address": {
"email": "cs.hemantsingh@gmail.com",
"region": "Uttar Pradesh",
"region_id": 566,
"region_code": "UP",
"country_id": "IN",
"street": [
"PMO Appartment"
],
"postcode": "201301",
"city": "Noida",
"telephone": "7992293862",
"firstname": "Hemant",
"lastname": "Singh"
}
}

Product Order PayloadResponse: 74


 

Related Article:

Cart Images: Get Product Image in Customer Cart Magento 2 REST API

How to Send Push Notifications on Android Application

Product Alert API: Get Magento 2 Product Alert Using API

Login With Number: Magento 2 Customer Login With Mobile Number

In this article, I am going to explain how to implement Magento 2 login customer via phone number functionality in Magento 2 and onwards version.

As we want to add the customer log-in functionality for the customer login with numbers like phone numbers or mobile numbers with the same fields.

So, in order to achieve this functionality, we have to implement the module.

Customer Login With Number in Magento 2

 

Why Customer Login With Phone Number?

When a customer wants to log in with the email then the customer will be able to log in or if the customer wants to login via their phone number then also that can be login.

Today everyone has a lack of time in this digital era, in such a situation, if we do not provide various facilities to our customers, then our customers will leave us.

That's why keeping in mind our customers, we cannot harass them by filling the registration form again and again.

They should have so much facility that they can log in as they want.

The Magento development company named Wishusucess.com has developed a module that can help your customer to log in via their mobile number or phone number or email id and password.

This module has important features that include Magento store customers can save their number while registration of their account, and they will also have the facilities to log in to their account and update their mobile number or phone number from their My Account section.

 

Features of Customer Log Via Number:

Customers can log in via their email or phone number or mobile number or both.

This customer login via the Mobile number module can be enabled or disabled from the admin panel.

Customers also can save their number while registering or after the registration from the My Account sections dashboard.

Allows customers to change their registered mobile number from their "My Account" section

Admin will have the option in the backend to view and update any customer number or phone number.

While checkout the product order customer also can log in via their mobile number or phone number.

Customer Login Via Mobile Number

Download the Module  From GitHub

Current Product Version - 2.4.x

Supported Framework Version - Magento 2.0.x, 2.1.x, 2.2.x,2.3.x, 2.4.x

Admin > Customers > All Customer > Account Information Magento 2 Customer Login With Number

 

Sorting Products: Magento 2 REST API For Sort By Product on List Page

 

Customer Account Information

However, Navigating into the admin panel

Customers > All Customers and view the list of customers.

You can also directly edit the customer numbers from this dashboard section.Customer Login With Number

Customer Image: Upload Customer Profile Pic Image Module in Magento 2

Customer Attribute: How to Add Custom Customer Attribute in Magento 2

 

Sorting Products: Magento 2 REST API For Sort By Product on List Page

This article will give an idea about how we can filter the product on the list page using Magento 2 REST API. So if you are looking for the sorting products module then this Wishusucess sort by position API helps you to get Sort By List of Options category products list page using Magento 2 Rest API.

Sorting Products REST API

Magento 2 default REST API does not provide this functionality to the users so you have to implement the module to get this product sorted.

There is no core REST API in Magento 2 for the sort by an option list. So, I am going to create a custom REST API in Magento 2o get this functionality on the category page.

 

Step To Create Sorting Products REST API

In order to provide better convenience to our customers on the Magento website, we try to implement many functionalities.

One of them is that we provide the option of sorting product to the customer on the category page or list page.

In this article, we will develop a rest API and through that, we will filter the product of the category page based on its price based on its name based on its position

Wishusucess/SortByPositionsApi/registration.php

Wishusucess/SortByPositionsApi/etc/module.xml

Wishusucess/SortByPositionsApi/etc/di.xml

Wishusucess/SortByPositionsApi/etc/webapi.xml

Wishusucess/SortByPositionsApi/Model/GetSortOrder.php

Wishusucess/SortByPositionsApi/Api/GetSortOrderInterface.php

 

Step 1: Registration of Sort By Positions REST Api

app/code/Wishusucess/SortByPositionsApi/registration.php

<?php
/**
* Category: Wishusucess Sort By Positions REST Api
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_SortByPositionsApi',
__DIR__
);

 

Step 2: SortByPositionsApi Module XML File

app/code/Wishusucess/SortByPositionsApi/etc/module.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess Sort By Positions REST Api
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Wishusucess_SortByPositionsApi" schema_version="0.0.1" setup_version="0.0.1">
</module>
</config>

 

Step 3: Sorting Products Dependency Injection

app/code/Wishusucess/SortByPositionsApi/etc/di.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess Sort By Positions REST Api
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Wishusucess\SortByPositionsApi\Api\GetSortOrderInterface" type="Wishusucess\SortByPositionsApi\Model\GetSortOrder" />
</config>

 

Step 4: Web API Routing of Sorting Products

Here we will decide the route path of our filter product model and how we will use that path to get the filter products.

app/code/Wishusucess/SortByPositionsApi/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess Sort By Positions REST Api
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route url="/V1/getsortorder" method="GET">
<service class="Wishusucess\SortByPositionsApi\Api\GetSortOrderInterface" method="getSortOrderData"/>
<resources>
<resource ref="admin"/>
</resources>
</route>
</routes>

 

Step 5: Create Model Class of Sorting Products

This class decides the sort order data using the getSortOrderData() method and this method will process over the catalog product to filter all products based on the conditions using getAttributeUsedForSortByArray().

app/code/Wishusucess/SortByPositionsApi/Model/GetSortOrder.php

<?php
/**
* Category: Wishusucess Sort By Positions REST Api
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\SortByPositionsApi\Model;

use Wishusucess\SortByPositionsApi\Api\GetSortOrderInterface;

class GetSortOrder implements GetSortOrderInterface {
/**
* @var \Magento\Catalog\Model\Config
*/
private $catalogConfig;

/**
* @var \Magento\Framework\Escaper
*/
private $escaper;

/**
* @param \Magento\Catalog\Model\Config $catalogConfig
* @param \Magento\Framework\Escaper $escaper
*/
public function __construct(
\Magento\Catalog\Model\Config $catalogConfig,
\Magento\Framework\Escaper $escaper
) {
$this->_catalogConfig = $catalogConfig;
$this->escaper = $escaper;
}

/**
* Return array of Sort By List of Options of category products list page
* 
* @return array
*/
public function getSortOrderData() {
$sortOrder = $this->_catalogConfig->getAttributeUsedForSortByArray();
$custom_array = [];
foreach ($sortOrder as $key => $value) {
$custom_array[] = $this->escaper->escapeHtml(__($value));
}
return $custom_array;
}
}

 

Step 6: Call Method of Sorting

app/code/Wishusucess/SortByPositionsApi/Api/GetSortOrderInterface.php

<?php
/**
* Category: Wishusucess Sort By Positions REST Api
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\SortByPositionsApi\Api;

interface GetSortOrderInterface {
/**
* Returns sort order list
*
* @api
* @return array
*/
public function getSortOrderData();
}

 

Now Run Below Command:


php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento cache:clean

php bin/magento cache:flush

 


Suggested Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

Recommended Posts:


Customer Image: Upload Customer Profile Pic Image Module in Magento 2

Customer Attribute: How to Add Custom Customer Attribute in Magento 2

Customer Image: Upload Customer Profile Pic Image Module in Magento 2

This article is all about the Magento 2 customer profile picture option on my account dashboard. I have customized the account dashboard sections and for that, I have created a REST API that will give the option to upload the customer image. So when customers will do the registration then they will see the options to upload picture options for profiles.

Magento 2 customer images upload option

After the registration, you will also see the option to upload customer profiles pictures on the My account dashboard.

As per the Magento 2 default functionality, Magento community editions don’t provide customer profile picture upload and update options so its REST API is also not available by default.

This Wishusucess_CustomerImage extension REST API will give more personalization to customers. This model will play a much better role in giving maximum and better personal experience to your customers.

When we provide this facility to the customer, then the customer likes to stay more on his dashboard, this also increases the customer interaction.

It allows you to upload your picture related to the customer on the screen in front of him and also gives the option to the admin to upload and delete the picture of that customer from the back end.

 

Steps for Magento 2 Customer Profile Picture Option

This module of the picture upload option displays a customer profile picture, and It maintains customer privacy as well.

This REST API of the customer profile picture upload option of the customer allows customers to update their profile images by just uploading another picture on the front end.

Backend Options of This Module

Display Customer profile picture in Customer Grid.

Admin also can upload the customer profile picture or delete the customer profile picture from the customer account section.

Allow Delete/Update picture on the from the customer account section.

Magento 2 Customer Image Upload

 

Step 1: Register Customer Image Module

app/code/Wishusucess/CustomerImage/registration.php

<?php
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_CustomerImage',
__DIR__
);

 

Step 2: Module XML file

app/code/Wishusucess/CustomerImage/etc/module.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_CustomerImage" setup_version="1.0.1" />
</config>

 

Step 3: Dependency Injection File

app/code/Wishusucess/CustomerImage/etc/di.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\CustomerImage\Api\CustomInterface" type="Wishusucess\CustomerImage\Model\Api\Custom"/>
</config>

 

Step 4: Route URL for Customer Profile Picture

app/code/Wishusucess/CustomerImage/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/customerimage/">
<service class="Wishusucess\CustomerImage\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 5: Define Frontend Route ID

app/code/Wishusucess/CustomerImage/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="customerimage" frontName="customerimage">
<module name="Wishusucess_CustomerImage" />
</route>
</router>
</config>

 

Step 6: Consturct Method

This method _construct() will help you to execute our code in a safe way at the start of a class. This method will call automatically when the class is constructed.

app/code/Wishusucess/CustomerImage/Model/Cbackground.php

<?php
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomerImage\Model;
use Magento\Framework\Model\AbstractModel;
class Cbackground extends AbstractModel
{
public function _construct() {
$this->_init('Wishusucess\CustomerImage\Model\Resource\Cbackground');
} 
}

 

Step 7: Initialize Resource Model

app/code/Wishusucess/CustomerImage/Model/Resource/Cbackground.php

<?php 
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomerImage\Model\Resource;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Cbackground extends AbstractDb
{
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
/* Custom Table Name */
$this->_init('customer_entity','entity_id');
}
}

 

Step 8: Execute Targeted Class

app/code/Wishusucess/CustomerImage/Model/Resource/Cbackground/Collection.php

<?php 
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomerImage\Model\Resource\Cbackground;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init('Wishusucess\CustomerImage\Model\Cbackground', 'Wishusucess\CustomerImage\Model\Resource\Cbackground');
}
}

 

Step 9: Store Profile Picture

app/code/Wishusucess/CustomerImage/Model/Api/Custom.php

<?php
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomerImage\Model\Api;

use Psr\Log\LoggerInterface;

class Custom
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $_branddata;

public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Wishusucess\CustomerImage\Model\Cbackground $branddata
) {
$this->resultPageFactory = $resultPageFactory;
$this->_branddata = $branddata;

}

/**
* @inheritdoc
*/

public function getPost($customerid)
{
$response = ['success' => false];

try {
$result= $this->_branddata->getCollection()->getData();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeurll=$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);


foreach( $result as $key=>$values)
{
if($values['entity_id']==$customerid)
{
$finaldata=$storeurll."media/sk_profile_pic/".$values['sk_profile_pic'];
}

}
$response=$finaldata;

} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 10: Controller Class of Customer Image

Now we have to create a custom controller class for customer profile images that need to process over the model and corporate with other classes.

app/code/Wishusucess/CustomerImage/Controller/Index/Index.php

<?php
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomerImage\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;

public function __construct(
\Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory 
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);


}
public function execute() {
$model = $this->_objectManager->create('Wishusucess\CustomerImage\Model\Cbackground'); 
$test = $model->load(45);
$array = $test->getCollection()->getData(); 
// var_dump($test->getCollection()->getData());
// echo "<pre>";
// print_r($test->getCollection()->getData()); 
// print_r(json_encode($test->getCollection()->getData()));

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeurll=$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);

echo "<pre>";
foreach( $array as $key=>$values)
{
if($values['entity_id']==45)
{
echo $storeurll."media/sk_profile_pic/".$values['sk_profile_pic'];
}
}
die();
}
}

 

Step 11: CustomInterface GET for Post API

app/code/Wishusucess/CustomerImage/Api/CustomInterface.php

<?php
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomerImage\Api;

interface CustomInterface
{
/**
* GET for Post api
* @return boolean|array
* @param string $customerId customer id.
* 
*/

public function getPost($customerid);
}

 

Step 12: Call Method To Execacute Your Code

app/code/Wishusucess/CustomerImage/Api/Custom.php

<?php
/**
* Category: Wishusucess_CustomerImage
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\CustomApi\Model\Api;

use Psr\Log\LoggerInterface;

class Custom
{
protected $logger;

public function __construct(
LoggerInterface $logger
)
{

$this->logger = $logger;
}

/**
* @inheritdoc
*/

public function getPost($value)
{
$response = ['success' => false];

try {
// Your Code here

$response = ['success' => true, 'message' => $value];
} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
$this->logger->info($e->getMessage());
}
$returnArray = json_encode($response);
return $returnArray; 
}
}

 

Now Run Below Command:

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento cache:clean

php bin/magento cache:flush

Magento 2 Customer Profile Pic

Check on GitHub

Key Features of Customer Image Upload Module:

This module gives you the option to upload customer profile images on the front end.

Customers can change the image multiple times.

This will display the customer profile images on the Customer Account dashboard.

 

Suggested Post:

Customer Attribute: How to Add Custom Customer Attribute in Magento 2

Cart Images: Get Product Image in Customer Cart Magento 2 REST API

How to Send Push Notifications on Android Application

 

Get Order API: Magento 2 Get Customer Order And Details Using API

I am creating a Magento 2 customer REST API module to get customer orders API using this web API route URL( get order API ).

So in order to get the order details first, we need to get the admin access token then we can add that tokens in the API header then we have to call order API with passing that AccessToken.

Get Order API in Magento 2

 

Create Custom Customer Orders API

I want to show here to get customer orders using Magento 2 REST API. This custom module will help you to get the customer's order in Magento 2.

In order to create a custom Magento 2 extension for customer REST  API, you have to create some basic files.

Here, I am creating a Model, Controller, and API component of the customer REST API.

app/code/Wishusucess/GetOrders/registration.php

app/code/Wishusucess/GetOrders/etc/module.xml

app/code/Wishusucess/GetOrders/etc/di.xml

app/code/Wishusucess/GetOrders/etc/webapi.xml

app/code/Wishusucess/GetOrders/frontend/routes.xml

app/code/Wishusucess/GetOrders/Model/Api/Custom.php

app/code/Wishusucess/GetOrders/Controller/Index/Index.php

app/code/Wishusucess/GetOrders/Api/CustomInterface.php

 

Step 1: Registration of Getting Order API

app/code/Wishusucess/GetOrders/registration.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_GetOrders',
__DIR__
);

 

Step 2: Create Module XML File

app/code/Wishusucess/GetOrders/etc/module.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_GetOrders" setup_version="1.1.4" />
</config>

 

Step 3: Define Dependency Injection

app/code/Wishusucess/GetOrders/etc/di.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\GetOrders\Api\CustomInterface" type="Wishusucess\GetOrders\Model\Api\Custom"/>
</config>

 

Step 4: Create Web API XML for Route URL

Now, we have to decide the method and route URL to get access to the other websites. The method will decide to perform the operation over the API request and the URL will decide /V1/wishusucess/getorders/ how we can get access the details.

app/code/Wishusucess/GetOrders/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/getorders/">
<service class="Wishusucess\GetOrders\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 5: Route ID

app/code/Wishusucess/GetOrders/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="wishusucess" frontName="wishusucess">
<module name="Wishusucess_GetOrders" />
</route>
</router>
</config>

 

Step 6: Custom API Model for Getting Order

app/code/Wishusucess/GetOrders/Model/Api/Custom.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\GetOrders\Model\Api;

use Psr\Log\LoggerInterface;

class Custom 
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $orderRepository;


public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->orderRepository = $orderRepository;

}

/**
* @inheritdoc
*/

public function getPost($orderid)
{
$response = ['success' => false];

try {
$order = $this->orderRepository->get($orderid);
$object['order_info'] = $order->getData();
$object['payment_info'] =$order->getPayment()->getData();
$object['shipping_info'] =$order->getShippingAddress()->getData();
$object['billing_info'] =$order->getBillingAddress()->getData();
$resul=array();
foreach ($order->getAllItems() as $item)
{
//fetch whole item information
$resul= $item->getData();

}
$object['items'] = $resul;

// $response = json_decode(json_encode($object), true);
$response = $object;

} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 7: Index Controller in Custermer Orders API

app/code/Wishusucess/GetOrders/Controller/Index/Index.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\GetOrders\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $_orderCollectionFactory;
protected $orderRepository;
protected $data;


public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
array $data = []
) {
$this->orderRepository = $orderRepository;
$this->data = $data;

parent::__construct($context);
}

public function execute() {
echo "<pre>";
$orderid = 12; // its called increment id
$order = $this->orderRepository->get($orderid);
$object['order_info'] = $order->getData();
$object['payment_info'] =$order->getPayment()->getData();
$object['shipping_info'] =$order->getShippingAddress()->getData();
$object['billing_info'] =$order->getBillingAddress()->getData();
$object['incrementid'] =$order->getIncrementId();
$object['grandtotal'] =$order->getGrandTotal();
$object['subtotal'] =$order->getSubtotal();
$object['customerid'] =$order->getCustomerId();
$object['customeremail'] =$order->getCustomerEmail();
$object['customerfirstname'] =$order->getCustomerFirstname();
$object['customerlastname'] =$order->getCustomerLastname();

print_r($object)

// print_r(json_decode(json_encode($object), true));

die();

}

}

 

Step 8: Create Custom Interface Customer Orders API

app/code/Wishusucess/GetOrders/Api/CustomInterface.php

<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Category: Wishusucess_GetOrders 
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\GetOrders\Api;

interface CustomInterface
{
/**
* GET for Post api
* @return boolean|array
* @param string $orderid order id.
*/

public function getPost($orderid);
}

 

Now run the below commands:

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento setup:static-content:deploy -f

php bin/magento c:c

 

Now I am showing you the testing result by using this custom REST API of a customer order in Magento 2. I am showing you the result by using the postman tool to check the valid web API URL.

First, we have to create an admin token then we will pass that admin token in the header of the order rest api.

Our customer rest API endpoint (/rest/V1/wishusucess/getorders) has to call on the postman tools.

You have to remember that we can not call our rest API without using the rest API endpoint on any other server.

Magento 2 customer Get Order API

 

Download API

Related Post:

Magento 2 Top Developers In USA: Develop Your E-Commerce Websites

File Permissions: Magento 2 Ownership And File Permission At Installation

Shipping Address API: Customer Shipping Details Using API in Magento 2

 

Recommended Post:

PayPal Account: How to Create New PayPal Account, Transfer

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

Shipping Address API: Customer Shipping Details Using API in Magento 2

I am going to explain how you can get the customer details by using customer shipping address API integration.

Our Magento development team has developed a module that helps you to retrieve the information of customer ID.

So by using this module help you through the entire shipping address information to show on the frontend on any kind of website like you can show it on react js website or node js website.

Magento 2 Shipping Address API

 

Why Shipping Address APIs?

No more complicated code is required for integration.

Wishusucess offers you to get customer shipping orders information by using the ShippingAddressApi.

You just have to call the API on your other website and then you will get the details of your customer ID.

 

Step 1: Shipping API Registration

app/code/Wishusucess/ShippingAddress/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_ShippingAddress',
__DIR__
);

 

Step 2: Module Name & Information

app/code/Wishusucess/ShippingAddress/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_ShippingAddress" setup_version="1.0.9" />
</config>

 

Step 3: Give Preference of API

This dependency injection file decide the dependency of your custom module. So this module has custom dependencies that going to injected by the object manager. We can also configure the setting but here that is not necessary.

app/code/Wishusucess/ShippingAddress/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\ShippingAddress\Api\CustomInterface" type="Wishusucess\ShippingAddress\Model\Api\Custom"/>
</config>

 

Step 3: Route Method And URL

Route URL used to decide the URL of your API and method decide what kind of operation we are going to perform so, here i have given /V1/wishusucess/shippingaddress/ route URL and i am using GET method to receive the information using API calls.

app/code/Wishusucess/ShippingAddress/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/shippingaddress/">
<service class="Wishusucess\ShippingAddress\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 4: Decide Route ID

Here you can decide the frontend id of your shipping address module by using the route id, So i have given route id shipping for this module.

app/code/Wishusucess/ShippingAddress/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="shipping" frontName="shipping">
<module name="Wishusucess_ShippingAddress" />
</route>
</router>
</config>

 

Step 5: Shipping Address API Model Class

app/code/Wishusucess/ShippingAddress/Model/Api/Custom.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ShippingAddress\Model\Api;

use Psr\Log\LoggerInterface;

class Custom 
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $_customerFactory;
protected $_addressFactory;

public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\AddressFactory $addressFactory,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->_customerFactory = $customerFactory;
$this->_addressFactory = $addressFactory;



}

/**
* @inheritdoc
*/

public function getPost($customerId)
{
$response = ['success' => false];

try {
$customer = $this->_customerFactory->create()->load($customerId); //insert customer id

//billing
$billingAddressId = $customer->getDefaultBilling();
$billingAddress = $this->_addressFactory->create()->load($billingAddressId);


//shipping
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);

$field_data['ShippingAddress']=$shippingAddress->getData();
$field_data['BillingAddress']=$billingAddress->getData();

$response= $field_data;
// print_r($cart);


} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 6: Controller To Execute API

Now here we have to get the customer id and then initialize that customer id in $customerId and then we have to load that customer id in $customer now we can find the customer shipping information and customer billing information from $customer.

Then execute() method will return after the execution of the getDefaultBilling() and getDefaultShipping().

app/code/Wishusucess/ShippingAddress/Controller/Index/Index.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ShippingAddress\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $_customerFactory;
protected $_addressFactory;
protected $_data;


public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\AddressFactory $addressFactory,
array $data = []
) {
$this->_customerFactory = $customerFactory;
$this->_data = $data;
parent::__construct($context);
}

public function execute() {
$customerId=41;
$customer = $this->_customerFactory->create()->load($customerId); //insert customer id

//billing
$billingAddressId = $customer->getDefaultBilling();
$billingAddress = $this->_addressFactory->create()->load($billingAddressId);


//shipping
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);


echo "<pre>";

print_r($customer->getData());

echo "------------------------";
// print_r($shippingAddress->getData());

die();

}

}

 

Step 7: API for Custom Interface

app/code/Wishusucess/ShippingAddress/Api/CustomInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_ShippingAddress
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\ShippingAddress\Api;

interface CustomInterface
{
/**
* GET for Post api
* @param string $customerId Customer id.
* @return boolean|array
*/

public function getPost($customerId);
}

 

So when you open your customer account summary on the Magento 2 website, which appears on the right of the Account Details page. It shows shipping addresses and billing addresses that also have the manage addresses on the customer page.

So by using this module you can get all these details through API calls on your other site. and from there you can edit the information, delete the information and add the new address by using different methods.

Here I have used only the GET method to retrieve the information but in order to perform other operations you have to use POST, DELETE, PUT, SAVE etc as per your requirement.

 

Download API

Related Post:

Latest Products API: Magento 2 Get Latest Products Using REST API Call

CMS REST API: Retrieve Magento 2 CMS Pages & Block Data Using API

 

Recommend Post:

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

 

 

 

 

Latest Products API: Magento 2 Get Latest Products Using REST API Call

In this Wishusucess custom API development of module series, I am going to explain how you can get all the latest products of the Magento 2 website on other websites using the latest products API call.

Wishusucess Magento 2 expert developer has developed a module which is Wishusucess_LatestProductsApi that will help you to get load all your products just by calling the API.

 

Create Product Yes/No Attribute

first I have created a product yes no attributes in Admin > Stores > Attributes > Product.

Now there I have decided an identifier that is latestproducts, now I am going to use this identifier in the controller and model class of this custom Magento 2 Latest Products yes/no attributes model.

At the end of module, we can get all collections just by rest API call on any other website.

 

Step 1: Registration of LatestProductsApi

app/code/Wishusucess/LatestProductsApi/registration.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_LatestProductsApi',
__DIR__
);

 

Step 2: Module Basic Information

app/code/Wishusucess/LatestProductsApi/etc/module.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_LatestProductsApi" setup_version="1.0.0" />
</config>

 

Step 3: Declare Dependency of Module

app/code/Wishusucess/LatestProductsApi/etc/di.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Wishusucess\LatestProductsApi\Api\CustomInterface" type="Wishusucess\LatestProductsApi\Model\Api\Custom"/>
</config>

 

Step 4: Latest Products API Routing URL

Here, I have decided on a routing method GET and route URL, and also I have added a custom service class which I have implemented in our custom module.

app/code/Wishusucess/LatestProductsApi/etc/webapi.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route method="GET" url="/V1/wishusucess/latestproductsapi/">
<service class="Wishusucess\LatestProductsApi\Api\CustomInterface" method="getPost"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>

 

Step 6: Routes URL ID

app/code/Wishusucess/LatestProductsApi/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
<route id="latestproductsapi" frontName="latestproductsapi">
<module name="Wishusucess_LatestProductsApi" />
</route>
</router>
</config>

 

Step 7: Controller Index File

Now, here I have added custom product attribute latestproducts in the controller class so that attribute filter the product based on 1 and 0 value of the attribute.

app/code/Wishusucess/LatestProductsApi/Controller/Index/Index.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\LatestProductsApi\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action {

/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;
protected $data;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory; 
$this->catalogProductVisibility = $catalogProductVisibility;
$this->data = $data;
parent::__construct($context);
}

public function execute() {
$collection = $this->_productCollectionFactory->create();
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
->addAttributeToFilter('latestproducts', '1');

$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$response = $collection;

echo "<pre>";
// print_r($response->getData());
$cart = array();
foreach($response as $value)
{
$cart[] = $value->getData();
}

print_r($cart);
die();

}

}

 

Step 8: Model Class Latest Products API

app/code/Wishusucess/LatestProductsApi/Model/Api/Custom.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\LatestProductsApi\Model\Api;

use Psr\Log\LoggerInterface;

class Custom 
{
/** @var \Magento\Framework\View\Result\PageFactory */
protected $resultPageFactory;

public function __construct(
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
) {
$this->resultPageFactory = $resultPageFactory;
$this->_productCollectionFactory = $productCollectionFactory; 
$this->catalogProductVisibility = $catalogProductVisibility;


}

/**
* @inheritdoc
*/

public function getPost()
{
$response = ['success' => false];

try {

$collection = $this->_productCollectionFactory->create();
$collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
->addAttributeToFilter('latestproducts', '1');

$collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());
$result= $collection;
$cart = array();
foreach($result as $value)
{
$cart[] = $value->getData();
}
$response= $cart;
// print_r($cart);


} catch (\Exception $e) {
$response = ['success' => false, 'message' => $e->getMessage()];
}
$returnArray = $response;
return $returnArray; 
}
}

 

Step 9: Latest Products API Interface

app/code/Wishusucess/LatestProductsApi/Api/CustomInterface.php

<?php
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_LatestProductsApi
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\LatestProductsApi\Api;

interface CustomInterface
{
/**
* GET for Post api
* @return boolean|array
*/

public function getPost();
}

 

Now Run Bellow Command:

php/bin magento setup:upgrade

php/bin magento setup:di:compile

php/bin magento setup:static-content:deploy -f

php/bin magento c:c

 

Now, I am going to test this module using the postman API tool.

So, first I will create an admin access token by using the below Magento 2 admin API.

https://wishusucess.com/rest/store_id/V1/integration/admin/token

Magento 2 Admin Access Token

Now we have received the admin access token so we will use this token to authorize the API request.

So I am going to add this token to the header section.

Authorization: Bearer Token

Content-Type: application/JSON

Method: POST

Payload: Not Required

Authorise Your Request With Token

Now with the admin access token, I am using this implemented token.

https://wishusucess.com/rest/store_id/V1/sparx/latestproduct/

So all the enabled lasted product is loading here.

Call Latest Products API

Related Post:

How To GET Products List Using Magento 2 REST API

How To Get Product Image URL Using REST API in Magento 2

How To Get Category List By REST API and GraphQL In Magento 2, E.g.

 

Recommended Post:

Elasticsearch: How to Install Elasticsearch in Ubuntu 18.04

Download Latest Product Custom Module on GitHub