How to Get New Arrival Product REST API in Magento 2

In this article, we will learn how to filter the products of a Magento 2 store using the REST API and we will also know how to get new arrival products REST API.

By the way, Magento 2 Provides a facility for the REST API that is well known as Swagger Module which contains all list of REST APIs resources:

Using this model, you can get the product by visualizing and testing it through REST API.

When you hit the URL of your store by typing swagger you will get the list details of all the APIs.

Like I have taken an example below, according to this example you enter your URL and hit it, then you will get the API.

Endpoint:

http://www.wishusucess.com/swagger

Here we are filtering the product on the basis of attribute and the name of that attribute is a new product.

So while filtering the product through Rest API, we will get the newly added product by filtering

 

 

Get New Arrival Products REST API

 

To filter a new product, what should be its search criteria and which method will be used, what access token will be used, the details of all these are given below.

Endpoint

https://www.wishusucess.com/rest/V1/products?searchCriteria[sortOrders][0][field]=created_at&searchCriteria[pageSize]=10

Method: GET

Header: 

  • Authorization: Bearer <admin token>
  • Content Type: application/json

Body: none

New Arrival Products REST API

Search Parameter for New Arrivals in REST API

 

Created At New Arrivals

Response:

{
"items": [
{
"id": 2007,
"sku": "WSH08-31-Purple",
"name": "Sybil Running Short-31-Purple",
"attribute_set_id": 10,
"price": 44,
"status": 1,
"visibility": 1,
"type_id": "simple",
"created_at": "2021-12-23 09:40:40",
"updated_at": "2021-12-23 09:40:40",
"weight": 1,
"extension_attributes": {
"website_ids": [
1
],
"category_links": [
{
"position": 0,
"category_id": "28"
},
{
"position": 0,
"category_id": "35"
},
{
"position": 0,
"category_id": "2"
}
]
},
"product_links": [],
"options": [],
"media_gallery_entries": [
{
"id": 3353,
"media_type": "image",
"label": "",
"position": 1,
"disabled": false,
"types": [
"image",
"small_image",
"thumbnail"
],
"file": "/w/s/wsh08-purple_main_1.jpg"
},
{
"id": 3354,
"media_type": "image",
"label": "",
"position": 2,
"disabled": false,
"types": [],
"file": "/w/s/wsh08-purple_back_1.jpg"
}
],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "image",
"value": "/w/s/wsh08-purple_main_1.jpg"
},
{
"attribute_code": "small_image",
"value": "/w/s/wsh08-purple_main_1.jpg"
},
{
"attribute_code": "thumbnail",
"value": "/w/s/wsh08-purple_main_1.jpg"
},
{
"attribute_code": "options_container",
"value": "container2"
},
{
"attribute_code": "msrp_display_actual_price_type",
"value": "0"
},
{
"attribute_code": "url_key",
"value": "sybil-running-short-31-purple"
},
{
"attribute_code": "required_options",
"value": "0"
},
{
"attribute_code": "has_options",
"value": "0"
},
{
"attribute_code": "tax_class_id",
"value": "2"
},
{
"attribute_code": "category_ids",
"value": [
"28",
"35",
"2"
]
},
{
"attribute_code": "description",
"value": "<p>Fortunately, it's okay to look cute while you're working out. The Sybil Running Short combines a fun, color-blocked design with breathable mesh fabric for sporty-fun style.</p>\n<p>&bull; Blue running shorts with green waist.<br />&bull; Drawstring-adjustable waist.<br />&bull; 4\" inseam. Machine wash/line dry.</p>"
},
{
"attribute_code": "size",
"value": "174"
},
{
"attribute_code": "color",
"value": "57"
}
]
}
],
"search_criteria": {
"filter_groups": [],
"sort_orders": [
{
"field": "created_at",
"direction": null
}
],
"page_size": 1
},
"total_count": 2046
}

 

Similar Posts:

Create Account REST API : How to Create an Account of Customer, Admin

Magento 2 Login REST API: How to Login Customer, Admin

Wishusucess on GitHub

Create Account REST API : How to Create an Account of Customer, Admin

In this article, I am going to explain to you how to use create account rest api in Magento 2. In this, I will also explain to you how to create customer and admin accounts using REST API.

Whenever you order a product inside the Magento store, there are three ways to do it.

By creating a customer account, we can order the product, which we call registered users or they are also called logged-in customers.

Another way is that customers can order products without registering an account, whom we know as guest users.

The third way is that the guest customer is registered only at the time of ordering.

As a guest user who logs in or creates an account when ordering
Through this article, I am going to explain how to register a client through the REST endpoint.

 

 

Admin Create Account REST API

Now if you are looking for the REST API endpoint to create Magento 2 admin users s you can follow the below steps.

 

Endpoint:

The below details are the basic structure of REST APIs to call in Magento 2.

<HTTP verb> http://<host>/rest/<scope>/<endpoint>

HTTP headers:

Through this section, we send the required authentication details and tell the Magento store that we are the authentic user who can access the requested data.

Payload:

Through this section, we send necessary valid details along with the endpoint.

POST <host>/rest/<store_code>/V1/tfa/provider/google/authenticate
{
"username": "admin",
"password": "<admin-password>",
"otp": "<otp-value>"
}

There is no API to create a Magento admin user you can get the access token of the admin user by using the rest API.

But you can create an admin account from the Magento 2 store in the admin.

Admin Panel > System > Permissions > All User > New User.

 

Response:

When you use the Magento admin rest API to get the access token that returns the admin’s access token in the following format.

4r2jdjdr11j6gmau8990hcj6qk5unh3i

Now, whenever you need to access the backend details or any other details then you have to use this token in the header for the authorization in every call and that header token validate then allows you to access the store details.

 

 

Customer REST API to Create Account

 

To create a customer, we can send all the details in the payload, in the first step I have only added four fields to create a customer in a short way.

But when you create a customer through rest API, all the other fields are optional, that's why you don't need to add all the fields in order to create customer accounts. You can create a customer by sending only four details in the payload in the Rest API.

 

Method 1: REST API to Create Customer in Magento 2

Endpoint:

POST <host>/rest/<store_code>/V1/customers
http://www.wishusucess.com/rest/V1/customers

Method: POST

Authorization: Not required

Body: raw: JSON

Headers: Content-Type: application/json

{
"customer": {
"email": "cs.hemantsingh@gmail.com",
"firstname": "Hemant",
"lastname": "Singh"
},
"password": "aaAdm378in@#123"
}

Create Account REST API in Magento 2

 

Response:

{
"id": 4,
"group_id": 1,
"created_at": "2022-01-14 18:38:21",
"updated_at": "2022-01-14 18:38:21",
"created_in": "Default Store View",
"email": "cs.hemantsingh@gmail.com",
"firstname": "Hemant",
"lastname": "Singh",
"store_id": 1,
"website_id": 1,
"addresses": [],
"disable_auto_group_change": 0,
"extension_attributes": {
"is_subscribed": false
}
}

 

