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

 

Magento 2 REST API: How To Call REST API in Magento 2

In this article I am going to explain to you from the scratch, so even if you don't have any idea about Magento 2 REST API then also you can easily call the REST API and send the request and receive the request.

Magento 2 series has already provided REST APIs for most of the Modules so you don't need to create REST API you can just call those APIs and get the data on a third-party service to send the request from the third-party websites.

But, you can also create a dynamic REST API which is known as custom APIs development in Magento 2. By using custom APIs you can also get the data post the data save the data etc.

 

What is Swager in Magento 2?

A swagger is an open-source tool.  That simplifies APIs in Magento 2 for the development that helps users or developers with the Swagger open source and professional toolset.

 

How to Call Swagger in Magento 2

There is one library that is swagger that helps you to get all the default Magento 2 REST APIs. You just have to enter the domain name and then type swagger and then press enter. You will get a list of the available APIs in Magento 2.

https://www.wishusucess.com/swagger/

Swagger Uses in Magento 2

 

Test Magento 2 REST API on Swagger

When you will press enter after your domain URL in formate like https://www.your-domain.com/swagger/ then the generated Swagger documentation provides the capability to test REST requests.

So just hit try out button and then test your required REST APIs.

You will get the relevant information regarding APIs. when you need to retrieve the data then you need a customer access token also.

 

How To Call Magento 2 REST API With Example

Here giving you the one example to call REST API in Magento 2. I have created a customer access token by using the following default REST API.

Step 1: Call REST API using Postman

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

How to Call Magento 2 REST API

In the above screenshot, you can see I have to call Magento 2 Apis by Using Postman. A postman is a tool is an application that provides facilities to test any kind of API. Here you can send requests by using Apis to any server and receive the response.

 

Step 2: How To Call REST APIs in GraphQL

This is the GraphQL method, here you can get the same result by using GraphQL in Magento 2.

Create Customer Mutation GraphQL

 

Related Post:

Category ID: How To Get Current Category ID in Magento 2

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

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

 

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

 

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

I am going to explain how we can load Magento 2 cms block content and cms page content on another website. By Using Wishusucess CMS REST API you can easily get the data to delete the data of your page and block.

Magento 2 CMS REST API

This module contains the only GET method but you can perform all kinds of getting operations over the cms page and cms block of your stores.

You can search page content by using the below route URL.

http://wishusucess.com/rest/all/V1/wishusucess/cmsPage/search

And for the block content search, you can use the below URL.

http://wishusucess.com/rest/all/V1/wishusucess/cmsBlock/search

For getting the whole cms page content we have to use below route URL of the cms page API

http://wishusucess.com/rest/store_id/V1/wishusucess/cmsPage/:pageId

The whole content of the block we can get by using below CMS Block REST API

http://wishusucess.com/rest/store_id/V1/wishusucess/cmsBlock/:blockId

 

Searching Using CMS REST API

We have also included the search content features using rest API on other websites. So you can easily call that API on any site and that will allow you to search the content of block and page.

You have to fill that search criterion to get the content of the block or page.

 

Available Endpoints Wishusucess_CMSApi

By using the following endpoint you can perform your desire action over the data on any website.

You just have to call the below endpoints:

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsPage/:pageId

You can retrieves page information based on the page id

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsPage/search

We can perform data retrieves operation on the list of pages.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsPageIdentifier/:identifier/storeId/:storeId

By giving integer value on page id we can get page content.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsBlock/:blockId

Can retrieve Magento 2 cms block data by giving block id.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsBlockIdentifier/:identifier/storeId/:storeId

Magento 2 cms block needs an identifier (string value) to get the block content using this REST API.

http://wishusucess.com/rest/store_id/rest/V1/Wishusucess/cmsBlock/search

Can get all the list of blocks on any website by using the above block rest API.

 

 

Step 1: Registration CMSApi

app/code/Wishusucess/CmsApi/registration.php

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

 

Step 2: Basic Information About CMSApi

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

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* 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_CmsApi" setup_version="0.1.0">
</module>
</config>

 

