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

Razorpay Payment: Step By Step Guide to Integrate Payment Method

I am going to explain Magento 2 Payment gateway integration. When we talk about Magento Payment gateways then Razorpay payment gateways are one of the most usable gateways in the Magento eCommerce application. This application integration can help you to grow your business.

By integration of Razorpay payment gateways store, owners can enable payment to accept from customers. This app will also add automated payouts functionality for both vendors & employees.

Razorpay Payment Integration Method

Read More: List of Top 7 Best Payment Gateways

 

Available Best Options in Razorpay Gateways

Payment Links:

Once you have created your profile and get verified with KYC from this application team then you can share payment links via a medium like an email, SMS, messenger, chatbot, etc. and by using those links anyone can pay and you will get that amount immediately in your account.

Payment Pages

The business owner also can get paid by creating a payment page with zero coding. This functionality also has the option to accept international & domestic payments.

Payment Buttons

Another best option provided by Razorpay is anyone can accept by Create, Copy & Collect With Payment Button. Bu for this Collect one has plan which needs to subscribe in order to make and receive any payments.

Subscriptions

There are various options for the users to subscribe to their plans according to the customer business needs with automated recurring transactions.

Split and Transfer Payments with Razorpay Route

The vendor also decides to split incoming payments automatically to vendor’s accounts which helps to manage the account.

 

Smart Collect

Razorpay SmartCollect offers to their customer that add functionality to make real-time transactions like NEFT, RTGS, IMPS, UPI payments by using Virtual Accounts & UPI-IDs.

 

Read More: How to Integrate Payment Gateways in Magento 2

 

Steps to Integrate Razorpay Payment

Here, I am giving to step by step guide to integrate Razorpay payment gateways with Magento 2.

Step 1: Download Payment Gateyas Module

You can visit their official website to download Magento 2 extension or you can also download it from the official GitHub account of Razorpay gateway.

Step 2: Installation

Now run the below command in order to install this payment gateway module in Magento 2.

Paste your download code in the app/code/ directory of your Magento installation.

Now run these commands:

bin/magento setup:upgrade

bin/magento setup:di:compile

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

bin/magento c:c
Razorpay Installation Via Composer

Install the extension through the composer package manager.

composer require razorpay/magento

bin/magento module:enable Razorpay_Magento

 

Step 3: Razorpay Payment Gateway Configuration

Now, Go to Admin > Stores > Configuration > Payment Method > Razorpay 

You should be able to see the Razorpay configuration here but If you do not see Razorpay in your gateway list, please clear your Magento Cache.

Magento Gateways Integration

Now you have to login into your Razorpay dashboard and then generate API keys and enter in the above-shown fields.

Generate API Key

Once you will do all the above settings then you will get options like the below image.

Magento 2 Pay Method

Now when you will do checkout then your screen will look something like the below image.

Payment Option on Checkout Page

Now, you can enjoy the Razorpay payment gateways method in Magento 2.

 

Recommended Post:

PayPal Account: How to Create New PayPal Account, Transfer

 

 

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

Infinite Scroll: Magento 2 Ajax Scroll for The Automatically Load Products

I am going to explain how we can create an Ajax Infinite Scroll extension in Magento 2. The extension will help the value of users to reduce product load time by automatically loading products when users scroll down the product list page like category page, catalog search page without reloading the whole page.

Infinite Scroll in Magento 2

The Ajax scroll extension for Magento 2 helps the website's owners to increase their sales and drive more revenue by improving the user experience.

As soon as you enable the Wishusucess_InfiniteScroll extension from the admin then you will be automatically able to add the autoload product functionality on the category page or any other product list page like a catalog search page in Magento 2.

 

Infinite Scroll Features:

By adding automatically loading of the product it increases the quality of user experience and reduces the product loading time.

Ensure the web site's performance by adding autoload functionality.

Easy to navigate the product for the customer.

Adds Automatically loads functionality for the products on any others products listing page.

If the list page doesn't have more products then it shows a message like there are no more products to load after loading all products.

Admin configuration is given to customizing loading text content.

Admin can decide the delay time from the Magento admin for scroll-down loading time.

Improve customer experience for the owners of the website and increase the conversion rate.

You can add for the multi-store environment.

Magento 2 Infinite Scroll Products

Magento 2 Infinite Scroll Free Extensions in 2022