Method 2: Create Customer REST API

In this step I am adding full customer details in payload else other details will be the same as the first methiod.

create customer rest api in detail

Response:

{
"id": 5,
"group_id": 1,
"default_billing": "3",
"default_shipping": "3",
"created_at": "2022-01-14 19:02:46",
"updated_at": "2022-01-14 19:02:47",
"created_in": "Default Store View",
"email": "cs.hemants@gmail.com",
"firstname": "Hemant",
"lastname": "Singh",
"store_id": 1,
"website_id": 1,
"addresses": [
{
"id": 3,
"customer_id": 5,
"region": {
"region_code": "UP",
"region": "Uttar Pradesh",
"region_id": 566
},
"region_id": 566,
"country_id": "IN",
"street": [
"Noida"
],
"telephone": "7992293862",
"postcode": "201301",
"city": "Noida",
"firstname": "Hemant",
"lastname": "Singh",
"default_shipping": true,
"default_billing": true
}
],
"disable_auto_group_change": 0,
"extension_attributes": {
"is_subscribed": false
}
}

 

If you log in to your Magento 2 store with any of the username and password details that you have given while creating the account using REST API, then it will log in successfully.

Or if you go to All Customers in the admin of the store, then your new account that has been created will appear.

Now if you want to implement login functionality using Magento rest api then you can use login rest API.

 

Read more: Magento 2 Login REST API: How to Login Customer, Admin

 

Other Post:

PayPal Account: How to Create New PayPal Account, Transfer

Wishusucess on GitHub

Magento 2 Login REST API: How to Login Customer, Admin

I am going to explain the Magento 2 login REST API for mobile applications so by using those REST APIs you can develop the application using the Magento 2 e-commerce framework.

So these APIs are basically used for the login system for the customers and admin users. You can take help of these proper rest ways to implement the login functionality.

 

 

Magento 2 Login REST API

 

To access the data of any store of your magento, first of all, you have to define yourself that you are the genuine person accessing that data.

Authentication means you have to prove as a genuine user of customer it admin that allows Magento e-commerce store to identify the access rights. It means you have the right to access (administrator, integration, client, or guest) resources of the API call.

Now if you just want to check some things as a front-end customer then you have to log in customer and for that, you have to get a customer access token.

But if you want to access internal details of the store then for that you must have to authenticate your identity and get an access token of admin details.

 

 

Magento 2 Login Rest API Customer

 

Step 1: You must have a customer account in order to get access tokens of customers. If you don't have a user account then you can create a customer account first.

Step 2: Now you have to send the customer user details like username and password in the payload with the POST method.

Step 3: Get customer access token in response.

 

API URL: {baseurl}/rest/V1/integration/customer/token

Endpoint:

https://wishusucess.com/rest/V1/integration/customer/token

Method: POST

Authorization: Not required

Body:

{
   "username":"cs.hemantsingh@gmail.com",
   "password":"Admin@#44123"
}

Magento 2 Login REST API

Response:

l2l6ccj0hwvm6pvj7uy7oflr7k7uvabv

 

 

Admin Login REST API in Magento 2

 

If any mobile application is developed using Magento eCommerce then at that time we need to login to Magento admin through rest API.

Let us know what is the complete step of admin login via REST API, by following which we can get this access token.

Step 1: You need a Magento store admin account in order to get access tokens of your stores via rest API.

Step 2: Now by hitting the below details you can get the admin access token. Along with the rest API URL you have to send the admin username and password in the payload with the POST method.

Step 3: Get admin access token in response.

 

API URL: {baseurl}/rest/V1/integration/admin/token

Endpoint: 

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

Method: POST

Header: Not required

Body:

{
    "username":"admin32",
    "password":"Admin555@#123"
}

Magento 2 Login REST API

Response:

9nnv93lsivrfvzyzt1cgdw8f3xnij05v

 

Read more: Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

Similar Post:

How to Make Payment Using PayPal REST API in Magento 2

Configure PayPal in Magento 2 : How to Integrate PayPal

How to Make Payment Using PayPal REST API in Magento 2

I am going to explain to you how to make payments using the PayPal REST API call to create orders through PayPal in Magento 2 e-commerce platform.

Here I am using the PayPal payment method to create an order for which I will pay through PayPal REST API and complete the order.

So it is important to have the right API calls as well as the right payload to fulfill the order.

When we hit the Paypal API, other details like basic authorization and header details must also be correct, otherwise, the payment will not be completed.

 

Read more: Configure PayPal in Magento 2 : How to Integrate PayPal

 

Now the correct point is what is the correct API call and payload to complete the order using PayPal express payment method to process checkout payment get it done the order.

So let's start steps one by one in order to complete the product order via Paypal rest API.

 

 

Step 1: Get an Access Token PayPal Sandbox App

 

First of all, we have to do the configuration of Magento admin, for that you can follow this step of Paypal Integration in Magento 2.

When your account is created and all its details are received then you reach this step to get access token using Paypal rest API.

You can proceed to the next step only after getting the required sandbox account details from the PayPal Developer Dashboard, for this you can complete those steps of the development environment to get OAuth 2.0 client ID and secret credentials for the sandbox accounts.

The access token you received authorizes you to access the PayPal REST API server by using those tokens.

 

Endpoint:

https://api-m.sandbox.paypal.com/v1/oauth2/token

Method: POST

Authorization: Basic Auth

Username: My app and credentials(client_id)

Password: Client secret

Body: x-www-form-urlencoded

grant_type = client_credentials

Get PayPal Access Token For Apps

 

Step 2: Create Order Using PayPal REST API

 

Now by using the below payload details you can create an order and complete the payment by using Paypal REST Apis call.

Endpoint:

https://api-m.sandbox.paypal.com/v1/payments/payment

Method: POST

Header:

Content-type: application/json

Authorization: <access-token>

Authorization: Basic Auth

Username: my app and credentials(client_id)

Password: Client secret

{
"intent": "authorize",
"experience_profile_id": "XP-T8WE-L7SC-RN4L-QJAS",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"currency": "USD",
"total": "1.25",
"details": {
"shipping": "0.1",
"subtotal": "1",
"tax": "0.15"
}
},
"payee": {
"email": "cs.hemantsingh@gmail.com"
},
"description": "Test paypal payment done on 13th Jan 2022",
"item_list": {
"items": [{
"name": "acessories belt monolog",
"quantity": "1",
"price": "1",
"sku": "test1",
"currency": "USD"
}],
"shipping_address": {
"recipient_name": "Hemant Singh",
"line1": "New test",
"city": "Saratoga",
"country_code": "US",
"postal_code": "95070",
"phone": "0116519999164",
"state": "CA"
}
}
}],
"redirect_urls": {
"return_url": "https://wishusucess.com/",
"cancel_url": "https://wishusucess.com/"
}
}

Create Order Using PayPal REST API

 

Response: Order Created Using PayPal Payment Method