Step 3: Dependency Injection of Module CMSApi

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

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* 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\CmsApi\Api\PageManagerInterface"
type="Wishusucess\CmsApi\Model\PageManager" />
<preference for="Wishusucess\CmsApi\Api\BlockManagerInterface"
type="Wishusucess\CmsApi\Model\BlockManager" />
<preference for="Wishusucess\CmsApi\Api\Data\BlockInterface"
type="Wishusucess\CmsApi\Model\Block" />
<preference for="Wishusucess\CmsApi\Api\Data\PageInterface"
type="Wishusucess\CmsApi\Model\Page" />
<preference for="Wishusucess\CmsApi\Api\Data\PageSearchResultsInterface"
type="Magento\Framework\Api\SearchResults" />
<preference for="Wishusucess\CmsApi\Api\Data\BlockSearchResultsInterface"
type="Magento\Framework\Api\SearchResults" />
<type name="Wishusucess\CmsApi\Model\BlockManager">
<arguments>
<argument name="collectionProcessor" xsi:type="object">Magento\Cms\Model\Api\SearchCriteria\BlockCollectionProcessor</argument>
</arguments>
</type>
<type name="Wishusucess\CmsApi\Model\PageManager">
<arguments>
<argument name="collectionProcessor" xsi:type="object">Magento\Cms\Model\Api\SearchCriteria\PageCollectionProcessor</argument>
</arguments>
</type>
</config>

 

Step 4: Route URL of CMS REST API

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

<?xml version="1.0"?>
<!--
/**
*
* Developer: Hemant Singh Magento Certified Developer
* Category: Wishusucess_CmsApi
* Website: http://www.wishusucess.com/
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Cms Page -->
<route url="/V1/wishusucess/cmsPage/:pageId" method="GET">
<service class="Wishusucess\CmsApi\Api\PageManagerInterface" method="getById"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsPageIdentifier/:identifier/storeId/:storeId" method="GET">
<service class="Wishusucess\CmsApi\Api\PageManagerInterface" method="getByIdentifier"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsPage/search" method="GET">
<service class="Wishusucess\CmsApi\Api\PageManagerInterface" method="getList"/>
<resources>
<resource ref="Magento_Cms::page"/>
</resources>
</route>
<!-- Cms Block -->
<route url="/V1/wishusucess/cmsBlock/:blockId" method="GET">
<service class="Wishusucess\CmsApi\Api\BlockManagerInterface" method="getById"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsBlockIdentifier/:identifier/storeId/:storeId" method="GET">
<service class="Wishusucess\CmsApi\Api\BlockManagerInterface" method="getByIdentifier"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>
<route url="/V1/wishusucess/cmsBlock/search" method="GET">
<service class="Wishusucess\CmsApi\Api\BlockManagerInterface" method="getList"/>
<resources>
<resource ref="Magento_Cms::block"/>
</resources>
</route>
</routes>

 

Step 5: CMSApi Block Model

app/code/Wishusucess/CmsApi/Model/Block.php

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

use Wishusucess\CmsApi\Api\Data\BlockInterface;

class Block extends \Magento\Cms\Model\Block implements BlockInterface
{
/**
* @inheritdoc
*/
public function getStoreId()
{
return $this->_getData(self::STORE_ID);
}

/**
* @inheritdoc
*/
public function setStoreId(array $storeIds)
{
$this->setData(self::STORE_ID, $storeIds);

return $this;
}
}

 

Step 6: Model Class for Block Manager

app/code/Wishusucess/CmsApi/Model/BlockManager.php

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

use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Model\BlockFactory;
use Magento\Cms\Model\ResourceModel\Block;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\App\Emulation;
use Wishusucess\CmsApi\Api\BlockManagerInterface;
use Wishusucess\CmsApi\Api\Data\BlockInterfaceFactory;
use Wishusucess\CmsApi\Api\Data\BlockSearchResultsInterfaceFactory;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;