In 2021-2022 there are too many infinite scroll extensions are there in the market but we have picked one of the best ajax scroll products for your websites.

Wishusucess_InifiniteScroll is one of the best Magento 2 modules for the infinite automatically loading products.

The best Ajax Scroll for the products is Wishusucess automatically scroll products in 2021, This is an absolutely free extension. You can also Find more Magento 2 extensions here.

Infinite Scroll Button

Change Configuration of Ajax Scroll

You will have the option to change the configuration from the admin. This extension allows websites owners to customize the button color and text from the Admin > Store > Configuration > Wishusucess > Ajax Scroll.

 

Helper Class of Ajax Scroll

If you are a developer and you need to implement the helper class of this module then you can use the bewlow code for the help.

<?php
/**
* Category: Wishusucess_InfiniteScroll
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/
namespace Wishusucess\InfiniteScroll\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var array
*/
protected $configModule;

public function __construct(
\Magento\Framework\App\Helper\Context $context
)
{
parent::__construct($context);
$this->configModule = $this->getConfig(strtolower($this->_getModuleName()));
}

public function getConfig($cfg='')
{
if($cfg) return $this->scopeConfig->getValue( $cfg, \Magento\Store\Model\ScopeInterface::SCOPE_STORE );
return $this->scopeConfig;
}

public function getConfigModule($cfg='', $value=null)
{
$values = $this->configModule;
if( !$cfg ) return $values;
$config = explode('/', $cfg);
$end = count($config) - 1;
foreach ($config as $key => $vl) {
if( isset($values[$vl]) ){
if( $key == $end ) {
$value = $values[$vl];
}else {
$values = $values[$vl];
}
}

}
return $value;
}
}

Magento 2.4 Installation Guide: How to Install Magento 2.4.2

How to Install Infinite Scroll Module

Download this module from here and paste it into the below directory of your store root installation directory.

app/code/Wishusucess/InfiniteScroll/

Now run the below code

php bin/magento setup:upgrade

php bin/magento setup:di:compile

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

php bin/magento cache:clean

 

Similar Magento 2 Extensions of Wishusucess

Sticky Mini-Cart: How To Add Sticky Add to Cart Extension in Magento 2

Speed Up Your Magento 2 Website By Lazy Loading Extension Free

Login With Number: Magento 2 Customer Login With Mobile Number

Sticky Mini-Cart: How To Add Sticky Add to Cart Extension in Magento 2

In this article, I will explain to you how to add the sticky mini-cart on the current page. This step will help you to make users add to the cart always visible for easier checkout.

When a Magento 2 user scrolls down the current category page, home page, or product details page then this sticky cart extension will allow you to make "Add to cart" always visible for the customer so the customer can easily add more items or subtract items from the cart.

Magento 2 Sticky Mini-Cart

The Customers will also have the option to view a brief of product detail such as images, prices.

If the customer is looking for any change while scrolling the category page or product list page then they no need to scroll back to the top because the cart bar is always visible.

Therefore, this Magento 2 sticky cart extension will add value for your website customers by adding the above extremely convenient shopping experience to the users. Thus this functionality helps store owners to increase sales.

And where customers sometimes used to leave in the middle without completing the checkout, they will now be able to place their order easily.

 

Sticky Mini-Cart for The Magento Customer

The Sticky cart for the customer adds value to the customer experiance, it fixes the customer mini cart details at the bottom of the page when the page is scrolled down which leads to improves user experience.

This extension was implemented by the Wishusucess Magento development team that increase the conversion rate by encouraging customers to add products to the cart or buy now button.

 

Features of Magento Sticky Mini-Cart

The website admin panel has been implemented in such a way that anyone can manage the panel of Wishusucess_Stickycart without any coding knowledge.

We have added Enabled/Disable the features of the Wishusucess_Stickycart quickly from the admin.

Customers can view a brief of the details while scrolling the store page and also can manage their mini-cart details by just clicking on the icons.

Admin users can customize the size requirement from the admin panel of the product images.

The module is completely implemented as a responsive design so you don't have to worry about the different devices like mobiles, tablets, laptops. The module will readjust itself based on the original layout.

 

Helper Class of Sticky Cart in Magento 2

Hereby using this helper class of sticky cart you can implement the custom module for the Magento websites.

<?php
/*
* @category: Wishusucess_Stickycart
* @Wishusucess: (http://www.wishusucess.com/)
* @licence: http://www.wishusucess.com/
*/
namespace Wishusucess\Stickycart\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var array
*/
protected $configModule;