{
"id": "PAYID-MHL4VTA69N500857X1559800",
"intent": "authorize",
"state": "created",
"payer": {
"payment_method": "paypal"
},
"transactions": [
{
"amount": {
"total": "1.25",
"currency": "USD",
"details": {
"subtotal": "1.00",
"tax": "0.15",
"shipping": "0.10"
}
},
"payee": {
"email": "cs.hemantsingh@gmail.com"
},
"description": "Test paypal payment done on 13th Jan 2022",
"item_list": {
"items": [
{
"name": "acessories belt monolog",
"sku": "acessoriebelt321",
"price": "1.00",
"currency": "USD",
"quantity": 1
}
],
"shipping_address": {
"recipient_name": "Hemant Singh",
"line1": "New test",
"city": "Saratoga",
"state": "CA",
"postal_code": "95070",
"country_code": "US",
"phone": "0116519999164"
}
},
"related_resources": []
}
],
"experience_profile_id": "XP-T8WE-L7SC-RN4L-QJAS",
"create_time": "2022-01-07T05:08:28Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAYID-MHL4VTA69N500857X1559800",
"rel": "self",
"method": "GET"
},
{
"href": "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-47V04030JC5984021",
"rel": "approval_url",
"method": "REDIRECT"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAYID-MHL4VTA69N500857X1559800/execute",
"rel": "execute",
"method": "POST"
}
]
}

 

 

Approval PayPal REST API Payments

 

Paypal Login Details: Enter your Paypal username

Password: Enter your Paypal password details

 

"href": "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-50C051037E557641M",
"rel": "approval_url",

"method": "REDIRECT"

 

Now you have to hit the approval URL in your response body and proceed as a guest for the testing purpose and it will redirect to the website to review the order.

PayPal REST API for Payment

As soon as you do this complete step, then your order will be completed and it will automatically go to your website.

Configure PayPal in Magento 2 : How to Integrate PayPal

I will tell you to step by step method to How to integrate the PayPal payment gateway on Magento 2 checkout page or configure PayPal in Magento 2.

PayPal comes by default with Magento, but we have to integrate it, then the PayPal payment option comes on the checkout page.

The Magento Ecommerce Framework provides a default model for integrating the PayPal Express checkout account. This feature was not there in the old version of Magento, but in the above version of 2.1.8, this facility has been given.

 

 

PayPal Payment Gateway in Magento 2

 

Paypal Express Checkout is also easy to integrate and it is easy for the customer to make the payment.

Due to this, the credibility of the website also increases. And when the website looks reliable in the eyes of the customer, then its sales also increase.

PayPal Payment Gateway is the most used payment gateway in the world which is also known for being the fastest and most secure.

It accepts payments in almost all currencies and mediums like debit cards, credit cards, etc.

The above-mentioned reason is sufficient that it is used in any online store or to accept online payment,

Then let us know how to add the PayPal Express Checkout payment method on your Magento website.

 

 

Steps to Configure PayPal in Magento 2

 

In order to configure PayPal Payment Gateway in Magento 2, we have to follow the following steps.

  • Expand the Paypal Express Checkout section in Magento 2, Admin.
  • Create a PayPal Account
  • Go to developer Paypal my account section and then get PayPal, API Username, API Password, and API Signature.
  • Fill in all the required details in Magento 2 admin.
  • Admin > Store > Configuration > Sales > Payment Method > Select Merchant Location > PayPal Express
  • Just select test mode for testing purposes or not for live site

Configure PayPal in Magento 2

 

Step 1: Create PayPal Account

 

You have to first log in from the developer account section of PayPal and then click on API & SDK.

Log into paypal account

 

Now you have to go inside of My Apps and credentials PayPal developer account then click on generate sandbox access token button then your business sandbox details will be generated.

Configure PayPal in Magento 2

 

Now you have to click on the Paypal personal or business mail manage the account you will see view/see the details.

Get PayPal Account APIs Key Details

 

After clicking on the above button you will get the API Credentials details of PayPal for the PayPal Integration.

Get My Apps Credentials PayPal

 

 

Step 2: Configure PayPal in Magento 2 Admin

 

Now just go inside of admin section and fill in all the details.

Admin > Store > Configuration > Sales > Payment Method > Select Merchant Location > PayPal Express

Now your Magento 2 Paypal payment method configuration has been done.

After successful completion, when you go to the frontend of your Magento 2 store you will see the PayPal payment option.

 

 

How Frontend Looks After PayPal Integration

 

I am giving you some details below, by which you will be confirmed that your PayPal payment method has been completed.

First of all, you have to go to the product details page of Magento 2 you will see the PayPal payment option.

Then you will go to the mini cart and there you will also see the PayPal payment method.

Now you will go to the checkout page of Magento 2 and there you will also see the PayPal payment method option

All these proofs prove that your PayPal payment integration has been successfully completed.

 

 

Add PayPal on Product Details Page

 

When PayPal is successfully added, then this automatic option will appear on the product detail page.

If you want to keep this payment option on the product detail page, then you can keep it, otherwise, you can also remove it.

Configure PayPal in Magento 2 Product Detail Page

 

 

 

PayPal Payment Option in MiniCart

 

This feature comes by default in Magento, when your PayPal account is properly integrated, then this payment option starts appearing.

Configure PayPal in Magento 2 on Minicart

 

 

Configure PayPal in Magento 2 on Checkout Page

 

Now in the last step, your PayPal payment option appears as a payment method on Magento 2 checkout page.

Here any customer can make his payment using the PayPal payment gateway option.

PayPal accepts all payment methods.

Add PayPal Payment Method on Checkout Page

 

 

Conclusion

 

Although there are other default payment methods on the Magento website, the PayPal payment method is the most important of them and also more popular.

Because it provides the facility of making payments with the fastest, most secure, and best user experience.

This contributes even more to connecting the customers of website owners,

Due to all these great experiences, your website plays an important role in increasing the sales rates and attracting more customers.

 

Payment Gateway Integration Helpline

 

If you face any problem in integrating any payment gateway, then feel free to call us or message us.

We will solve any kind of problem immediately.

Helpline number:

Skype: cs.hemantsingh@gmail.com

Phone: +91-8197565002

 

Similar Posts:

Best Payment Gateway For Magento 2: List of Top 7 And How To Integrate

Best Payment Gateway For Magento 2: List of Top 7 And How To Integrate

In this article, I am going to explain to you how you should choose and integrate payment gateway and the pros and cons of online payments gateways providers. I will also discuss the best payment gateway for Magento 2 websites in 2022.

If you want to advance your business in the Internet world, then it does not matter whether you are the owner of an eCommerce platform or doing any other work.

You have to think about your customers and provide them with a secure, quick, and easy-to-use payment system that will help them make their payments, otherwise, your business will be very difficult to run.

Business owners also have to keep in mind whether they choose the payment system keeping in mind their needs and keeping in mind their customers or not.