/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BlockManager extends ManagerBase implements BlockManagerInterface
{
/**
* @var BlockRepositoryInterface
*/
private $blockRepository;

/**
* @var FilterProvider
*/
private $filterProvider;

/**
* @var BlockFactory
*/
private $blockFactory;

/**
* @var Block
*/
private $blockResource;

/**
* @var BlockSearchResultsInterfaceFactory
*/
private $searchResultsFactory;

/**
* @var Block\CollectionFactory
*/
private $blockCollectionFactory;

/**
* @var CollectionProcessorInterface
*/
private $collectionProcessor;

/**
* @var BlockInterfaceFactory
*/
private $blockDtoFactory;

/**
* @var DataObjectHelper
*/
private $dataObjectHelper;

/**
* @var State
*/
private $appState;

/**
* @var Emulation
*/
private $emulation;

/**
* @param BlockRepositoryInterface $blockRepository
* @param FilterProvider $filterProvider
* @param BlockFactory $blockFactory
* @param Block $blockResource
* @param Block\CollectionFactory $blockCollectionFactory
* @param BlockSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
* @param BlockInterfaceFactory $blockDtoFactory
* @param DataObjectHelper $dataObjectHelper
* @param State $appState
* @param Emulation $emulation
*/
public function __construct(
BlockRepositoryInterface $blockRepository,
FilterProvider $filterProvider,
BlockFactory $blockFactory,
Block $blockResource,
Block\CollectionFactory $blockCollectionFactory,
BlockSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor,
BlockInterfaceFactory $blockDtoFactory,
DataObjectHelper $dataObjectHelper,
State $appState,
Emulation $emulation
) {
$this->blockRepository = $blockRepository;
$this->filterProvider = $filterProvider;
$this->blockFactory = $blockFactory;
$this->blockResource = $blockResource;
$this->searchResultsFactory = $searchResultsFactory;
$this->blockCollectionFactory = $blockCollectionFactory;
$this->collectionProcessor = $collectionProcessor;
$this->blockDtoFactory = $blockDtoFactory;
$this->dataObjectHelper = $dataObjectHelper;
$this->appState = $appState;
$this->emulation = $emulation;
}

/**
* @inheritdoc
*/
public function getById($blockId)
{
$block = $this->blockRepository->getById($blockId);
$content = $this->getBlockContentFiltered($block->getContent());
$block->setContent($content);

return $block;
}

/**
* @inheritdoc
*/
public function getByIdentifier($identifier, $storeId = null)
{
$block = $this->blockFactory->create();
$block->setStoreId($storeId);
$this->blockResource->load($block, $identifier, BlockInterface::IDENTIFIER);

if (!$block->getId()) {
throw new NoSuchEntityException(
__('CMS Block with identifier "%1" does not exist.', $identifier)
);
}

$content = $this->getBlockContentFiltered($block->getContent());
$block->setContent($content);

return $block;
}

/**
* @inheritdoc
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
$storeId = $this->getStoreIdBySearchCriteria($searchCriteria);

if ($storeId !== null) {
$this->emulation->startEnvironmentEmulation($storeId);
}

/** @var \Magento\Cms\Model\ResourceModel\Block\Collection $collection */
$collection = $this->blockCollectionFactory->create();
$this->collectionProcessor->process($searchCriteria, $collection);

$items = [];
/** @var \Magento\Cms\Model\Block $block */
foreach ($collection->getItems() as $block) {
$content = $this->getBlockContentFiltered($block->getContent());
$block->setContent($content);
$blockDto = $this->blockDtoFactory->create();
$this->dataObjectHelper->populateWithArray(
$blockDto,
$block->getData(),
\Wishusucess\CmsApi\Api\Data\BlockInterface::class
);
$blockDto->setId($block->getId());
$items[] = $blockDto;
}

$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
$searchResults->setItems($items);
$searchResults->setTotalCount(count($items));

if ($storeId !== null) {
$this->emulation->stopEnvironmentEmulation();
}

return $searchResults;
}

/**
* @param string $content
* @return string
*/
private function getBlockContentFiltered($content)
{
$emulatedResult = $this->appState->emulateAreaCode(
Area::AREA_FRONTEND,
[$this->filterProvider->getBlockFilter(), 'filter'],
[$content]
);

return $emulatedResult;
}
}

 

Step 7: CMSApi Model Manager for Search Criteria

app/code/Wishusucess/CmsApi/Model/ManagerBase.php

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

use Magento\Framework\Api\SearchCriteriaInterface;

class ManagerBase
{
/**
* @param SearchCriteriaInterface $searchCriteria
* @return int
*/
protected function getStoreIdBySearchCriteria(SearchCriteriaInterface $searchCriteria)
{
$filterGroups = $searchCriteria->getFilterGroups();

$storeIds = [];
foreach ($filterGroups as $filterGroup) {
foreach ($filterGroup->getFilters() as $filter) {
if ($filter->getField() == 'store_id') {
$storeIds = array_merge($storeIds, explode(',', $filter->getValue()));
}
}

if (count($storeIds) > 1) {
return 0; // default store
} else {
// if store_id wasn't passed as a filter,
// we should not continue with store emulation
return null;
}
}

return (int) array_shift($storeIds);
}
}

 