/**
* @var \Magento\Framework\Json\Helper\Data
*/
protected $jsonHelper;

public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Json\Helper\Data $jsonHelper
)
{
parent::__construct($context);
$this->configModule = $this->getConfig(strtolower($this->_getModuleName()));
$this->jsonHelper = $jsonHelper;
}

public function getConfig($cfg='')
{
if($cfg) return $this->scopeConfig->getValue( $cfg, \Magento\Store\Model\ScopeInterface::SCOPE_STORE );
return $this->scopeConfig;
}

public function getConfigModule($cfg='', $value=null)
{
$values = $this->configModule;
if( !$cfg ) return $values;
$config = explode('/', $cfg);
$end = count($config) - 1;
foreach ($config as $key => $vl) {
if( isset($values[$vl]) ){
if( $key == $end ) {
$value = $values[$vl];
}else {
$values = $values[$vl];
}
}

}
return $value;
}

public function isEnabled()
{
return $this->getConfigModule('general/enabled');
}
public function getWidthImage()
{
return $this->getConfigModule('general/width_image');
}
public function getHeightImage()
{
return $this->getConfigModule('general/height_image');
}
public function getHeightScroll()
{
return $this->getConfigModule('general/height_scroll');
}

public function getExcludeProducts()
{
return $this->getConfigModule('general/exclude_products');
}

public function getStickyCartConfigJson($product)
{ 
$data = [
"typeProduct" => $product->getTypeId(),
"scrollHeight" => $this->getConfigModule('general/height_scroll'),
"hiddenBottom" => $this->getConfigModule('general/hidden_bottom')
];
foreach ($data as $key => $value) {
if(is_numeric($value)){
$data[$key] = (float) $value;
continue;
}
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if(!is_null($value)){
$data[$key] = $value; 
}
}
return $this->jsonHelper->jsonEncode($data);
}

}

 

How to Install Magento 2 Wishusucess Sticky Mini-Cart

Download the module and paste it into the below directory:

root_directory_of store/app/code/Wishusucess/Stickycart/

Now run the below command step by step:-

php bin/magento setup:upgrade

php bin/magento setup:di:compile

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

php bin/magento cache:clean

 

Help And Support by Magento Team

In case of any problem, you can talk to our Magento 2 development team. Basic installation is absolutely free.

If you want to add any new features to it, then our team is available 24 hours for this, you can tell your requirement to our development team and within 24 hours your features will be implemented.

 

Similar Module

Speed Up Your Magento 2 Website By Lazy Loading Extension Free

Login With Number: Magento 2 Customer Login With Mobile Number

 

Speed Up Your Magento 2 Website By Lazy Loading Extension Free

This is the biggest problem for most of the Magento 2 website owners, how to provide a better experience to their customers, it is necessary to eliminate its lazy loading problem, because if the website loading time is higher then that would be worse for your customer to experience the website.

Our Magento team understands this problem and has developed Magento 2 Lazy Load extension which provides a better experience for your customer.

It minimizes the loading problem of your website, due to which your website loads very quickly on your customer's computer and it also helps you to be at the top of the search.

The biggest contributor to its success in any online eCommerce business is its better application and it is very important for that application to load on the customer's device quickly and efficiently.

 

Magento 2 Lazy Loading Module

By using this Magento 2 Lazy Loading extension of the Wishusucess developer team you can boost your website performance up to 70% of your current speed.

Therefore, it will increase the chances that your customers will stay on your website for a long time. Then customers will want to browse most of your pages that also increases the sales of your products.

It will also help your website to rank in google because of the faster speed of your website because a faster website also adds the improvement of SEO ranking.

Especially, the Wishusucess LazyLoading module works effectively with all Magento 2 pages such as Content Management pages, the home pages, category pages, product pages, etc.

Lazy Loading Module in Magento 2

 

Lazy Loading Adds Business Values:

It reduces the page load so faster websites Improve the user experience greatly by consuming less load time.

A faster website adds value in the search engine rank like google so it will improve the SEO ranking of your website with faster loading speed.

This module will help you to reduce the bandwidth of the server to it will save you money.

 

Lazy Loading Product Image in Magento 2

With Wishusucess Lazy Load Extension in Magento 2 website helps websites owners to speed up their websites. It will help you to decrease the load time of the product images.

 