The payment solution you choose must meet the needs of both your customers and your business. Therefore, your business must protect your customers from fraud, and also take care that your business is not affected.

The payment method added to your business should be convenient to use and compatible with your website.Best Payment Gateway For Magento 2

When we use a payment gateway to make an online payment, that gateway enables us to process the credit or debit card electronically to accept the payment.

Many times it happens that due to the complex online system, customers leave the website without completing the order.

In such a situation it becomes necessary that the payment gateway of your website should be friendly according to your target customer.

 

Payment Gateway Integration With eCommerce Store

When it comes to e-commerce, payment solutions play an important role in this, at that time we have to make sure that it accepts all your payment methods and credit cards.

According to data in 2022, by far the most popular payment method is a credit card.

If we take out the percentage by adding all the regions, then up to seventy percent of the people prefer to pay by credit card only.

Now the rest of the percentage is occupied by some leading payment companies like PayPal, Amazon, etc.

When your business is global, then your payment method needs to have the option to pay in all types of currency so that customers from every region can pay according to their currency.

When we integrate the payment methods then that differ by two major factors:

  • Whether you must be in compliance with any financial regulation (PCI DSS), and
  • the degree of user experience concerning the checkout and payment procedure.

PCI DSS Compliance:

When we do not store sensitive data of any of our customers, it is not required because when we add third-party payment gateways, all the processing, and regulatory burden is handled by those parties. So you do not need these certificates.

But when you store those data, then it becomes necessary for you to follow those industry rules and regulations.

The Payment Card Industry Data Security Standard (PCI DSS) came into existence in 2004 that handle essential elements for processing card payments.

 

Best Payment Gateway for Magento 2 in 2022

Here, I am giving you the list of best payment gateway which according to 2022 comes in the name of best payment gateway.

Stripe

Stripe is one of the most popular eCommerce payment gateways solutions. That accepts all major electronic payment methods, including Apple Pay, WeChat Pay, and Android Pay.

Pricing does not charge for setup but the standard package charges 2.9 percent + $0.30 per transaction. And the international processing is approx 1 percent on each transaction. Strip also offers customized plans for the business.

 

Read More: How to Integrate Payment Gateway in Magento With Example

 

PayPal

Paypal Payment Gateway provides its service to every corner of the world, This electronic payment gateway is the best payment gateway for Magento e-commerce, its service is worthy of praise.

PayPal provides all kinds of packages for its customers, according to which customers can upgrade the plan according to their convenience. That is one of the best scalable solutions for all types of businesses sized.

PayPal Offers to Process:

  • Credit cards, debit cards, and PayPal payments themselves
  • Other processing services: PayPal Payments Pro, PayPal Express Checkout, and Braintree.

Braintree is a separate payment solution for mobile and web payment systems for e-commerce that completely waives off your international fees. You don't have to pay any extra charges.

PayPal’s Pricing:

  • Zero setup fees.
  • Domestic transactions: 2.9 percent + $0.30 per transaction.
  • Outside the US transactions: are 3.9 percent + a fee based on the currency used. T
  • PayPal Payments Pro charges $30 monthly for a subscription.

 

Amazon Pay

Amazon Pay is also a leading payment gateway method, this eCommerce giant designed its service for the smaller business owner and targets the online retailers.

Amazon Pay offers its processing service for all major cards like credit cards, debit cards, and other major payment methods.

Pricing:

  • Domestic transactions: 2.9 percent + $0.30 per transaction.
  • International is 3.9 percent.
  • The refund amount is $20 + taxes, if applicable.
  • No charges for installation or setup or monthly fees.

 

Authorize.net

Authorize.net's main customers are small and medium-sized businesses and their targeted business model is also designed for them.

This service accepts almost all payment methods, including Paypal and Amazon Pay.

Its security service is quite advanced which facilitates its customers for a seamless transaction for web and mobile applications.

Pricing:

Domestic transaction: 2.9 percent + $0.30 per transaction.

There is a $25 monthly fee for a gateway and $49 for a merchant account setup.

 

2Checkout

2Checkout offers its service in approximately 87 currencies and 15 languages. Its service is such that it easily connects with businesses of different sizes and offers them a worthy choice of customizable service.

Pricing:

  • No setup charges.
  • Domestic transaction: 3.5 percent + $0.35 per transaction.
  • 2Monetize charges: 6.0 percent + $0.60 per transaction.

 

Read more: Step By Step Guide For How To Add Razorpay Payment Gateway

 

Why Custom Payment Gateway?

The third-party payment system is perfect for small or middle-class merchants because it gives them good facility on a certain amount in less time but custom payment gateway becomes necessary for large entrepreneurs or big business organizations that they should not have any kind of restriction.

Having a system to make your own payment according to your own direction, free from all kinds of extra instructions, is an essential step in making the business successful.

However, a custom payment gateway can give you several benefits:

Low Transaction Fee:

If you create your own payment gateway, then the first benefit is that you are saved from transactional charges.

When a large business saves some amount on every single transaction, that becomes a huge number which helps in business growth.

Customization:

When you decide on a custom payment method, then you can completely customize it according to your business, which facilitates the payment of the customer of your business and increases your business growth.

You can also customize your transaction fee according to your business.

Once you have developed the facility to make a custom payment, you can also offer your service to another business and in return, you can do business deals or apply some transaction charges.

 

Conclusion

In conclusion, we can say that you can choose the payment gateway according to the convenience of your business.

If you are a small-scale merchant then it is better to use a third-party payment gateway.

When you use your own payment gateway, it increases your customer's trust in your business and contributes significantly to your sales growth.

Custom payment gateway needs development and maintenance all the time, it should have good ability to eliminate any kind of fraud methods

 

Recommended Post:

PayPal Account: How to Create New PayPal Account, Transfer

How to Add Owl Carousel Slider in Magento 2 Products

In this tutorial, I am going to explain to you how you can add owl carousel slider in Magento 2. When making the user interface of Magento, it has to be taken care of that how to show more and better content in less space.

Add owl carousel Slider Magento 2

Owl carousel slider is very helpful to have that user interface look good. This slider is most widely used in eCommerce websites.

Magento 2 website owners mostly use the Owl Carousel slider to display various types of products such as new arrival products, most viewed products, more liked products slider, featured product slider, best seller product slider, etc.

 

How to Add Owl Carousel Slider in Magento 2

1) In the first step, we will add

 app/code/Wishusucess/OwlSlider/view/frontend/templates/slider.phtml file
<!--
/**
* Created By : Hemant Kumar Singh Magento 2x Developer
*/
-->
<!DOCTYPE html>
<html>
<body>
<div class="carousel-wrap">
<div class="owl-carousel">
<div class="item"><img src="http://wishusucess.com/350x300?text=1"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=2"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=3"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=4"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=5"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=6"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=7"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=8"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=9"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=10"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=11"></div>
<div class="item"><img src="http://wishusucess.com/350x300?text=12"></div>
</div>
</div>
</body>
</html>

 

2) In the second step you have to add this javascript file to your custom extension.