Step 8: CMS API For Page Model

app/code/Wishusucess/CmsApi/Model/Page.php

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

use Wishusucess\CmsApi\Api\Data\PageInterface;

class Page extends \Magento\Cms\Model\Page implements PageInterface
{
/**
* @inheritdoc
*/
public function getStoreId()
{
return $this->_getData(self::STORE_ID);
}

/**
* @inheritdoc
*/
public function setStoreId(array $storeIds)
{
$this->setData(self::STORE_ID, $storeIds);

return $this;
}
}

 

Step 9: Page Manager CMS REST API

app/code/Wishusucess/CmsApi/Model/PageManager.php

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

use Magento\Cms\Api\Data\PageInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Cms\Model\PageFactory;
use Magento\Cms\Model\ResourceModel\Page;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\App\Emulation;
use Wishusucess\CmsApi\Api\Data\PageInterfaceFactory;
use Wishusucess\CmsApi\Api\Data\PageSearchResultsInterfaceFactory;
use Wishusucess\CmsApi\Api\PageManagerInterface;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;

/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PageManager extends ManagerBase implements PageManagerInterface
{
/**
* @var PageRepositoryInterface
*/
private $pageRepository;

/**
* @var FilterProvider
*/
private $filterProvider;

/**
* @var PageFactory
*/
private $pageFactory;

/**
* @var Page
*/
private $pageResource;

/**
* @var Page\CollectionFactory
*/
private $pageCollectionFactory;

/**
* @var PageSearchResultsInterfaceFactory
*/
private $searchResultsFactory;

/**
* @var CollectionProcessorInterface
*/
private $collectionProcessor;

/**
* @var PageInterfaceFactory
*/
private $pageDtoFactory;

/**
* @var DataObjectHelper
*/
private $dataObjectHelper;

/**
* @var State
*/
private $appState;

/**
* @var Emulation
*/
private $emulation;

/**
* @param PageRepositoryInterface $pageRepository
* @param FilterProvider $filterProvider
* @param PageFactory $pageFactory
* @param Page $pageResource
* @param Page\CollectionFactory $pageCollectionFactory
* @param PageSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
* @param PageInterfaceFactory $pageDtoFactory
* @param DataObjectHelper $dataObjectHelper
* @param State $appState
* @param Emulation $emulation
*/
public function __construct(
PageRepositoryInterface $pageRepository,
FilterProvider $filterProvider,
PageFactory $pageFactory,
Page $pageResource,
Page\CollectionFactory $pageCollectionFactory,
PageSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor,
PageInterfaceFactory $pageDtoFactory,
DataObjectHelper $dataObjectHelper,
State $appState,
Emulation $emulation
) {
$this->pageRepository = $pageRepository;
$this->filterProvider = $filterProvider;
$this->pageFactory = $pageFactory;
$this->pageResource = $pageResource;
$this->pageCollectionFactory = $pageCollectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
$this->pageDtoFactory = $pageDtoFactory;
$this->dataObjectHelper = $dataObjectHelper;
$this->appState = $appState;
$this->emulation = $emulation;
}

/**
* @inheritdoc
*/
public function getById($pageId)
{
$page = $this->pageRepository->getById($pageId);
$content = $this->getPageContentFiltered($page->getContent());
$page->setContent($content);

return $page;
}

/**
* @inheritdoc
*/
public function getByIdentifier($identifier, $storeId = null)
{
$page = $this->pageFactory->create();
$page->setStoreId($storeId);
$this->pageResource->load($page, $identifier, PageInterface::IDENTIFIER);

if (!$page->getId()) {
throw new NoSuchEntityException(
__('CMS Page with identifier "%1" does not exist.', $identifier)
);
}

$content = $this->getPageContentFiltered($page->getContent());
$page->setContent($content);

return $page;
}

/**
* @inheritdoc
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
$storeId = $this->getStoreIdBySearchCriteria($searchCriteria);

if ($storeId !== null) {
$this->emulation->startEnvironmentEmulation($storeId);
}

/** @var \Magento\Cms\Model\ResourceModel\Page\Collection $collection */
$collection = $this->pageCollectionFactory->create();
$this->collectionProcessor->process($searchCriteria, $collection);

$items = [];
/** @var \Magento\Cms\Model\Page $page */
foreach ($collection->getItems() as $page) {
$content = $this->getPageContentFiltered($page->getContent());
$page->setContent($content);
$pageDto = $this->pageDtoFactory->create();
$this->dataObjectHelper->populateWithArray(
$pageDto,
$page->getData(),
\Wishusucess\CmsApi\Api\Data\PageInterface::class
);
$pageDto->setId($page->getId());
$items[] = $pageDto;
}

$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
$searchResults->setItems($items);
$searchResults->setTotalCount(count($items));

if ($storeId !== null) {
$this->emulation->stopEnvironmentEmulation();
}

return $searchResults;
}