Optimize SEO for Magento 2 Stores

Faster websites improve the SEO ranking in google so it will help your website to rank in Google Search. Wishusucess Lazy Load Magento 2 extension results improve the SEO ranking in faster website speed.

Reduce server bandwidth
By loading images and videos on-demand, you can reduce server requests and page size. This will certainly save a huge amount of bandwidth for your website.

Apply Lazy Loading on All Pages

We have designed it in such a way that this extension works for all kinds of pages including CMS pages, home pages, category pages, product pages, etc.

Download LazyLoading Extension

 

Magento Helps and Supports

If you want to improve your e-commerce website or want to make it completely new then you can contact our team. Our team is committed to providing you with the best experience at the lowest cost.

Improve SEO Ranking of your Website

 

Other Post:

PayPal Account: How to Create New PayPal Account, Transfer

 

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

 

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

This article is all about creating custom customer attribute so here, I am going to explain this. Magento 2 custom attributes provide you the options to add additional required fields for the customer. So by adding this custom field in customer you can collect information that is required to support the order, fulfillment, and customer management processes.

Add Customer Attribute in Magento 2

Do you want to provide the best service for your customers in your business? so, you might need some additional fields to collect information.

By installing this custom customers attributes module of Wishusucess you can add custom attributes to the Account Registration of the customer, Address Book, and Billing Information.

 

How to Add Custom Attribute in Customer Account

If you want to add extra fields in the customer registration page, then for that you have to create a file named setup install data and in that, you have to set the field type keeping in mind the requirements of your attribute.

Wishusucess/CustomerAttribute/registration.php

Wishusucess/CustomerAttribute/etc/module.xml

Wishusucess/CustomerAttribute/Setup/InstallData.php

As soon as you create these three files your model will be ready and after that, you have to run the command to install the Magento model.

For example, you want to add a mobile number or phone number or some other required field to the customer account page. So you just have to follow the following code to create a field for custom attributes.

Let’s follow the below steps to Create a Custom Attribute in Magento 2 :

You may also like this :

How to Override Block, Controller, and Model in Magento 2

 

Step 1: Create Customer Attribute Registration File

app/code/Wishusucess/CustomerAttribute/registration.php

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

 

Step 2: Create Module XML File

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

<?xml version="1.0"?>
<!--
/**
* Category: Wishusucess_CustomerAttribute',
* 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_CustomerAttribute" setup_version="1.0.7" />
</config>

 

Step 3: InstallData.php File For Customer Custom Attribute

Here, you can decide your custom customer attribute identifier name, label, and others properties types.

So you have to enter an attribute code to identify the Magento 2 attribute within the system.

There is some default rule that needs to follow while creating your InstallData PHP file.

While adding custom attributes your attribute code must begin with a letter and can include any combination of lowercase letters (a-z) and numbers (0-9).

The custom attribute code can not be greater than thirty characters in length, and also you have to keep in mind that you cannot include any special characters or spaces.

The underscore character (_) we can use while defining the name.

app/code/Wishusucess/CustomerAttribute/Setup/InstallData.php

<?php
/**
* Category: Wishusucess_CustomerAttribute
* Developer: Hemant Singh Magento 2x Developer
* Website: http://wwww.wishusucess.com
*/ 
namespace Wishusucess\CustomerAttribute\Setup;

use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
* Install data
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{

/**
* CustomerSetupFactory
* @var CustomerSetupFactory
*/
protected $customerSetupFactory;

/**
* $attributeSetFactory
* @var AttributeSetFactory
*/
private $attributeSetFactory;

/**
* initiate object
* @param CustomerSetupFactory $customerSetupFactory
* @param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
)
{
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}

/**
* install data method
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{

/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

/** @var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
/**
* customer registration form default field mobile number
*/
$customerSetup->addAttribute(Customer::ENTITY, 'wishusucess_customerattribute', [
'type' => 'varchar',
'label' => 'Wishusucess Customer Attribute',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
//add attribute to attribute set
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'wishusucess_customerattribute')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer', 'customer_account_create'],
]);

$attribute->save();


}
}

 

Now, you need to run the below Magento 2 command to get install your custom attribute module.

php bin/magento s:up

php bin/magento s:s:d -f

php bin/magento c:c

 

Now you can see the result in

Admin > All Customer > Customer Name 

Magento 2 Custom Attribute

Download This Module

 

Suggested Post:

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