app/code/Wishusucess/OwlSlider/view/frontend/web/js/common.js
/**
* Created By : Hemant Kumar Singh Magento 2x Developer
*/
require(['jquery', 'owlcarousel'], function($) {
$(document).ready(function() {
$('.owl-carousel').owlCarousel({
loop: true,
margin: 10,
nav: true,
navText: [
"<i class='fa fa-caret-left'></i>",
"<i class='fa fa-caret-right'></i>"
],
autoplay: true,
autoplayHoverPause: true,
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
});
});
});

 

3) Now in the third step you have to add the javascript file in the phtml file so you have to create a file.

app/code/Wishusucess/OwlSlider/view/frontend/owlslider_index_index.xml
<?xml version="1.0"?>
<!--
/**
* Created By : Hemant Kumar Singh Magento 2x Developer
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
layout="1column"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<script src="Wishusucess_OwlSlider::js/common.js" async="async" />
</head>
<body>
<referenceBlock name="content">
<block class="Magento\Framework\View\Element\Template"
name="proslider"
template="Wishusucess_OwlSlider::productslider.phtml" />
</referenceBlock>
</body>
</page>

 

4) In the fourth step we have to add an owl slider

app/code/Wishusucess/OwlSlider/view/frontend/requirejs-config.js
/**
* Created By : Hemant Kumar Singh Magento 2x Developer
*/
var config = {
paths: {
owlcarousel: "Wishusucess_OwlSlider/js/owl.carousel"
},
shim: {
owlcarousel: {
deps: ['jquery']
}
}
};

 

Now in order to make your slider more attractive and beautiful, you can add extra CSS and js files in your Magento 2 custom OwlSlider module’s web folder. We can add this code as per our requirement and can add this slider on any cms page also.

That’s it !!!

You can check the full module here: GitHub

 

Read more: Magento 2.4 Installation Guide: How to Install Magento 2.4.2

 

How to Call Owl Slider in Magento2 Related Products

This step will help you to add the Owl Slider in Magento 2.x You just have to follow the below steps.

I assume that you are using a custom Magento 2 theme so here I am taking as an example.

ThemeVender : Wishusucess

ThemeName:   WishusucessTheme

Let's start

If you want to put the slider in the related product on the product details page of Magento 2 then you can follow the steps given below.

This step will help you to add Owl Slider for Related Product in the product detail page.

You need to update

app/design/frontend/Wishusucess/WishusucessTheme/Magento_Theme/Magento_Catalog/templates/product/list/items.phtml

The file to implement OwlCarousel for Related Products.

 

Step 1: Download OwlCarousel from here: Owl Carousel

Please put all OwlCarousel JS files owl.carousel.min.js and owlcarousel.js in this directory

app/design/frontend/Wishusucess/WishusucessTheme/Magento_Catalog/web/js

After that put all OwlCarousel CSS files owl.carousel.css and owl.theme.default.css etc... in this directory

app/design/frontend/Wishusucess/WishusucessTheme/web/css/owlcarousel/assets

 

Step 2: Include OwlCarousel CSS files using default_head_blocks.xml layout XML file.

For that create

app/design/frontend/Wishusucess/WishusucessTheme/Magento_Theme/layout/default_head_blocks.xml

default_head_blocks.xml file code.

<?xml version="1.0"?>
<!--
/**
* Hemant Kumar Singh Magento 2x Developer
* Website url: http://www.wishusucess.com/
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/> 
<css src="css/owlcarousel/assets/owl.carousel.min.css" />
<css src="css/owlcarousel/assets/owl.theme.default.min.css" />
</head>
</page>

 

Step 3: Include OwlCarousel JS using requirejs config file.

Now you have to create a file

app/design/frontend/Wishusucess/WishusucessTheme/Magento_Catalog/requirejs-config.js

requirejs-config.js file code.

var config = {
paths: { 
'owlcarousel': "Magento_Catalog/js/owlcarousel"
}, 
shim: {
'owlcarousel': {
deps: ['jquery']
}
}
};

 

Step 4: Update items.phtml File

Copy from

/vendor/magento/module-catalog/view/frontend/templates/product/list/items.phtml

and paste to

app/design/frontend/Wishusucess/WishusucessTheme/Magento_Theme/Magento_Catalog/templates/product/list/items.phtml

Now update the item.phtml file to implement OwlCarousel

Here, I am giving you the items.phtml code, you can just copy and paste.

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* Developer: Hemant Kumar Singh Magento 2x Developer
*/

// @codingStandardsIgnoreFile

/* @var $block \Magento\Catalog\Block\Product\AbstractProduct */
?>

<?php
switch ($type = $block->getType()) {

case 'related-rule':
if ($exist = $block->hasItems()) {
$type = 'related';
$class = $type;

$image = 'related_products_list';
$title = __('Related Products');
$items = $block->getAllItems();
$limit = $block->getPositionLimit();
$shuffle = (int) $block->isShuffled();
$canItemsAddToCart = $block->canItemsAddToCart();

$showAddTo = false;
$showCart = false;
$templateType = null;
$description = false;
}
break;

case 'related':
/** @var \Magento\Catalog\Block\Product\ProductList\Related $block */
if ($exist = $block->getItems()->getSize()) {
$type = 'related';
$class = $type;

$image = 'related_products_list';
$title = __('Related Products');
$items = $block->getItems();
$limit = 0;
$shuffle = 0;
$canItemsAddToCart = $block->canItemsAddToCart();

$showAddTo = true;
$showCart = false;
$templateType = null;
$description = false;
}
break;

case 'upsell-rule':
if ($exist = $block->hasItems()) {
$type = 'upsell';
$class = $type;

$image = 'upsell_products_list';
$title = __('We found other products you might like!');
$items = $block->getAllItems();
$limit = $block->getPositionLimit();
$shuffle = (int) $block->isShuffled();

$showAddTo = false;
$showCart = false;
$templateType = null;
$description = false;
$canItemsAddToCart = false;
}
break;

case 'upsell':
/** @var \Magento\Catalog\Block\Product\ProductList\Upsell $block */
if ($exist = count($block->getItemCollection()->getItems())) {
$type = 'upsell';
$class = $type;

$image = 'upsell_products_list';
$title = __('You may also like');
$items = $block->getItemCollection()->getItems();
$limit = $block->getItemLimit('upsell');
$shuffle = 0;

$showAddTo = false;
$showCart = false;
$templateType = null;
$description = false;
$canItemsAddToCart = false;
}
break;

case 'crosssell-rule':
/** @var \Magento\Catalog\Block\Product\ProductList\Crosssell $block */
if ($exist = $block->hasItems()) {
$type = 'crosssell';
$class = $type;

$image = 'cart_cross_sell_products';
$title = __('More Choices:');
$items = $block->getItemCollection();

$showAddTo = true;
$showCart = true;
$templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
$description = false;
$canItemsAddToCart = false;
}
break;

case 'crosssell':
/** @var \Magento\Catalog\Block\Product\ProductList\Crosssell $block */
if ($exist = count($block->getItems())) {
$type = 'crosssell';
$class = $type;

$image = 'cart_cross_sell_products';
$title = __('More Choices:');
$items = $block->getItems();

$showAddTo = true;
$showCart = true;
$templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
$description = false;
$canItemsAddToCart = false;
}
break;

case 'new':
if ($exist = $block->getProductCollection()) {
$type = 'new';
$mode = 'grid';
$type = $type . ' ' . $mode;

$class = 'widget' . ' ' . $type;

$image = 'new_products_content_widget_grid';
$title = __('New Products');
$items = $exist;

$showAddTo = true;
$showCart = true;
$templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
$description = ($mode == 'list') ? true : false;
$canItemsAddToCart = false;
}
break;

case 'other':
break;
}
?>