/**
* @param string $content
* @return string
*/
private function getPageContentFiltered($content)
{
$emulatedResult = $this->appState->emulateAreaCode(
Area::AREA_FRONTEND,
[$this->filterProvider->getPageFilter(), 'filter'],
[$content]
);

return $emulatedResult;
}
}

 

Step 10: Block Manager Class of CMSApi

app/code/Wishusucess/CmsApi/Api/BlockManagerInterface.php

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

interface BlockManagerInterface
{
/**
* @param int $blockId
* @return \Magento\Cms\Api\Data\BlockInterface
*/
public function getById($blockId);

/**
* @param string $identifier
* @param int $storeId
* @return \Magento\Cms\Api\Data\BlockInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getByIdentifier($identifier, $storeId = null);

/**
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Wishusucess\CmsApi\Api\Data\BlockSearchResultsInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

 

Step 11: Page Manager Interface

app/code/Wishusucess/CmsApi/Api/PageManagerInterface.php

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

interface PageManagerInterface
{
/**
* @param int $pageId
* @return \Magento\Cms\Api\Data\PageInterface
*/
public function getById($pageId);

/**
* @param string $identifier
* @param int $storeId
* @return \Magento\Cms\Api\Data\PageInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getByIdentifier($identifier, $storeId = null);

/**
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Wishusucess\CmsApi\Api\Data\PageSearchResultsInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

 

Step 12: Block Interface of API

app/code/Wishusucess/CmsApi/Api/Data/BlockInterface.php

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

interface BlockInterface extends \Magento\Cms\Api\Data\BlockInterface
{
/**#@+
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const STORE_ID = 'store_id';
/**#@-*/

/**
* @return int[]
*/
public function getStoreId();

/**
* @param int[] $storeIds
* @return BlockInterface
*/
public function setStoreId(array $storeIds);
}

 

Step 13: Search Result Interface

app/code/Wishusucess/CmsApi/Api/Data/BlockSearchResultsInterface.php

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

use Magento\Framework\Api\SearchResultsInterface;

interface BlockSearchResultsInterface extends SearchResultsInterface
{
/**
* @return \Wishusucess\CmsApi\Api\Data\BlockInterface[]
*/
public function getItems();

/**
* @param \Wishusucess\CmsApi\Api\Data\BlockInterface[] $items
* @return BlockSearchResultsInterface
*/
public function setItems(array $items);
}

 

Step 14: Get Page Store Id

app/code/Wishusucess/CmsApi/Api/Data/PageInterface.php

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

interface PageInterface extends \Magento\Cms\Api\Data\PageInterface
{
/**#@+
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const STORE_ID = 'store_id';
/**#@-*/

/**
* @return int[]
*/
public function getStoreId();

/**
* @param int[] $storeIds
* @return BlockInterface
*/
public function setStoreId(array $storeIds);
}

 

Step 15: Page Search Result Interface

app/code/Wishusucess/CmsApi/Api/Data/PageSearchResultsInterface.php

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

use Magento\Framework\Api\SearchResultsInterface;

interface PageSearchResultsInterface extends SearchResultsInterface
{
/**
* @return \Wishusucess\CmsApi\Api\Data\PageInterface[]
*/
public function getItems();

/**
* @param \Wishusucess\CmsApi\Api\Data\PageInterface[] $items
* @return PageSearchResultsInterface
*/
public function setItems(array $items);
}

 

Related Post:

Featured Product API: Get Featured Product Using Magento 2 REST API

How To Call Magento 2 REST API For Customer Account Update

How To GET Products List Using Magento 2 REST API

 

Recommended Post

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

Download API