<?php if ($exist):?>
<div class="clearfix"></div>
<?php if ($type == 'related' || $type == 'upsell'): ?>
<?php if ($type == 'related'): ?>
<div class="block <?= /* @escapeNotVerified */ $class ?>" data-mage-init='{"relatedProducts":{"relatedCheckbox":".related.checkbox"}}' data-limit="<?= /* @escapeNotVerified */ $limit ?>" data-shuffle="<?= /* @escapeNotVerified */ $shuffle ?>">
<?php else: ?>
<div class="block <?= /* @escapeNotVerified */ $class ?>" data-mage-init='{"upsellProducts":{}}' data-limit="<?= /* @escapeNotVerified */ $limit ?>" data-shuffle="<?= /* @escapeNotVerified */ $shuffle ?>">
<?php endif; ?>
<?php else: ?>
<div class="block <?= /* @escapeNotVerified */ $class ?>">
<?php endif; ?>
<div class="block-title title">
<strong id="block-<?= /* @escapeNotVerified */ $class ?>-heading" role="heading" aria-level="2"><?= /* @escapeNotVerified */ $title ?></strong>
</div>
<div class="block-content content" aria-labelledby="block-<?= /* @escapeNotVerified */ $class ?>-heading">
<?php if ($type == 'related' && $canItemsAddToCart): ?>
<div class="block-actions">
<?= /* @escapeNotVerified */ __('Check items to add to the cart or') ?>
<button type="button" class="action select" role="select-all"><span><?= /* @escapeNotVerified */ __('select all') ?></span></button>
</div>
<?php endif; ?>
<div class="products wrapper grid products-grid products-<?= /* @escapeNotVerified */ $type ?>">
<div id="relateditem_carousel" class="products list items product-items owl-carousel owl-theme"> 
<?php $iterator = 1; ?>
<?php foreach ($items as $_item): ?>

<?php $available = ''; ?>
<?php if (!$_item->isComposite() && $_item->isSaleable() && $type == 'related'): ?>
<?php if (!$_item->getRequiredOptions()): ?>
<?php $available = 'related-available'; ?>
<?php endif; ?>
<?php endif; ?>
<?php if ($type == 'related' || $type == 'upsell'): ?>
<?= /* @escapeNotVerified */ ($iterator++ == 1) ? '<div class="item product product-item" style="display: none;">' : '</div><div class="item product product-item" style="display: none;">' ?>
<?php else: ?>
<?= /* @escapeNotVerified */ ($iterator++ == 1) ? '<div class="item product product-item">' : '</div><div class="item product product-item">' ?>
<?php endif; ?>
<div class="product-item-info <?= /* @escapeNotVerified */ $available ?>">
<?= /* @escapeNotVerified */ '<!-- ' . $image . '-->' ?>
<a href="<?= /* @escapeNotVerified */ $block->getProductUrl($_item) ?>" class="product photo product-item-photo">
<?= $block->getImage($_item, $image)->toHtml() ?>
</a>
<div class="product details product-item-details">
<!--<strong class="product name product-item-name"><a class="product-item-link" title="<?= $block->escapeHtml($_item->getName()) ?>" href="<?= /* @escapeNotVerified */ $block->getProductUrl($_item) ?>">
<?= $block->escapeHtml($_item->getName()) ?></a>
</strong>-->

<!--<?= /* @escapeNotVerified */ $block->getProductPrice($_item) ?>-->

<?php if ($templateType): ?>
<?= $block->getReviewsSummaryHtml($_item, $templateType) ?>
<?php endif; ?>

<?php if ($canItemsAddToCart && !$_item->isComposite() && $_item->isSaleable() && $type == 'related'): ?>
<?php if (!$_item->getRequiredOptions()): ?>
<div class="field choice related">
<input type="checkbox" class="checkbox related" id="related-checkbox<?= /* @escapeNotVerified */ $_item->getId() ?>" name="related_products[]" value="<?= /* @escapeNotVerified */ $_item->getId() ?>" />
<label class="label" for="related-checkbox<?= /* @escapeNotVerified */ $_item->getId() ?>"><span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span></label>
</div>
<?php endif; ?>
<?php endif; ?>

<?php if ($showAddTo || $showCart): ?>
<div class="product actions product-item-actions">
<?php if ($showCart): ?>
<div class="actions-primary">
<?php if ($_item->isSaleable()): ?>
<?php if ($_item->getTypeInstance()->hasRequiredOptions($_item)): ?>
<button class="action tocart primary" data-mage-init='{"redirectUrl": {"url": "<?= /* @escapeNotVerified */ $block->getAddToCartUrl($_item) ?>"}}' type="button" title="<?= /* @escapeNotVerified */ __('Add to Cart') ?>">
<span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
</button>
<?php else: ?>
<?php $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
?>
<button class="action tocart primary"
data-post='<?= /* @escapeNotVerified */ $postData ?>'
type="button" title="<?= /* @escapeNotVerified */ __('Add to Cart') ?>">
<span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
</button>
<?php endif; ?>
<?php else: ?>
<?php if ($_item->getIsSalable()): ?>
<div class="stock available"><span><?= /* @escapeNotVerified */ __('In stock') ?></span></div>
<?php else: ?>
<div class="stock unavailable"><span><?= /* @escapeNotVerified */ __('Out of stock') ?></span></div>
<?php endif; ?>
<?php endif; ?>
</div>
<?php endif; ?>

<?php if ($showAddTo): ?>
<div class="secondary-addto-links actions-secondary" data-role="add-to-links">
<?php if ($addToBlock = $block->getChildBlock('addto')): ?>
<?= $addToBlock->setProduct($_item)->getChildHtml() ?>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<?= ($iterator == count($items)+1) ? '</div>' : '' ?>
<?php endforeach ?>
</div> 
</div>
</div>
</div>
<script type="text/javascript">
requirejs(['jquery','owlcarousel'],function(jQuery,owlCarousel){
(function($) {
$(window).load(function () {
$('#relateditem_carousel').owlCarousel({
items:4,
lazyLoad:false,
loop:false,
margin:10,
nav:false,
dots:false,
autoplay:true,
response:true,
autoplayHoverPause:false,
autoWidth:false,
responsive : {
0 : {
items:1,
},
420 : {
items:2,
},
768 : {
items:3,
},
991 : {
items:4,
}
}
});
});
})(jQuery);
});
</script> 
<?php endif;?>

 

Step 5: Now run the following CLI commands.

sudo rm -rf pub/static/frontend/*

sudo rm -rf var/cache/*

php bin/magento setup:upgrade

 

Owl Slider on Detail Page in Magento 2

Thats' all!!

 

 

Related Posts:

How to Get Data on Frontend From System Configuration File in Magento2

Add JS File in Magento 2 Module: How to Add Java Script

Add Multiple Product Attribute Using InstallData in Magento2

In this article, I am going to explain how to add multiple product attribute or create product attributes by using the installData.php file programmatically in Magento 2.

Magento 2  eCommerce follows the EAV database model, So in such a situation, it becomes necessary that its standard should be followed. So in order to add the custom attributes in Magento 2, we have to create the InsatllData PHP file.

In the chances of any online e-commerce website being successful, it matters a lot that how well you define the product.

When we want to define the product in a better way, we take the help of custom attribute which plays an important role in conveying to the customer of that store easily.

Custom product attribute is one of the important characteristics of the products. That is responsible to define the character and specification of the product so the customer easily understands their requirement and influence to buy that product. Examples of product attributes can be any type like product price,  product quantity, product size, etc.

 

Steps to Add Product Attribute Programmatically

In order to create the product attributes we have to follow the following steps, Wishusucess MultipleAttribute module will help you to understand how to add a product attribute in Magento 2.

  • Create file InstallData.php
  • Define the install() method
  • Create custom attribute

 

In the first step, we have to create an InstallData file then in the second step we will define the install method and in the third step, we will add a custom attribute.

 

Magento 2 Add Multiple Product Attribute Programmatically

We will create a file inside of Setup folder with the InstallData file name in the below location.

Wishusucess/ProductAttributes/Setup/InstallData.php

Now the content will look like the below class.

<?php
namespace Wishusucess\ProductAttributes\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
/**
* EAV setup factory
*
* @var EavSetupFactory
*/
private $eavSetupFactory;

/**
* Init
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

/**
* Add attributes to the eav/attribute
*/
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'wishusucess_featured',
[
'group' => 'General',
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Featured Product',
'input' => 'boolean',
'class' => '',
'source' => '',
'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
],
);

$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'wishusucess_bestseller',
[
'group' => 'General',
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Bestseller Product',
'input' => 'boolean',
'class' => '',
'source' => '',
'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
],
);

$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'wishusucess_specialproducts',
[
'group' => 'General',
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Special Product',
'input' => 'boolean',
'class' => '',
'source' => '',
'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
],
);

$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY, 
'wishusucess_newproducts',
[
'group' => 'General',
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'New Product',
'input' => 'boolean',
'class' => '',
'source' => '',
'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
]
);
}
}

 

Step 4: Run Magento 2 Command

Now run the below command

php bin/magento setup:upgrade

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

php bin/magento c:c

That's it!!

Now go to the Admin > Catalog > Product > Click on any product you will see like the below image.

Add multiple product attribute in Magento 2

The above code will help you to create multiple filter product attribute like best seller attribute, featured attribute, a new attribute, special attribute by using a single file.

 

If you are looking for this complete extension then you can check our GitHub link.

 

Related article

How to Get Data on Frontend From System Configuration File in Magento2

Add JS File in Magento 2 Module: How to Add Java Script

How to Get Data on Frontend From System Configuration File in Magento2

When we create a model inside Magento 2, we also give the system configuration of that model so that the admin user can manage it easily.

System Configuration Data Data in phtml

And any extension or model is considered good only when its user experience is good.

The more you manage or customize the admin side of the extension, the better your admin experience will be.

In this article, I am going to tell you how to create a configuration of System.xml in the admin of any model and get its data in the front end.

 

Get System Configuration Data in Phtml File

The system.xml is a configuration file that is used to manage any extension or module in Magento 2 by giving the option on the admin side to customize or change the behavior.

Configuration options are available in Magento 2

Store -> Settings -> Configuration

 

Step 1: Create Registration File

Here in the first step, you have to create a registration file to register your Magento 2 module or extension.

Wishusucess/SystemHelloworld/registration.php
<?php
/**
* @Developer: Hemant Kumar Singh Magento 2x Developer
* @Website: http://www.wishusucess.com/
*/ 
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Wishusucess_SystemHelloworld',
__DIR__
);

 

Step 2: Create Module XML File

Now you have to create a module XML file to give the module version and basic information of your Magento 2 System configuration module.

Wishusucess/SystemHelloworld/etc/module.xml
<?xml version="1.0"?>
<!--
/**
* @Developer: Hemant Kumar Singh Magento 2x Developer
* @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_SystemHelloworld" setup_version="1.0.0" active="true"></module>
</config>

 

Step 3: Create System Configuration XML File

The system. xml file is known as the configuration file that we used to create admin configuration fields in Magento 2 Module or extension.

This file decides the admin setting options for any extension or Module.

Store -> Setting -> Configuration
Wishusucess/SystemHelloworld/etc/adminhtml/system.xml
<?xml version="1.0"?>
<!--
/**
* @Developer: Hemant Kumar Singh Magento 2x Developer
* @Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="wus" translate="label" sortOrder="10">
<label>Wishusucess</label>
</tab>
<section id="wishusucess_systemhelloworld" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Hello World</label>
<tab>wus</tab>
<resource>Wishusucess_SystemHelloworld::wishusucess_systemhelloworld</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>General Configuration</label>
<field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Module Enable</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="text_title" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Title</label>
<comment>This title text.</comment>
</field>
<field id="text_description" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Description</label>
<comment>This is description text.</comment>
</field>
</group>
</section>
</system>
</config>

 

Step 4: Config XML file for Admin

Now we are going to create a config XML file that we used to provide the default value in admin configuration fields in Magento 2 admin.

Wishusucess/SystemHelloworld/etc/config.xml
<?xml version="1.0"?>
<!--
/**
* @Developer: Hemant Kumar Singh Magento 2x Developer
* @Website: http://www.wishusucess.com/
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<wishusucess_systemhelloworld>
<general>
<enable>0</enable>
<text_title>Wishusucess System Config Hello World</text_title>
<text_description>Wishusucess System Configuration Hello World Module</text_description>
</general>
</wishusucess_systemhelloworld>
</default>
</config>

 

Now till here, if you will run the below command then you will see the configuration like below screenshot

php bin/magento setup:upgrade

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

php bin/magento cache:clean

Magento 2 Create System Configuration

 

Step 5: System Configuration Helper Class

Now here we will get the data from a system XML file, we will initialize the path of each field id of the system.xml file in Magento 2.

In order to initialize the field path, we will prefer the order hierarchy.

Section_id/group_id/field_id
Wishusucess/SystemHelloworld/Helper/Data.php
<?php
/**
* @Developer: Hemant Kumar Singh Magento 2x Developer
* @Website: http://www.wishusucess.com/
*/
namespace Wishusucess\SystemHelloworld\Helper;
use Magento\Framework\App\Config\ScopeConfigInterface;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

/**
* Admin configuration paths
*
*/
const IS_ENABLED = 'helloworld_config/general/enable';

const TEXT_TITLE = 'helloworld_config/general/text_title';

const TEXT_DESCRIPTION = 'helloworld_config/general/text_description'; 
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $scopeConfig;

/**
* Data constructor
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
) {
parent::__construct($context);

}

/**
* @return $isEnabled
*/
public function isEnabled()
{
$isEnabled = $this->scopeConfig->getValue(self::IS_ENABLED, 
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);

return $isEnabled;
}

/**
* @return $textTitle
*/
public function getTextTitle()
{
$textTitle = $this->scopeConfig->getValue(self::TEXT_TITLE,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);

return $textTitle;
}

/**
* @return $textDescription
*/
public function getDisplayText()
{
$textDescription = $this->scopeConfig->getValue(self::TEXT_DESCRIPTION,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);

return $textDescription;
}

}

 

Step 6: Call Helper in Block Class

Here, we have to create a block class in order to call the helper. So that we can directly use the block function in the phtml file.

Wishusucess/SystemHelloworld/Block/AdminConfiguration.php
<?php
/**
* @Developer: Hemant Kumar Singh Magento 2x Developer
* @Website: http://www.wishusucess.com/
*/
namespace Wishusucess\SystemHelloworld\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Wishusucess\SystemHelloworld\Helper\Data;
use Magento\Framework\App\Config\ScopeConfigInterface;

class AdminConfiguration extends \Magento\Framework\View\Element\Template
{ 
public function __construct(
\Magento\Backend\Block\Template\Context $context,
Data $helper,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, 
array $data = []
)
{ 
$this->helper = $helper;
$this->scopeConfig = $scopeConfig;
parent::__construct($context, $data);
}

/*
* @return bool
*/
public function isEnabled()
{
return $this->helper->isEnabled();
} 
/*
* @return string
*/
public function getDisplayText()
{
return $this->helper->getDisplayText();
} 
}

 

Step 7: Call System Config Value in PHTML File

Now you will call the block method here so that the data of your admin field can be printed.

Another way is that you can directly call the helper class in this file and use its method.

In Magento 2, any system XML fields show the data of the common file ie admin fields on the front end

Wishusucess/SystemHelloworld/view/frontend/templates/helloworld.phtml
<?= $isEnabled; ?>

<?= $getTextTitle; ?>

<?= $getDisplayText; ?>

Or

<?php
$helper = $this->helper('Wishusucess\SystemHelloworld\Helper\Data');
$isEnabled = $helper->isEnabled();
$getTextTitle = $helper->getTextTitle();
$getDisplayText = $helper->getDisplayText();
?>
//Print Text title
<?php echo $getTextTitle; ?>

//Print Text Description 
<?php $getDisplayText; ?>

 

Now make this module enable and save it, then call this phtml in cms page or block if you want to check this simple module in Magento 2.

<p>{{block class="Wishusucess\SystemHelloworld\Block\AdminConfiguration" template="Wishusucess_SystemHelloworld::helloworld.phtml"}}</p>

 

Run the below command and then check

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

php bin/magento cache:clean

 

Magento 2 Get Data on Frontend from System XML

That's all !!

If you need any help with Magento 2 extension or module development you can directly contact me.

Thanks

Check with GitHub

 

Similar Posts:

Add JS File in Magento 2 Module: How to Add Java Script

Magento 2 Featured Products: How to Add Featured Products

Add JS File in Magento 2 Module: How to Add Java Script

When we create a magneto model or extension then at that time we also need to use javascript and style sheet file etc.
Let us know how we add js file in Magento 2 or style sheet in  Magento 2 module or extension.

Add JS file in Magento 2

Magento 2 has its own structure to define the javascript and CSS file. So we will follow the same path in order to add the js file to execute JavaScript code.

Here, I am going to explain with an example so I will create a Magento 2 module to add a JS file to execute the code and pass the parameters inside a script.

 

Steps to Add JS File in Magento 2 Module

There are five steps to add the js and CSS file in Magento 2 module.

  • Create or add in the existing module.
  • Create a requirejs-config.js and a JavaScript module file.
  • Create a layout update to add a template that will enable the JavaScript module.
  • Create a template file.

 

Step 1: Create a New Module

app/code/Wishusucess/AddJsfile/registration.php
<?php
/**
* Developer: Hemant Singh Magento 2x Developer
* Website: http://www.wishusucess.com/
*/

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Wishusucess_AddJsfile',
__DIR__
);

 

Step 2: Create a Module XML file

app/code/Wishusucess/AddJsfile/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Wishusucess_AddJsfile" setup_version="0.0.1">
</module>
</config>

 

Step 3: Create requirejs-config.js and a JavaScript

Add the file

app/code/Wishusucess/AddJsfile/view/frontend/requirejs-config.js
var config = {
map: {
'*': {
hello: 'Wishusucess_AddJsfile/js/hello',
}
}
};

 

Step 4: Add JS File in Magento 2 Extension

In this step, we will add the javascript file in Magento 2 extension or module.

And finally, add the file

app/code/Wishusucess/AddJsfile/view/frontend/web/js/hello.js
define([
"jquery"
], function($){
"use strict";
return function(config, element) {
alert(config.message);
}
}
)

 

Step 5: Add XML File

Now we have to create a layout file in order to add a template file so that will enable the JavaScript in that file of the module.

And then add the file catalog_product_view.xml

app/code/Wishusucess/AddJsfile/view/frontend/layout/catalog_product_view.xml
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" template="Wishusucess_AddJsfile::hello.phtml" />
</referenceContainer>
</body>
</page>

Step 6: Create a Template File

So, this template is a frontend view so we can choose any template in order to show the js functionality.

Now, suppose we have a template file hello.phtml and we want to add the javascript in that file so we will add in the file like below.

 app/code/Wishusucess/AddJsfile/view/frontend/templates/hello.phtml
<div data-mage-init='{"hello": {"message": "Hello Wishusucess Magento Team!"}}'>
Content
</div>

 

Step 6: Run Below Magento 2 Command

Now we have to run the below upgrade and cache command in Magento 2 root directory.

bin/magento setup:upgrade

bin/magento cache:clean

 

Read more: System XML File: How to Create Admin Configuration in Magento 2

 

Add CSS File in Magento 2 Module

In this step, we will learn how we can add the style sheet in Magento 2 extension or Module.

In order to add the CSS file in the Module. first, we will create a CSS file.

app/code/Wishusucess/AddJsfile/view/frontend/web/css/cssfilename.css

 

Recommended Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2