# nopCommerce – Documentation (English) --- # nopCommerce Documentation nopCommerce is an open source eCommerce software that contains both a catalog frontend and an administration tool backend. nopCommerce is a fully customizable shopping cart, stable, secure and extendable. From downloads to documentation, [nopCommerce.com](https://www.nopCommerce.com) offers a comprehensive base of information, resources, and support of the nopCommerce community. The nopCommerce documentation is here to help you through the process of setting up your store. These will allow you to up-and-run your site quickly! --- # Installing nopCommerce nopCommerce can be downloaded as a ready to install eCommerce engine or as full source code ready to be modified. This chapter will cover everything you need to know for downloading and installing nopCommerce. - [Technology & system requirements](xref:en/installation-and-upgrading/technology-and-system-requirements) - [Installation guide](xref:en/installation-and-upgrading/installing-nopcommerce/index) - [Choose a hosting company](xref:en/installation-and-upgrading/installing-nopcommerce/choose-a-hosting-company) - [Installing local (for developers only)](xref:en/installation-and-upgrading/installing-nopcommerce/installing-local) - [Installing on Windows](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-windows) - [Installing on Microsoft Azure](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-microsoft-azure) - [Installing on Linux](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-linux) - [Pre-installed nopCommerce](xref:en/installation-and-upgrading/installing-nopcommerce/pre-installed-nopcommerce) - [Fully-Managed Private Cloud Hosting by Everleap](xref:en/installation-and-upgrading/installing-nopcommerce/everleap-fully-managed-hosting) - [Upgrading nopCommerce](xref:en/installation-and-upgrading/upgrading-nopcommerce) --- # Technology & system requirements In order to run nopCommerce, you will need the following installed on your server/computer: ## Supported operating systems * Windows * Windows 10 Client (1607 or above) * Windows 11 (23H2 or above) * Windows Server 2016 or above * Linux * Red Hat Enterprise Linux 8 or above * Fedora 41 or above or * Debian 13 or above * Ubuntu 22.04 or above * openSUSE Leap 16 or above * SUSE Enterprise Linux 15.7 or above * Alpine Linux 3.21 or above * macOS * macOS 15.0 or above >[!NOTE] > > Find a complete [list of supported operating systems here](https://github.com/dotnet/core/blob/main/release-notes/10.0/supported-os.md). ## Supported web servers * Internet Information Service (IIS) 7.0 or above * For nopCommerce 5.00: Install .NET 10 runtime ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-10.0.12-windows-hosting-bundle-installer)). * For nopCommerce 4.90: Install .NET 9 runtime ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-9.0.9-windows-hosting-bundle-installer)). * For nopCommerce 4.80: Install .NET 9 runtime ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-9.0.0-windows-hosting-bundle-installer)). * For nopCommerce 4.70: Install .NET 8 runtime ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-8.0.4-windows-hosting-bundle-installer)). * For nopCommerce 4.60: Install .NET 7 runtime ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-7.0.5-windows-hosting-bundle-installer)). * For nopCommerce 4.50: Install .NET 6 runtime ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-6.0.1-windows-hosting-bundle-installer)). * For nopCommerce 4.40: Install .NET 5 runtime ([download](https://dotnet.microsoft.com/download/dotnet/thank-you/runtime-aspnetcore-5.0.3-windows-hosting-bundle-installer)). * For nopCommerce 4.30: Install .NET Core 3.1 runtime ([download](https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.3-windows-hosting-bundle-installer)). * For nopCommerce 4.20: Install .NET Core 2.2 runtime ([download](https://dotnet.microsoft.com/download)). * For nopCommerce 4.10: Install .NET Core 2.1 runtime ([download](https://dotnet.microsoft.com/download)). * For nopCommerce 4.00: Install .NET Core Window Server hosting runtime ([download](https://dotnet.microsoft.com/download)) * For nopCommerce 3.90 or below: ASP.NET 4.5 (MVC 5.0) and Microsoft .NET Framework 4.5.1 or above ## Supported databases * MS SQL Server 2018 or above * MySql Server 8 or above (starting from nopCommerce 4.30) * PostgreSQL 15 or above (starting from nopCommerce 4.40) ## Supported browsers * Microsoft Edge. Microsoft Internet Explorer 9 and above (IE6 and IE7 were supported in versions prior to 3.60, IE8 was supported in versions prior to 4.10) * Mozilla Firefox 2.0 and above * Google Chrome 1.x and above * Apple Safari 12.x and above **For nopCommerce 5.00 or above: MS Visual Studio 2026 (version 18.0 or above). And don't forget to install .NET 10 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-10.0.401-windows-x64-installer)). Required for developers who want to edit the source code.** *For nopCommerce 4.90 or above: MS Visual Studio 2022 (version 17.14 or above). And don't forget to install .NET 9 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-9.0.305-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.80 or above: MS Visual Studio 2022 (version 17.12 or above). And don't forget to install .NET 9 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-9.0.100-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.70 or above: MS Visual Studio 2022 (version 17.9 or above). And don't forget to install .NET 8 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-8.0.204-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.60 or above: MS Visual Studio 2022 (version 17.5 or above). And don't forget to install .NET 7 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-7.0.302-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.60 or above: MS Visual Studio 2022 (version 17.5 or above). And don't forget to install .NET 7 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-7.0.302-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.50: MS Visual Studio 2022 (version 17.0 or above). And don't forget to install .NET 6 SDK ([download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-6.0.406-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.40 or above: MS Visual Studio 2019 (version 16.9 or above). And don't forget to install .NET 5 SDK ([download](https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.408-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.30: MS Visual Studio 2019 (version 16.3 or above). And don't forget to install .NET Core SDK ([download](https://dotnet.microsoft.com/download/dotnet-core/thank-you/sdk-3.1.426-windows-x64-installer)). Required for developers who want to edit the source code.* *For nopCommerce 4.20 or above: MS Visual Studio 2017 (version 15.9 or above). And don't forget to install .NET Core SDK ([download](https://dotnet.microsoft.com/download)). Required for developers who want to edit the source code.* *For nopCommerce 4.10: MS Visual Studio 2017 (version 15.7 or above). And don't forget to install .NET Core SDK ([download](https://dotnet.microsoft.com/download)). Required for developers who want to edit the source code.* *For nopCommerce 4.00 or below: MS Visual Studio 2017 (version 15.3 or above). And don't forget to install .NET Core SDK ([download](https://dotnet.microsoft.com/download)). Required for developers who want to edit the source code.* > [!NOTE] > > If you're installing nopCommerce on Windows and going to use the multi-store feature with SSL, then Windows Server 2012 with IIS 8 is required because it supports SNI (Server Name Indication). --- # Installing nopCommerce nopCommerce is a cross-platform solution and can be run on Windows and Linux. You can also install nopCommerce on Microsoft Azure or use the pre-installed nopCommerce version, which is the easiest way to create your nopCommerce store. Choose one of the following options: - [Installing local (for developers only)](xref:en/installation-and-upgrading/installing-nopcommerce/installing-local) - [Installing on Windows](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-windows) - [Installing on Microsoft Azure](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-microsoft-azure) - [Installing on Linux](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-linux) - [Pre-installed nopCommerce](xref:en/installation-and-upgrading/installing-nopcommerce/pre-installed-nopcommerce) - [Fully-Managed Private Cloud Hosting by Everleap](xref:en/installation-and-upgrading/installing-nopcommerce/everleap-fully-managed-hosting) --- # Hosting providers Whether you intend to use nopCommerce out of the box or make changes to the code, eventually, you will need to host your website so that the public can visit your site and buy your products. Hosting providers literally host your website and provide a way for users to get there. nopCommerce can be hosted with almost any provider. Choosing a hosting provider is an important decision. There are a lot of factors that should be considered before selecting a provider. First and foremost, you'll need to ensure your provider fits the [technology & system requirements](xref:en/installation-and-upgrading/technology-and-system-requirements). In addition, the following factors should be considered: 1. **Uptime** - A good provider should guarantee 99.9 percent uptime. Uptime simply means that your site will be up and running and available for users. If your site is consistently down or not available, you won't sell many products. 1. **Support** - Look for providers who offer 24/7 technical support. Ideally, you want 24/7 phone support, but sometimes this can be hard to find. Look for a provider who offers phone, email, and live chat support. 1. **Cost** - For example, Windows hosting is relatively inexpensive for the most part. Choose a provider who offers annual or semi-annual discounts. 1. **Dedicated IP address** - Most nopCommerce installations will require an SSL certificate as you will be processing credit cards. Check with your provider about the cost of a dedicated IP address for your domain, as it should not be a very high cost. 1. **Backups** - Ensure your provider offers backups of your installation and database. This can either be automated backups or manual, but you will feel safer knowing your data has been backed up. 1. **Growth options** - As your site gets more users and you make more sales, your site will need to grow as well. A good provider will offer options for growing your site, from more disk space to more database space. This would also include moving from a shared server to a dedicated server. > [!TIP] > > You can learn more about the recommended nopCommerce hosting partners here - [Hosting partners](https://www.nopcommerce.com/hosting-partners?utm_source=docs_nopcommerce&utm_medium=link&utm_content=hosting&utm_campaign=parnters_page). --- # Installing local This chapter describes how to download nopCommerce software, upload it to your server, define the file permissions, and install it on your system. You may also watch the screencast about nopCommerce installation on our [YouTube channel](https://www.youtube.com/watch?v=L7NGodeB9sQ). Before you begin the installation, ensure that your web host meets the [minimum requirements to run nopCommerce](xref:en/installation-and-upgrading/technology-and-system-requirements). > [!NOTE] > > For more information on hosting selection guidelines, visit [this page](xref:en/installation-and-upgrading/installing-nopcommerce/choose-a-hosting-company). There are several options available when downloading nopCommerce. In order to determine which option to download, you need to decide how you will use it. The following options are available: 1. **Web (no source)**. This option is available for users who do not wish/need to develop any custom code. This is a precompiled version of nopCommerce that can simply be uploaded to your hosting provider and used immediately. With this option, users can still modify the look and feel or user interface (UI) of their site to suit their needs, but they do not have to worry about the development. 1. **Source code**. This option contains a full Visual Studio solution. It is for those users who wish to customize the code within nopCommerce. It contains all the source code used to develop nopCommerce and must be opened in Visual Studio. It also includes scripts to build and compile the solution to upload to your hosting provider. 1. **Upgrade script**. The upgrade script option is for users who have a nopCommerce installation already in place. The script will upgrade your current installation to the latest version. With each of these options, excluding the upgrade script, you can deploy nopCommerce to your development environment and your hosting provider. Choose the option you would like to [download](https://www.nopcommerce.com/en/download-nopcommerce) and click the appropriate download link to start your download. It is recommended to create a new folder on your desktop to store your downloaded files for easy access. ## Running the site using IIS (package without the source code) To use IIS, copy the contents of the extracted nopCommerce folder to an IIS virtual directory (or site root), and then view the site using a browser. If you are using nopCommerce 3.90 or below, then configure it to run in integrated mode, and configure the application pool to run the .NET Framework version 4. Please note that it's not required for nopCommerce 4.00 and above. ## Running the site using Visual Studio (package with the source code) This step describes how to launch a site in Visual Studio. To run the site in Visual Studio, extract the full source code archive to a local folder. Launch Visual Studio and select **File → Open → Project/Solution**. Navigate to the folder where you extracted the archive and open the `NopCommerce.sln` solution file. Run `Nop.Web` project. ## Getting the "ready to deploy" package (without the source code) from a package with the source code If you're using nopCommerce **3.20 (or above)**, then please follow these steps: - Open the solution in Visual Studio. - Rebuild the entire solution. - Publish the **Nop.Web** project from Visual Studio. When publishing, ensure that configuration is set to *Release*. ## Installation process nopCommerce requires written permissions for the directories and files described below: - **For nopCommerce versions 4.00 and above:** - `\App_Data\` - `\bin\` - `\Logs\` - `\Plugins\` - `\Plugins\Uploaded\` - `\wwwroot\.well-known\` - `\wwwroot\bundles\` - `\wwwroot\db_backups\` - `\wwwroot\files\` - `\wwwroot\files\exportimport\` - `\wwwroot\icons\` - `\wwwroot\images\` - `\wwwroot\images\thumbs\` - `\wwwroot\images\uploaded\` - `\wwwroot\sitemaps\` - `\App_Data\DataProtectionKeys\` - `\App_Data\plugins.json` (after installation) - `\App_Data\appsettings.json` (or dataSettings.json for earlier versions; after installation) - **For nopCommerce versions 2.00-3.90:** - `\App_Data\` - `\bin\` - `\Content\` - `\Content\Images\` - `\Content\Images\Thumbs\` - `\Content\Images\Uploaded\` - `\Content\files\ExportImport\` - `\Plugins\` - `\Plugins\bin\` - `\Global.asax` - `\web.config` These permissions are validated during the installation process. If you have no written permissions, a warning message will be displayed, requesting you to configure permissions. Before installing nopCommerce, ensure you have a database server installed on your system. You can use any of the following authentication methods to connect to the server: - **SQL server account**: When connecting using this method, logins are created in the SQL server that is not based on the Windows user accounts. Both the user name and the password are created using the SQL server and stored in the SQL server. When using this method you must enter your login and password. - **Integrated Windows authentication**: When connecting using this method, the SQL Server validates the account name and password using the Windows principal token in the operating system. This means the user identity is confirmed by Windows. The SQL Server requests no password and does not perform the identity validation. Windows authentication is the default authentication mode and is much more secure than SQL server authentication. Windows authentication uses Kerberos security protocol, provides password policy enforcement with regard to complexity validation for strong passwords, provides support for account lockout, and supports password expiration. A connection made using Windows authentication is sometimes called a trusted connection, because the SQL server trusts the credentials provided by Windows. Once you open the site for the first time, you will be redirected to the installation page as follows: ![nopCommerce installation](_static/installing-local/installation.jpg) In the *Store information* panel, fill the following details: - **Admin user email**: this is the email address of the first admin of the site. - **Admin user password**: you will need to supply a password for the admin account. - **Confirm the password**: confirm the admin user password. - **Country**: select the country from the dropdown list. It allows preconfiguring your store based on the country you selected. For example: - download and preinstall a language pack from the official site - preconfigure some settings (for example, PangV or "Display tax/shipping info" settings for Germany) - preconfigure some shipping details, VAT settings, currencies, measures, and more. - **Create sample data**: select this checkbox if you would like sample products to be created. This is recommended so you can start working with your site before adding any of your own products. You can always delete these items later, or unpublish them so that they no longer appear on your site. - **Subscribe to nopCommerce newsletter**: select this checkbox if you want to subscribe to nopCommerce newsletter during installation. In the *Database information* panel, you need to enter the following info: - **Database**: here you can select either Microsoft SQL Server, MySQL, or PostgreSQL. - **Create database if it doesn't exist**: it is recommended that you create your database and database user beforehand to ensure a successful installation. Simply create a database instance and add the database user to it. The installation process will create all the tables, stored procedures, and more. - **Enter raw connection string (advanced)**: select this checkbox if you want to enter a **Connection string** instead of filling the connection fields. - **Server name**: this is the IP, URL, or server name of your database. Get your server name from the database management system or from the hosting control panel. - **Database name**: this is the name of the database used by nopCommerce. If you opted to create your database ahead of time, use the name you gave your database here. - **Use integrated Windows authentication**: if you are installing at a hosting provider, you can use your SQL Server account and supply the credentials you created with your database. In this case don't select this option. If you are using a development environment, you can select Windows authentication. In this case, select this checkbox. If you are using Windows authentication, the account hosting the application pool in IIS must be a user in the database. - **SQL Username**: enter your database user login. - **SQL Password**: enter your database user password. - **Specify custom collation**: this is an advanced setting and should be left clear. Click **Install** to start the installation process. When the setup process is complete, your new site's home page will be displayed. > [!NOTE] > > The **Restart installation** button at the bottom of the installation page enables you to restart the installation process in case anything goes wrong. > > [!NOTE] > > If you are using nopCommerce 3.90 or below, ensure that your application pool is set to the *Integrated* mode. > > [!NOTE] > > If you want to completely reset a nopCommerce site to its default settings, you can delete the **ConnectionStrings** section from the `appsettings.json` (or `dataSettings.json` for earlier versions) file located in the `App_Data` directory. You can even delete this whole file but note that in this case, it will be recovered on the next run with default values, so you can lose your settings. --- # Installing on Windows This chapter describes how to download nopCommerce software, upload it to your server and install it. You can also watch the screencast about nopCommerce installation on our [YouTube channel](https://www.youtube.com/watch?v=L7NGodeB9sQ). Before you begin the installation, ensure that your web host meets the [minimum requirements to run nopCommerce](xref:en/installation-and-upgrading/technology-and-system-requirements). > [!NOTE] > > For more information on hosting selection guidelines, visit [this page](xref:en/installation-and-upgrading/installing-nopcommerce/choose-a-hosting-company). ## Download nopCommerce To install nopCommerce on Windows you should download it first. Go to [download page](https://www.nopcommerce.com/download-nopcommerce) and choose the **Package without source code** version for Windows. This is a precompiled version of nopCommerce that can simply be uploaded to your hosting provider and used immediately. ## Upload the nopCommerce files The next step is to upload the nopCommerce files to your server. To do this, you need to use an FTP connection, which allows transferring files between computers. Follow these steps to set this up: 1. Choose and download one of the FTP client applications that you will use for transferring files. 1. Find your FTP credentials in your hosting control panel. 1. In your FTP client application, set up the connection between your computer and the server using the FTP credentials you found in the previous step. 1. Upload the nopCommerce files to the server. ## Create a database Before running nopCommerce, create a new database instance in your hosting control panel. This database will be used to store your website data. > [!NOTE] > > When creating the database, choose MS SQL Server version *2012* or *above* if requested. We will use the name, server name (or IP, URL), user login, and password of your database during the installation process later. These credentials are required for the database connection. ## Create a new website Create a new website in your hosting control panel. Then find a URL that allows you to access this site. ## Install nopCommerce Using the URL from the previous step, access the website from your browser. Once you open the site for the first time, you will be redirected to the installation page as follows: ![nopCommerce installation](_static/installing-local/installation.jpg) In the *Store information* panel, fill the following details: - **Admin user email**: this is the email address of the first admin of the site. - **Admin user password**: you will need to supply a password for the admin account. - **Confirm the password**: confirm the admin user password. - **Country**: select the country from the dropdown list. It allows preconfiguring your store based on the country you selected. For example: - download and preinstall a language pack from the official site - preconfigure some settings (for example, PangV or "Display tax/shipping info" settings for Germany) - preconfigure some shipping details, VAT settings, currencies, measures, and more. - **Create sample data**: select this checkbox if you would like sample products to be created. This is recommended so you can start working with your site before adding any of your own products. You can always delete these items later, or unpublish them so that they no longer appear on your site. In the *Database information* panel, you need to enter the following info: - **Database**: here you can select either Microsoft SQL Server, MySQL, or PostgreSQL. Choose the first one if you are installing nopCommerce on Windows. - **Create database if it doesn't exist**: it is recommended that you create your database and database user beforehand to ensure a successful installation. Simply create a database instance and add the database user to it. The installation process will create all the tables, stored procedures, and more. - **Enter raw connection string (advanced)**: select this checkbox if you want to enter a **Connection string** instead of filling the connection fields. - **Server name**: this is the IP, URL, or server name of your database. Get your server name from the hosting control panel. - **Database name**: this is the name of the database used by nopCommerce. If you opted to create your database ahead of time, use its name here. - **Use integrated Windows authentication**: if you are installing at a hosting provider, you don't need this option. - **SQL Username**: enter your database user login. - **SQL Password**: enter your database user password. - **Specify custom collation**: this is an advanced setting and should be left clear. Click **Install** to start the installation process. When the setup process is complete, your new site's home page will be displayed. > [!NOTE] > > The **Restart installation** button at the bottom of the installation page enables you to restart the installation process in case anything goes wrong. > > [!IMPORTANT] > > If you want to completely reset a nopCommerce site to its default settings, you can delete the `appsettings.json` file from the `App_Data` directory. --- # Installing on Linux This chapter describes how to install the nopCommerce software on Linux system on the example of *Xubuntu 22.04*: - [Installing on Linux](#installing-on-linux) - [Install and configure software](#install-and-configure-software) - [Add the .Net repository](#add-the-net-repository) - [Install the .NET Core Runtime](#install-the-net-core-runtime) - [Install MySql Server](#install-mysql-server) - [Install nginx](#install-nginx) - [Get nopCommerce](#get-nopcommerce) - [Create the nopCommerce service](#create-the-nopcommerce-service) - [Installation process](#installation-process) - [Troubleshooting](#troubleshooting) - [Gdip](#gdip) - [SSL](#ssl) - [See also](#see-also) ## Install and configure software .NET is available in the Ubuntu .NET backports package repository. ### Add the .Net repository Open a terminal and run the following commands: ```cmd sudo add-apt-repository ppa:dotnet/backports ``` ![nopCommerce installation](_static/installing-on-linux/add_repository.png) ### Install the .NET Core Runtime Update the products available for installation, then install the .NET runtime: ```cmd sudo apt-get update sudo apt-get install -y aspnetcore-runtime-10.0 ``` > [!NOTE] > > If you have an error, see the detailed information on the [Install .NET SDK or .NET Runtime on Ubuntu](https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu-install) page. You can see all installed .Net Core runtimes by the following command: ```cmd dotnet --list-runtimes ``` ### Install MySql Server Install the MySql server 8.0 version: ```cmd sudo apt-get install mysql-server-8.0 ``` ![nopCommerce installation](_static/installing-on-linux/install_mysql.png) By default, the root password is empty; let's set it. Run the following command to access the MySQL prompt: ```cmd sudo mysql ``` Run the following ALTER USER command to switch the root user’s authentication method to mysql_native_password, which uses a password. Replace ‘password’ with your desired new password, and make sure to keep the single quotes around the password: ```cmd ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; ``` > [!NOTE] > > It’s important to choose a strong, unique password for your MySQL root user. A strong password should be at least 12 characters long, include a mix of uppercase and lowercase letters, numbers, and special characters. Type **exit** and press Enter to exit the MySQL prompt. ![nopCommerce installation](_static/installing-on-linux/config_mysql.png) > [!NOTE] > > If you have a problem with configuring root password on your MySql server, please read the following articles: > [How to Reset the Root Password](https://dev.mysql.com/doc/refman/8.0/en/resetting-permissions.html) and > [MySQL Error: 'Access denied for user 'root'@'localhost'](https://stackoverflow.com/questions/41645309/mysql-error-access-denied-for-user-rootlocalhost). ### Install nginx Install the nginx package: ```cmd sudo apt-get install nginx ``` ![nopCommerce installation](_static/installing-on-linux/install_nginx.png) Run the nginx service: ```cmd sudo systemctl start nginx ``` and check its status: ```cmd sudo systemctl status nginx ``` ![nopCommerce installation](_static/installing-on-linux/status_nginx.png) To configure nginx as a reverse proxy to forward requests to your ASP.NET Core app, modify /etc/nginx/sites-available/default. Open it in a text editor and replace the contents with the following: ```cmd # Default server configuration # server { listen 80 default_server; listen [::]:80 default_server; server_name nopCommerce.com; location / { proxy_pass http://localhost:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; } ``` ## Get nopCommerce Create a directory: ```cmd sudo mkdir /var/www/nopCommerce ``` Download and unpack nopCommerce: ```cmd cd /var/www/nopCommerce sudo wget https://github.com/nopSolutions/nopCommerce/releases/download/release-5.00.1/nopCommerce_5.00.1_NoSource_linux_x64.zip sudo apt-get install unzip sudo unzip nopCommerce_5.00.1_NoSource_linux_x64.zip ``` Create couple directories to run nopCommerce: ```cmd sudo mkdir bin sudo mkdir logs ``` Change the file permissions: ```cmd cd .. sudo chgrp -R www-data nopCommerce/ sudo chown -R www-data nopCommerce/ ``` ## Create the nopCommerce service Create the */etc/systemd/system/nopCommerce.service* file with the following contents: ```cmd [Unit] Description=Example nopCommerce app running on Xubuntu [Service] WorkingDirectory=/var/www/nopCommerce ExecStart=/usr/bin/dotnet /var/www/nopCommerce/Nop.Web.dll Restart=always # Restart service after 10 seconds if the dotnet service crashes: RestartSec=10 KillSignal=SIGINT SyslogIdentifier=nopCommerce-example User=www-data Environment=ASPNETCORE_ENVIRONMENT=Production Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false [Install] WantedBy=multi-user.target ``` Start the service: ```cmd sudo systemctl start nopCommerce.service ``` Check the nopCommerce service status: ```cmd sudo systemctl status nopCommerce.service ``` ![nopCommerce installation](_static/installing-on-linux/status_nopCommerce.png) Restart the nginx server: ```cmd sudo systemctl restart nginx ``` Now that everything is ready, you can proceed to install and configure the store. ## Installation process The further installation process for nopCommerce is the same as the installation process on Windows; you can see the instruction following [this link](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-windows#install-nopcommerce). ## Troubleshooting ### Gdip *If you have a problem with loading images in the RichText Box (The type initializer for 'Gdip' threw an exception), just install the libgdiplus library*: ```cmd sudo apt-get install libgdiplus ``` ### SSL *If you want to use SSL on your site, don't forget to set the `UseProxy` setting to **`true`** in the **appsettings.json** file*. ## See also - [Running nopCommerce on Linux VPS. Part 2](https://www.nopcommerce.com/running-nopcommerce-on-linux-vps-part-2) --- # Installing on Microsoft Azure There are three ways to deploy nopCommerce on Microsoft Azure: 1. **FTP**. Use this method if you already have a package ready to deploy (no source code). You can publish to a local file system, then upload the published files through FTP. How to get FTP credentials for Azure? You should go to **[Azure.com](https://azure.microsoft.com/) → My Account → Management portal → Choose your website → go to Dashboard → quick glance**. Here, you can find the FTP credentials or *Reset your deployment credentials* or *Download the publish profile*. For the new Azure portal, go to [portal.azure.com](http://portal.azure.com/) → browse websites → navigate to your website → Properties. Here, you can find the FTP credentials or *Reset your deployment credentials* or *Download the publish profile*. 1. **Visual Studio** - web deploy. You can also deploy directly to Azure from *Visual Studio*. Download or get the deployment credentials from Azure using the method above and setup a web deploy profile in *Visual Studio*. 1. **Web platform installer**. nopCommerce is available in the Azure Web Sites application gallery. So go to Azure portal, click "*start, new site, from gallery*". Select nopCommerce from the list of available applications. After you enter your database connection information and click *`OK`*, nopCommerce will be ready to launch. >[!TIP] > > If you get the error "HTTP Error 500.32 - ANCM Failed to Load dll," it might be that the platform has to be changed to 64bit (through Azure: **App Settings - Settings - Configuration - General settings - Platform settings - Platform**). Once the site is deployed, you have to install nopCommerce. Please [read more about it here](xref:en/installation-and-upgrading/installing-nopcommerce/index). Azure has support for multiple instances since version 3.70. It's great for any application scalability. Now you should not worry about whether your site can handle many visitors. So what exactly has been done to support multiple instances in Azure and web farms? * **BLOB storage account support in Microsoft Azure**. Please learn more about [storage accounts in Azure here](https://azure.microsoft.com/documentation/articles/storage-introduction/). *How to configure:* * Once your BLOB storage is set up in Azure, open your `appsettings.json` (or `web.config` in previous versions) file, find the **AzureBlobStorage** element and specify your BLOB storage connection string, container, endpoint. >[!IMPORTANT] > >These settings are valid for nopCommerce version 4.80 and below. * Once you have configured BLOB storage in Azure, open the **Azure Blob Storage** plugin configuration page and specify the BLOB storage connection string, container, and endpoint. >[!IMPORTANT] > >These settings are relevant for nopCommerce version 4.90 and above. * **Distributed caching and session management support**. Supported options are SQL Server and Redis. To configure SQL Server, see [DistributedCacheConfig](https://docs.nopcommerce.com/en/developer/tutorials/appsettings-json-file.html#distributedcacheconfig) section for more details. Following description assumes that [Redis](http://redis.io/) has been chosen as a caching server (already available in Azure, Amazon, other cloud hosting companies). *How to configure:* * First, you have to install and setup Redis. Please find more about [how to use Redis in Azure here](https://azure.microsoft.com/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/). * Once it's done you have to configure it in nopCommerce. In order to enable caching in Redis open `appsettings.json` file. Find the **DistributedCacheConfig** config section. There, set **DistributedCacheType** to Redis and **Enabled** to *`true`* and then specify **ConnectionString** pointing to your Redis server (configured in the first step). * For version 3.90 (and below), you also have to enable Redis as our distributed session management. Please open the `web.config` file. Find and uncomment the **sessionState** element. Specify its attributes (such as *host*, *accessKey*, etc.) pointing to your Redis server. * Recommended settings of the `appsettings.json` file to improve stability (for nopCommerce 4.50 and below): * **UsePluginsShadowCopy** - set it to *`false`* to prevent the problem with IIS pool recycle and horizontal scaling. * **Configure Azure monitoring agents as crawlers (nopCommerce 4.70 and above)**. When using Azure Traffic Manager endpoint monitoring (for example, when the Path is set to `/`) or Azure App Service **Always On**, their requests to the root URL can create a new guest customer on each call. To avoid this, configure these user agents as crawlers in the `additional.crawlers.xml` file (see the `CrawlerOnlyAdditionalUserAgentStringsPath` setting in `appsettings.json`): ```xml ``` * Ensure that the nopCommerce schedule tasks are run on one instance at a time. To configure this : * For version 3.90 (and below), open the `web.config` file, find the **WebFarms** element, and set its **MultipleInstancesEnabled** attribute to *`true`*. If you use Microsoft Azure Websites (not cloud services), then set the **RunOnAzureWebsites** attribute to *`true`* as well. * For newer versions no configuration change is required because the task runner uses the distributed cache to ensure that tasks will run on one instance at a time. ## Installation process The further installation process for nopCommerce is the same as the installation process on Windows; you can see the instruction following [this link](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-windows#install-nopcommerce). ## Web farms You can also configure load balancing with IIS web farms. Please [read more about it here](xref:en/installation-and-upgrading/installing-nopcommerce/web-farms). --- # Load balancing and web farms in nopCommerce Load balancing is the distribution of a workload across many nodes. It is typically used for balancing HTTP traffic over multiple servers acting together as a web front end. There are several ways to configure load balancing in nopCommerce: 1. Use cloud-based autoscaling appliances like Microsoft's Azure Web Apps. Please [find more about it here](xref:en/installation-and-upgrading/installing-nopcommerce/installing-on-microsoft-azure). 1. Configure load balancing with IIS web farms. This approach is described below. We highly recommend you to read [this tutorial](https://docs.microsoft.com/en-us/iis/web-hosting/scenario-build-a-web-farm-with-iis-servers/overview-build-a-web-farm-with-iis-servers) by Microsoft before you start configuring a web farm for nopCommerce. So Microsoft suggests two ways to build a web farm with IIS servers: 1. Local Content Infrastructure 1. Shared Network Content Infrastructure nopCommerce supports both ways and handles content replication by using Distributed File System Replication (DFSR) if you use **Local Content Infrastructure** or uses a central location to manage the content with **Shared Network Content Infrastructure**. ## nopCommerce configuration First of all, you have to configure the initial settings of your web farm in IIS and add the first instance of your nopCommerce store there. Then, you have to configure a few settings in the nopCommerce admin area to allow nopCommerce to work with web farms: 1. Go to **Configuration → Settings → All settings (advanced)**. Find the **mediasettings.useabsoluteimagepath** setting and change its value to *false* 1. Go to **Configuration → Settings → App settings** and find the *Distributed cache configuration* tab. Select the **Use distributed cache** checkbox and choose the option you prefer: - *Redis*. In this case, you just need to enter the **Connection string** to your Redis server below - *SQL Server*. In this case, you need to prepare a new table in your database using the "sql-cache create" command first. Read more about it in [Microsoft docs](https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-5.0#distributed-sql-server-cache). Then fill in the **Connection string**, **Schema name**, and **Table name** fields 1. Since our web farm utilizes Application Request Routing (ARR) to control traffic using a proxy server, select the **Use proxy servers** checkbox 1. Click the **Save** button. The nopCommerce application will be restarted. ## Web farm configuration ### Admin area redirection rule Since a web farm hosts multiple instances of an application, you need to choose one of the nopCommerce instances as a primary one to avoid file locking. This primary node will process requests from the admin panel. The rule should look as follows: ```xml ``` Where `admin.wf.local` is the address of your primary instance. ### Load balancing rules After you set up the web farm, you need to configure a load balancing rule in the **Application Request Routing** section. Add the condition that prevents handling requests intended for the primary node (admin area requests in our case): ```xml ``` Where `wf-local` is the web farm name. You can add the rules we described above in two ways: 1. Include them in the `applicationHost.config` file (**system.webServer/rewrite/globalRules** section) 1. Use the **URL Rewrite script** section in IIS Manager > [!NOTE] > > In some cases, ARR has issues handling URLs of javascript files containing more than one “.” symbol. For example, it can affect minified js-files ending with `.min.js`. To avoid errors when processing such files, we recommend directly routing these requests to one of the nopCommerce instances. As you can see in the examples above, we do this for the whole `lib_npm` directory by routing to the primary instance. When the configuration is finished, add new instances to your web farm. ### File replication When you start the configuration of file replication, please make sure that the following folders of the primary instance are set up to support replication to all other nodes (instances): - /App_Data - /Plugins - /Themes - /wwwroot > [!NOTE] > > All actions that assume restarting the nopCommerce application (for example, plugin installation, updating of the app settings), require manual restarting of all application pools related to the web farm. --- # Pre-installed nopCommerce You can use a simple and fast nopCommerce installation solution created by the nopCommerce team in collaboration with our hosting partner, WinHost. Our hosting plan comes with the platform preinstalled. That means you can start working on your website right away. ## Advantages * No need to waste time searching for reliable hosting and choosing an appropriate hosting plan and installing nopCommerce. * The preinstalled hosting plan ensures fast and reliable work of nopCommerce. * WinHost is offering a 30 day free hosting trial for pre-installed nopCommerce stores. Learn more about [the pre-installed nopCommerce hosting](https://www.winhost.com/a/noponwh$nopcommerce). --- # Fully-managed private cloud hosting for nopCommerce The nopCommerce team in collaboration with the Everleap Managed Services has launched the Fully-managed Private Cloud hosting for mission-critical websites to boost their performance and increase reliability. We proactively monitor your application. If we see any issues, we will notify you and provide solutions or recommendations for resolution. To better understand your hosting requirements, we offer you a free consultation. Based on your requests, we will design a customized hosting infrastructure to meet your business needs and provide you with a flat monthly fee. For your convenience, we also offer free database and website migration services. ## Benefits of using our private cloud *-* **High performance.** Your website will be the only one on the server, so there is no resource contention leading to performance degradation. *-* **Unlimited scalability.** Scaling and upgrading your hosting infrastructure will not be disruptive, with minimum or no downtime. *-* **Flat monthly cost.** The custom infrastructure is designed to meet your technical and business requirements without charging you for increasing traffic or any other user activities on your website. *-* **Better security.** Lower security risks since there is an individual web host for your project and no one would upload a vulnerable third-party application. *-* **Free 24/7 technical support.** You will also get 2 hours of advanced support services per month (e.g. DBA consultation). [Get a free consultation](https://www.nopcommerce.com/en/private-cloud-hosting-solution?utm_source=docs_nopcommerce&utm_medium=documentation&utm_campaign=everleap-managed-solution#request-consultation) or learn more about the [Fully-managed Private Cloud Hosting](https://www.nopcommerce.com/private-cloud-hosting-solution?utm_source=docs_nopcommerce&utm_medium=documentation&utm_campaign=everleap-managed-solution) by Everleap. > \* Please note that the starting price is $199/mo. If your hosting budget is below, we recommend you to use this [hosting service](https://www.nopcommerce.com/pre-installed-nopcommerce?utm_source=docs_nopcommerce&utm_medium=documentation&utm_campaign=pre-installed). --- # Upgrading nopCommerce This chapter describes how to upgrade nopCommerce to the [latest](https://www.nopcommerce.com/download-nopcommerce) version. You might want to do this because you've seen a message at the nopCommerce news section of your dashboard telling you that a new release is available. nopCommerce doesn't support automatic upgrades, you have to do it manually. > [!IMPORTANT] > > Since version 4.40 we don't use SQL upgrade scripts anymore. The upgrade is performed automatically with migrations (during the first application start). So when you upgrade from 4.30 to 4.40 you need to skip step 2 from the list below! Follow the next steps: 1. Make a backup of everything on your site, including the database. This is extremely important so that you can roll back to a running site no matter what happens during migration. 1. **[To upgrade to nopCommerce 4.30 and below]** Then you have to execute SQL upgrade scripts. You have to execute them stepwise. For example, if your current version is 3.90 and the latest available version is 4.20, then you have to upgrade to 4.00, then to 4.10, and then to 4.20. So download the required upgrade scripts from the [download nopCommerce](https://www.nopcommerce.com/download-nopcommerce) page. Once an upgrade script is downloaded, execute it over your database. > [!NOTE] > > Don't forget to read the `Readme.txt` file provided with the upgrade script. Sometimes it contains important notes regarding upgrading to the newest version. 1. Remove all files from the previous version except JSON files in the 'App_Data' directory such as `appsettings.json` and `plugins.json`. These files should be saved since we will use them later. For earlier versions: if such files as `dataSettings.json`, `Settings.txt` or `InstalledPlugins.txt` exist save them as well. 1. Upload the new site files (get the [latest version](https://www.nopcommerce.com/download-nopcommerce)). 1. Ensure that everything is OK. > [!NOTE] > > As you deploy, make sure that the target `appsettings.json` is updated as per the latest nopCommerce version so that the production site continues to point to the production database. In earlier nopCommerce versions it can be `dataSettings.json` and `Settings.txt` files. Also, make sure that the `plugins.json` (`InstalledPlugins.txt`) file is also updated per the latest nopCommerce version. > > [!NOTE] > >If you're upgrading nopCommerce to version 4.50 from one of the previous versions, please ensure that your connection string contains one of the following parameters: `Encrypt=false` or `TrustServerCertificate=True` (depending on your server requirements). You can manually add these parameters to your connection string in the \App_Data\appsettings.json file. This step is caused by the `Microsoft.Data.SqlClient` library that changed the default value of the `Encrypt` option from `false` to `true`. > > [!NOTE] > > If you stored your pictures on the file system, then also backup them (`\wwwroot\Images\`) and copy back after the upgrade. > > [!NOTE] > > **(upgrading from 3.X to 4.X)**: If you want to upgrade from a version 3.90 to the latest version, you would need to install 4.00 first (over the existing database), run the 3.90 to 4.00 migration SQL script, and then upgrade to 4.10, 4.20, and further. ## Troubleshooting If you experience problems after the upgrade, you can always restore your backup and replace the files with ones from your previous version. You can always post a question on our [forums](https://www.nopcommerce.com/boards/). > [!Note] > > If when doing advanced search on our forums you cannot find what you need, then try a Google search focused into nopCommerce site: [your search words **site:[nopcommerce.com](https://www.nopcommerce.com/ "nopcommerce.com")**]. --- # Getting started If you are a novice in nopCommerce, follow the steps below to set up and run your store: ## 1. Configure your store - [Configure general store settings](xref:en/getting-started/advanced-configuration/your-store-information) - [Configure payment methods](xref:en/getting-started/configure-payments/payment-methods/index) - [Configure shipping options](xref:en/getting-started/configure-shipping/index) - Configure users list: create [different groups](xref:en/running-your-store/customer-management/customer-roles) of users, give them [separate access to the areas of your site](xref:en/running-your-store/customer-management/access-control-list) and offers, and more. ## 2. Create a catalog and add products A catalog is what your customers constantly deal with. That's why it is crucial to make it easy to browse and find the products needed. ### Create categories and manufacturers Categories and manufacturers will be used in your catalog for product filtering. Learn how to deal with them to make the site navigation easier. - [Categories](xref:en/running-your-store/catalog/categories) - [Manufacturers](xref:en/running-your-store/catalog/manufacturers) ### Add products You can add products manually one by one or import your catalog from an xml file. - [Products](xref:en/running-your-store/catalog/products/index) ### Define product variations What if your products are variable, for example, you sell sneakers in various colors and sizes? In nopCommerce you can set up specification and product attributes to manage this. - [Grouped products (variants)](xref:en/running-your-store/catalog/products/grouped-products-variants) ## 3. Improve customer experience in your store Now that your catalog is filled with products, ensure that your customers get all the support needed on their journey to a purchase. ### Product reviews Personal buying experience counts. It gives people more trust in you as a seller. Learn here how to make product reviews available for your online store and manage them. - [Product reviews](xref:en/running-your-store/catalog/products/product-reviews) ### LiveChat support Often your customers need to ask a question right here and right now. The LiveChat option can be a good way to help them. Find chat plugins in the nopCommerce marketplace. - [Learn more about Plugins in nopCommerce](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) ### Wishlists A wishlist is a good option for deferred purchasing. Let your customers add some products to wishlist to buy them later or share with friends. It is also a good option for you to analyze your customers' behaviors. - [Shopping carts and wishlists](xref:en/running-your-store/order-management/shopping-carts-and-wishlists) ## 4. Marketing & promotional tools Marketing your store is essential to gain your customers' loyalty and raise awareness among potential customers. There are many marketing options in nopCommerce: you can offer special prices, advise products depending on shopping behavior, promote your store through email campaigns, and much more. - [Promotional tools](xref:en/running-your-store/promotional-tools/index) ### Discounts and special prices Applying special prices to products can encourage your customers to make a purchase sooner and (or) to buy more. - [Discounts](xref:en/running-your-store/promotional-tools/discounts) - [Tier prices](xref:en/running-your-store/promotional-tools/tier-prices) ### Loyalty program The reward points functionality in nopCommerce allows customers to earn points for certain actions (registration, making purchases). - [Reward points](xref:en/running-your-store/promotional-tools/reward-points) ### Cross-marketing In nopCommerce, you can offer your customers [additional products](xref:en/running-your-store/promotional-tools/cross-sells-and-related-products) they may like based on their shopping behaviors. It is also a good opportunity for you to up-sell some products. ### Email campaigns Create [email campaigns](xref:en/running-your-store/promotional-tools/email-campaigns) to easily and quickly reach your target audience with special offers, news, educational content, and more. ## 5. nopCommerce special features for stores of any kind Whether you want to give a shot to a small project or you are to start a marketplace, you can rely on nopCommerce. There are many options to fulfill your business requirements: ### Multi-store nopCommerce enables you to run more than one store using one interface from a single nopCommerce installation and manage all admin operations from a single panel. [Learn here](xref:en/getting-started/advanced-configuration/multi-store) how to set up several stores. - [Multi-store](xref:en/getting-started/advanced-configuration/multi-store) ### Multi-vendor Multi-vendor and drop shipping tools enable you to sell online without having to keep stocks or ship orders. Watch the [video tutorial](https://www.youtube.com/watch?v=MH6r6tqfLF8&index=9&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) on multi-vendor support. - [Vendor management](xref:en/running-your-store/vendor-management) > [!TIP] > > If you have issues configuring your store catalog, don't hesitate to place questions on [community forums](http://www.nopcommerce.com/boards/forum/5/general-support) or request [premium support](http://www.nopcommerce.com/nopcommerce-premium-support-services) services. --- # nopCommerce interface This chapter covers the basics of the nopCommerce interface. Once logged in, you should see the **Administration** hyperlink at the top of your website. Or you can simply add `/admin` to the end of your site's URL to open the admin area. For example, `www.example.com/admin`. The first screen displayed after logging in to the nopCommerce administration area is the *Dashboard*: ![dashboard](_static/admin-area-overview/dashboard.png) The dashboard has the following sections: * **Start accepting orders** is a section that contains all the main topics related to setting up your store. This wizard will literally take you "by the hand" through the administration panel and tell you how everything works. * **nopCommerce news** is a section that shows important news, sales and promotions information from nopCommerce. * **Common statistics** of your webstore, which includes numbers of orders, pending return requests, registered customers, and low-stock products. * Other sections showing the vital statistics of your webstore: **orders, new customers, order totals, incomplete orders, latest orders, popular search keywords, bestsellers by quantity, bestsellers by amount**: ![Stats](_static/admin-area-overview/stats.jpg) Learn more about [these reports here](xref:en/running-your-store/reports). The dashboard sections are easily collapsed by clicking the ![item](_static/admin-area-overview/item.png) icon. ## Common nopCommerce page elements ### Sidebar ![Sidebar](_static/admin-area-overview/sidebar.png) The sidebar is placed on the left of each page in the administration area. It allows you to navigate through the nopCommerce administrator's functionality. The sidebar can be easily collapsed by clicking the "hamburger" icon next to the logo ![dashboard2](_static/admin-area-overview/hamburger.jpg) ### Search field ![dashboard3](_static/admin-area-overview/search.jpg) On the top of the sidebar, there is a search field. Start typing a name of a section you want to navigate to, the search line automatically suggests the options, proceed you directly to the required one. ### System menu ![dashboard4](_static/admin-area-overview/menu.jpg) This part of the interface shows the name of a logged-in user, the logout button, the public store link, and a small menu from which a user can select to clear cache or restart the application. ## Basic and advanced modes On some pages in the administration area, you will see the following switch: ![dashboard5](_static/admin-area-overview/dashboard5.png) This two-position *Basic-Advanced* switch allows you to switch between page display modes. For the convenience of use, we created the **Basic** mode where the most frequent settings are shown. If you cannot find the required setting on the page, switch to the **Advanced** mode to see all available settings. On some pages, the switch has a **Settings** button beside it. You can use it to set up the basic mode according to your needs by adding/removing the required settings. ![dashboard6](_static/admin-area-overview/dashboard6.png) Click **Settings** to see a list of the available settings. Select the checkboxes of the **desired setting**. The added settings will then be displayed in the **Basic** mode. ![dashboard7](_static/admin-area-overview/dashboard7.png) --- # Catalog Products are the basis of an online store, and product management is a very important part of your store management strategy. Product information helps customers decide whether they want to purchase an item or not. So make sure to have quality product content in the store because it builds your customers' confidence that they are getting exactly what they need and expect. The most important components of product management in nopCommerce are adding products, manufacturers, setting up product categories to make navigation easy, adding good product descriptions and appealing pictures, listing all possible product variants, defining product tags to make product search quick and effective. ## A catalog on the example of a live store In the following examples, we will use our demo store based on the "Nop Venture Theme" by Nop-Templates. Please find more about this [third-party theme here](https://www.nopcommerce.com/nop-venture-theme-14-plugins-nop-templatescom). There are some tips to help you create a well-designed catalog for your customers. ### Categories - When adding categories to your store, ensure they clearly describe the products (or subcategories) they contain. As on the following example, the Boards category only contains boards: ![Category](_static/index/category.jpg) *Create categories using the **Add new** button on the **Catalog → Categories** page*. - Use subcategories when you need to divide a general category into specific ones. It makes the search process easier for your customers. As on the example below, the Water Sports category contains the Surf, Windsurf, and Kitesurf subcategories: ![Subcategories](_static/index/subcategories.jpg) *Add the **Parent category** on the category edit page to turn it into a subcategory.* - Add the most popular categories to the top menu, which is visible on each page, to attract more customers: ![Categories](_static/index/categories.jpg) *To do this, use the **Include in top menu** checkbox on the category edit page.* - Add the most interesting categories to the home page. These categories will be first what a customer sees when visiting your store: ![Homepage categories](_static/index/homepage-categories.jpg) *To do this, use the **Show on home page** checkbox on the category edit page.* - Allow your customers to search in categories using filters: ![Filters](_static/index/filters.jpg) *The filter functionality uses [specification attributes](xref:en/running-your-store/catalog/products/specification-attributes).* - Allow your customers to sort products and change the display mode: ![Sort](_static/index/sort.jpg) *For more information about sorting, visit the [Catalog settings - Product sorting](xref:en/running-your-store/catalog/catalog-settings#product-sorting) section. Use the **Allow customers to select page size** and **Page size options** fields from the category edit page to set up the display mode.* To learn how to create a category, visit the [Categories](xref:en/running-your-store/catalog/categories) chapter. ## See also - [Categories](xref:en/running-your-store/catalog/categories) - [Manufacturers](xref:en/running-your-store/catalog/manufacturers) - [Attributes](xref:en/running-your-store/catalog/products/product-attributes) - [Products](xref:en/running-your-store/catalog/products/index) - [YMM (Year-Make-Model) Filter](xref:en/running-your-store/catalog/ymm) - [Price lists](xref:en/running-your-store/catalog/price-lists) - [Catalog settings](xref:en/running-your-store/catalog/catalog-settings) --- # Design This chapter covers the basics of your store design configuration. There is a separate guide on this topic. In this chapter, we examine the theme installation process and media settings. If you need further information on graphic theme customization, refer to the [designer's guide](xref:en/developer/design/index). ## Learn more in the following chapters - [Choose and install a theme](xref:en/getting-started/design-your-store/choose-and-install-a-theme) - [Media settings](xref:en/getting-started/design-your-store/media-settings) --- # Choose and install a theme After downloading a new theme, which is in a zip file, extract the contents of your zip file and copy them to the **Themes** folder as shown in the picture below: ![p1](_static/choose-and-install-a-theme/instal_theme1.jpg) 1. Go to **admin panel → Configuration → Settings → General settings**. ![p2](_static/choose-and-install-a-theme/instal_theme2.png) 1. Select your new theme in the **Default store theme** field and click **Save**. 1. Go to the public store. You should be able to see the new theme applied to your store. --- # Uploading your logo The logo of your site is usually displayed on each site page in the page header. Your logo will look perfect in most nopCommerce themes regardless of which one you choose and how often you change it. Follow these steps to upload a new logo to your site: 1. Go to **Configuration → Settings → General settings**. The *General settings* window will be displayed: ![General settings](_static/uploading-your-logo/upload.png) 1. Find the **Logo** field, then click the **Browse** button beside it and choose an image file. The chosen image will be uploaded. You can remove the uploaded image by clicking the **tap to undo** button. ![General settings](_static/uploading-your-logo/tap_to_undo.png) 1. Click the **Save** button in the top right to activate the logo on your site. 1. Visit the public site to make sure the logo looks nice. --- # Uploading favicons Starting from version 4.20, you can automatically upload favicons through the admin area. > [!NOTE] > > For a multi-store case, you need to repeat this uploading procedure for each store. 1. To upload favicons, go to **Configuration → Settings → General settings.** The *Favicon and app icons* panel will be displayed: ![settings_block](_static/adding-a-favicon/settings_block.png) 1. Click the green **Upload single icon or icons archive** button; the file selection dialog will be opened: ![file_selection_dialog](_static/adding-a-favicon/file_selection_dialog0.png) Here, you need to copy the path to your icons (it varies depending on the store and virtual directory). For example, `/icons/icons_0`. 1. There are several options for what to upload, depending on how friendly your site favicons should be for various devices: - The most complete option is to use one of the favicon generators. In this manual, we will show an example of using a [RealFaviconGenerator](https://realfavicongenerator.net/). Thanks to this service, the full favicon package will be uploaded in a few clicks. - Go to this generator main page where you will be invited to choose a picture for the favicon ![realfavicongenerator](_static/adding-a-favicon/realfavicongenerator.png) - After selecting a picture and clicking **Continue with this picture**, you will be redirected to the next page. Here you can adjust the display settings of favicons for specific devices and applications - iOS Web Clip, Android Chrome, Windows Metro, macOS Safari, and others. The service will automatically show display examples. You can customize them to your needs or leave the default ones. - At the bottom of the same page, you can find the **Favicon Generator Options** panel. ![favicon_generator_options](_static/adding-a-favicon/favicon_generator_options.png) - In this section, you must set certain settings. In the **Path** tab, select the option `I cannot or I do not want to place favicon files at the root of my web site. Instead I will place them here` and specify the path from step 2. ![favicon_path](_static/adding-a-favicon/favicon_path.png) - In the **Version/Refresh** tab, select the option depending on whether your site is already in production. The setting description will help you with this. ![favicon_version](_static/adding-a-favicon/favicon_version.png) - In the **Additional files** tab it is necessary to select the option to generate an html file in the package. ![favicon_additional_fields](_static/adding-a-favicon/favicon_additional_fields.png) - Now that all settings are set, click the button to generate. ![generate_button](_static/adding-a-favicon/generate_button.png) - Get your favicon package. ![download_package](_static/adding-a-favicon/download_package.png) - The simplest option is to only use the **favicon.ico** file, which has been successfully used on many sites for a long time, until devices with different screen resolutions appeared. - Find a sample favicon package that is located in `wwwroot/icons/samples/` directory and copy it. - In the new package, delete all files except for **favicon.ico** and **html_code.html**. - Replace the file **favicon.ico** in this package with your new favicon. - Edit the **html_code.html** file. Leave the only line there: ``, assuming that `/icons/icons_0` is the path from the step 2. - Save these two files into a package. Your favicon package is ready. - An intermediate option is using the full favicon package without a generator. 1. Find a sample favicon package that is located in `wwwroot/icons/samples/` directory and copy it. 1. Replace the pictures in the new package with your own ones considering the original sizes. 1. Edit the **html_code.html** file, replace all entries of the `/icons/icons_0` with the path saved in step 2. 1. Save this package. Your favicon package is ready. 1. Return to the admin area with a prepared favicon package to upload. Select the desired file and click **Upload single icon or icons archive**. ![upload_package](_static/adding-a-favicon/file_selection_dialog.png) 1. Ensure your package is successfully uploaded. ![success](_static/adding-a-favicon/success.png) 1. To see the new favicon on the site, you should clear the cache in the admin area and browser, then reload the page. > [!TIP] > > To create a favicon package, you can use any generators, third-party services or do it manually. The only requirement is the existence of the **html_code.html** file with the html code, which will be placed in the `` element of the site pages. --- # Swiper widget Swiper widget allows you to display a slider on the home page of your store. ## Configure the Swiper plugin Go to **Configuration → Widgets**. The *Widgets* window will be displayed: ![Widgets](_static/swiper/widgets.png) Click **Edit** beside the Swiper widget. The window will be expanded as follows: ![Swiper Edit](_static/swiper/swiper_edit.png) Select the **Is active** checkbox to enable the plugin. Click **Configure**. The *Configure – Swiper* window will be displayed as follows: ![Swiper - Configure](_static/swiper/swiper_configure.png) Perform the following for each slide you would like to upload: ![Swiper - Add slide](_static/swiper/swiper_add_slide.png) * In the **Picture** field, click *Browse* to upload the required picture. * In the **Title** field, enter title for picture. Leave empty if you don't want to display any text. * In the **Image alternate text** field, enter the alternate text that will be added to the image. * In the **URL** field, enter the required URL or leave it empty if you do not want the picture to be clickable. Click **Add**. Now you can go to the home page of your public store and the updated image slider: ![Homepage](_static/swiper/swiper_homepage.png) --- # Top menu & footer > [!WARNING] > > This article is relevant for nopCommerce versions 4.80 and below. The new menu generation method, available starting with nopCommerce 4.90, is described in article [Menu](xref:en/running-your-store/content-management/menu). In nopCommerce, you can choose how the top menu and footer will be displayed. You can include the most important and interesting links in the top menu to attract more customers and add service links to the footer to provide the current store information to your clients. ## Top menu In the Default Clean theme, the top menu looks as follows: ![Default Clean theme top menu](_static/top-menu-and-footer/top-menu.jpg) As you can see, it displays the store categories. Please note, if you want a category to be displayed in the top menu you should select the **Include in top menu** checkbox on the category edit page. For more details, read below. You can include the following items in the top menu: - Categories - Custom topics (pages) - Links to the site's sections See below how to add each of these items. ### Categories To include a category in the top menu, go to the category edit page in the admin area: choose **Catalog → Categories**. Then click the **Edit** button beside the category. The *Edit category details* window will be displayed: ![Edit category details](_static/top-menu-and-footer/category-details.jpg) Select the **Include in top menu** checkbox and click **Save**. > [!NOTE] > > If this category is a subcategory, then ensure that its parent category has this property enabled as well. ### Custom topics (pages) To include a topic in the top menu, go to the topic edit page in the admin area: choose **Content management → Topics (pages)**. Then click the **Edit** button beside the topic. The *Edit topic details* window will be displayed: ![Edit topic details](_static/top-menu-and-footer/topic-details-top-menu.jpg) Select the **Include in top menu** checkbox and click **Save**. ### Links to the site's sections To include some of the site's sections in the top menu, go to **Configuration → Settings → General settings**. Proceed to the *Top menu items* panel: ![Top menu settings](_static/top-menu-and-footer/general-settings-top-menu.jpg) Choose the items you want to be displayed in the top menu from the following list: - **Display "Home page"** - **Display "New products"** - **Display "Search"** - **Display "My account"** - **Display "Blog"** - **Display "Forums"** - **Display "Contact us"** Then click **Save**. > [!NOTE] > > The "New products" menu item will only be displayed when the "New products" page is enabled on the **Configuration → Settings → Catalog settings** page (*Additional sections* panel). ## Footer In the Default Clean theme, the footer looks as follows: ![Default Clean theme footer](_static/top-menu-and-footer/footer.jpg) By default, it displays site section links grouped by three types: *Information, Customer service, My account*. You can remove any of the displayed links or add new ones. You can include the following items in the footer: - Custom topics (pages) - Links to the site's sections See below how to add each of these items. ### Custom topics To include a topic in the footer, go to the topic edit page in the admin area: choose **Content management → Topics (pages)**. Then click the **Edit** button beside the topic. The *Edit topic details* window will be displayed: ![Edit topic details](_static/top-menu-and-footer/topic-details-footer.jpg) Choose where you want the topic link to be displayed. You can select one or more checkboxes: - **Include in footer (column 1)** - **Include in footer (column 2)** - **Include in footer (column 3)** For example, if you choose **Include in footer (column 1)**, then the link will be displayed in the *Information* column. Click **Save** to save the changes. ### Link to the site's sections To include some of the site's sections in the footer, go to **Configuration → Settings → General settings**. Proceed to the *Footer items* panel: ![Footer settings](_static/top-menu-and-footer/general-settings-footer.jpg) Choose the items you want to be displayed in the footer from the following list: - **Display "Sitemap"** > [!NOTE] > > The "Sitemap" menu item will only be displayed when the **Sitemap enabled** checkbox is selected on the **Configuration → Settings → General settings** page (*Sitemap* panel). - **Display "Contact us"** - **Display "Search"** - **Display "News"** - **Display "Blog"** - **Display "Forums"** - **Display "Recently viewed products"** > [!NOTE] > > The "Recently viewed products" menu item will only be displayed when the "Recently viewed products" page is enabled on the **Configuration → Settings → Catalog settings** page (*Additional sections* panel). - **Display "Compare products list"** > [!NOTE] > > The "Compare products list" menu item will only be displayed when the "Compare products" functionality is enabled on the **Configuration → Settings → Catalog settings** page (*Compare products* panel). - **Display "New products"** > [!NOTE] > > The "New products" menu item will only be displayed when the "New products" page is enabled on the **Configuration → Settings → Catalog settings** page (*Additional sections* panel). - **Display "My account"** - **Display "Orders"** - **Display "Addresses"** - **Display "Shopping cart"** > [!NOTE] > > The "Shopping cart" menu item will only be displayed to a certain customer when the "Public store. Enable shopping cart" permission is enabled for the customer's role. To manage permissions, go to the **Configuration → Access control list** page. Or read more about permissions in the [Access control list](xref:en/running-your-store/customer-management/access-control-list) section. - **Display "Wishlist"** > [!NOTE] > > The "Wishlist" menu item will only be displayed to a certain customer when the "Public store. Enable wishlist" permission is enabled for the customer's role. To manage permissions, go to the **Configuration → Access control list** page. Or read more about permissions in the [Access control list](xref:en/running-your-store/customer-management/access-control-list) section. - **Display "Apply for vendor account"** > [!NOTE] > > The "Apply for vendor account" menu item will only be displayed when the **Allow customers to apply for vendor account** checkbox is selected on the **Configuration → Settings → Vendor settings** page (*Common* panel). Click **Save** to save the changes. ### Follow us To customize the **Follow us** block of the footer, go to **Configuration → Settings → General settings**. Proceed to the *Social media* panel as follows: ![Social media settings](_static/top-menu-and-footer/social-media-settings.jpg) Enter your social media links: - **Facebook page URL** - **X page URL** - **YouTube channel URL** - **Instagram URL** - **TikTok URL** - **Snapchat URL** - **Pinterest URL** - **Tumblr URL** ### Newsletter The newsletter block is displayed in the footer by default. To hide this block go to **Configuration → Settings → Customer settings**. Proceed to the *Account* panel and select the **Hide newsletter box** checkbox as follows: ![Newsletter box settings](_static/top-menu-and-footer/newsletter-settings.jpg) Click **Save** to save the changes. The footer will be updated accordingly. ### Powered by nopCommerce According to the terms of the nopCommerce license, without purchasing the *Copyright removal key*: - You may NOT remove or hide the "Powered by nopCommerce" statement that appears at the bottom of each page within a nopCommerce-powered website - When users click on the "powered by nopCommerce" text it must direct them to . The "Powered by nopCommerce" link must be in the same format, unedited, as delivered in the program source code. This obligation shall also apply to any copies or derivative works! - The copyright notice at the footer of your store (website) must remain intact, unedited and clearly visible. Please do NOT attempt to edit, remove or hide the copyright notice in any way. Upon purchase of a "copyright removal key," you are permitted to remove the "Powered by nopCommerce" statement. Copyright infringement is illegal — please be advised. For more information please visit the [nopCommerce copyright removal key](https://nopcommerce.com/nopcommerce-copyright-removal-key?utm_source=documentation&utm_medium=link&utm_campaign=powered_by_nopcommerce&utm_content=topmenu_footer) page. --- # Media Settings This section describes how to set the media details of your store. This includes defining products, variants and avatar image sizes, and more. To define the media settings, go to **Configuration → Settings → Media settings**. In the *Common* panel, define the settings as follows: ![p1](_static/media-settings/media_sett_common.png) - Click the **Change** button above the **Pictures are stored into** option to choose between database or file system. > [!NOTE] > > It is recommended to make a backup of the database before clicking the **Change** button. - In the **Maximum image size** field, enter the maximum image size (meaning, the longest side) allowed for image upload (in pixels). - Select **Multiple thumb directories** to have multiple thumb directories. It is useful when your hosting company has limitations on the amount of files per directory. - In the **Default image quality (0 - 100)** enter the quality of uploaded images. Once changed you have to manually delete all already generated thumbs. - Select **Import product images using hash** to use HASHBYTES to compare pictures with uploaded products. Please note that this functionality is not supported by some databases. - Select **Picture zoom** to enable picture zoom on the product details page. - **Allow SVG uploads in admin area** - Since the *svg* format is a vector drawing and is described in the form of XML, to increase security, you can disable the addition of images of this format in the admin panel. In the *Product* panel, define the settings as follows: ![p1](_static/media-settings/media_sett_product.png) - In the **Product detail image size** field, enter the default size for the product detail images in pixels. - In the **Product thumbnail image size (catalog)** field, enter the default size for the product thumbnail images displayed on the category or manufacturer pages in pixels. - In the **Product thumbnail image size (product page)** field, enter the default size for the product thumbnail images (in pixels) displayed on the product details page (used when you have more than one product image). - In the **Associated product image size** field, enter the default size for the associated product images in pixels. Associated products are a part of grouped products. - **Default image** - You can select a default image that will be shown in the public store for products that do not have images. In the *Product 3D models* panel, define the settings as follows: ![p1](_static/media-settings/media_sett_3d.png) - **Camera control**: Enables or disables user interaction with the camera, allowing customers to manually orbit and pan around the model. - **Zoom**: Allows users to zoom in and out to view the fine details of the product. - **Auto-rotate**: Enables automatic rotation of the 3D model when the page loads, drawing attention to the interactive element. - **Lazy loading**: Delays loading the 3D viewer and asset files until the user interacts with the gallery, improving initial page load speed. - **Upload size limit**: Defines the maximum allowed file size for `.GLB` uploads to prevent server overload and optimize performance. In the *Other pages* panel, define the settings as follows: ![p1](_static/media-settings/media_sett_other.png) - In the **Category thumbnail image size** field, enter the default size for the product thumbnail images on the category pages in pixels. - In the **Manufacturer thumbnail image size** field, enter the default size for the product thumbnail images on the manufacturer pages in pixels. - In the **Vendor thumbnail image size** field, enter the default size for the product thumbnail images on the vendor pages in pixels. - In the **Cart/wishlist thumbnail image size** field, enter the default size for product thumbnail images in the shopping cart and wishlist in pixels. - In the **Mini-shopping cart thumbnail image** size field, enter the default size (in pixels) of the product thumbnail images displayed in the mini-shopping cart block. - In the **Avatar image size** field, enter the default size for the avatar images. This page enables **multi-store configuration**, it means that the same settings can be defined for all stores, or differ from store to store. If you want to manage settings for a certain store, choose its name from the *Multi-store configuration drop-down* list and select all needed checkboxes at the left side to set custom value for them. ## Tutorials - [Managing media settings](https://www.youtube.com/watch?v=3JS4Zj4TBwQ) --- # Configure payments **Payments** is the core of e-commerce. This section will cover global store settings that allow payments to be received. > [!NOTE] > > nopCommerce is partnering with leading payment providers and supports leading payment gateways, which can be found in the nopCommerce [marketplace](https://www.nopcommerce.com/en/marketplace). This chapter describes how to set up the payment methods, currencies, and payment method restrictions. > [!TIP] > > How to install a payment (or any other) plugin is covered in [Plugins in nopCommerce](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) chapter. ## See also - [Payment methods](xref:en/getting-started/configure-payments/payment-methods/index) - [Advanced configuration](xref:en/getting-started/configure-payments/advanced-configuration/index) - [Payment method restrictions](xref:en/getting-started/configure-payments/advanced-configuration/payment-method-restrictions) - [Currencies](xref:en/getting-started/configure-payments/advanced-configuration/currencies) --- # Payment methods A payment method is how a customer pays for the order. nopCommerce supports both *online* and *offline transactions*. For the online methods, nopCommerce integrates with third-party payment gateways so that customer's credit card information is automatically sent through the gateway (as either an authorization or authorization and charge) upon completion of an order. You can have multiple payment methods active at the same time. A customer can select how they want to pay at the checkout. To define payment methods, go to **Configuration → Payment methods**. > [!TIP] > > By default, there are several payment methods available in nopCommerce, but you can find more payment plugins in the nopCommerce [marketplace](https://www.nopcommerce.com/marketplace). For the payment method development details, refer to the [document](xref:en/developer/plugins/payment-method). ![methods](_static/index/payment-methods.jpg) To activate a payment method, click **Edit** beside the required method, select the **Is active** checkbox and click **Update**. The **Is active** option changes from *false* to *true*. Different payment methods support different options. There are **4 payment options** that a payment method might or might not support: * **Supports capture** indicates whether this method allows processing money transfer after the amount was charged. * **Refund** indicates this method allows making a money refund after the amount was charged and captured. * **Partial refund** indicates whether this method allows making a partial money refund after the amount was charged and captured. * **Void** indicates whether this method allows making a money refund before the amount was charged (when the payment status is pending). * **Recurring support** indicates whether this method allows recurring payments. Click **Configure** beside a payment method to set it up. ## See also * [PayPal Commerce](xref:en/getting-started/configure-payments/payment-methods/paypal-commerce) * [PayPal Zettle](xref:en/getting-started/configure-payments/payment-methods/paypal-zettle) * [PayPal Standard](xref:en/getting-started/configure-payments/payment-methods/paypal-standard) * [PayPal Smart Payment Buttons](xref:en/getting-started/configure-payments/payment-methods/paypal-smart-payment-buttons) * [Check/money order](xref:en/getting-started/configure-payments/payment-methods/check-money-order) * [Credit card (manual processing)](xref:en/getting-started/configure-payments/payment-methods/credit-card-manual-processing) --- # PayPal Commerce `PayPal Commerce` gives your buyers a simplified and secure checkout experience. PayPal intelligently presents the most relevant payment types to your shoppers automatically, making it easier for them to complete their purchases using such methods as Credit Card payments, Apple Pay, Google Pay, PayPal Credit, Venmo, iDEAL, Bancontact, and other payment types. ## Configure the payment method To configure the `PayPal Commerce` plugin, go to **Configuration → Payment methods**. Then find the **PayPal** payment method on this page. This will not be difficult to do as it's our recommended payment method. ![List](_static/paypal-commerce/list.png) Also, access to the plugin configuration is available from the navigation menu. ![List](_static/paypal-commerce/list_2.png) Follow these steps to configure `PayPal Commerce`: ### 1. Connect PayPal account It doesn't matter whether you already have a PayPal business account, or only a personal one, or none at all, the connecting starts the same way: 1. Open the PayPal Commerce configuration page in the admin area. You will see the following form: ![PayPal Commerce Onboarding](_static/paypal-commerce/onboarding.png) 1. Select the type of account you want to connect, production or sandbox. If you want to test the plugin first, enable **Use sandbox** setting. 1. Click **Sign up for PayPal** button and you will see the following pop-up window allowing you to fill in some data and connect an account: ![PayPal Commerce Onboarding Popup](_static/paypal-commerce/popup-form-first-page.png) You will need to go through few steps to fill in all the required details, the number of details will vary depending on whether you are creating a new account, connecting an existing one, or converting a personal account to a business. 1. Once you are done and approved to use PayPal payments, go back to the plugin configuration page and refresh it. You will see the following form: ![PayPal Commerce Onboarding completed](_static/paypal-commerce/onboarding-completed.png) Here you will see notifications about successful connection, if there are warnings or errors, refer to **System → Log** to find out more details. There will also be the status of the account connection process, if any of the steps is not completed, log into your PayPal personal account and complete this step. If you connected a sandbox account, there will also be a reminder about the need to create a production account after completing the testing. 1. In case you already have REST API App created in your PayPal account and want to continue using it, you should select **Specify API credentials manually** checkbox and specify the credentials in the fields below as follows: ![PayPal Commerce Credentials](_static/paypal-commerce/credentials.png) ### 2. Configure the plugin 1. Find the **PayPal Commerce** payment method on the **Configuration → Payment methods** page and click **Configure**, you'll see the following settings block: ![PayPal Commerce Configuration](_static/paypal-commerce/configuration.png) * Choose the **Payment type** to either capture payment immediately or authorize payment for an order after order creation. * Select the **Use Custom Card Fields** to enable Advanced Credit and Debit Card Payments in your store. This is a PCI compliant solution to accept debit and credit card payments directly on your store without the need for customers to redirect to third-party sites. * Select the **Use Apple Pay** to enable Apple Pay in your store. Before getting started in sandbox/production environment verify any domain names in your environment that will show an Apple Pay button. Apple Pay transactions only work on a domain and site registered to you. 1. [Download](https://paypalobjects.com/devdoc/apple-pay/well-known/apple-developer-merchantid-domain-association) the domain association file for your environment. 1. Host the file on your site for each domain and subdomain you want to register, at */.well-known/apple-developer-merchantid-domain-association*. 1. Log into the PayPal Merchant Account, go to **Payment Methods**, then select the **Manage** link in the **Apple Pay** section and **Add Domain** there. * Select the **Use Google Pay** to enable Google Pay in your store. * Select the **Use Alternative Payments Methods** to enable alternative payments methods in your store. With alternative payment methods, customers across the globe can pay with their bank accounts, wallets, and other local payment methods. For example, a customer in the Netherlands might want to pay using iDEAL, which is used by more than half of consumers in the Netherlands for online purchases, whereas a customer in Belgium on the same website might want to pay using Bancontact, a popular payment method there. The plugin automatically will render all eligible buttons in a single location by default. * Select the **Use Vault** to enable PayPal Vault. It allows to securely store customers payment information and use it in subsequent transactions without customers having to re-enter payment details. * Select the **Skip 'Confirm Order' page** to skip this step during checkout so that after approving the payment on PayPal site, customers will redirected directly to the 'Order Completed' page. * Select the **Use shipment tracking** to use the package tracking. To automatically sync the shipment status with PayPal, specify the tracking number and carrier when creating or editing the shipment in the admin area: ![Shipment](_static/paypal-commerce/shipment.png) 1. Then proceed to the *Feature PayPal Prominently* panel: ![PayPal Commerce Configuration](_static/paypal-commerce/display-settings.png) On this panel, define the display settings: * Select the **Display buttons on shopping cart** checkbox to display PayPal buttons on the shopping cart page in addition to the default checkout button. * Select the **Display buttons on product details** checkbox to display PayPal buttons on product details pages allowing buyers to complete a purchase without going through the full checkout process. * Select the **Display logo in header links** checkbox to display a PayPal logo in the header links. These logos and banners are a great way to let your buyers know that you choose PayPal to securely process their payments. * If the previous checkbox is selected, the **Logo source code** field is displayed. In this field, enter the source code of the logo. Find more logos and banners on PayPal Logo Center. You can also modify the code to fit correctly into your theme and site style. * Select the **Display logo in footer** checkbox to display a PayPal logo in the footer. These logos and banners are a great way to let your buyers know that you choose PayPal to securely process their payments. * If the previous checkbox is selected, the **Logo source code** field is displayed. In this field, enter the source code of the logo. Find more logos and banners on PayPal Logo Center. You can also modify the code to fit correctly into your theme and site style. 1. Click **Save** to save the plugin settings. > [!NOTE] > > You don't need to activate the plugin, it'll be enabled immediately after installation. If for some reason you don't intend to use it in your store, you can disable it on **Configuration → Local plugins** page. ### 3. Configure PayPal Pay Later Messaging PayPal offers short-term, interest-free payments and other special financing options that buyers can use to buy now and pay later, while sellers get paid up-front. Pay Later offers vary depending on the country. With Pay Later offers, sellers can give shoppers increased buying power and flexibility to spread the cost of their purchases over time. For more information about Pay Later, see [Buy now, pay later](https://www.paypal.com/digital-wallet/ways-to-pay/buy-now-pay-later). 1. Click the **Pay Later** link on the **Configuration → PayPal Commerce** menu item, you'll see the following configurator: ![PayPal Commerce Pay Later](_static/paypal-commerce/pay-later-settings.png) Here you can customize your Pay Later messaging. 1. Click **Publish Shanges** to save the configuration. ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **PayPal Commerce**. To find it faster, use the *Search* panel in the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Local Plugins](_static/paypal-commerce/local-plugins.png) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Edit plugin](_static/paypal-commerce/edit-plugin.png) 1. You can set up the following limits: * In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). 1. Click **Save**. --- # PayPal Zettle *PayPal Zettle* is the complete point of sale solution (POS) that gives you the power to accept card, contactless, and mobile payments. And it easily syncs with your nopCommerce store, helping you do business where you sell today and plan to sell tomorrow, whether online, in-store, or on-the-go. Use your PayPal details to sign up and link your accounts in minutes, so your earnings can be added directly into your PayPal account. ## Configure the POS method To configure the `PayPal Zettle` plugin, go to **Configuration → POS**. Then find the **PayPal Zettle** POS solution: ![List](_static/paypal-zettle/find.jpg) Follow these steps to configure `PayPal Zettle`. 1. Create a PayPal Business account If you already have a PayPal account, just proceed to the next section. If you don't then register a Business account following these instructions. Then download the PayPal Zettle POS app, and order your card reader. ![step1](_static/paypal-zettle/signUp1step.png) > [!NOTE] > > If you already have an account, you will be redirected to the authorization. ![step2](_static/paypal-zettle/signUp2step.png) ![step3](_static/paypal-zettle/signUp3step.png) ![step4](_static/paypal-zettle/signUp4step.png) ![step5](_static/paypal-zettle/signUp5step.png) 1. Configure the PayPal Zettle plugin Open the PayPal Zettle configuration page in the admin area. You will see the following form: ![Configure plugin](_static/paypal-zettle/configure_plugin.jpg) 1. Go to your **merchant account**. ![Configure plugin](_static/paypal-zettle/merchant_account.jpg) Review the information and click **Create key**. A client ID will be created together with the API key. ![Create API key](_static/paypal-zettle/create_api_key_1.jpg) On the **Create API key page**, click **Copy key** and paste it into the field on this plugin configuration page, do the same for **Client ID**. ![Create API key](_static/paypal-zettle/create_api_key_2.jpg) > [!NOTE] > > The API key will be displayed only once, so make sure to make a copy of it. Click **Save** to save the plugin settings. After entering, information about the current connection status will be displayed, a disconnect button, some profile details. If any errors occur during connection or inconsistencies between store settings and *Zettle* profile, warnings will be shown. For the correct operation of the plugin we should correct them. ![Create API key](_static/paypal-zettle/configure_connected.jpg) 1. Product Library Synchronization Product Library Synchronization is the main feature of the plugin. Synchronization is configured on the same page in a separate panel. We don’t have separation between Initial Synchronization and Updates. Everything is configured and launched in one place, it doesn't matter if this is initial synchronization or next regular updates. ![Synchronization](_static/paypal-zettle/sync.jpg) > [!TIP] > > We have full instructions here how to make the synchronization and each point has a prompt. The source of truth is the nopCommerce store so sinchronization of the products is one-sided - from the nopCommerce store to the Zettle catalog. Herewith we can choose whether to delete the products in the catalog or leave them. Synchronization can be automatic (scheduled task) or manually started by the merchant from this page. For automatic, we have to **Enable auto synchronization** and set the **Auto synchronization period**. Before synchronization, we need to choose which products we want to import into the *Zettle* catalog. For this, there is a spreadsheet below the settings. ![Synchronization](_static/paypal-zettle/sync2.jpg) Only those products will be synchronized that are included in this spreadsheet. In the future, with any changes to the product (updating details, deletion, image change, etc.) these changes will be synchronized with the catalog. Synchronization of a specific product can be paused (property **Active**). > [!NOTE] > > Settings **Sync enabled** (same as **Active**), **Price sync enabled**, **Image sync enabled**, **Inventory tracking enabled** are applied when adding a product to the table, so these are settings by default. They can also be set for each specific product. During synchronization, either the product itself will be imported or its product attribute combinations if they are indicated. Also we could add existing discounts when synchronizing. 1. Inventory Synchronization The second feature of the plugin is **Inventory Synchronization**. This synchronization works in both side, and for changes in the store (nopCommerce) and changes in the catalog (Zettle). In order to track inventory for a product, we need to enable **Inventory tracking enabled**. On the next sync, tracking will be enabled and the changes will start syncing. If we no longer need tracking for a product, we must disable this option accordingly. Now we should save the synchronization settings and **start** it. > [!TIP] > > You can find out the details of the synchronization process in the log. > ![Log](_static/paypal-zettle/log.jpg) ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **PayPal Zettle**. To find it faster, use the *Search* panel in the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Plugins](_static/paypal-zettle/plugins.jpg) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Edit](_static/paypal-zettle/edit.jpg) 1. You can set up the following limits: * In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save**. --- # PayPal Standard > [!Important] > > This plugin is currently deprecated and has been replaced by the [**PayPal Commerce**](xref:en/getting-started/configure-payments/payment-methods/paypal-commerce) plugin. PayPal Standard is the easiest way to securely accept credit card and PayPal payments online. To configure the PayPal Standard plugin, go to **Configuration → Payment methods**. Then find the **PayPal Standard** payment method in the payment method list: ![List](_static/paypal-standard/list.jpg) ## Activate the method, edit its name, and display order You can edit the payment method name, which will be displayed for customers in the public store, or its display order. To do this, click the **Edit** button in the plugin row on the payment method list page. You will be able to enter **Friendly name** and **Display order**. In this row, you can also activate the plugin or make it inactive using the **Is active** field. Click the **Update** button. Your changes will be saved. ## Configure the payment method To use the **PayPal Standard** plugin as a payment method, please follow these steps: 1. Register a Business account on [https://www.paypal.com/bizsignup](https://www.paypal.com/bizsignup/). Then fill in the information about yourself and your business: ![step1](_static/paypal-standard/signUp1step.png) > [!NOTE] > > If you already have an account, you will be redirected to the authorization. ![step2](_static/paypal-standard/signUp2step.png) ![step3](_static/paypal-standard/signUp3step.png) ![step4](_static/paypal-standard/signUp4step.png) ![step5](_static/paypal-standard/signUp5step.png) 1. In the top navigation bar, click the **Settings** icon ![settings](_static/paypal-standard/settings_icon.png) 1. Select **Website payments** in the left panel and click **Update** in the **Website preferences** line. ![websitepayments](_static/paypal-standard/websitepaymentsppal.png) 1. In the **Auto return for website payments** section, set the switch to **On.** As the **Return URL**, enter the URL of your site, which will receive ID transactions sent by PayPal after customer payment. In our case, it's `http://localhost:15536/Plugins/PaymentPayPalStandard/PDTHandler` but don't forget to replace localhost with your site URL. ![autoreturnURLPP](_static/paypal-standard/autoreturnURLPP.png) 1. In the **Payment data transfer** section, set the switch to **On** and copy **Identity Token.** ![PDTtoken](_static/paypal-standard/PDTtoken.png) 1. To configure the plugin in the admin panel of nopCommerce, go to **Configuration → Payment methods**. In the **PayPal Standard** line, click **Configure**. ![nopconfig](_static/paypal-standard/nopConfigPP.png) 1. In the **Business Email** field, enter the email specified when registering a Business account on paypal.com. 1. In the **PDT Identity Token** field, enter the copied **Identity Token** from clause #5. 1. Click **Save**. For the **IPN** (Instant Payment Notification) activation: 1. Select **Notifications** in the left panel and click the **Update in the Instant payment notifications** line. ![notifications](_static/paypal-standard/notificationsPP.png) 1. Familiarize yourself with the information regarding **IPN** and click **Choose IPN Settings**. ![chooseIPN](_static/paypal-standard/chooseIPNSettings.png) 1. Select **Receive IPN messages (Enabled)**. As **Notification URL**, enter the URL of your IPN handler. ![editIPN](_static/paypal-standard/editIPN.png) 1. Click **Save.** You should get a message that you have successfully activated IPN. > [!NOTE] > > Instant Payment Notification (IPN) is a PayPal message service that sends a notification when a transaction is affected. Once IPN is integrated, sellers can automate their back office so that they don't have to wait for payments to come in to trigger the order fulfillment. ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **PayPal Standard**. To find it faster, use the *Search* panel at the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Plugins](_static/paypal-standard/plugin.jpg) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Plugins](_static/paypal-standard/edit.jpg) 1. You can set up the following limits: - In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option just leave this field empty. > [!IMPORTANT] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). - Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!IMPORTANT] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). - Click **Save**. ## Known Issues ### Error: Things don't appear to be working at the moment (PayPal) If you see the error "Things don't appear to be working at the moment. Please try again later" ![paypalerror](_static/paypal-standard/file-6jjW2AH7yT.png) The error is caused by a setting within your PayPal Account. **Step 1**: On the left sidebar, under "Products & Services," click "Website Payments" **Step 2**: Click "Update" next to the "Website Preferences" section **Step 3**: Scroll down to the "Encrypted Website Payments" section, select "Off" on the right, and then save your changes. ![encryptedwebsitepayments](_static/paypal-standard/file-c2yKWw2xMN.png) After saving the change, you can go back to your site and try the button/forms again, and they should work. --- # PayPal Smart Payment Buttons > [!Important] > > This plugin is currently deprecated and has been replaced by the [**PayPal Commerce**](xref:en/getting-started/configure-payments/payment-methods/paypal-commerce) plugin. PayPal Checkout with Smart Payment Buttons gives your buyers a simplified and secure checkout experience. PayPal intelligently presents the most relevant payment types to your shoppers automatically, making it easier for them to complete their purchases using such methods as Pay with Venmo, PayPal Credit, credit card payments, iDEAL, Bancontact, Sofort, and other payment types. ## Video tutorial Watch this [video tutorial](https://youtu.be/lJxVqjwUFkY) to learn how to configure PayPal Smart Payment Buttons. ## Configure the payment method To configure the PayPal Smart Payment Buttons plugin, go to **Configuration → Payment methods**. Then find the **PayPal Smart Payment Buttons** payment method in the payment method list: ![List](_static/paypal-smart-payment-buttons/list.jpg) Follow these steps to configure PayPal Smart Payment Buttons: ### 1. Activate the payment method To do this, click the **Edit** button in the plugin row on the payment method list page. Activate the plugin by selecting the **Is active** checkbox. Click the **Update** button. Your changes will be saved. ### 2. Create a PayPal account If you already have a PayPal account, just proceed to the [next section](#3-set-up-the-paypal-developer-dashboard). Register a Business account on [PayPal](https://www.paypal.com/us/webapps/mpp/referral/paypal-business-account2?partner_id=9JJPJNNPQ7PZ8). Then fill in the information about yourself and your business: ![Step 1](_static/paypal-smart-payment-buttons/signUp1step.png) > [!NOTE] > > If you already have an account, you will be redirected to the authorization. ![Step 2](_static/paypal-smart-payment-buttons/signUp2step.png) ![Step 3](_static/paypal-smart-payment-buttons/signUp3step.png) ![Step 4](_static/paypal-smart-payment-buttons/signUp4step.png) ![Step 5](_static/paypal-smart-payment-buttons/signUp5step.png) ### 3. Set up the PayPal Developer Dashboard 1. Log into the [Developer Dashboard](https://developer.paypal.com/developer/applications) with your PayPal account credentials. 1. In **My Apps & Credentials**, use the toggle to switch between live and sandbox testing apps. ![My Apps & Credentials](_static/paypal-smart-payment-buttons/my-apps.jpg) 1. Navigate to the *REST API apps* section and click **Create App**. ![Create App](_static/paypal-smart-payment-buttons/rest.jpg) 1. Type a name for your app and click **Create App**. The app details page will open and display your credentials. 1. Copy and save the **Client ID** and **Secret** for your app. 1. Review your app details and save your app if you made any changes. ### 4. Configure the payment method in nopCommerce 1. Find the **PayPal Smart Payment Buttons** payment method on the **Configuration → Payment methods** page and click **Configure**. The *Configure - PayPal Smart Payment Buttons* page will be displayed as follows: ![Configure](_static/paypal-smart-payment-buttons/configure.jpg) 1. Define the following settings on the *Configure - PayPal Smart Payment Buttons* page: * **Use sandbox** if you want to test the payment method first. * Enter the **Client ID** you saved in the previous steps. * Enter the **Secret** you saved in the previous steps. * Choose the **Payment type** to either capture payment immediately or authorize payment for an order after order creation. 1. Then proceed to the *PayPal Prominently* panel: ![Create App](_static/paypal-smart-payment-buttons/display.jpg) On this panel, define the display settings: * Select the **Display buttons on shopping cart** checkbox to display PayPal buttons on the shopping cart page instead of the default checkout button. * Select the **Display buttons on product details** to display PayPal buttons on product details pages; clicking on them matches the behavior of the default 'Add to cart' button. * Select the **Display logo in header links** checkbox to display a PayPal logo in the header links. These logos and banners are a great way to let your buyers know that you choose PayPal to securely process their payments. * If the previous checkbox is selected, the **Logo source code** field is displayed. In this field, enter the source code of the logo. Find more logos and banners on PayPal Logo Center. You can also modify the code to fit correctly into your theme and site style. * Select the **Display logo in footer** checkbox to display a PayPal logo in the footer. These logos and banners are a great way to let your buyers know that you choose PayPal to securely process their payments. * If the previous checkbox is selected, the **Logo source code** field is displayed. In this field, enter the source code of the logo. Find more logos and banners on PayPal Logo Center. You can also modify the code to fit correctly into your theme and site style. Click **Save** to save the plugin settings. ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **PayPal Smart Payment Buttons**. To find it faster, use the *Search* panel at the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Plugins](_static/paypal-smart-payment-buttons/plugins.jpg) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Edit](_static/paypal-smart-payment-buttons/edit.jpg) 1. You can set up the following limits: * In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save**. --- # Check/money order Check/money orders are often used by government agencies or large businesses. Rather than paying directly through your site, shoppers will request that you send them a **Purchase order (PO)**, and they will send the payment back. Most of the order processing is handled outside of the software. To configure this payment method, go to **Configuration → Payment methods**. Find the **Check/money order (Payments.CheckMoneyOrder)** payment method list: ![List](_static/check-money-order/list.jpg) ## Activate the method, edit its name, and display order You can edit the payment method name, which will be displayed for customers in the public store, or its display order. To do this, click the **Edit** button in the plugin row on the payment method list page. You will be able to enter **Friendly name** and **Display order**. In this row, you can also activate the plugin or make it inactive using the **Is active** field. Click the **Update** button. Your changes will be saved. ## Configure the payment method On the **Configuration → Payment methods** page, find the **Check/money order (Payments.CheckMoneyOrder)** payment method and click the **Configure** button. The *Configure - Check/money order* window will be displayed as follows: ![purchaseorder](_static/check-money-order/purchaseorder.png) Set up the payment method as follows: * In the **Description** field, enter the info that will be shown to customers during checkout. * Define the **Additional fee** for using this method. * In the **Additional fee. Use percentage** field, define whether to apply an additional percentage fee to the order total. If not enabled, a fixed value is used. * The **Shippable product is required** field indicates whether shippable products are required in order to display this payment method during checkout. Click **Save**. ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **Check/money order**. To find it faster, use the *Search* panel at the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Plugins](_static/check-money-order/plugin.jpg) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Plugins](_static/check-money-order/edit.jpg) 1. You can set up the following limits: * In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save**. --- # Credit card (manual processing) This is a special payment plugin that allows all orders to be successfully entered on the website, but it does NOT really charge a customer or make calls to any live payment gateway. It is recommended to use this payment method if you want to perform one of the following: * Process all orders offline * Process them manually via another back-office system * Test the site end-to-end before going live To configure this payment method, go to **Configuration → Payment methods**. Then find the **Credit card (Payments.Manual)** payment method in the payment method list: ![List](_static/credit-card-manual-processing/list.jpg) ## Activate the method, edit its name, and display order You can edit the payment method name, which will be displayed for customers in the public store, or its display order. To do this, click the **Edit** button in the plugin row on the payment method list page. You will be able to enter **Friendly name** and **Display order**. In this row, you can also activate the plugin or make it inactive using the **Is active** field. Click the **Update** button. Your changes will be saved. ## Configure the payment method On the **Configuration → Payment methods** page, find the **Credit card (Payments.Manual)** payment method and click the **Configure** button. The *Configure - Credit card* window will be displayed as follows: ![manualprocessing](_static/credit-card-manual-processing/manualprocessing.png) Set up the payment method as follows: * In the **After checkout mark payment as** field, specify the transaction mode. * Define the **Additional fee** for using this method. * In the **Additional fee. Use percentage** field, define whether to apply an additional percentage fee to the order total. If not enabled, a fixed value is used. Click **Save**. ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **Credit card**. To find it faster, use the *Search* panel at the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Plugins](_static/credit-card-manual-processing/plugin.jpg) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Plugins](_static/credit-card-manual-processing/edit.jpg) 1. You can set up the following limits: * In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save**. ## Tutorials * [Configuring Credit card (manual processing) payment method](https://www.youtube.com/watch?v=dN2q27dKvUU) --- # Advanced configuration - [Payment method restrictions](xref:en/getting-started/configure-payments/advanced-configuration/payment-method-restrictions) - [Currencies](xref:en/getting-started/configure-payments/advanced-configuration/currencies) --- # Payment method restrictions Payment method restrictions allow you to restrict payments coming from certain countries. To restrict a payment method, go to **Configuration → Payment restrictions**. ![paymentmethodrestrictions](_static/payment-method-restrictions/payment_method_restrictions.png) Select the checkbox(es) for the country or countries in which you want the payment method(s) to be unavailable. Click **Save**. > [!NOTE] > > If required, you can select the entire restriction column for all countries. --- # Currencies In nopCommerce, the **only primary store currency is used**. The primary store currency is the currency against which all other allowed currencies will be configured. Although nopCommerce allows having multiple currencies for displaying your product prices, the primary currency is used for payment transactions with online payment gateways. If you are using an online payment gateway (such as PayPal), the amount is sent to the payment gateway and will be the price you entered in primary store currency. Primary store currency is only used by the store administrators. It is used for setting product prices and does not have to be the same as the published currencies. If you only have one published currency, the store will display neither currency selector nor currency symbol with prices. If more than one currency is published, all prices will be marked with the currently selected currency. nopCommerce recommends removing any currency that is not required. nopCommerce uses an **exchange rate** to calculate the amounts for published currencies. The exchange rate is entered when a currency is added or edited. Alternatively, you can use a **real-time exchange** rate service to calculate the amount, and the price of the product will be multiplied by the exchange rate provided. Exchange rates fluctuate on a daily basis. Therefore, you can edit the exchange rate as often as you need to keep up to date. Actual transactions are only handled in your store's primary currency. On credit card transactions, banks will usually make exchanges automatically based on the most up-to-date currency values. To define currency settings, go to **Configuration → Currencies**. ![Currencies](_static/currencies/currencies1.png) From the **Current exchange rate provider** dropdown list, select the exchange rate provider that will be used to get live rates. > [!NOTE] > > By default, there is only one exchange rate provider available in nopCommerce — ECB. To get live rates from ECB, you should select EUR as the primary exchange rate currency. Select the **Auto update enabled** checkbox to enable receiving an automatic update of currency rates every hour. Click **Save**. > [!NOTE] > > By default, all the currency rates are updated once per hour. You can change currency rates updating settings in **System → Schedule tasks**; choose **Update currency exchange rates**. ![Schedule task](_static/currencies/tasks.jpg) ## Add a new currency Click the **Add new** button. ![currencies3](_static/currencies/currencies3.png) Define the currency settings: * Currency **Name**. * **Currency code**. For a list of currency codes, go to: * Enter the exchange **Rate** against the primary exchange rate of the currency. * From the **Display locale** dropdown list, select the display locale for currency values. * Enter **Custom formatting** to be applied to the currency values. In this field, you can specify any symbols for the currency displaying in the public store, the number of decimal places and more. * In the **Limited to stores**, select a pre-created store from the dropdown list. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). * From the **Rounding type** dropdown list, choose one of the types of rounding: * *Default rounding* * *Rounding up with 0.05 intervals (0.06 round to 0.10)* * *Rounding down with 0.05 intervals (0.06 round to 0.05)* * *Rounding up with 0.10 intervals (1.05 round to 1.10)* * *Rounding down with 0.10 intervals (1.05 round to 1.00)* * *Rounding with 0.50 intervals* * *Rounding with 1.00 intervals (1.01–1.49 round to 1.00, 1.50–1.99 round to 2.00)* * *Rounding up with 1.00 intervals (1.01–1.99 round to 2.00)* * Select the **Published** checkbox to enable this currency to be visible and selected by visitors to your store. nopCommerce supports a multi-currency pricing display. If you have several published currencies, customers will be able to select the currency they want. * In the **Display order** field, enter the display order of this currency. A value of 1 represents the top of the list. Click **Save**. ## Get live rates Click the **Get live rates** button in the top right of the *Currencies* window. The panel will be expanded at the bottom of the page as follows: ![Live rates](_static/currencies/live-rates.jpg) Click **Apply all** here or apply new rates for all the currencies needed manually using the **Apply rate** button. ## Tutorials * [Managing currencies in nopCommerce](https://www.youtube.com/watch?v=2nzVxGyc5-M) --- # Configure shipping This section will cover the configuration process of shipping and handling multiple warehouses in nopCommerce. It will include both manual shipping configuration and setting up shipping via API of individual shipping providers like UPS. Please note that nopCommerce offers integration with third-party shipping services and optimizations. They can be found in the nopCommerce [marketplace](http://www.nopcommerce.com/marketplace) and the [technology partners](http://www.nopcommerce.com/technology-partners) section. ## See also * [Shipping settings](xref:en/getting-started/configure-shipping/shipping-settings) * [Shipping providers](xref:en/getting-started/configure-shipping/shipping-providers/index) * [Warehouses](xref:en/getting-started/configure-shipping/advanced-configuration/warehouses) * [Dates and ranges](xref:en/getting-started/configure-shipping/advanced-configuration/dates-and-ranges) * [Measures](xref:en/getting-started/configure-shipping/advanced-configuration/measures) * [Pickup points](xref:en/getting-started/configure-shipping/advanced-configuration/pickup-points) * [Countries, states](xref:en/getting-started/configure-shipping/advanced-configuration/countries-states) --- # Shipping settings This chapter describes how to set up the shipping details of a store. Besides the location and warehouse set, other things make good logistics as well. To manage shipping settings, go to **Configuration → Settings → Shipping settings**. Define your shipping settings in the *Common* panel as follows: ![Shipping Settings](_static/shipping-settings/shipping-settings-common.jpg) * Select **Estimate shipping enabled (cart page)** to display estimated shipping information based on the customer's shipping address on the shopping cart page. See the screenshot below to understand what it looks like. * Select **Estimate shipping enabled (product page)** to display estimate shipping information based on the customer's shipping address on the product details page. See the screenshot below to understand what it looks like. ![Estimate shipping](_static/shipping-settings/estimate-shipping.png) * Select the **Use a city name for estimate shipping** checkbox to allow customers to enter a city name instead of a ZIP or postal code. * Select the **"Pick up in store" enabled** to display the pickup in store option during checkout at the shipping address step. Users will see the following screen: ![Shipping Address](_static/shipping-settings/shipping-address.png) ![Pickup Point Address](_static/shipping-settings/Pickup-Point-address.png) * Tick the **Ignore additional shipping charge for pick up in store** checkbox if needed. * Choose to **Display pickup points on the map** if you want to display them on Google Maps. Customers should not enter a shipping address and choose a shipping method when this option is selected. * **Google maps API key**. If the previous setting is turned on specify the Google maps API key here. > [!Note] > > You can also specify a fee for the 'Pick up in store' option. To do this, go to **Configuration → Shipping → Pickup points** and configure the appropriate pickup point provider. Learn more here: [Pickup points](xref:en/getting-started/configure-shipping/advanced-configuration/pickup-points). * Select **Free shipping over 'x'** to enable free shipping for orders over a certain total amount. The following field is then displayed, enabling you to define the value of 'x'. * In the **Value of 'x'** field, enter the value over which all orders with a total greater than this will qualify for free shipping. * **Calculate 'x' including tax**. If it is not selected the value is calculated excluding tax. * Select **Use warehouse location** to use it when requesting shipping rates. This is useful when you ship from multiple warehouses. * Select **Consider associated products dimensions and weight** to consider associated products dimensions and weight on shipping; clear, for example, if the main product already includes them. * In the **Sort shipping methods by** dropdown, select the field to sort shipping methods by. Define your shipping settings in the *Notifications* panel as follows: ![Shipping Settings notifications](_static/shipping-settings/shipping-settings-notifications.jpg) * Tick **Notify customer about shipping from multiple locations** if required. This is useful when you ship from multiple warehouses. * Select **Display shipment events (customers)** to enable customers to view shipment events on their shipment details page. > [!NOTE] > > Note: to be enabled, this feature must be supported by the shipment computation method. * Tick **Display shipment events (store owners)**, to enable store owners to view shipment events on their shipment details page. > [!NOTE] > > Note: to be enabled, this feature must be supported by the shipment computation method as well. Then define the *checkout* settings: ![Shipping Settings checkout](_static/shipping-settings/shipping-settings-checkout.jpg) * Select the **Hide shipping total if shipping not required** checkbox if you want to hide the *Shipping total* label if shipping is not required. * Select the **Ship to the same address** checkbox to display the "ship to the same address" option during checkout ("billing address" step). In this case "shipping address" with appropriate options (for example, pick up in store) will be skipped. > [!NOTE] > > When using this setting make sure that all billing countries (**Configuration → Countries**) support shipping (**Allows shipping** checkbox selected). * Select **Bypass shipping method page** if there's only one shipping method available. This page will not be displayed during the checkout process. Define the *shipping origin details*: ![Shipping Settings origin](_static/shipping-settings/shipping-settings-origin.jpg) It includes address fields such as: * Select the **Country**. * Select the **State/province**. * Define the **County/region**. * Enter the required **City**. * Enter the required **Address 1**. * Enter the required **Zip/postal code**. and other fields. Click **Save**. --- # Shipping providers If you sell shippable products, you will need to set up shipping methods for your store to deliver orders to customers. You can either define your own shipping methods or use the predefined shipping methods provided by popular carriers, such as UPS. nopCommerce has preinstalled shipment plugins connecting the platform with leading shipping providers, in addition to inbuilt tools for complex shipping calculations, such as shipping by weight or by total and fixed rate shipping. > [!TIP] > > By default, there are several shipping providers available in nopCommerce, but you can find more shipping providers in the nopCommerce [marketplace](https://www.nopcommerce.com/marketplace). If you decide to define and use your own shipping methods, the shipping rates for these methods should be entered manually. If you decide to use the shipping methods provided by the carrier companies like UPS, the shipping rates for these methods will need to be obtained from the respective carrier companies. All shipment options are implemented as plugins and can be found and installed in the *Local plugins* section (**Configuration → Plugins → Local plugins**). Learn how to set up the required shipment options in the following chapters: * [Manual (fixed or by weight and by total)](xref:en/getting-started/configure-shipping/shipping-providers/manual) * [UPS](xref:en/getting-started/configure-shipping/shipping-providers/ups) --- # Manual (fixed or by weight and by total) Manual (fixed or by weight and by total) shipping allows setting fixed fees or calculating fees by weight and by total to all pre-defined shipping methods. To see an example of how this method can be applied to your store, please see the [Example](#example) section below. ## Define the manual shipping provider Go to **Configuration → Shipping → Shipping providers**. The *Shipping providers* window will be displayed: ![Manual shipping methods](_static/manual/methods.jpg) Enable the manual shipping rate computation method as follows: * In the **Manual (fixed or by weight and by total)** row, click the **Edit** button. * In the **Is active** column, select the checkbox. * Click the **Update** button. The *false* option becomes *true*. Click the **Configure** button beside the Manual (fixed or by weight and by total) option in the list. You can switch *Fixed rate* shipping fee calculation to shipping *By weight/total* calculation by clicking the button at the top of the page. ## Configure fixed rate ![Manual configure](_static/manual/fixed-rate-configure.jpg) Click the **Edit** button beside a shipping method and enter the **Rate** and **Transit days** (if needed) for it. Click **Update**. > [!NOTE] > > You can add/remove shipping methods in the *Shipping methods window* accessed by clicking ![button](_static/manual/manual-shipping-manage-button.png) and restrict some methods for chosen countries by clicking ![restrictions](_static/manual/manual-shipping-restrictions.png) on the top. ## Configure rate by weight/total ![by weight](_static/manual/manual-shipping-by-weight-total.png) The **shipping by weight and by total** option allows setting different shipping fees based on a shipment's weight and total. The ability to charge different fees depending on the shipment's weight and total helps to keep a company's shipping costs down when heavy items are shipped yet offer reasonable shipping costs to customers who purchase light products. Use formula **[additional fixed cost] + ([order total weight] - [lower weight limit]) × [rate per weight unit] + [order subtotal] × [charge percentage]** to calculate the fees, where: * **additional fixed cost** is the cost of the shipment in case the weight is below a certain level (lower weight limit). * **rate per weight unit** is the cost of each weight unit above the lower weight limit. * **order subtotal and charge percentage** are parameters for calculating the extra cost based on the order subtotal. For example, if you have the following shipping conditions: * if the weight is 0 to 1 pound and the order subtotal is from $1 to $10, the cost is $10. You should create the **following shipping rules**: * Order weight from: **0** * Order weight to: **1** * Order subtotal from: **1** * Order subtotal to: **10** * Additional fixed cost: **10** * Lower weight limit: **0** * Rate per weight unit: **0** * if the weight is 1.1 pounds to 2 pounds and the order subtotal is from $11 to $1000,000, the cost is $15. You should create the **following shipping rules**: * Order weight from: **1.000** * Order weight to: **2** * Order subtotal from: **11** * Order subtotal to: **1000000** * Additional fixed cost: **15** * Lower weight limit: **0** * Rate per weight unit: **0** * over 2 pounds, the cost is $3 per each additional 0.5 pounds. You should create the **following shipping rules**: * If your fixed cost is $15 the cost per pound over 2 pounds is $6 * Order weight from: **2.0001** * Order weight to: **99999** * Additional fixed cost: **15** * Lower weight limit: **2** * Rate per weight unit: **6** > [!NOTE] > > An additional weight will be charged proportionally; > for example, for 2.1 pounds, $15 + (0.1 * 6)= $15.6 will be charged To add a new shipping rule, click **Add record**. The *Add new record* window will be displayed: ![Add rule](_static/manual/manual-shipping-add-new.jpg) Define the following information: * **Store** in which the calculated fees will be applied. Choose * to apply the rules to all stores. * **Warehouse** from which the shipping will be done. Choose * to apply the rules to all warehouses. * **Country, State/province, Zip** of a shipment destination. * Select a **Shipping method** from the list of precreated options. Use **Manage shipping methods** on the top to add/remove shipping methods or proceed to the [Configure shipping methods](#configure-shipping-methods) section to learn more. * Create your weight configuration by filling the **Order weight from** and **Order weight to** fields. If the customer's shipment weight falls into this range, the additional cost will be fixed and calculated according to this record. * Configure the pricing rules for this record using fields **Order subtotal from, Order subtotal to, Additional fixed cost, Lower weight limit, Rate per weight unit, Charge percentage (of subtotal)** fields. * Define the **Transit days** field, which defines the number of days for delivery. > [!NOTE] > > Make sure that the setting **Configuration → Settings → Shipping settings → Consider associated products dimensions and weight** is true. Click **Save**. > [!NOTE] > > If you wish to limit your customers only to methods configured on that screen select the **Limit shipping methods to configured ones** checkbox on the bottom of the page. ## Configure shipping methods A store owner can define the required shipping method list used in *Manual (fixed or by weight and by total)* provider. To manage shipping methods: Go to **Configuration → Shipping → Shipping providers**. Then click the **Configure** button beside the *Manual (fixed or by weight and by total)* provider. The configuration window will be displayed: ![Configure](_static/manual/fixed-rate-configure.jpg) Click **Manage shipping methods**; the *Shipping methods window* will be displayed: ![Methods](_static/manual/fixed-rate-methods.jpg) Click **Add new** button; the *Add a new shipping method* window will be displayed as follows: ![Add new](_static/manual/fixed-rate-methods-add-new.jpg) Define the following fields for a new record: * **Name** of the shipping method seen by a customer. * **Description** for the shipping method seen by a customer. * **Display order** of the shipping method. A value of 1 represents the top of the list. Click **Save**. > [!NOTE] > > You can click **Edit** in the *Shipping methods* window to edit existing shipping methods as described above. ## Shipping method restrictions A store owner can define restrictions for specific shipping methods in certain countries. To do so, go to **Configuration → Shipping → Shipping providers**. Click the **Configure** button beside the *Manual (fixed or by weight and by total)* provider. The configuration window will be displayed: ![Configure](_static/manual/fixed-rate-configure.jpg) Click **Shipping method restrictions**; the *Shipping method restrictions* window will be displayed: ![Methods](_static/manual/fixed-rate-restrictions-methods.jpg) Select one or more of the shipping methods that you want to disable in certain countries. If required, you can select the entire restriction column for all countries. Click **Save**. ## Example Let's say you have a store located in the USA that ships within the USA and to Canada. You set up three shipping methods available: * **Ground** that allows shipping by land transport. * **Next day air** that provides one-day air shipping. * **2nd day air** allowing two-days air shipping. > [!TIP] > > You can add your own shipping methods by clicking the **Manage shipping methods** button on the *Configure - Manual (Fixed or By Weight and By Total)* page. Then, let's say the shipping fee depends on the order total and shipping address. For example: * If a customer pays $150 for their order, we provide free shipping by the **Ground** method within the USA only. If the order total is less than $150, we will charge $10. The delivery within the USA will take 5 days. * For Canada, a customer should make an order worth $250 to have free shipping by the **Ground** method. If the order total is less than $250, we will charge $20. The delivery will take 7 days in this case. * If a customer needs a **Next day air** delivery, it will cost $60 for the USA. Let's say you wish to disable the **Next day air** option for Canada. * If a customer is ready to wait one more day, we suggest to use **2nd day air** shipping, which costs $40 both for the USA and Canada. Considering all the requirements above, we will set up the payment method on the *Configure - Manual (Fixed or By Weight and By Total)* page as follows: * **Ground** method ![Configuration Ground](_static/manual/configuration-ground.jpg) * **Next day air** method ![Configuration Next day air](_static/manual/configuration-nextday.jpg) * **2nd day air** method ![Configuration 2nd day air](_static/manual/configuration-2ndday.jpg) To disable the **Next day air** option for Canada, click the **Shipping method restrictions** button and fill the *Shipping method restrictions* as follows: ![Configuration example](_static/manual/restrictions-example.jpg) ### Let's see what the shipping options look like in the public store 1. Whenever a customer from the USA visits the product page (or shopping cart page), the shipping estimation will be displayed as follows: ![Estimation](_static/manual/estimate-product-page.jpg) > [!TIP] > > By the way, you can disable shipping estimation by clearing the **Estimate shipping enabled (cart page)** and **Estimate shipping enabled (product page)** checkboxes on the **Configuration → Settings → Shipping settings** page. When the customer proceeds for the shipping details, the following options will be displayed: ![Estimation USA](_static/manual/estimation-popup-usa.jpg) 2. Whenever a customer chooses Canada from the shipping estimation window, the following options will be displayed: ![Estimation Canada](_static/manual/estimation-popup-canada.jpg) As you can see, the **Next day air** option is no longer available. > [!TIP] > > In case you want to provide pickup points to your customers, see how to set this up in the [Pickup points](xref:en/getting-started/configure-shipping/advanced-configuration/pickup-points) chapter. ## Tutorials * [Configuring manual shipping method](https://www.youtube.com/watch?v=1nYj0NqVUWw&t=8s) --- # UPS ## Define the UPS Real Time Shipping Calculations 1. Create a UPS user account via [UPS.com](https://www.ups.com/), then go to [developer.ups.com](https://developer.ups.com/), and create an app to receive the following: * Client ID * Client Secret > [!NOTE] > > This is to use UPS OAuth, which is required for all new accounts after June 2023, and all accounts after June 2024 ![Shipping rate methods](_static/ups/ups-apps-configuration.jpg) 2. Add UPS Products to enable shipment tracking, rate calculations, etc. Recommended products are: * Rating * Address Validation * Landed Cost Quoting * Tracking * Shipping * Time In Transit 3. In the nopCommerce admin area, go to **Configuration → Settings → Shipping Settings**. Configure the shipping point location. The default option is to configure a single **Shipping Origin**, which is configured lower on the page. However you may also choose **Use Warehouse Location**, if you wish to use the settings configured in **Configuration → Shipping → Warehouse**. The **Use Warehouse Location** checkbox is revealed by choosing **Advanced** from the page configuration selector under the **Shipping settings** header. ![Shipping rate methods](_static/ups/shipping-settings-advanced.jpg) 4. In the nopCommerce admin area, go to **Configuration → Shipping → Shipping providers**. ![Shipping rate methods](_static/ups/shipping-rate-methods.jpg) 5. Enable this method as follows: * In the UPS (United Postal Service) row, click the **Edit** button. * In the Is **active** column, select the check mark. * Click **Update**. The *false* option will becomes *true*. 6. Click **Configure** beside the UPS (United Parcel Service) option in the list. The *Configure – UPS (United Parcel Service)* window will be displayed as follows: ![Configure page](_static/ups/ups-configure.jpg) > [!WARNING] > > Beginning in June of 2024, you will no longer be able to transact with UPS APIs using an access key for authentication and are required to update your security model to OAuth 2.0 7. Enter the following information obtained from the UPS provider, and choose the options that are relevant to your store: * Select the **Use sandbox** checkbox to use the testing environment. * Enter the **Client ID** of the UPS provider. * Enter the **Client Secret** obtained from the provider. * Enter your **Account Number** obtained from the provider. * Select your required **UPS Customer Classification** as follows: * Rates Associated With Shipper Number * Daily Rates * Retail Rates * Regional Rates * General List Rates * Standard List Rates * Select the required **UPS Pickup Type** as follows: * Daily Pickup * Customer Counter * One Time Pickup * On Call Air * Letter Center * Air Service Center * Select the required **UPS Packaging Type** as follows: * Unknown * Letter * Customer Supplied Package * Tube * P A K * Express Box * 10 kg Box * 25 kg Box * Pallet * Small Express Box * Medium Express Box * Large Express Box * Select the **Insure package** checkbox, to indicate the package will be insured. * Enter **Additional handling charge**. It is an additional fee to charge your customers. * Select the **Carrier Services** you want to offer to your customers. * Select to get rates for **Saturday Delivery enabled**. * Select the **Packing type**, as follows: * Pack by dimensions * Pack by one item per package * Pack by volume * Tick the **Pass dimensions** checkbox to pass package dimensions when requesting for rates. * Select the **Weight type** – pounds or kilograms. * Select the **Dimensions type** – inches or centimeters. * Tick the **Tracing** checkbox to record system tracing in the system log. The entire request and response XML will be logged (including AccessKey/Username, Password). Do not leave this enabled in a production environment. Click **Save**. --- # Advanced configuration * [Warehouses](xref:en/getting-started/configure-shipping/advanced-configuration/warehouses) * [Dates and ranges](xref:en/getting-started/configure-shipping/advanced-configuration/dates-and-ranges) * [Measures](xref:en/getting-started/configure-shipping/advanced-configuration/measures) * [Pickup points](xref:en/getting-started/configure-shipping/advanced-configuration/pickup-points) * [Countries, states](xref:en/getting-started/configure-shipping/advanced-configuration/countries-states) --- # Countries, states This section describes how to manage countries (where your customers are located) and states. To define the countries and states, go to **Configuration → Countries**. ![countries](_static/countries-states/countries1_1.png) > [!TIP] > > By default, all the countries are uploaded. You can *publish* and *unpublish* countries by selecting them and clicking the corresponding buttons at the top of the page. ## Add a new country To add a new country, click **Add new**. ![addcountry](_static/countries-states/addcountry.png) In the *country info* panel, define the following country settings: * The **Name** of the country. * **Allows billing** to customers located in this country. * **Allows shipping** to customers located in this country. * Enter **Two letter ISO** code of this country. * Enter **Three letter ISO** code of this country. * Enter **Numeric ISO code** of this country. * Select the **Subject to VAT** checkbox to indicate whether customers in this country are charged the EU VAT (the European Union value added tax). > [!NOTE] > > This field is only used when the EU VAT option is enabled on the tax settings page (Configuration → Settings → Tax settings). * To tie a certain store to a country, select the required stores in the **Limited to stores** field, as follows: > [!NOTE] > > This list is only used when you have several stores configured. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). * Select the **Published** checkbox to enable this country to be visible for new account registrations and creation of shipping and billing addresses. * Enter the **Display order** of this country. A value of 1 represents the top of the list. Click **Save**. ## Adding new states and provinces In the *State and provinces* panel, you can add states and provinces of the country. > [!TIP] > > By default, the states of the USA are added. ![addcountry2](_static/countries-states/states.jpg) Click the **Add a new state/province** button at the bottom of the panel to add a new state or province. ![countries3](_static/countries-states/countries3.png) Define the following state/province details: * **Name** of the state or province. * **Abbreviation** for the province or state. * Select the **Published** checkbox to publish the state or province on the website. * In the **Display order** field, enter the display order of this province or state. A value of 1 represents the top of the list. Click **Save** ## Export/import states You can export a list of states of all the countries that were added to the system or import the additional ones using the corresponding buttons at the top of the **Configuration → Countries** page. ![Export/import](_static/countries-states/export-import.jpg) > [!NOTE] > > The imported file should have the same format as the exported one. --- # Warehouses nopCommerce supports multiple warehouses. This tool allows a store owner to keep track of inventory in different warehouses and improve logistics. The following section describes how to add warehouses. This includes warehouse details, such as name, country, address, and more. To add new warehouses: 1. Go to **Configuration → Shipping → Warehouses**. The *Warehouses* window will be displayed: ![Warehouses](_static/warehouses/warehouses.png) 1. Click **Add new**. The *Add a new warehouse* window will be displayed: ![Add new](_static/warehouses/warehouses-add-new.png) 1. Define the following warehouse details: * **Name**. * **Country** of the warehouse. * **State/province** of the warehouse. * **County/region** of the warehouse. * **City** of the warehouse. * **Address 1** of the warehouse. * **Zip/postal code** of the warehouse. * **Phone number** of the warehouse. * In the **Admin comment** field, enter an optional comment or information for internal use. Then, you will be able to choose a warehouse for you products or even use multiple warehouses functionality on the product edit page: ![Multiple warehouses](_static/warehouses/multiple.jpg) --- # Dates and ranges ## Delivery dates Delivery dates are time ranges displaying approximate delivery time to a customer. The delivery dates can be applied to products and displayed on the product details pages. * Go to **Configuration → Shipping → Dates and ranges**. The two following panels will be displayed in the *Dates and ranges* window: ### Delivery dates panel ![Delivery dates](_static/dates-and-ranges/delivery-dates.png) Click **Add new**. The *Add a new delivery date* window will be displayed: ![Add new](_static/dates-and-ranges/delivery-dates-add-new.png) * In the **Name** field, enter the name of the new delivery date; usually, it is a date range. * In the **Display order** field, enter the display order of this delivery date. 1 represents the top of the list. Click the **Save** button. ### Product availability ranges panel Here, you can set up product availability ranges. These options will be displayed on the product editing page. ![Availability ranges](_static/dates-and-ranges/avialability-ranges.png) Click **Add new** to add your own range. The *Add a new product availability range* window will be displayed: ![Add new availability ranges](_static/dates-and-ranges/avialability-ranges-add-new.png) * In the **Name** field, enter the name of the new range, for example, 2 months. * In the **Display order** field, enter the display order of this availability range. 1 represents the top of the list. Click the **Save** button. --- # Measures This section describes how to add new units of weights and dimensions. To add new dimension or weight units: Go to **Configuration → Shipping → Measures**. The *Dimensions* and *Weight* sections will be expanded as follows: ![dimensions](_static/measures/dimensions.png) ![weights](_static/measures/weights.png) At the bottom of the section, define the following new unit details: * **Name** of the new dimension (weight) unit. * **System keyword** for this unit. * **Ratio to primary dimension (weight)** unit. * **Display order** of the measure in the list. A value of 1 represents the top of the list. Then click **Add new record**. The new dimension (weight) unit will be added to the *Dimensions* (*Weights*) table. > [!NOTE] > > You can set the primary dimension (weight) unit by clicking **Mark as primary dimension (weight)**. Click **Edit** beside the measure to edit its details as described above. --- # Pickup points Pickup point is an option providing customers the flexibility to select where they can receive parcels. > [!NOTE] > > This option is only available when the checkbox **"Pick up in store" enabled** is selected on the shipping settings page (**Configuration → Settings → Shipping settings**). To manage pickup point providers: Go to **Configuration → Shipping → Pickup points**; the *Pickup point providers* page will be displayed: ![Pickup point providers](_static/pickup-points/pickup-point-providers.jpg) By default, only one **Pickup in store** option is available. Make sure the pickup point provider is active. If not click the **Edit** button and select the checkbox in the **Is active** column. Then save the changes by clicking the **Update** button. To edit existing pickup points or add new ones, click **Configure** in the grid. The *Configure - Pickup in store* page will be opened: ![Pickup point configure](_static/pickup-points/pickup-in-store-configure.png) Click **Add a new pickup point**; the *Add new* window will be displayed: ![New pickup point](_static/pickup-points/pickup-point-add-new.png) Define the following details: * **Name** of the pickup point. * **Description** if needed. * Select the **Country** from the dropdown list. * Select the **State/province** from the dropdown list. * **City**. * **Address 1**. * **Zip/postal code**. * Pickup point's **Opening hours**. * **Pickup fee** if needed. * **Display order** of this pickup point. * **Store(s)** using this pickup point. **Save** changes. Click **Edit** beside the pickup point to edit the details entered before. --- # Configure taxes This chapter covers the settings of the nopCommerce tax tools. > [!NOTE] > > This chapter includes nopCommerce in-built tax instruments, not third-party tax services. nopCommerce supports external services as well, but they require plugins from the [marketplace](http://www.nopcommerce.com/marketplace) to be installed. The installation process of such modules is described in the [Plugins](xref:en/developer/plugins/index) chapter. ## EU VAT configuration guide To set up nopCommerce VAT support for shops in the EU, go to **Configuration → Settings → Tax settings**. In the *Common* panel: * Set **Tax based on** to **Shipping address**. In the *VAT* panel: * Select **EU VAT enabled**. This will ensure that tax is charged only for shipments within the EU. * Select the **Country** your shop is in. * If applicable, select *Allow VAT exemption*. This will ensure that your VAT registered customers who are shipping within the EU but outside the country in which the store is located will not be charged VAT. * Select the **Assume VAT always valid** checkbox to skip VAT validation. Entered VAT numbers will always be valid. It will be a client's responsibility to provide the correct VAT number. * If you checked **Allow VAT exemption**, then you might want to select the "**Use web service**" and "**Notify admin when a new VAT number is submitted**" checkboxes too. Click the **Save** button. Go to **Configuration → Countries**. Make sure that all the countries in the scope of the VAT have **Subject to VAT** set to *true*. ![Countries](_static/index/countries.jpg) > [!NOTE] > > Jersey, Guernsey, and the other Channel Islands are neither a part of the UK nor within the scope of the VAT. If you sell to those places, you might need to change that. Go to **Configuration → Tax categories**. ![Tax categories](_static/index/tax-categories.jpg) Set up a tax category for each VAT rate in your country. For example, "Standard Rate," "Zero rate," "Discounted rate." Delete default classes that are already there but not applicable. Go to **Configuration → Tax providers**. Select the **Manual (fixed or by country/state/zip)** as the default one using the **Mark as primary provider** button. ![Tax providers](_static/index/tax-providers.jpg) Click **Configure** in the **Manual (fixed or by country/state/zip)** provider line to edit tax rates. At the top of the page, you will see the button. Click on the button to switch to the **Fixed rate** mode. ![Configure](_static/index/configure.jpg) On this page, you can see your VAT rate categories. Click **Edit** beside each category and enter the percentage rates. Then click the **Update** button. Make sure that all products have a tax category assigned to them on their [product pages](xref:en/running-your-store/catalog/products/add-products). ![Product](_static/index/product.jpg) ## See also * [Tax settings](xref:en/getting-started/configure-taxes/tax-settings) * [Tax providers](xref:en/getting-started/configure-taxes/tax-providers/index) --- # Tax settings This section describes your store's tax settings, for example, defining prices including or excluding tax, defining the tax display type, and more. To manage your tax settings, go to **Configuration → Settings → Tax settings**. ![Tax settings](_static/tax-settings/tax-settings.jpg) First of all define **common** tax settings: * From the **Tax based on** dropdown list, select the required option on which the tax is based, as follows: * **Billing address**. When this option is selected, the tax is based on the customer's billing address. If the billing address is unknown, the default address is used (entered below). * **Shipping address**. When this option is selected, the tax is based on the customer's shipping address. If the shipping address is unknown, the default address is used (entered below). * **Default address**. When this option is selected, the tax is based on the default address that is entered below. * **Automatically detect country by IP address** When this setting is enabled, if the customer's billing/shipping address is not already set, the country of address used for tax calculation will be determined automatically by the GEO service (by IP address). * Choose the **Default tax category** for products. It will be pre-selected on the *Add new product* page. * **Tax based on pickup point address** checkbox defines if a pickup point address should be used for tax calculation when the pickup point is chosen. * Select the **Prices include tax** checkbox to indicate whether entered prices include tax. Then define the **default tax address (used for tax calculation)** as follows: * Select the **Country**. * Select the **State/province**. * Define the **County/region**. * Define the **City**. * Define the **Address 1**. * Enter **Zip/postal code**. In the **Tax displaying** panel you can set up how tax will be displayed for customers: * Select the **Allow customers to select tax display type** checkbox to indicate whether customers are allowed to select the tax display type. When cleared the **Tax display type** dropdown list is displayed: * **Excluding tax**: select to enforce excluding tax. * **Including tax**: select to enforce including tax. * Select the **Display tax suffix** checkbox to display the tax suffix (incl. tax\excl. tax). * Select the **Display all applied tax rates** checkbox to display all applied tax rates on a separate line in the shopping cart page. * Select the **Hide zero tax** checkbox to hide the zero tax value in the order summary. * Select the **Hide tax in order summary** checkbox to hide the tax value in the order summary when prices are shown as tax inclusive. * Select the **Force tax exclusion from order subtotal** checkbox to always exclude tax from the order subtotal (irrelevant to the selected tax display type). This checkbox affects only pages where the order totals are displayed. In the *Shipping* panel, select the **Shipping is taxable** checkbox to indicate that the shipping is taxable. The following fields are then displayed: * **Shipping price includes tax**: select to indicate the shipping price includes tax. * **Shipping tax category**: select the required tax category used for the shipping tax calculation. In the *Payment* panel, select the **Payment method additional fee is taxable** checkbox to indicate the payment method additional fee is taxable. The following options will be displayed: * **Payment method additional fee includes tax**: select to indicate that the payment method additional fee is taxable. * **Payment method additional fee tax category**: from the dropdown list, select the required tax category used for the payment method additional fee tax calculation. Then set up the VAT in the *VAT* panel: * Select the **EU VAT enabled** checkbox to indicate that European Union Value Added Tax is enabled. When this option is selected, customers will be requested for the *Company VAT number* during registration or on the customer account details page. This VAT number can be automatically validated through a web service, if the **Use web service** checkbox is ticked, or manually on the customer details page in the administration area by the store owner. * **EU VAT enabled for guests** - Check to enable EU VAT (the European Union Value Added Tax) for guest customers. They will have to enter it during the checkout at the billing address step. * **VAT number required** - Check if 'EU VAT number' is required. * **Your shop country**: from the dropdown list, select the country where your store is located. * **Allow VAT exemption**: select this checkbox to exempt eligible VAT registered customers from VAT. * **Assume VAT always valid**: select this checkbox to skip VAT validation. Entered VAT numbers will always be valid. It is the client's responsibility to provide the current VAT number. * **Use web service**: select this checkbox to use the web service to validate VAT numbers. * **Notify admin when a new VAT number is submitted**: select this checkbox to receive a notification by email when a new VAT number is submitted. > [!NOTE] > > If VAT is enabled, then it charges 0% tax to shipping outside the EU and 0% to those who have supplied a validated and approved VAT number and are shipping within the EU but outside the shop country. Refer to the article for further information on the EU VAT. > > [!TIP] > > Read how to set up the EU VAT here: [EU VAT configuration guide](xref:en/getting-started/configure-taxes/index#eu-vat-configuration-guide). Click **Save**. ## Tutorials * [Managing tax settings](https://www.youtube.com/watch?v=8iF5nQvIoLs&feature=youtu.be) --- # Tax providers To define tax rate providers go to **Configuration → Tax providers**. ![Tax providers](_static/index/tax-providers.png) Only one tax rate provider can be used for tax calculation. Adding new tax providers is only recommended for advanced users. To select the default tax provider click the **Mark as primary provider** button. > [!TIP] > > By default, there are several tax providers available in nopCommerce, but you can find more tax providers in the nopCommerce [marketplace](https://www.nopcommerce.com/marketplace). The configuration of tax providers is described in the following chapters: * [Avalara tax provider](xref:en/getting-started/configure-taxes/tax-providers/avalara) * [Manual (fixed or by country/state/zip)](xref:en/getting-started/configure-taxes/tax-providers/manual) --- # Manual (fixed or by country/state/zip) To configure the Manual (fixed or by country/state/zip) tax provider, go to **Configuration → Tax providers**. ![Tax providers](_static/manual/tax-providers.png) Click **Configure** in the **Manual (fixed or by country/state/zip)** provider line to edit tax rates. You can switch *Fixed rate* tax calculation to *Country/state/zip* tax calculation by clicking the appropriate button at the top left. To manage tax categories, click the **Manage tax categories** button at the top right. ## Fixed rate Click the button **By country** at the top of the page to switch the editor to **Fixed rate** mode. ![Configure](_static/manual/configure-confirm.jpg) Please note that the tax rules will be applied those that are displayed on the configuration page when switching between *Fixed rate* and *By country* modes. ![Configure](_static/manual/configure.jpg) On this page, you can see the precreated tax categories. Click **Edit** beside each category and enter the percentage rates. Then click the **Update** button. Make sure your products have a tax category assigned to them on their [product pages](xref:en/running-your-store/catalog/products/add-products). ![Product](_static/manual/product.jpg) > [!NOTE] > > This section only shows precreated tax categories. Click the **Manage tax categories** button to edit tax categories or read how to manage tax categories here: [configure tax categories](#configure-tax-categories). ## By country Click the button **Fixed rate** at the top of the page to switch the editor to **By country** mode. ![By country](_static/manual/tax-by-country.png) Define the new tax rate as follows: * Select the **Store** for which the rate is defined. Select an * to apply this rate to all stores. * Select the **Country** for which the tax rate is defined. * Select the **State/province** for which the tax rate is defined. If an asterisk (*) is selected, this tax rate will apply to all customers from the selected country regardless of the state. * Enter **Zip** Code of an area for which the tax rate is defined. If this field is empty, then this tax rate will apply to all customers from the selected country or state regardless of the ZIP Code. * Select the **Tax category** for which to apply the tax rate. * In the **Percentage** field, enter the required percentage. Click **Add tax rate**. The new tax rate will be displayed as follows: ![Add tax rate](_static/manual/add-tax-rate.png) > [!NOTE] > > This section only shows precreated tax categories. Click the **Manage tax categories** button to edit tax categories or read how to manage tax categories here: [configure tax categories](#configure-tax-categories). ## Configure tax categories To define tax categories, go to **Configuration → Tax categories**. The *Tax categories* window will be displayed: ![Tax categories](_static/manual/tax-categories.jpg) To add a new tax category, enter the category **Name**, and the **Display order** of this tax classification at the bottom of the panel. In the **Display order** field, the value of 1 represents the top of the list. Then click **Add new record** to save the new tax category. --- # Avalara tax provider ## Connect to AvaTax After installing the Avalara tax provider, you need to configure the integration. > [!NOTE] > > Make sure that the plugin is installed and selected as "Enabled" (**Configuration → Local plugins**). To enable the plugin, click **Edit** and select the **Is enabled** checkbox. ![Local plugins](_static/avalara/local-plugins.png) To configure the Avalara tax provider, go to **Configuration → Tax providers**. ![Tax Providers](_static/avalara/tax-providers.png) Click **Mark as primary provider**. Click **Configure** beside the Avalara tax provider option in the list. Follow the instructions at the top of the page to create an account. Then configure the plugin; each field's function will be annotated when "?" is hovered on. 1. Configure your AvaTax credentials: ![Configuration Credentials](_static/avalara/avalara-configuration-common.png) * **Account ID**: provided during your AvaTax account activation process. * **License key**: provided during your AvaTax account activation process. * **Company**: company profile identifier in the AvaTax admin console. * **Use sandbox** is enabled to commit a test transaction. * **Enable logging** enables logging of all requests to the Avalara services. 2. Configure tax calculation settings: ![Configuration Tax](_static/avalara/avalara-configuration-tax-calculation.png) * **Commit transactions** is enabled to commit transactions right after they are saved. * **Validate address** is enabled to validate the address entered. * **Tax origin address** is used for tax requests to the Avalara services. * **Use tax rate tables to estimate** determines whether to use tax rate tables to estimate. This will be used as a default tax calculation for catalog pages and adjusted and reconciled to the final transaction tax during checkout. Tax rates are looked up by ZIP Code (US only) in a file periodically updated by Avalara (see Schedule tasks). * **Tax rates by address only** is shown if the previous setting is clear. Enable it to get tax rates by the address only (reduces the number of API calls but may bias results). 3. Configure tax exemption settings: ![Configuration Exemption](_static/avalara/avalara-configuration-exemption.png) * **Enable exemption certificates** is enabled to activate tax exemption certificates. * **Limited to customer roles** is used to restrict customers who have access to this functionality. * **Auto validate certificates** is enabled to automatically validate new uploaded/created certificates. * **Allow edit info** is enabled to allow customers to edit their info (such as name, phone, address) when managing certificates. * **Display 'No valid certificates' message** is enabled to display a message that there are no valid certificates for the customer on the order confirmation page. ![Configuration Exemption None](_static/avalara/avalara-configuration-exemption-none.png) > [!TIP] > > This message text can be edited in the language resources. 4. **Save** and click the **Test connection** button to perform the test connection. 5. To perform the *test tax calculation*, fill the address form at the bottom of the page (please note that the nopCommerce Avalara tax plugin commits transactions to US addresses only) and click **Test tax transaction**. ![Configuration Test](_static/avalara/avalara-configuration-test.png) ## Assign AvaTax code Navigate to **Configuration → Tax categories**. At the top right of the page, you will see the branded **Avalara tax codes** button. Clicking it will show the following dropdown menu: > [!IMPORTANT] > > The **Avalara tax codes** button will only be displayed if the *Avalara* plugin is selected as the main tax provider on the *Configuration → Tax providers page*. ![Tax categories](_static/avalara/tax-categories.jpg) * **Export tax codes to Avalara** – exports all codes from your store to your AvaTax backend. * **Import Avalara system tax codes** – imports all AvaTax tax codes from Avalara. ![Tax categories import](_static/avalara/tax-categories-import.jpg) * **Delete Avalara system tax codes** – deletes all codes exported from Avalara. ## Assign an AvaTax system tax code to an item 1. Go to **Catalog → Products**. 1. Select a product to open the product details screen and click **Edit**. 1. On the **Product Details** screen, in the **Price** panel, assign the appropriate code from the dropdown list in the **Tax category** field. ![Product tax category](_static/avalara/product-tax-category.png) > [!IMPORTANT] > > Ensure that **SKU** is entered for better navigation in the AvaTax backend. 1. Click **Save**. 1. To see a listing of all available AvaTax system tax codes, visit [http://taxcode.avatax.avalara.com](http://taxcode.avatax.avalara.com). ## Item Classification Managed Tariff Code Classification is an Avalara service that assigns Harmonized System (HS) tariff codes to your product catalog. Once Avalara has classified the items you sell, include tariff codes in AvaTax calculations automatically or export them for use in your own business application. Customs authorities use Harmonized System (HS) tariff codes to calculate tariff rates for all internationally traded products. Unlike sales and use tax codes, tariff codes aren't universal. Assign fully qualified tariff codes to the products that you sell internationally to calculate customs duties and import taxes. In AvaTax, parent products are classified with a tariff code and any child SKUs inherit that classification. 1. Activate the *Item Classification* functionality on the tab with the same name. 1. Specify for which countries HS classification codes are to be obtained. 1. Save the settings using the **Save** button. ![Item classification](_static/avalara/item-classification.png) 1. Go to the **Item Classification settings** in your Avalara personal account. ![Item classification avalara](_static/avalara/item-classification-avalara.png) 1. Specify the endpoint address for the webhook - `{your.store.url}/avalara/item-classification-webhook` ![Item classification endpoint](_static/avalara/item-classification-endpoint.png) 1. Go to the plugin configuration page again and specify which products should be sent for classification. ![Item classification sync](_static/avalara/item-classification-sync.png) 1. Click the **Sync now** button to start the process of sending products for classification. After receiving a response from Avalara service, the table will be filled with the received values (You need to update the tables manually). After that the received classification code values will be transferred to calculate tax rates. ## Validate a customer address 1. Ensure **Validate address** checkbox is on; in that case, the address will be validated automatically. 1. User will see the following screen: ![Validate address](_static/avalara/validate-customer-address.png) ## Tax exemption There are two ways to enable the tax exemption using this plugin: 1. Assign an AvaTax tax exempt category to a specific customer or an entire customer role in the admin area: * Click **Customers → Customers → Edit customer** * Find the highlighted **Entity use code** field and select the field, select the appropriate customer type code. ![Customer details](_static/avalara/customer-entity-use-code.png) * Click **Save** > [!NOTE] > > It is not necessary to select **Tax exempt** checkbox: assigning **Entity use code** is enough. 2. Activate the exemption certificates feature: > [!IMPORTANT] > > You will need a [CertCapture account](https://avlr.co/3bA1P1X) for this feature to work correctly. * Ensure that the **Enable exemption certificates** checkbox is on; in that case, customers will be able to manage their tax exemption certificates before making a purchase. * A new page will be added in the account section ![Tax exemption certificates](_static/avalara/exemption-certificates.png) --- # Email accounts This chapter describes how to set up email accounts associated with your store: a general contact email, a sales representative email, a customer support email, and more. To manage email accounts, go to **Configuration → Email accounts**. The *Email accounts* window displays the email accounts of the store owner, as shown below. After the email accounts are configured, the store owner can select the required email account on the message template details page as described in the [Message templates](xref:en/running-your-store/content-management/message-templates) chapter. ![Email accounts](_static/email-accounts/email-accounts.png) ## Add a new email account To add a new email account, click **Add new**. The *Add a new email account* window will be displayed: ![Add a new email account](_static/email-accounts/email-accounts-add-new.png) Define the following email account information: * In the **Email address** field, enter the email address for all outgoing emails of your store. Example: `sales@yourstore.com`. > [!NOTE] > > Some of the email providers may not use this setting unless this email address is added as an sending email alias/account in the email account which you're using for authentication. * In the **Email display name** field, enter the displayed name for outgoing emails of your store. Example: "Your store sales department." * In the **Host** field, enter the host name of IP address of your email server. * In the **Port** field, enter the SMTP port of your email server. * Select the **SSL** checkbox to use Security Sockets Layer to encrypt the SMTP connection. * In the **Max number of emails** field, enter the maximum number of emails sent at one time. * Choose the **Authentication method** that will be used to identify the client when connecting to the SMTP server. * *No authentication* (no additional fields) * *NTLM (the default network credentials)* * *Login/Password* * In the **User** field, enter the user name of your email server. * In the **Password** field, enter the password of your email server. * *Google (OAuth2)* ![Email account - Google](_static/email-accounts/email-accounts-google.png) * The **Client ID**. Public identifier for application. * The **Client Secret**. The secret known only to the application and the authorization server. * *Microsoft (OAuth2)* ![Email account - Microsoft](_static/email-accounts/email-accounts-microsoft.png) * The **Tenant identifier** can be a GUID (the ID of your Microsoft Entra instance), domain name or one of placeholders: "organizations", "consumers", "common". * The **Client ID**. Public identifier for application. * The **Client Secret**. The secret known only to the application and the authorization server. Click **Save**. The window will be expanded as follows: ![Email account - Details](_static/email-accounts/email-accounts-details.png) In the **Send email to** field, enter the email address for the test email and click **Send test email**. --- # Advanced configuration * [How to install and configure SSL certificates](xref:en/getting-started/advanced-configuration/how-to-install-and-configure-ssl-certificates) * [Your store information](xref:en/getting-started/advanced-configuration/your-store-information) * [GDPR settings](xref:en/getting-started/advanced-configuration/gdpr-settings) * [Localization](xref:en/getting-started/advanced-configuration/localization) * [Custom HTML](xref:en/getting-started/advanced-configuration/custom-html) * [External authentication methods](xref:en/getting-started/advanced-configuration/external-authentication-methods) * [Multi-factor authentication](xref:en/getting-started/advanced-configuration/multi-factor-authentication) * [Integrating Jotform AI Agent](xref:en/getting-started/advanced-configuration/jotform) * [Configure analytics](xref:en/getting-started/advanced-configuration/configure-analytics) * [Plugins in nopCommerce](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) * [Multi-store](xref:en/getting-started/advanced-configuration/multi-store) * [Security settings](xref:en/getting-started/advanced-configuration/security-settings) * [SMS providers](xref:en/getting-started/advanced-configuration/sms-providers/index) * [ChatGPT shopping](xref:en/getting-started/advanced-configuration/chatgpt-shopping) * [Google AI Commerce Search](xref:en/getting-started/advanced-configuration/google-ai-commerce-search) * [PunchOut](xref:en/getting-started/advanced-configuration/punchout) * [robots.txt settings](xref:en/getting-started/advanced-configuration/robots-txt) * [PDF settings](xref:en/getting-started/advanced-configuration/pdf-settings) * [All settings](xref:en/getting-started/advanced-configuration/all-settings) --- # How to install and configure SSL certificates What is an SSL certificate? SSL stands for Secure Socket Layer. SSL certificates validate your website's identity and encrypt the information visitors send to (or receive from) your site. When you have an SSL certificate protecting your website, your customers can rest assured that the information they enter on any secured page is private and can't be viewed by cyber crooks. ## How to get an SSL certificate 1. First, to implement SSL on your website, you will need to get an SSL certificate from an SSL Certificate Provider, aka Certification Authority. There are plenty of Certification Authorities for securing an SSL certificate on your website, such as SSL.com, Namecheap, or GoDaddy. 2. Then, you need to install the SSL certificate you bought on your server. The way you do this depends on the server. For more instructions and recommendations, you should refer to the SSL Certificate Provider guideline or your server documentation. In this article, I will just provide you with a link to such guideline by GoDaddy: [Install SSL certificates](https://www.godaddy.com/help/install-ssl-certificates-16623). 3. In the last step, you need to set up your nopCommerce store in the admin area. To do this, go to the **Configuration → Stores** page. Select the store you want to set up and click the **Edit** button beside it. The *Edit store details* window will be displayed as follows: ![Store](_static/how-to-install-and-configure-ssl-certificates/store.jpg) - Enter your **Store URL** with the `https://` prefix. - Select the **SSL enabled** checkbox. > [!WARNING] > > Do not enable it until you have an SSL certificate installed on the server. ## Troubleshooting ### Admin panel is not available due to problems with SSL certificate A common problem is when the SSL certificate is not installed on the server or there are problems with the SSL configuration. At the same time, the **SSL enabled** setting was activated in the store (as we have done in the previous section). **Affected versions**: All **Solution**: Run the following SQL Query: ```sql UPDATE [dbo].[Store] SET [SslEnabled] = 'False' ``` ### Mixed Content HTTP and HTTPS Mixed content occurs when a site operates over the SSL security protocol, but some of the resources (for example, images) are loaded over an insecure HTTP connection. This causes errors on the page, as the original request was secured over HTTPS. When using a load balancer, similar problems can arise due to the fact that it communicates with the application over HTTP. **Affected versions**: 4.20 and below **Solutions**: - Make sure you have activated the setting: ```json securitysettings.forcesslforallpages = true ``` - Make sure your website is listening on port 443 on the hosting server. **Affected versions**: All **Solutions**: - Missing field `UseHttpXForwardedProto` in the request header. Try to enable the `UseHttpXForwardedProto` setting in the `appsettings.json` file and restart the website. ```json "UseHttpXForwardedProto": true ``` - You can fix it by adding the CSP "upgrade-insecure-requests" directive. This can be done either in the `web.config` file. Or by embedding the same inline directive in the `` section of the document using the `` element: ```XML ``` - In the case of using Cloudflare, check if your SSL setting is in `Full` or `Flexible` mode by logging into your Cloudflare dashboard and clicking the `SSL/TLS app` to check the SSL setting. ### Infinite redirection loop (ERR_TOO_MANY_REDIRECTS) When an unauthorized user tries to log in or visit the shopping cart, the site enters an infinite redirection loop. **Affected versions**: All **Solutions**: - Try to delete cookies on the site; this procedure may slightly differ depending on the browser used. Alternatively, you can simply open the page in private mode to check if this is the cause of the error. - Clear Server, Proxy, and Browser Cache. - Check HTTP to HTTPS Redirects on Server. It could very well be that the HTTPS redirect rules on your server were misconfigured. You can add a redirect rule to your IIS from http to https. The rule pattern has the following form: ```xml ``` - ERR_TOO_MANY_REDIRECTS is also often commonly caused by reverse-proxy services, such as Cloudflare. This usually happens when their Flexible SSL option is enabled and you already have an SSL certificate installed with your web host. When flexible is selected, all requests to your hosting server are sent over HTTP. Your host server most likely already has a redirect in place from HTTP to HTTPS, and therefore, a redirect loop occurs. To fix this, you need to change the Cloudflare Crypto settings from Flexible to either Full or Full (strict). --- # Your store information In default nopCommerce installation, only one store is created and needs to be configured, as described below. To set up the default store, go to **Configuration → Stores**. ![mainstore](_static/your-store-information/mainstore.png) Click **Edit** beside the default store to configure it. ![editstore](_static/your-store-information/Store-Edit.png) ## Info Configure your main store details as follows: * Define the **Store name**. * Enter your **Store URL**. * Press the button **SSL** if your store is SSL secured. SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral. SSL is the industry standard used by millions of websites to protect online transactions with their customers. > [!IMPORTANT] > > Only press this button after you have installed the SSL certificate on your server. Otherwise, you won't be able to access your site and will have to manually edit the appropriate record in your database ([Store] table). > > [!TIP] > > Read more about setting SSL up in the following chapter: [How to install and configure SSL certificates](xref:en/getting-started/advanced-configuration/how-to-install-and-configure-ssl-certificates). * The **HOST values** field is a list of possible HTTP_HOST values of your store (for example, `yourstore.com`, `www.yourstore.com`). Filling this field is only required when you have a [multi-store solution](xref:en/getting-started/advanced-configuration/multi-store) to determine the current store. This field enables distinguishing requests to distinct URLs and determines the current store. You can also see the current HTTP_HOST value in **System → System information**. * In the **Default language** field, choose the default language of your store. You may also leave it unselected. In this case, the first found one (with the lowest display order) will be used. * Define the **Display order** for this store. 1 represents the top of the list. * Define the **Company name**. * Define the **Company address**. * Set your **Company phone number**. * In the **Company VAT** field, enter the VAT number of your company (used in the EU). ## SEO The store owner can localize the main website keyword, meta title, and meta description for each store. ![SEO](_static/your-store-information/SEO.png) ## See also * [Setting up multi-Store](xref:en/getting-started/advanced-configuration/multi-store) * [Countries](xref:en/getting-started/configure-shipping/advanced-configuration/countries-states) * [Languages](xref:en/getting-started/advanced-configuration/localization) * [Security settings](xref:en/getting-started/advanced-configuration/security-settings) * [PDF settings](xref:en/getting-started/advanced-configuration/pdf-settings) * [GDPR settings](xref:en/getting-started/advanced-configuration/gdpr-settings) --- # GDPR settings *GDPR* (General Data Protection Regulation) is a revised European Union's new data privacy law which impacts how all companies collect, use, and share the personal data of their European customers. The regulation entered into force on May 24, 2016, and applies since May 25, 2018. The regulation is an essential step to strengthen individuals' fundamental rights in the digital age and facilitate business by clarifying rules for companies and public bodies in the digital single market. For more information, please refer to this source: [https://ec.europa.eu/info/law/law-topic/data-protection/data-protection-eu_en](https://ec.europa.eu/info/law/law-topic/data-protection/data-protection-eu_en) ## Configure GDPR To enable GDPR settings in your nopCommerce store, go to **Administration → Configuration → Settings → GDPR settings**. ![Configure](_static/gdpr-settings/configure.jpg) Then select the **GDPR enabled** checkbox. Additional settings will allow you to capture a log of the following activities: * **Log "accept privacy policy" consent**. * **Log "newsletter" consent**. * **Log user profile changes**. * **Delete inactive customers after months** - The default value is 36 months. You can add consents on your nopCommerce site by clicking the **Add consent** button in the *Consents* panel: ![Consents](_static/gdpr-settings/consents.jpg) To add a new consent, you will be redirected to the *Add consent* window: ![Add consent](_static/gdpr-settings/add-consent.jpg) Define the following consent settings: * **Message** or question that will be displayed to customers. * Whether the consent **Is required**. * Whether the consent will be **Displayed during registration**. * Whether the consent will be **Displayed on "customer info" page** in the "My account" section. * **Display order** is the consent display order. 1 represents the first item in the list. Here is an example of a consent option on a customer info page: ![agreement](_static/gdpr-settings/agreement.png) If you have enabled the consent log settings, then you can see the log activity by going to: **Administration → Customers → GDPR requests (log)**. ![log](_static/gdpr-settings/log.png) When the GDPR setting is enabled, the store owner can also perform actions like: * **Permanent delete** for deletion of a customer record. * **Export data** for exporting customer data. To do this, go to **Administration → Customers → Edit customer** page. ![customerdetails](_static/gdpr-settings/customerdetails.png) ## Tutorials * [Managing GDPR settings in nopCommerce](https://www.youtube.com/watch?v=6bLc_TDqD18&feature=youtu.be) --- # Localization In nopCommerce, your store can have several languages installed. However, the customers will only see the data that has been defined in their selected language. > [!TIP] > > By default, the English language is installed. To see or edit the installed languages, go to **Configuration → Languages**: ![language](_static/localization/Language.png) > [!NOTE] > > You can download new language packs from the official [Translations](https://www.nopcommerce.com/translations) page. ## Adding a new language To add a new language, click **Add new**. In the *Add a new language* window, define the following settings: ![addlanguage](_static/localization/addlanguage.png) * The **Name** of the new language. * The **Language culture** — a specific language code (for example, de-AT for Austrian German). > [!NOTE] > > When updating the **Language culture** field, please make sure the appropriate CLDR package is installed for this culture. You can set CLDR for the specified culture in the *Localization* panel of the **Configuration → Settings → General Settings** page. * The **Unique SEO code** — a two-letter language SEO code used to generate URLs like `http://www.yourstore.com/en/` when you have more than one published language. > [!NOTE] > > The **SEO friendly URLs with multiple languages** option should be enabled in the **Configuration → Settings → General settings → Localization settings** panel. * The **Flag image file name** — enter the flag image file name. The image should be saved under the `…/images/flags` directory. You can also choose an image from a predefined list. * Select **Right-to-Left** if needed (for example, for Arabic or Hebrew). > [!NOTE] > > The active theme should support RTL (have an appropriate CSS style file). This option only affects the public store. * The **Default currency** for a specific language. If not specified, then the first found one (with the lowest display order) will be used. * **Limited to stores option** allowing to set this language for a specific store(s). You can choose the store(s) from a precreated list. Leave this field empty if you don't use this option. > [!NOTE] > > To use the store limitation, the **Ignore "limit per store" rules (sitewide)** option should be disabled in the **Configuration → Settings → Catalog settings → Performance** panel. * **Publish** the language to enable it to be visible and selected by visitors to your store. * **Display order** of the language. 1 represents the top of the list. Click **Save** to save the changes. > [!NOTE] > > Since language cultures are only loaded when the application is starting, you have to restart the application once a language is added or deleted. > > [!NOTE] > > After adding a new language, you will be able to import and export string resources using the **Import resources** and **Export resources** buttons at the top of the page. The *String resources* panel on the language edit page will allow you to view the existing language resources and add new ones manually. ## Import language pack If you wish to add a new language to your store, you should: 1. Visit the nopCommerce [translations](https://www.nopcommerce.com/translations) page. 1. Choose the nopCommerce version and download the desired language pack. 1. Go to **Configuration → Languages** and click the **AddNew** button. ![LanguageAddNew](_static/localization/language-add-new.png) 1. Fill in the required fields and click **Save and continue edit**. ![LanguageSave](_static/localization/language-save.png) 1. Click **Import resources**. And specify the path to the language pack file (*.xml) that you downloaded. ![LanguageImport](_static/localization/language-import.png) If you found a mistake in translation or want custom naming, you can edit the string resources in the *String resources* panel. ## Manage string resources Go to **Configuration → Languages**. The *Languages* window will be displayed: ![Languages](_static/localization/languages.png) Click the **Edit** button beside the language. In the **Edit language details** window, find the **String resources** panel. For example, you want to change the name of a panel at the top of the page from "Administration" (on the picture below) to "Control panel." ![Example 1](_static/localization/lang-example-before-change.jpeg) 1. To find the locale resource you need to edit, in the **Resource name** field, enter "administration." If the resource exists, it will be found. Click **Edit** beside it. 1. Enter a new value in the **Value** field and click **Update**. ![Example 2](_static/localization/lang-resource-edit.png) 1. The changes will be applied: ![Example 3](_static/localization/lang-example-after-change.jpeg) To add a new string resource, use the **Add new record** panel. This window enables you to add a new resource record to the grid as follows: ![Add new record](_static/localization/lang-add-resource.png) * In the **Resource name** field, enter the resource string identifier. * In the **Value** field, enter a value for this resource string identifier. Click **Save**. ## Localization settings To configure localization settings, go to **Configuration → Settings → General settings**: ![Localization settings](_static/localization/lang-localization-settings.jpg) * To set the [CLDR](http://cldr.unicode.org/) pattern for localizing client-side validation to the current culture, click the **Set CLDR for current culture** button. * Select the **Load all locale resources on startup** checkbox to load all locale resources on the application startup. When enabled, all locale resources will be loaded on the application startup. The application start will be slower, but then all pages can be opened much faster. * Select the **Load all localized properties on startup** checkbox to load all localized properties on the application startup. When enabled, all localized properties (such as localized product properties) will be loaded on the application startup. The application start will be slower, but then all pages can be opened much faster. It's only used with two or more languages enabled. It is not recommended to enable it when you have a large catalog (several thousand localized entities). * Select the **Load all search engine friendly names on startup** checkbox to load all search engine friendly names (slugs) on the application startup. When enabled, all slugs will be loaded on the application startup. The application start will be slower, but then all pages can be opened much faster. It is not recommended to enable it when you have a large catalog (several thousand entities). * Select the **Use images for language selection** checkbox to use images instead of language names. * Select the **SEO friendly URLs with multiple languages enabled** checkbox to allow SEO-friendly URLs for all languages. When enabled, your URLs will be `http://www.yourStore.com/en/` or `http://www.yourStore.com/fr/` (SEO-friendly). > [!NOTE] > > You must restart the application after the **SEO friendly URLs with multiple languages enabled** setting is updated. Otherwise, it can cause errors. * Select the **Automatically detect language** checkbox for detecting language based on customer browser settings. ## Localize entities If you have more than one language installed in your store, you will be able to enter some fields displayed to customers in different languages. For example: ![Fields](_static/localization/fields.jpg) * In the *Standard tab*, enter the text that will be displayed to customers if the localized fields are not specified. * In the *tabs with language names*, enter the localized text. --- # Custom HTML settings To manage *Custom HTML* settings, go to **Configuration → Settings → General settings**. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ## Custom HTML Although typical programming knowledge is not required to fully use nopCommerce, in some cases you may need to add header and footer code. For example, you might want to use analytics, which is a popular reason for your site's files to get hacked. Many tools and tracking scripts require you to add code snippets to your site’s header or footer. In this entry, we’ll show you how to add code to the nopCommerce header or footer HTML. A standard website will break down into a few different components, much like a text document: - Header. Your site's header contains a number of "preload" elements and details about your *Secure Sockets Layer (SSL)* certificate, encryption, any JavaScript, and more. - Body. - Footer. This works similar to your header, but ends at the bottom of the page instead. Servers will load pages linearly - header, body, then footer. This means that the header code will load first, and the footer code after everything else. Define the *Custom HTML* settings as follows: ![Security](_static/custom-html/custom-html.jpg) This will add any code at the global (i.e. site-wide) level. --- # External authentication methods External authentication methods allow users to log in to a nopCommerce site without entering their credentials: email and password. Users can be authenticated using an external site (such as Facebook or Google). nopCommerce has a built-in external authentication through Facebook. You can set up other methods using plugins from the [marketplace](https://www.nopcommerce.com/marketplace). After an external authentication method is configured and marked as active, users will see a new authentication option on the login page. ## Manage the external authentication methods Go to **Configuration → Authentication → External authentication**. The *External authentication* window will be displayed: ![External auth](_static/external-authentication-methods/external-authentication.png) Click **Edit** beside an authentication method and select **Is active** to activate the method. You can also define the method's **Display order**. Then click the **Update** button to save the changes. Click **Configure** for the method configuration. ## Manage Facebook authentication The Facebook authentication method is a built-in external authentication plugin. To configure authentication with Facebook, please follow these steps: 1. On the **Configuration → Authentication → External authentication** page, click **Configure** beside the **Facebook authentication**. The *Configure - Facebook authentication* window will be displayed: ![Facebook](_static/external-authentication-methods/facebook.jpg) 1. Navigate to the [Facebook for Developers](https://developers.facebook.com/apps) page and sign in. If you have no Facebook account, use the Sign up for Facebook link on the login page to create one. 1. Tap the **+ Add a New App button** in the upper right corner to create a new App ID. (If this is your first app with Facebook, the text of the button will be **Create a New App**.) 1. Fill in the form and tap the **Create App ID button**. 1. The *Product Setup* page will be displayed, letting you select the features for your new app. Click **Get Started** on *Facebook Login*. 1. Click the **Settings** link in the menu on the left; you will be presented with the *Client OAuth Settings* page with some defaults already set. 1. Enter `https://yoursitename.com/signin-facebook` into the **Valid OAuth Redirect URIs** field, replacing `yoursitename.com` with your site URL. 1. Click **Save Changes**. 1. Click the **Dashboard** link in the left navigation. 1. Copy your **App ID/API Key** and **App secret** in the form on the plugin configuration page. Click the **Save** button. On the login page of the public store, see the newly added authentication method. ## See also * [Plugins in nopCommerce](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) --- # Multifactor authentication Multifactor Authentication (MFA) (in our case, it is Two-Factor Authentication – 2FA) is an authentication method that requires a user to provide two or more verification factors to gain access to a resource. MFA is a core component of a strong identity and access management (IAM) policy. Rather than just asking for a username and password, MFA requires one or more additional verification factors, which decreases the likelihood of a successful cyberattack. nopCommerce implements a built-in multifactor authentication through Google Authenticator. You can set up other methods using plugins from the [marketplace](https://www.nopcommerce.com/marketplace). ## Manage the multifactor authentication methods By default, the Google Authenticator plugin is not installed. To install the plugin, go to **Configuration → Local plugins**. 1. Search for *Google Authenticator* in the **Plugin name** field. 1. Click the **Install** button. 1. Then click the **Restart application to apply changes** button to apply changes. 1. Go to **Configuration → Authentication → Multi-factor authentication**. The *Multi-factor authentication* window will be displayed: ![Multi-factor auth](_static/multi-factor-authentication/list.jpg) 1. Click **Edit** beside an authentication method and select **Is active** to activate the method. You can also define the method's **Display order**. Then click the **Update** button to save the changes. ## Configuring the Google Authenticator plugin Click **Configure** for the method configuration. The *Configure - Google Authenticator* page will be displayed as follows: ![Multi-factor auth](_static/multi-factor-authentication/google-authenticator.jpg) On this page, you have to enter: - Your **Business prefix** so that users can differentiate the account information for your store in the GoogleAuthenticator app. - **QRPixelsPerModule** to set the number of pixels per unit. The module is one square in the QR code. By default, it is 3 for a 171 × 171 pixel image. Then click **Save**. On this page, you can also search for customers by email using the *Search* panel. ## How it works To understand how the multifactor authentication works in nopCommerce, see the diagram above. - The **2FA configured** scheme represents the process when 2FA is already configured by a customer. ![How it works](_static/multi-factor-authentication/2FA_configured.jpg) - The **2FA setup** scheme represents the process when a 2FA setup is needed to be done by a customer. ![How it works](_static/multi-factor-authentication/2FA_setup.jpg) ## Multifactor authentication page in public store To configure multi-factor authentication, a customer should visit the **My account - Multi-factor authentication** page, which is displayed as follows: ![How it works](_static/multi-factor-authentication/my-account.jpg) Steps to activate MFA: 1. Activate the **Is enabled** setting. 1. Choose one of the multifactor authentication providers (by default, there is only one). 1. Save. 1. Configure the selected multifactor authentication provider by following the instructions on the individual settings page of the selected provider. > [!WARNING] > > After saving the selected provider, make sure to configure it; otherwise, you will be denied access the next time you try to enter your account. --- # Integrating Jotform AI Agent into a nopCommerce Store ## What are Jotform AI Agent? [Jotform AI Agent](https://www.jotform.com/ai/agents/?partner=nopCommerce) are powerful customer service tools that provide real-time assistance. Jotform AI Agent isn't just a chatbot. It can answer questions about shipping times, return policies, and product availability instantly, reducing bounce rates during off-hours. It can recommend products based on user input, and guide users to specific product pages within your nopCommerce store. By offering personalized conversations and 24/7 availability, they enhance customer satisfaction and streamline your support workflows, leading to better retention and higher sales. ## First Steps to Get Started 1. [Sign up for a Jotform](https://www.jotform.com/?partner=nopCommerce) (or log in if you already have one). 1. Head on over to your Workspace page and click on the Create button in the top-left corner. ![Create button](_static/jotform/create.png) 1. Click "AI Agent". ![start](_static/jotform/start.png) 1. On the Describe the Agent page that opens, enter a description of the AI Agent you want to create in the Describe the Agent field. For example: “Create a customer support agent that promptly answers questions, resolves issues and provides helpful solutions.”. Or you can click on one of the buttons below it for a predefined one, and then click on Send. ![describe](_static/jotform/describe.png) This creates an AI Agent based on what you wrote and takes you straight to AI Agent Builder so you can tweak and customize it even more. ![builder](_static/jotform/builder.png) ## How to Customize Agent Persona Customizing your AI Agent’s persona is simple and helps tailor its interactions to your specific needs. You can easily adjust the AI Agent’s name, role, tone of voice, and even how chatty it is, allowing for a more personalized and effective user experience. By fine-tuning these settings, you can shape how your AI Agent communicates, making each conversation feel more natural and engaging. Whether you want it to be formal, casual, or somewhere in between, the choice is entirely up to you! For more details, check out Jotform AI Agent guides on: 1. [How to Customize Agent Avatar](https://www.jotform.com/help/how-to-customize-agent-avatar/?partner=nopCommerce/?partner=nopCommerce) 1. [How to Customize Agent Design](https://www.jotform.com/help/how-to-customize-agents-design/?partner=nopCommerce) 1. [How to Customize Agent Persona](https://www.jotform.com/help/how-to-customize-agent-persona/?partner=nopCommerce) 1. [How to Train Your AI Agent](https://www.jotform.com/help/how-to-train-your-ai-agent/?partner=nopCommerce) 1. [How to Customize Agent Actions and Triggers](https://www.jotform.com/help/how-to-customize-agent-actions-and-triggers/?partner=nopCommerce) 1. [How to Teach Your Agent by Chatting](https://www.jotform.com/help/how-to-teach-your-agent-by-chatting/?partner=nopCommerce) 1. [How to Train an AI Agent with URLs](https://www.jotform.com/help/how-to-train-an-ai-agent-with-urls/?partner=nopCommerce) 1. [How to Let Your Agents to Search Specific Keywords in Defined Website](https://www.jotform.com/help/how-to-let-your-agents-to-search-specific-keywords-in-defined-website/?partner=nopCommerce) ## Integration with nopCommerce * See the "[How to Use Agent as Chatbot](https://www.jotform.com/help/how-to-use-agent-as-chatbot/)" article to understand how to create an embed code * Then in the plugin settings, check the Enabled box ![Configuration page](_static/jotform/config-page.png) * You will see the **Embed code** text box input * Copy the javascript code from jotform.com and press the save button ![End of configuration](_static/jotform/configured.png) --- # Google analytics plugin This section describes how to add and integrate the **Google analytics** plugin into your store. To configure the Google analytics plugin: Go to **Configuration → Widgets**. The *Widgets* window will be displayed: ![Widgets](_static/configure-analytics/google-analytics-widgets.png) ## Activate the plugin Click **Edit** beside **Google analytics**. The window will be expanded as follows: ![Google analytics](_static/configure-analytics/google-analytics-widgets-edit.jpg) Select the **Is active** checkbox to enable the Google analytics plugin. Then click the **Update** button to save the changes. ## Configure the plugin Click **Configure** beside **Google analytics**. The *Configure – Google analytics* window will be displayed as follows: ![Google analytics - Configure](_static/configure-analytics/google-analytics-widgets-configure.png) Perform the following steps to enable Google analytics integration: * Create a **Google analytics account** following the link [http://www.google.com/analytics/](http://www.google.com/analytics/) and follow the wizard to add your website * Copy the **Google analytics ID** into the **ID** box in the form. * Enter the **Tracking code** generated by Google Analytics. {GOOGLEID} and {CUSTOMER_TRACKING} will be dynamically replaced. * Select the **Enable eCommerce** checkbox to pass information about orders to the Google eCommerce feature. If selected, the following fields will be displayed: * Select **Use JS to send eCommerce info** to use JS code to send e-commerce info from the order completed page. In the case of redirection payment methods, some customers may skip it. Otherwise, e-commerce information will be sent using an HTTP request. Information is sent each time an order is paid, but UTM is not supported in this mode. * Select **Include tax** to include tax when generating tracking code for e-commerce part. * Select the **Include customer ID** checkbox to include customer identifier to the script. Click **Save**. Google Analytics will be integrated into your store. --- # Plugins in nopCommerce Plugins are a set of components adding specific capabilities to a nopCommerce store. Examples of plugins include payment modules, shipping rate computation methods, and more. This section describes how to install plugins manually. nopCommerce [marketplace](http://www.nopcommerce.com/marketplace) has a variety of plugins expanding your store functions. Plugins can be installed either by downloading from the marketplace or accessing the storefront directly from the admin panel. The plugins on the marketplace can be sorted by category, version, name or rating and can be free or paid. The plugins available on the marketplace are developed by the nopCommerce team, solution partners or third-party vendors. > [!NOTE] > > Plugins labeled "By nopCommerce team" are developed by the nopCommerce team and distributed freely. Third-party services connectors are developed within the *technology partnership program*; they are subject to the nopCommerce [premium support services](http://www.nopcommerce.com/nopcommerce-premium-support-services) and distributed freely as well. ## To install a plugin 1. A user has two options for uploading a plugin. You can use any of your convenience: * Upload the plugin to the `/plugins` folder in your nopCommerce directory. And restart your application (or click the **Reload list of plugins** button). * Upload the plugin or theme using the **Upload plugin or theme** button indicating the path to the location of the archive with the plugin in your local storage. > [!TIP] > > You can download more nopCommerce plugins in our [extensions directory](https://www.nopcommerce.com/marketplace). ![Upload plugin](_static/plugins-in-nopcommerce/plugin-upload.png) 1. Scroll down through the list of plugins to find the newly installed plugin. 1. Click the **Install** link to install the plugin. 1. Click the **Restart application to apply changes** button in the top panel to finish the installation process. 1. The plugin will be displayed in the plugins list (**Configuration → Local plugins**). > [!NOTE] > > If you're running nopCommerce in medium trust, then it's recommended to clear your `\Plugins\bin\` directory. ## To configure a plugin 1. Go to **Configuration → Local plugins**. The plugins list will be displayed: ![Local plugins](_static/plugins-in-nopcommerce/local-plugins.png) 1. Click the **Configure** link beside the plugin to go to the plugin's configuration page. If there is no **Configure** button beside a plugin, this indicates the plugin requires no configuration. ## To change the plugin's friendly name, display order, and limitations 1. Go to **Configuration → Local Plugins**. The plugins list will be displayed: ![Local plugins](_static/plugins-in-nopcommerce/local-plugins.png) 1. Click the **Edit** button beside the plugin. Edit plugin details as follows: ![Edit plugin](_static/plugins-in-nopcommerce/plugin-edit.jpg) 1. Enter the **Friendly name**. 1. In the **Display order** field, define the required location to display this plugin. 1 represents the top of the list. 1. Select the **Is enabled** field if you want to enable the plugin in the store. 1. From the **Limited to customer roles** dropdown list, choose roles you want to be able to use this plugin. 1. In the **Limited to stores** field, define the stores in which the plugin will be used. 1. Click **Save** at the top of the page. ## To uninstall a plugin 1. Go to **Configuration → Local plugins**. The plugins list will be displayed: ![Local plugins](_static/plugins-in-nopcommerce/local-plugins.png) 1. Click the **Uninstall** link beside the plugin to uninstall. The plugin will be uninstalled. The link in the **Installation column** will change to **Install**, enabling you to reinstall the plugin at any time. 1. Click the **Restart application to apply changes** button in the top panel to finish the uninstallation process. ## Tutorials * [Installing a plugin (for versions 3.90 - 4.10)](https://youtu.be/eLDsSm-4gKA) * [Managing access to plugins per customer role](https://www.youtube.com/watch?v=52lVVpQ3Qag) --- # Multi-store nopCommerce enables you to run more than one store using one interface from a single nopCommerce installation. This enables you to host more than one front-end store on different domains and manage all admin operations from your single administration panel. You can share the catalog data between stores, have a product in more than one store, and your customers can log in to all of your stores using the same credentials. ## Configuring multi-store ### 1. Hosting control panel part In the following example we will describe the setup of two sample stores: * `www.store1.com` * `www.store2.com` 1. Upload and install the site on `www.store1.com`. This is the only place where nopCommerce files and DLLs are stored. > [!NOTE] > > Read more about how to install nopCommerce in the following chapter: [Installing nopCommerce](xref:en/installation-and-upgrading/installing-nopcommerce/index). 1. In the control panel of `www.store2.com` (meaning your hosting control panel, not the nopCommerce administration area), ensure that all requests to `www.store2.com` are forwarded (not redirected) to `www.store1.com`. Perform this using CNAME records. This step is crucial. 1. In the control panel of `www.store1.com`, configure a domain alias for `www.store2.com`. This step can be complicated for some users (ask your system administrator to perform this step if you have issues). After completing the steps above, when accessing `www.store2.com` from your browser, the content of `www.store1.com` will be displayed. The next step is to configure the stores in the nopCommerce administration area, which will be described below. You can then start uploading content for both stores. 1. Optional (sample): This step can be performed from the Plesk control panel below as follows: Whenever `www.store2.com` is redirected to `www.store1.com`, the web server for Plesk does not know how to display `www.store2.com` since it uses Name-Based Virtual Hosting. Therefore, you must create a domain alias for `www.store2.com` as described below: * Log in to the domain panel of `www.store1.com` either directly or via the **Open in Control Panel** link from the server administration panel. * In the **Websites & Domains** tab, select the **Add New Domain Alias** link near the bottom of the tab. * Enter the full alias. For example, `store2.com`. * Ensure the **Web service** option is selected. * The **Mail** service is optional. Select this option if you want emails from `www.store2.com` to be redirected in a similar way. * Ensure the **Synchronize DNS zone with the primary domain** option is clear. ### 2. nopCommerce administration area part Once the installation and technical setup are done, you can manage your stores from the nopCommerce administration area. Go to **Configuration → Stores**. The *Stores* window will be displayed: ![Stores window](_static/multi-store/mainstore.png) > [!NOTE] > > By default, only one store is created. To set up several stores, click **Add new** and define the following store settings: ![Create](_static/multi-store/create.jpg) * Define the **Store name**. * Enter your **Store URL**. * Select the **SSL enabled** checkbox if your store is SSL secured. SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral. SSL is the industry standard used by millions of websites to protect online transactions with their customers. > [!IMPORTANT] > > Only select this option after you have installed the SSL certificate on your server. Otherwise, you won't be able to access your site and will have to manually edit the appropriate record in your database ([Store] table). > > [!TIP] > > Read more about setting SSL up in the following chapter: [How to install and configure SSL certificates](xref:en/getting-started/advanced-configuration/how-to-install-and-configure-ssl-certificates). * The **HOST values** field is a list of possible HTTP_HOST values of your store (for example, `store1.com`, `www.store1.com`). Filling this field is only required when you have a multi-store solution to determine the current store. This field enables distinguishing requests to distinct URLs and determines the current store. You can also see the current HTTP_HOST value in **System → System information**. * In the **Default language** field, choose the default language of your store. You may also leave it unselected. In this case, the first found one (with the lowest display order) will be used. * Define the **Display order** for this store. 1 represents the top of the list. * Define the **Company name**. * Define the **Company address**. * Set your **Company phone number**. * In the **Company VAT** field, enter the VAT number of your company (used in the EU). Add another store by clicking the **Add new** button on the **Configuration → Stores** page and filling in the similar fields. The two stores have now been configured using a single nopCommerce installation: * `www.store1.com` * `www.store2.com` > [!NOTE] > > The multi-store solution (distinction of stores by HTTP_HOST) does not work for sites in virtual directories on the same domain. For example, you cannot have one store on `http://www.site.com/store1` and the second store on `http://www.site.com/store2` since the HTTP_HOST value for both sites is the same (`www.site.com`). ## Configuring entities for multi-store Once the stores have been set up and configured, you can define your entities for each store. Do this by filling the **Limited to stores** field of the details pages for each of the following: [Products](xref:en/running-your-store/catalog/products/index), [Categories](xref:en/running-your-store/catalog/categories), [Manufacturers](xref:en/running-your-store/catalog/manufacturers), [Languages](xref:en/getting-started/advanced-configuration/localization), [Currencies](xref:en/getting-started/configure-payments/advanced-configuration/currencies), [Message templates](xref:en/running-your-store/content-management/message-templates), [Blogs](xref:en/running-your-store/content-management/blog), [News](xref:en/running-your-store/content-management/news), [Topics](xref:en/running-your-store/content-management/topics-pages). Scroll down to the **Limited to stores** field and choose the name of the existing store from the dropdown menu as shown in the *Edit product details* screen below: ![Mappings](_static/multi-store/product-limited-to-store.png) ## Configuring settings for multi-store Different [themes](xref:en/getting-started/design-your-store/choose-and-install-a-theme) can also be configured for different stores. In addition, you can override any setting value per store. For example, go to **Settings → Order settings** and see the **Multi-store configuration for** dropdown list where you can choose the store you want to override the settings for: ![Override settings](_static/multi-store/override-settings.jpg) When you choose the store, the page will be refreshed, and you will be able to define any field for the chosen store. Then just click **Save** to save the settings. --- # Security settings To manage security settings, go to **Configuration → Settings → General settings**. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ## Security Define the *Security* settings as follows: ![Security](_static/security-settings/security.jpg) * In the **Admin area allowed IP** field, enter the IP addresses that are allowed to access the back end. Leave this field empty if you do not want to restrict access to the back end. Use commas between the IP addresses (for example, 127.0.0.10, 232.18.204.16). * Select **Enable honeypot** to enable [honeypot](https://en.wikipedia.org/wiki/Honeypot_(computing)). In computer terminology, a honeypot is a trap set to detect, deflect or, in some manner, counteract attempts of unauthorized use of information systems. * In the **Encryption private key** field, enter the encryption private key used for storing sensitive data. Click **Change** at any time to change this key. All sensitive data are encrypted using this private key. > [!NOTE] > > It is recommended to make a backup of your database before you change the encryption key. Sensitive data include all credit card information (only when this credit card information is stored in the store database). ## CAPTCHA CAPTCHA is a program that can tell whether a human or a computer is trying to access your website. nopCommerce uses reCAPTCHA by Google. reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site while letting your valid users pass with ease. Define the *CAPTCHA* settings as follows: ![CAPTCHA](_static/security-settings/captcha.jpg) This panel will reveal the following settings when **CAPTCHA enabled** is selected: * **Type of reCAPTCHA**: choose `reCAPTCHA v2` or `reCAPTCHA v3`. The difference between them is that reCAPTCHA v2 shows the "I'm not a robot" checkbox, whereas reCAPTCHA v3 is invisible to customers. Read more about [reCAPTCHA v2](https://developers.google.com/recaptcha/docs/display) and [reCAPTCHA v3](https://developers.google.com/recaptcha/docs/v3). * **reCAPTCHA v3 score threshold** is enabled when reCAPTCHA v3 is selected. Read [more about the score threshold](https://developers.google.com/recaptcha/docs/v3). * Show CAPTCHA on the **login** page. * Show CAPTCHA on the **registration** page. * Show CAPTCHA on the **forgot password** page. * Show CAPTCHA on the **contact us** page. * Show CAPTCHA on the **email wishlist to a friend** page. * Show CAPTCHA on the **email product to a friend** page. * Show CAPTCHA on the **blog page (comments)**. * Show CAPTCHA on the **news page (comments)**. * Show CAPTCHA on the **newsletter block**. * Show CAPTCHA on the **product reviews** page. * Show CAPTCHA on the **apply for vendor account** page. * Show CAPTCHA on the **forum** page. * Show CAPTCHA on the **guest checkout** page. * Enter the reCAPTCHA **public key**. * Enter the reCAPTCHA **private key**. > [!NOTE] > > Dropped support for Recaptcha v1. --- # SMS providers To define SMS providers go to **Configuration → SMS providers**. ![SMS providers](_static/index/sms_providers.png) Only one SMS provider can be used for sending notifications. Adding new SMS providers is only recommended for advanced users. To select the default SMS provider click the **Mark as primary provider** button. ## Enable sign-in with phone number 1. Go to **Configuration → Settings → Customer settings**. [Password and security](xref:en/running-your-store/customer-management/customer-settings) section. 2. Select the **'Login by phone' enabled** checkbox (an additional option to sign in by email address). 3. Make sure the **'Phone number' enabled** option is selected in the *Customer form fields* panel, otherwise customers will not be able to specify the number to send the code to. 4. Save the settings. ## How it works 1. A customer enters the phone number on the sign-in page of the public store. 2. The store asks the primary SMS provider (Twilio in this case) to send a verification code to this number. 3. The customer enters the received code, and the store verifies it before signing the customer in. > [!TIP] > > By default, there are several SMS providers available in nopCommerce, but you can find more SMS providers in the nopCommerce [marketplace](https://www.nopcommerce.com/marketplace). The configuration of SMS providers is described in the following chapters: * [Twilio SMS provider](xref:en/getting-started/advanced-configuration/sms-providers/twilio) --- # Twilio SMS provider [Twilio](https://www.twilio.com/) is a cloud communication platform with programmable SMS sending. nopCommerce supports Twilio out of the box, so no third-party plugin is required. In nopCommerce, the SMS provider is used to send a **one-time verification code (OTP)** when a customer signs in to the store with a phone number. This option is additional: customers can continue to sign in with an email address or a username. ## Twilio account The provider works over the Twilio REST API, so a Twilio account is required: 1. Sign up for a Twilio account and complete the verification in the [Twilio Console](https://console.twilio.com/). 2. Get a phone number that supports SMS. In the **Account Dashboard**, click **Get a phone number**, or go to **Phone Numbers → Manage → Buy a number** and make sure the number has the **SMS** capability enabled. 3. Copy the account credentials from the **Account Dashboard**: * **Account SID** — a 34-character identifier that begins with "AC". It acts as a login and identifies the account (or subaccount) the messages are sent from. * **Auth token** — the key used to authorize API requests. > [!IMPORTANT] > > Sending SMS requires a positive balance on the Twilio account. Messages are charged per segment, and the rates depend on the destination country. > > [!NOTE] > > Some countries and networks require additional procedures (sender registration, short code approval, and so on) before commercial messages can be delivered. Complete all the applicable verification or registration requirements for the countries your customers are in. ## Configure the provider 1. Go to **Configuration → SMS providers**. 2. Find the **Twilio SMS provider** entry in the list and click **Mark as primary provider** to make nopCommerce use it for sending SMS. Only one provider can be used at a time. > [!NOTE] > > If another provider was used before, its primary status is removed automatically. 3. Click **Configure** beside the Twilio SMS provider option in the list to open the credentials page. ![SMS Twilio](_static/twilio/configure.png) 4. Fill in the following fields: * **Balance info**: the current balance of your Twilio account. This field is read-only and is displayed after the provider is configured. Click **Check the account balance** to update the value. * **Account SID**: the **Account SID** copied from the **Account Dashboard** of the Twilio Console. * **Auth token**: the **Auth token** copied from the **Account Info** pane of the **Console Dashboard** page. Treat it as a password: it grants full access to the account. * **Phone number**: the Twilio account phone number the verification codes are sent from. Enter the number in the international format, for example `+12345678900`. 5. Click **Save**. > [!TIP] > > Twilio filters messages by account, so you can test the sending without using a real mobile number: send a message to the Twilio **Virtual Phone** number `+18777804236` and check the message in the Virtual Phone interface. Note that only messages sent from your account are displayed there. ## Troubleshooting If customers do not receive the verification code, check the following: * The **Account SID**, **Auth token**, and **Phone number** values are copied correctly and contain no extra spaces. * The **Balance info** field shows a positive balance, since verification codes are not sent when the account is exhausted. * The sender number is SMS-capable, and the verification or registration requirements for the destination country are completed. * The recipient number is specified in the international format, for example `+12345678900`. * The details of the failed requests and the final delivery status are available in the Twilio Console (**Message → Logs**). > [!NOTE] > > A successful response from the Twilio API means the message was accepted for sending, not that it was delivered. Always check the message log in the Twilio Console for the final status. --- # ChatGPT shopping ChatGPT Shopping makes your products discoverable in ChatGPT. The integration is implemented as the *ChatGPT Shopping* plugin (system name *Feed.ChatGptShopping*) and is available in nopCommerce 5.00. The plugin generates a structured product feed that follows the OpenAI product feed specification, so ChatGPT accurately indexes and displays your products with up-to-date prices and availability. Your products will appear in AI-powered results when shoppers are actively exploring options, comparing products, and deciding what to buy. The feature works similarly to Google Shopping. ## How it works - The plugin generates a product feed in the JSONL format (one product per line). The file is gzip-compressed and UTF-8 encoded. - The feed file is generated for each store and stored at a static public URL, so it can be shared with the ChatGPT Shopping service. - OpenAI periodically fetches the feed from the configured URL, keeping product data in ChatGPT up to date. - The feed powers product discovery only: products are marked as eligible for search and ads, but not for checkout, so shoppers complete purchases on your store. ## Install the plugin 1. Go to **Configuration → Local plugins**. 1. Search for *ChatGPT Shopping* in the **Plugin name** field. The plugin belongs to the *Promotion feeds* group. 1. Click the **Install** button. 1. Click the **Restart application to apply changes** button to apply changes. > [!NOTE] > > On installation, the plugin enables the **Use absolute image path** media setting (required for absolute product image URLs) and adds the *Synchronization (ChatGPT Shopping)* scheduled task, which is disabled by default. ## Configure the plugin To configure the plugin, go to **Configuration → Local plugins** and click **Configure** beside *ChatGPT Shopping*. ![ChatGPT shopping](_static/chatgpt-shopping/configure.png) This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). Define the following settings: - **Currency** — the currency used to generate the feed. Product prices are converted to this currency. - **Language** — the language used to generate the feed. Localized product names and descriptions are used. - **Target countries** — the target countries for which the feed is generated. Use ISO 3166-1 alpha-2 country codes separated by commas (e.g., US,CA,GB). Omitted or empty does not mean worldwide. - **Store country** — the store country. Use an ISO 3166-1 alpha-2 country code (e.g., US). Omitted or empty does not select another market. - **Enable auto synchronization** — enable or disable automatic synchronization of the feed. If enabled, the feed is automatically synchronized at the specified interval. - **Auto synchronization period** — the period (in minutes) for auto synchronization. It must be greater than 0 when auto synchronization is enabled. - **Product thumbnail image size** — the default size (in pixels) for product thumbnail images in the feed. - **Generated file path (static)** — the public URL of the generated feed file. The path is static for your store and can be shared with the ChatGPT Shopping service. Click **Save** to save the changes. Use **Generate feed** to generate the feed manually. ## Generate the feed Click the **Generate feed** button to generate the feed for the current store scope. If no specific store scope is selected, the feed is generated for all stores. The feed includes products that are published, not deleted, and visible individually. Store mapping and access control lists (ACL) are taken into account. The feed file is stored at `files/exportimport/{store ID}-chatgptshopping_products.jsonl.gz`. The public URL of each generated file is displayed in the **Generated file path (static)** field. Each feed entry contains the following product data: - **item_id** — the product SKU, unique per product. The GTIN and the manufacturer part number (MPN) are also submitted when specified. - **title** — the product name (up to 150 characters). - **description** — the full product description converted to plain text (up to 5,000 characters). The short description is used if the full description is empty. - **url** — the product details page URL. - **brand** — the manufacturer name. - **product_category** — the category breadcrumb (e.g., Apparel & Accessories > Shoes). - **condition** — the product condition (`new` by default). - **image_url** and **additional_image_urls** — the main product image and additional images (up to 10 images in total), resized to the configured thumbnail size. - **video_url** — the product video URL. - **price** — the product price without discounts, in the `amount CURRENCY` format (e.g., `79.99 USD`), converted to the selected currency. - **availability** — the stock status: `in_stock`, `out_of_stock`, or `pre_order`. Pre-order products also include the `availability_date`. - **seller_name** and **seller_url** — your store name and store URL. - **review_count** and **star_rating** — the number of approved product reviews and the average product rating. - **target_countries** and **store_country** — the geo tagging data defined in the plugin settings. ## Automatic synchronization To keep the feed up to date, the plugin adds the *Synchronization (ChatGPT Shopping)* scheduled task. By default, the task is disabled and runs every 8 hours (480 minutes) when enabled. You can enable the task and specify the synchronization period in the plugin configuration. The task can also be managed in **System → Schedule tasks**. For further details, refer to [Schedule tasks](xref:en/running-your-store/system-administration/schedule-tasks). > [!NOTE] > > Do not forget to restart the application once auto synchronization settings have been modified. ## Connect the feed to ChatGPT To make your products available in ChatGPT Shopping, complete the following steps: 1. Generate the product feed. 1. Verify that the feed is publicly accessible. 1. Sign in to the [ChatGPT Merchant Portal](https://chatgpt.com/merchants/). 1. Register your store (if you haven't already). 1. Add a new product feed and provide the public URL of the generated JSONL feed. 1. Complete the verification process and submit the feed for processing. 1. Regenerate the feed whenever your catalog changes. OpenAI will periodically fetch the latest version from the configured URL. For more information, see the official OpenAI documentation: - [Power product discovery in ChatGPT](https://chatgpt.com/merchants/) - [Provide a structured product feed as file upload to an SFTP server](https://developers.openai.com/commerce/specs/file-upload/overview) - [Product feed specification](https://developers.openai.com/commerce/specs/file-upload/products). --- # Google AI Commerce Search Google AI Commerce Search is Google's AI-powered product discovery service. It understands what a shopper is actually looking for and returns the most relevant products from your catalog, which improves search relevance and, as a result, conversions and average order value. In nopCommerce, the integration is implemented as the *Google AI Commerce Search* plugin (system name *AIRecommendation.GoogleAI*), available since nopCommerce 5.00. The plugin belongs to the *AI-powered recommendation* group. ## How it works - The plugin imports your product catalog into a Google Cloud catalog (project → location → catalog → branch) through the Retail API. - Once the data is imported, Google builds and indexes the catalog, and the search engine returns product IDs ranked by relevance for the entered keywords. - Product changes made in nopCommerce are sent to Google immediately, so the index stays up to date without manual re-imports. - Search results returned by Google are mapped back to nopCommerce products. nopCommerce re-applies its own restrictions (published products, availability dates, store mapping, access control lists, price range) and displays the products in the order returned by Google, so shoppers see Google ranking on top of standard nopCommerce search. - Categories, manufacturers, product tags, and specification attribute filters selected by a shopper are passed to Google as search filters, so filtering is applied by the search engine itself. - Google uses the visitor ID to personalize and re-rank results. The plugin passes the value of the `_ga` cookie (Google Analytics) as the visitor ID, therefore the [Google Analytics](xref:en/getting-started/advanced-configuration/configure-analytics) plugin is required. > [!NOTE] > > The AI-powered recommendation provider is used for keyword-based product search only, i.e., the autocomplete dropdown of the search box and the search results page. Other product lists are not affected. ## Prerequisites Before you install the plugin, prepare the Google Cloud side of the integration: 1. Enable the Retail API for your Google Cloud project. 1. Create a catalog with a default branch (the plugin works with a single catalog and branch). 1. Create a service account and grant it the role required to work with the Retail API (*Retail Editor* is enough for the full synchronization; *Retail Viewer* can be used if the catalog is imported by another tool, e.g. BigQuery). 1. Create a JSON key for the service account and download it. ### Authorize nopCommerce Authorization is handled by [Identity and Access Management (IAM)](https://docs.cloud.google.com/iam/docs/overview) and the plugin supports [Application Default Credentials (ADC)](https://docs.cloud.google.com/docs/authentication/application-default-credentials), which allows the same code to run in development and production environments. The most reliable way to configure ADC for this integration is to use a service account key. Copy the downloaded JSON key file to your server (for example, to the `/etc/gcloud/` directory) and point the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to it: - Linux (terminal or the `.bashrc` startup script): ```sh export GOOGLE_APPLICATION_CREDENTIALS="/etc/gcloud/your-service-account-key.json" ``` - Windows (PowerShell, machine scope): ```powershell [System.Environment]::SetEnvironmentVariable('GOOGLE_APPLICATION_CREDENTIALS', 'C:\gcloud\your-service-account-key.json', 'Machine') ``` - Docker (pass the variable and mount the key file): ```sh docker run -e GOOGLE_APPLICATION_CREDENTIALS=/app/key.json -v /etc/gcloud/your-service-account-key.json:/app/key.json my-retail-app ``` Restart the application afterwards, so the new environment variable is picked up. ## Install the plugin 1. Go to **Configuration → Local plugins**. 1. Search for *Google AI Commerce Search* in the **Plugin name** field. The plugin belongs to the *AI-powered recommendation* group and requires the *Google Analytics* plugin. 1. Click the **Install** button. 1. Click the **Restart application to apply changes** button to apply changes. 1. On the plugin details page, select the **Enabled** checkbox to make the plugin the active AI-powered recommendation provider. Only one AI-powered recommendation provider can be active at a time. > [!NOTE] > > On installation, the plugin enables the **Use absolute image path** media setting, which is required to pass absolute product image URLs to Google, and it fills the default values for the configuration: *global* location, *default_catalog* catalog, and *default_branch* branch. ## Configure the plugin To configure the plugin, go to **Configuration → Local plugins** and click **Configure** beside *Google AI Commerce Search*. ![Google AI Commerce Search](_static/google-ai-commerce-search/configure.png) The configuration page describes how Google Cloud authorization works and provides the following settings: - **Enabled** — enable or disable the plugin. When disabled, the plugin neither synchronizes data with Google nor returns search results. - **Project ID** — the Google Cloud project ID that owns the catalog. - **Location ID** — the Google Cloud location (region) ID of the catalog, for example `global`. - **Catalog ID** — the Google Cloud catalog ID. - **Branch ID** — the Google Cloud branch ID that receives the product data. - **Sync Allowed** — enable or disable synchronization of product data with Google. Disable it if your catalog is imported by another tool (for example, BigQuery) or if you only want to use Google for search. - **Search Allowed** — enable or disable searching products through Google. - **Log Requests** — enable or disable logging of the requests sent to Google. Useful for debugging and testing; the requests are written to the nopCommerce log file. All four identifiers (project, location, catalog, and branch) are required and must match the values in the Google Cloud console. Click **Save** to save the changes. ## Import the catalog To import the whole catalog into Google, click the **Sync catalog now** button. You need to enable the **Sync Allowed** setting and grant the *Edit products* permission to run this action. The plugin converts the products and imports them in batches (500 products per request), then displays a notification with the number of successfully imported products and the number of failures. The import result is also written to the nopCommerce log. Only published products are imported, and store mapping and access control lists are taken into account. Each product is submitted with the following data: - **ID** — the product SKU, or the product ID when the SKU is empty. - **Type** — *Primary* for regular products and *Variant* for product attribute combinations and grouped product variants. - **Primary product ID** — the SKU (or ID) of the parent product for variants. - **Name**, **GTIN**, **URL**, **language code** — the language code of the default admin language is used. - **Title** — the product short description (up to 1,000 characters). - **Description** — the product full description (up to 5,000 characters). - **Price** — the product price (the overridden price for a variant) in the primary store currency. - **Availability** — `IN_STOCK`, `OUT_OF_STOCK`, or `BACKORDER`, calculated depending on the inventory management method and the stock quantity. - **Rating** — the average rating and the number of approved product reviews. - **Categories** — the full category path (e.g., `Sports & Fitness > Athletic Clothing > Shoes`). Full paths are strongly recommended by Google for better search and recommendation quality. - **Brands** — manufacturer names. - **Attributes** — specification attributes and their option names. - **Tags** — product tags. - **Images** — the product image; the first combination image is used for variants. ## Synchronize product changes When both the **Enabled** and **Sync Allowed** settings are enabled and the plugin is the active AI-powered recommendation provider, the plugin keeps Google up to date automatically: - a product or a product attribute combination that is created is sent to Google; - a product or a product attribute combination that is updated is updated in Google; - a product or a product attribute combination that is deleted is removed from Google. If these settings are disabled or another AI-powered recommendation provider is active, no requests are sent, and you can rely on the full catalog import instead. ## Search on the public store When both the **Enabled** and **Search Allowed** settings are enabled, keyword-based product search on the public store is served by Google: - The keywords entered by a shopper are sent to the `default_search` placement of the configured catalog and branch. - Category, manufacturer, product tag, and specification attribute filters are converted into the Retail API filter syntax. - The visitor ID is taken from the `_ga` cookie, so results can be personalized. Make sure the Google Analytics plugin is installed and configured and that its cookie is not blocked for your store. - The search page size is limited to 120 products per request (the maximum allowed by the Retail API). - The returned product IDs or SKUs are mapped back to nopCommerce products; duplicate entries (for example, several variants of the same product) are reduced to a single product. - If Google returns no products for the entered keywords or the request fails, nopCommerce falls back to the standard product search, so shoppers still get results. > [!IMPORTANT] > > Google returns results only for products that are already imported into the catalog and indexed. Run **Sync catalog now** after the initial configuration, and keep the catalog synchronized, otherwise shoppers may get no AI-powered results. ## Troubleshooting - **No search results** — make sure the catalog has been imported, the **Enabled** and **Search Allowed** settings are enabled, and the plugin is the active AI-powered recommendation provider. Keep in mind that nopCommerce falls back to the standard search when Google returns nothing. - **Authentication errors** — verify that the `GOOGLE_APPLICATION_CREDENTIALS` environment variable is set for the account that runs the application, that the key file is readable, and that the application has been restarted after the variable was changed. - **Permission denied errors** — make sure the service account has the required Retail API role and that the Retail API is enabled for the project. - **Empty or irrelevant results** — improve the source data: full category paths, product tags, specification attributes, images, prices, and availability all influence ranking. - **Debugging** — enable the **Log Requests** setting and check the nopCommerce log for the requests sent to Google. ## Further reading - [AI Commerce Search overview](https://cloud.google.com/retail/docs) - [How it works](https://cloud.google.com/retail/docs/how-it-works) - [Import products](https://cloud.google.com/retail/docs/import/products) - [Filter and order results](https://cloud.google.com/retail/docs/filter-and-order) - [Search API reference](https://cloud.google.com/retail/docs/reference/rpc/google.cloud.retail.v2#google.cloud.retail.v2.SearchRequest) - [Access control for the Retail API](https://cloud.google.com/retail/docs/access-control) --- # PunchOut PunchOut is a procurement protocol that seamlessly connects your store to enterprise buyer procurement systems, such as SAP Ariba, Coupa, Oracle eProcurement, and more. It allows buyers to access your store directly from their procurement system, browse the catalog, and add products to the shopping cart without leaving their purchasing workflow. The cart content is then transferred back to the procurement system as a requisition. In nopCommerce, the integration is implemented as the *PunchOut cXML Integration* plugin (system name *Misc.PunchOut*) and is available since nopCommerce 5.00. The plugin belongs to the *Misc* group and implements the PunchOut protocol using cXML (version 1.2.014). ## How it works 1. A procurement system sends a `PunchOutSetupRequest` (cXML document) to your store. 1. nopCommerce validates the request, creates a PunchOut session, and returns a `PunchOutSetupResponse` containing the Start Page URL. 1. The user is redirected from the procurement system to the nopCommerce storefront and is automatically authenticated. 1. The user browses the catalog and adds products to the shopping cart as usual. 1. During an active PunchOut session, the standard **Checkout** button is replaced with **Submit for Approval**. 1. When **Submit for Approval** is clicked, nopCommerce generates a `PunchOutOrderMessage` (cXML) from the current shopping cart. 1. The browser automatically posts the `PunchOutOrderMessage` back to the procurement system using the *BrowserFormPost* URL provided in the original setup request. 1. The procurement system creates or updates the requisition based on the received cart data. 1. No order is created in nopCommerce, and payment processing is skipped. 1. The PunchOut session is completed and the user is returned to the procurement system. > [!NOTE] > > - PunchOut sessions are stored in the database and expire automatically. > - All inbound and outbound cXML documents are logged for auditing and troubleshooting. > - Multiple procurement systems can be configured using separate PunchOut client credentials. > - The standard nopCommerce checkout flow is bypassed for active PunchOut sessions. ## Install the plugin 1. Go to **Configuration → Local plugins**. 1. Search for *PunchOut cXML Integration* in the **Plugin name** field. The plugin belongs to the *Misc* group. 1. Click the **Install** button. 1. Click the **Restart application to apply changes** button to apply changes. ## Configure the plugin To configure the plugin, go to **Configuration → Local plugins** and click **Configure** beside *PunchOut cXML Integration*. The configuration page contains the following sections: - **Common settings** — general plugin settings. - **Identity** — the PunchOut client credentials allowed to connect to your store. - **Session** — the active and completed PunchOut sessions. - **Log** — the inbound and outbound cXML documents. Define the following general settings: ![PunchOut](_static/punchout/configure_common.png) - **Is active** — enable or disable the plugin. The plugin is disabled by default; when it is disabled, nopCommerce responds to incoming setup requests with the *Service Unavailable* error. - **Time to expire** — the time in hours after which the PunchOut session will expire (24 hours by default). - **Unit of measure code** - the unit of measure code for PunchOut session. - **Restricted customer roles** — select customer roles that will not have access to the PunchOut feature. If no role is selected, all customers will have access. By default, the *Administrators* role is restricted. Click **Save** to save the changes. ## Configure identities A procurement system authenticates itself by the *Identity* and *Shared secret* credentials sent in the `Sender` element of the setup request. nopCommerce validates the credentials and rejects requests with an invalid shared secret. In the **Identity** section, manage the senders allowed to connect to your store: ![PunchOut](_static/punchout/configure_identity.png) - Use the search field to filter identities by the identity value. - The grid lists the **Identity** and **Shared secret hash** columns. Both values can be edited inline. When you change the value in the "Shared secret hash" column, you are, in effect, entering a new secret key that will then be hashed. - Use the **Edit** and **Delete** buttons to manage the identities. - In the *Add new record* block, enter the **Identity** and **Shared secret** of the procurement system and click the **Add new record** button. > [!IMPORTANT] > > The shared secret is stored as a SHA-256 hash. Provide the identity and shared secret to your procurement system administrator, so the same credentials can be configured on the procurement system side. > ![PunchOut](_static/punchout/punchout_shared_secret_authentication_flow.png) ## The PunchOut session on the storefront When a buyer follows the Start Page URL, nopCommerce activates the session and signs the buyer in automatically. If a customer with the contact email from the setup request does not exist, a new customer is created and assigned to the *Registered* customer role. The *ShipTo* address from the setup request is saved as the customer's shipping address. During an active PunchOut session: - The buyer can browse the home page, catalog, product pages, and the shopping cart only; navigation to any other page is redirected to the home page. - The standard **Checkout** button is replaced with **Submit for Approval**, and item discounts are hidden on the cart page. - Checkout, contact forms, product reviews, and customer account pages (account information, registration, password recovery, addresses, downloadable products, avatar, GDPR tools, gift card balance, multi-factor authentication) are not available. - Product reviews are disabled on product details pages. If the session expires, the session data is cleared and the buyer is redirected to the home page with the *Your PunchOut session has expired* notification. ## Manage sessions The **Session** section lists PunchOut sessions with the session ID, buyer cookie, activity state, customer email (linked to the customer edit page), store, and creation date. Use the **Close Session** button to close a session manually. ![PunchOut](_static/punchout/configure_session.png) ## View the log The **Log** section lists all inbound and outbound cXML documents. Each entry contains the session ID, message type (*SetupRequest*, *SetupResponse*, or *OrderMessage*), and creation date. Filter the log by the creation date. ![PunchOut](_static/punchout/configure_log.png) Click the **View** button to see the entry details: session ID, message type, direction (*Inbound* — from the procurement system to nopCommerce, or *Outbound* — from nopCommerce to the procurement system), raw XML, URL, identity, error message (if any), and creation date. Delete single entries on the log entry page, or clear the whole log using the **Clear log** button. ## cXML messages The plugin implements the following cXML messages (version 1.2.014): - **PunchOutSetupRequest** — sent by the procurement system to `POST /punchout/setup`. nopCommerce reads the sender credentials, buyer cookie, *BrowserFormPost* URL, contact email, and *ShipTo* address. - **PunchOutSetupResponse** — returned by nopCommerce. It contains the Start Page URL (`/punchout/start?sessionId=...`) that redirects the buyer to the storefront. - **PunchOutOrderMessage** — generated from the current shopping cart and posted to the *BrowserFormPost* URL. It contains the buyer cookie, the cart total, and the cart items with the product SKU (`SupplierPartID`), description (the product name and attribute values), quantity, unit price, and currency. Error responses use the standard cXML `Response/Status` element with the appropriate status code: `401` for an invalid shared secret, `400` for a malformed request, and `503` when the plugin is disabled. ## Further reading - [Getting Started with cXML (PDF)](https://xml.cxml.org/current/cXMLGettingStarted.pdf) - [cXML Reference Guide (PDF)](https://xml.cxml.org/current/cXMLReferenceGuide.pdf) - [cXML 1.2.014 DTD](http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd) --- # robots.txt settings To manage *robots.txt* settings, go to **Configuration → Settings → General settings**. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ## robots.txt A *robots.txt* file tells search engine crawlers which URLs the crawler can access on your site. This is used mainly to avoid overloading your site with requests; it is not a mechanism for keeping a web page out of Google. To keep a web page out of Google, block indexing with `noindex` or password-protect the page. Define the *robots.txt* settings as follows: ![Security](_static/robots-txt/robots-txt.jpg) - **Allow sitemap.xml** - Check to allow robots to access the sitemap.xml file. - **Disallow languages** - The list of languages to disallow. Leave this field blank if you don't want to restrict certain languages to robots. - **Disallow paths** - The list of paths to disallow. - **Localizable disallow paths** - The list of localizable paths to disallow. - **Additions rules** - Enter additional rules for the robots.txt file. Rules are instructions for crawlers about which parts of your site they can crawl. Read this page about [Google's interpretation of the robots.txt specification](https://developers.google.com/search/docs/crawling-indexing/robots/robots_txt) for the complete description of each rule. > [!NOTE] > > You also may extend the robots.txt data by adding the *robots.additions.txt* file to the wwwroot directory of your site. --- # PDF settings When running a store, you might need automatically generated PDF files, like invoices and terms of agreement. To define PDF settings, go to **Configuration → Settings → General settings** and find the *PDF* panel: ![PDF panel](_static/pdf-settings/pdf.png) * In the **PDF logo area**, drag and drop the logo file to be uploaded. This image file will be displayed on the PDF order invoices. It is recommended to use a small image. * In the **Invoice footer text (left column)** field, enter the text that will appear at the bottom of the generated invoices (left column). * In the **Invoice footer text (right column)** field, enter the text that will appear at the bottom of the generated invoices (right column). * Select **Use Letter page size** if you want your PDF documents to have the Letter page size. When this checkbox is clear, the A4 page size is used by default. * Select **Disable PDF invoices for pending orders** if you don't want your customers to be able to print PDF invoices for pending orders. ## Tutorials * [Adding business information (branding) on PDF invoice](https://youtu.be/TeXmuNWsdD4) --- # All settings *All settings* is an advanced tool for modifying all settings of the site on a single screen. For example, you have multiple stores and need to create an exact copy of the first store setting-wise. Then, doing all the changes on a single screen with the help of *All settings* can save you a lot of time. > [!NOTE] > > Modifying the settings in this window is only recommended for advanced users. It is not recommended to modify these settings unless the user knows the system very well. To define the settings: Go to **Configuration → Settings → All settings (advanced)**. The *All settings (advanced)* window will be displayed: ![All settings](_static/all-settings/allsettings.png) ## Add a new setting You can add a new setting using the *Add new record* panel at the bottom of the page. Define the following fields for the new setting: * Enter the **Setting name**. * Enter the **Value** of the setting. * Define in which **Store** the setting is applicable. Click **Add new record** to add this setting. ## Edit the existing setting To edit the existing setting, click the **Edit** button in the setting line. You will be able to edit the **Setting name** and its **Value**. Then click **Update** to save the changes. ![Edit setting](_static/all-settings/edit.jpg) --- # Running your store * [Product management](xref:en/running-your-store/catalog/index) * [Order management](xref:en/running-your-store/order-management/index) * [Customer management](xref:en/running-your-store/customer-management/index) * [Vendor management](xref:en/running-your-store/vendor-management) * [Promotional tools](xref:en/running-your-store/promotional-tools/index) * [Search engine optimization](xref:en/running-your-store/search-engine-optimization) * [Reports](xref:en/running-your-store/reports) * [System administration](xref:en/running-your-store/system-administration/index) --- # Products Adding and setting up products are among the most important tasks for a shop owner. You need to define product types, sort your products into categories, add various product options and appealing product images, define product tags and other SEO parameters. All these will help you make the product search and comparison easy for customers, resulting in more purchases. Adding products also includes some important internal settings, such as inventory and shipping parameters. Learn how to create products in nopCommerce in the following chapters: - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [Bulk edit products](xref:en/running-your-store/catalog/products/bulk-edit-products) - [Product attributes](xref:en/running-your-store/catalog/products/product-attributes) - [Specification attributes](xref:en/running-your-store/catalog/products/specification-attributes) - [Downloadable products](xref:en/running-your-store/catalog/products/downloadable-products) - [Grouped products (variants)](xref:en/running-your-store/catalog/products/grouped-products-variants) - [Recurring products](xref:en/running-your-store/catalog/products/recurring-products) - [Rental products](xref:en/running-your-store/catalog/products/rental-products) - [Import/export](xref:en/running-your-store/catalog/products/import-export-products) - [Product tags](xref:en/running-your-store/catalog/products/product-tags) - [Product reviews](xref:en/running-your-store/catalog/products/product-reviews) --- # Add products Setting up products in the best way possible is crucial for a store. Make sure to miss no detail, such as displaying various size and color options, giving thorough product descriptions, adding appealing pictures. To add a new product, go to **Catalog → Products**. Click **Add new** button in the top right corner. ![Products](_static/add-product-for-beginners/products.jpg) > [!NOTE] > > You can import products from an external file by clicking the **Import** button. Once you have a list of products, you can export it to an external file for backup purposes, by clicking the **Export** button. After clicking the **Export** button, you will see the dropdown menu enabling you to **Export to XML (all found)** or **Export to XML (selected)** and **Export to Excel (all found)** or **Export to Excel (selected)**. Additionally, it is possible to **Download catalog as PDF** to print the selected products into a PDF file. To remove products from the list, select the items to be deleted and click the **Delete (selected)** button. The *Add a new product* page is available in two modes: **advanced** and **basic** (advanced mode by default). You can switch to the basic mode, which only displays the required fields. ![Add a new product](_static/add-product-for-beginners/add_a_new_product.png) You can also set up the *basic* mode to choose which fields you want to be required. To do this, click the **Settings** button beside the switch. The *Setting* pop-up window will be displayed as follows: ![Settings](_static/add-product-for-beginners/settings.jpg) Select the fields needed and click **Save**. Note that the page will be refreshed in this case. ## Product info Start by filling in general information in the *Product info* panel: - Enter the **Product name**. - Enter the product's **Short description** that will be displayed in the catalog. - Enter the product's **Full description** that will be shown on the product details page. Here, you can add text, bullet points, links or additional images. Make sure to write a detailed description, as it affects your buyers' decision-making. - Enter the product **SKU**. This is the product stock-keeping unit used internally for tracking the product. This is your unique internal ID used to track this product. - **Categories**. You can assign a product to as many categories as you want. You can manage [product categories](xref:en/running-your-store/catalog/categories) in **Catalog → Categories**. - **Manufacturers**. You can assign a product to as many manufacturers as you want. You can manage [manufacturers](xref:en/running-your-store/catalog/manufacturers) in **Catalog → Manufacturers**. - Select **Published** to make the product visible in your store. - Enter the **Product tags** — keywords for product identification. Enter the tags, separating them by commas. The more products are associated with a particular tag, the larger it will look in the *Popular tags* cloud displayed on the sidebar of the catalog page. Read more about how to manage product tags in the [Product tags](xref:en/running-your-store/catalog/products/product-tags) section. ![Popular tags](_static/add-product-for-beginners/popular_tags.png) - Enter the **GTIN (global trade item number)**. These identifiers include UPC (in North America), EAN (in Europe), JAN (in Japan), and ISBN (for Books). - Enter the **Manufacturer part number**. It's a part number provided for the product by the manufacturer. - Select the **Show on homepage** checkbox to display this product on your store's home page. Recommended for your most popular products. If this checkbox is selected, the store owner can also specify the **Display order** of the product. 1 represents the top of the list. - Set up the **Product type** as *Simple* or *Grouped*. Read more about product types in the [Grouped products (variants)](xref:en/running-your-store/catalog/products/grouped-products-variants) chapter. - The **Product template** field is visible if you have custom product templates installed on the **System → Templates** page. - Select **Visible individually** if you want the product to be in the catalog or search results; otherwise, the product will be hidden in the catalog and only accessible from a grouped product details page. - Select **Age verification** if the product is subject to an age restriction. The customer's age is then verified against the minimum age specified for the **'Date of Birth' enabled** field in **Configuration → Settings → Customer settings**, so make sure that field is enabled and its **Minimum age to purchase** value is set appropriately (for example, to check that a customer is over 18). Read more about how to configure the date of birth field in the [Customer settings](xref:en/running-your-store/customer-management/customer-settings) section. > [!NOTE] > > When the customer's date of birth cannot be verified, the product cannot be purchased. - Choose **Customer roles** that will be able to see the product in the catalog. Leave this field empty if this option is not required and the product can be seen by everyone. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Configuration → Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). - Choose the stores in the **Limited to stores** field if the product is sold in specific stores. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). - **Vendor**. You can manage [vendors](xref:en/running-your-store/vendor-management) in **Customers → Vendors**. - **Require other products** is to define whether the product requires other products. In case it does, select the **Required product IDs**, entering them separated by commas, and ensure that there are no circular references, for example, A requires B, B requires A. Choose to **Automatically add these products to the cart** if required. - Select **Allow customer reviews** to enable customers to review this product. - Define the **Available start date** and/or **Available end date** of the product availability. - Select **Mark as new** to mark the product as recently added. This way, you can manage a list of products displayed on the "New products" page. You can also specify a period during which this product will be marked as new using the **Mark as new. Start date** and **Mark as new. End date** fields. - In the **Admin comment** field, enter a comment for information purposes. This comment will be for internal use only, not visible to customers. ## Price In the *Price* panel, define: - **Price** in a predefined currency. > [!NOTE] > > You can change the store currency in **Configuration → Currencies**. Read more about [currencies](xref:en/getting-started/configure-payments/advanced-configuration/currencies). - **Old price**. If it is larger than zero, it becomes visible in the public store and displayed beside the new price for comparison. - **Product cost**, the sum of all costs associated with the production of the product or service. This is not displayed to customers. - **Price lists**. Choose the price lists that apply to this product. A price list defines how the product price is changed (percentage or amount increase/decrease, or a fixed price) and which customer roles it is applied to. You can manage price lists in **Catalog → Price lists**, where a **Manual price** can also be set for each product to override the calculated value. > [!NOTE] > > If several active price lists apply to the same product, the **Price list strategy** setting in **Configuration → Settings → Catalog settings** defines which price is used. With the *Minimal price* strategy, all matching price lists are applied and the lowest calculated price is taken. With the *Use by priority* strategy, price lists are applied in the order of their priority values, and the price of the first applicable price list is taken. - **Disable buy button**. This can be useful for products "upon request." - **Disable wishlist button**. - **Available for pre-order** if the product is not in the store yet, but you want to allow customers to order it. The *Pre-order* button will be displayed to replace the standard *Add to cart* button in the public store. When this option is selected, the **Pre-order availability start date** field will be displayed. Enter the availability start date of the product in UTC. The *Pre-order* button will be changed to *Add to cart* when this date comes. - **Call for price** to show *Call for pricing* or *Call for quote* instead of the price on the product details page in the public store. This can help you establish contact with your customers and give additional information about the product they are interested in. - **Customer enters price** to indicate that a customer must enter the price. When selected, the following fields will be displayed: - In the **Minimum amount** field, enter the minimum amount for the price. - In the **Maximum amount** field, enter the maximum amount for the price. - **PAngV (base price) enabled** if the product has a base price. This is required according to German law (PAngV). For example, if you sell 500 mL of beer for €1.50, you have to show the base price: €3.00 per 1 L. When selected, the following fields will be displayed: - **Amount in product** — the amount of the product being sold. - **Unit of product** — the measure of the previously entered value. - **Reference amount** — the base amount. - **Reference unit** — the measure of the previously entered value. - **Discounts**. Learn how to [set up discounts](xref:en/running-your-store/promotional-tools/discounts). > [!NOTE] > > If you want to use discounts, make sure the **Ignore discounts (sitewide)** setting is disabled in the **Configuration → Settings → Catalog settings → Performance** panel. - Whether the product is exempted from tax by selecting **Tax exempt**. Otherwise, from the **Tax category** dropdown list, select the required tax classification for this product. Tax categories can be configured by the store owner in the **Configuration → Tax → Tax categories**. - Set up [tier prices](xref:en/running-your-store/promotional-tools/tier-prices) if required. ## Shipping Define product-specific shipping details in the *Shipping* panel: - Select **Shipping enabled** if the product can be shipped. The section will expand for more details. - Set the product parameters that will be used for the shipping calculation: **Weight, Length, Width, Height**. > [!NOTE] > > You can change predefined measures in **Configuration → Shipping → Measures**. - **Free shipping**, if any. - **Ship separately** if the product should be shipped separately from other products. If the order includes several items of the product, all of them will be shipped separately. - **Additional shipping charge**. - **Delivery date** that will be displayed in the public store. > [!NOTE] > > You can manage delivery date options in **Configuration → Shipping → Delivery dates**. > [!NOTE] > > There is the **Estimate shipping enabled (product page)** setting, which can be enabled in **Configuration → Settings → Shipping settings**. > This setting allows displaying estimated shipping information based on the customer's shipping address in a pop-up window on the product details page. ## Inventory Define the [inventory settings for the product as described here](xref:en/running-your-store/order-management/inventory-management). ## Multimedia On this panel you can add all media content related to the current product. ### Pictures In the *Pictures* panel, you can add the product pictures. ![Multimedia pictures](_static/add-product-for-beginners/multimedia-pictures.jpg) You can upload multiple image files at once using the **Upload files** button. After the pictures are uploaded, you can set the following values for each of them: - In the **Alt** field, enter a value for the "alt" attribute of the "img" HTML element. If empty, the default rule will be used (for example, product name). - In the **Title** field, enter a value for the "title" attribute of the "img" HTML element. If empty, the default rule will be used (for example, product name). - Define the **Display order** of the image on the product page. 1 represents the top of the list. > [!NOTE] > > To upload pictures in *.svg format you will need to activate the following setting > ![Setting svg](_static/add-product-for-beginners/svg_setting.jpg) > > [!TIP] > > [YouTube tutorial: Importing mass product images](https://www.youtube.com/watch?v=9BUqR_OGiq4) ### Videos On the "Video" tab, you can add links to embedded videos from any video hosts such as *YouTube* or *Vimeo*. ![Multimedia videos](_static/add-product-for-beginners/multimedia-videos.jpg) #### YouTube Embed Link 1. Find your video on YouTube and click the "Share" button. 1. Choose "Embed" from the pop-up menu. ![youtube video share](_static/add-product-for-beginners/youtube_share_embed.png) 1. Copy the link enclosed in quotation marks. ![youtube video share copy](_static/add-product-for-beginners/youtube_share_embed_copy.png) 1. Paste this link into the "Embed video URL" field as described above. Note that videos must be either Public or Unlisted to be embedded; Private videos cannot be embedded. #### Vimeo Embed Link 1. Locate your video on Vimeo and click the "Share" button. ![vimeo video share](_static/add-product-for-beginners/vimeo_share.png) 1. Copy the link enclosed in quotation marks. ![vimeo video share](_static/add-product-for-beginners/vimeo_share_embed_copy.png) 1. Paste this link into the "Embed video URL" field as described above. ### 3D model This feature enables uploading and displaying 3D models within the product image gallery. It provides customers with an interactive way to explore products, including functionality such as model rotation. #### File Requirements Store owners must prepare 3D model files in the **.GLB** format. The following 3D design and editing software can be used to create compatible models: - Maya - Blender - 3ds Max - ZBrush - Substance Painter - Photoshop Supports only **one** `.GLB` file per product. ![3d model](_static/add-product-for-beginners/multimedia_3d.png) All uploaded `.GLB` files are stored in the `\Nop.Web\wwwroot\images\3d\` directory. A placeholder file is used if no custom model is uploaded. > [!NOTE] > > Additional global configurations for this feature are available on the [Media settings](xref:en/getting-started/design-your-store/media-settings) page. ## Product attributes In the *Product attributes* panel, you can add product attributes. Learn more about [product attributes and how to create them](xref:en/running-your-store/catalog/products/product-attributes). ![Product attributes](_static/add-product-for-beginners/product_attributes2.png) ### Add a new attribute Once you have a list of the attributes created, click **Add a new attribute** in the *Attributes* tab. The *Add a new attribute* window will be displayed as follows: ![Add a new attribute](_static/add-product-for-beginners/add-attribute.jpg) Set up a new attribute: - From the **Attribute** dropdown list, select an attribute. - Fill the **Text prompt** field if you want some text to be shown in front of this attribute in the public store. - Select **Is required** to set this attribute as required for customers. - Define the **Control type** for this attribute (for example, dropdown list, radio button list). > [!NOTE] > > For the "Date picker" control type, it is possible to set a number of years to be displayed by using **catalogsettings.countdisplayedyearsdatepicker** parameter on the *All settings (advanced)* page. For example, if you set zero, then only the current year will be displayed. If you set 5, then the current year and the next 5 years will be displayed. Read about how to set this up on the [All settings](xref:en/getting-started/advanced-configuration/all-settings) page. - Define the **Display order** of the attribute on a product page. 1 represents the top of the list. Click **Save and continue edit**. The **Values** panel now displays the predefined values for this attribute. Click **Edit** in the value row if required. ### Edit an attribute value ![Edit a value](_static/add-product-for-beginners/attribute-value.jpg) Edit the attribute value details as follows: - Select the **Attribute value type**. There are two attribute value types, *Simple* and *Associated to product*. Choose the *Associated to product* type if you want this attribute value to be another product from your catalog and track its stock as well. Here, you can use *bundled products functionality* allowing customers to buy various combinations or sets of products as a single product, and shoppers would have an opportunity to set the required quantity of the attributes using the **Customer enters quantity** field described below. If the previous setting is *Associated to product*, the following fields will be displayed: - **Associated product** allows you to choose the product associated to this attribute. Use the **Associate a product** button to choose a product. > [!NOTE] > > Make sure there is no warning after you've chosen the associated product. Such as: > ![Assotiated warning](_static/add-product-for-beginners/assotiated-warning.jpg) - Select the **Customer enters quantity** field to allow a customer to enter the quantity of the attribute (which represents the associated product). - If the previous field is clear, you can specify the **Product quantity**. The minimum allowed value is 1. - Enter the **Name** of the attribute. - Specify the **RGB color** to be used with the color squares attribute control. - In the **Price adjustment** field, enter the price applied when choosing this attribute value. For example, '10' to add 10 dollars. Or 10% if **Price adjustment. Use percentage** is selected. - Select **Price adjustment. Use percentage**, which determines whether to apply a percentage to the product. If not enabled, a fixed value is used. - Use the **Weight adjustment** field to specify the weight adjustment applied when choosing this attribute value. - Specify the **Cost** field. The attribute value cost is the cost of all components that make up this value. This may be either the purchase price if the components are bought from third-party suppliers or the combined cost of materials and manufacturing processes if the component is made in-house. - Select the **Is pre-selected** field if this attribute value should be preselected for the customer. - Enter the **Display order** of the attribute value. 1 represents the first item in the attribute value list. - Choose a **Picture** associated to this attribute value. This picture will replace the main product image when this product attribute value is clicked (selected). Click **Save**. ### Attribute conditions If required, define conditions for this attribute in the *Condition* panel. Conditional attributes appear if a previous attribute is selected, such as having an option for personalizing clothing with a name and only providing the text input box if the "Personalize" radio button is selected. ![Condition](_static/add-product-for-beginners/condition.jpg) - Select the **Enable condition** checkbox to enable the condition. - Select the **Attribute** and its value. When the value is selected, the condition will be fulfilled and the attribute will be displayed. ### Attribute combinations In the *Attribute combinations* tab, define various attribute combinations and the following information for each of them: ![product_attributes3](_static/add-product-for-beginners/product_attributes3.png) Click the **Add combination** button to select a new combination and enter its details: ![Combination](_static/add-product-for-beginners/new-combination.jpg) For each combination, define: - The attributes within the combination. - The current **Stock quantity** of this combination. - If you have enabled 'Manage stock by attributes' on the product details page, you can perform a number of actions when the current stock quantity falls below (reaches) the **Minimum stock quantity** (for example, Low stock report). - **Allow out of stock** if you want to allow your customers to purchase a product with certain attributes when out of stock. - **SKU**. - **Manufacturer part number**. - **GTIN**. - **Overridden price** if the price for products with certain attributes is different from the regular product price. For example, you can give a discount this way. Leave empty to ignore the field. > [!NOTE] > > All other applied discounts will be ignored when this field is specified. - In **Notify admin for quantity below**, enter the quantity below which the admin will be notified. - Choose a **Picture** associated to this attribute combination. This picture will replace the main product image when this product attribute combination is selected. Click **Save**. > [!NOTE] > > Note that some attribute control types that support custom user input (for example, file upload, textboxes, date picker) are useless with attribute combinations. To generate all possible combinations, use the **Generate all possible combinations** button. Or use the **Generate several combinations** button to manually choose some attribute values to generate necessary combinations. ## Specification attributes Specification attributes are product features, such as screen size or number of USB ports, visible on a product details page. Specification attributes can be used for filtering products on the category details page. Read more about [specification attributes](xref:en/running-your-store/catalog/products/specification-attributes). > [!NOTE] > > Unlike product attributes, specification attributes are used for information only. ![Specification attributes](_static/add-product-for-beginners/spec.jpg) In the *Specification attributes* panel, add specification attributes. >[!NOTE] > > You can add an attribute for your product using the existing list of attributes, or, if you need to create a new one, go to **Catalog → Attributes → Specification attributes**. To add a new attribute, click the **Add attribute** button and fill the *Add a new product specification attribute* section: ![Add a new spec](_static/add-product-for-beginners/add_a_new_specification_attribute2.png) - Select the **Attribute type** from the dropdown list. - Choose the **Attribute** from the list of the precreated attributes. - Choose the **Attribute option**. - **Allow filtering** by this option on a category page if required. - Select **Show on product page** to make the attribute visible on a product page. - Set the attribute **Display order**. 1 represents the top of the list. Click **Save**. ## Product class Define whether the product is a - [Gift card](xref:en/running-your-store/promotional-tools/gift-cards) - [Downloadable product](xref:en/running-your-store/catalog/products/downloadable-products) - [Rental](xref:en/running-your-store/catalog/products/rental-products) - [Recurring product](xref:en/running-your-store/catalog/products/recurring-products) ## SEO Define the following SEO parameters for the product page: - **Search engine friendly page name** — the page name used by search engines. If you enter nothing, then the product page URL will be formed using the product name. If you enter custom-seo-page-name, then the following custom URL will be used: `http://www.yourStore.com/custom-seo-page-name`. - **Meta title** — a title for the web page. - **Meta keywords** — a brief and concise list of the most important themes (keywords and key phrases) related to the product. These words will be added to the product page header. - **Meta description** — a brief description of the product that will be added to the product page header. Read more about [SEO](xref:en/running-your-store/search-engine-optimization). ## Related products and cross-sells Set up [related products and cross-sells as described here](xref:en/running-your-store/promotional-tools/cross-sells-and-related-products). ## Purchased with orders To view a list of orders in which the product was purchased, go to the *Purchased with orders* panel. Here, you can check an order's status and view an order in detail. ![puchased_with_orders](_static/add-product-for-beginners/puchased_with_orders.png) ## Stock quantity history In this tab, you can view all the product quantity changes, orders with the product. ![stock_quantity_history](_static/add-product-for-beginners/stock_quantity_history.png) ## Setting up a product page The following sections describe product page settings: [Product fields](xref:en/running-your-store/catalog/catalog-settings#product-fields), [Product page](xref:en/running-your-store/catalog/catalog-settings#product-page), and [Share](xref:en/running-your-store/catalog/catalog-settings#share). ## See also - [Product categories](xref:en/running-your-store/catalog/categories) - [Product manufacturers](xref:en/running-your-store/catalog/manufacturers) - [Order management](xref:en/running-your-store/order-management/index) - [Webinar. First steps in nopCommerce](https://www.youtube.com/watch?v=B_CfgJH0ylM&list=PLnL_aDfmRHwsJn1rnKaXdIcJg4pKJeeXs) ## Tutorials - [Video tutorial: Adding a new product](https://www.youtube.com/watch?v=wVgTgdQVWPQ&index=2&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) --- # Bulk edit products To bulk edit products, go to **Products → Bulk edit products**. The bulk edit products page lists all current products. ![Bulk edit products](_static/bulk-edit-products/bulk-edit-products.jpg) Usually, when you want to edit a product you go to the edit page of that product. It doesn’t matter with a small change but will become complicated and time-consuming when you need to modify a bunch of products. The bulk product editing feature provides a simple and convenient way to bulk edit a portion of product information. The list of fields available for editing consists of: - Product name - SKU - Price - Old price - Stock quantity - Published There is a '**Save selected**' button and a '**Save all**' button in the top right hand corner of the page. Once clicked, any new values entered will be saved to the database. ![Bulk edit products 1](_static/bulk-edit-products/bulk-edit-products_1.jpg) You can also add products by clicking the '**Add new**' button at the end of the table. --- # Product attributes Product attributes are variations of a product (such as color, size). A user can create various combinations of attributes. For example, a product can be in various sizes and colors. Thus, a user would create two attributes and their values, for example, "size" (S, M, L) and "color" (red, blue, white) and then set up groups according to the availability of the products. In nopCommerce, product attributes are used in **inventory tracking** and can also cause a **price difference**. To define product attributes, go to **Catalog → Attributes → Product attributes**. ![Product attributes](_static/product-attributes/product_attributes.png) > [!NOTE] > > By default, there are no product attributes precreated in nopCommerce. ## Adding product attributes Click **Add new** to add an attribute. ![Add new](_static/product-attributes/add_a_new_product_attribute.png) In the *Add a new product attribute* window, fill the **Name** and **Description** fields. Click **Save and continue edit** to proceed to the *Predefined values* editing panel. > [!TIP] > > [YouTube tutorial: Adding a product with color attributes](https://youtu.be/QihipwQ61YU) ## Adding predefined values In the *Predefined values* panel, click **Add a new value**, and the *Add a new value window* will be opened: ![Adding predefined values](_static/product-attributes/add_a_new_value.png) In the *Add a new value* window, define: - The attribute **Name**. - The **Price adjustment** applied when choosing this attribute value. For example, '10' to add 10 dollars. Or 10% if **Price adjustment. Use percentage** is selected. - **Price adjustment. Use percentage** checkbox allows for determining percentage price adjustment instead of an absolute value. - The **Weight adjustment** applied when choosing this attribute value. - The **Cost** attribute value is the cost of all components that make up this value. This may be either the purchase price if the components are bought from third-party suppliers or the combined cost of materials and manufacturing processes if the component is made in-house. - Whether the value **Is pre-selected** for a customer. - The **Display order** in an attribute list. After filling the fields, click **Save**. > [!TIP] > > It's not necessary to create attribute values when adding the product attribute; you can create them later when applying a certain product attribute to the product. > Once the attributes and values are set, they can be grouped and managed in the *Product attributes* panel on the product edit page. > > [!NOTE] > > Some store owners prefer to highlight products differentiated by attributes and create a separate product with each specific attribute (for example, separately listed blue T-shirts and red T-shirts). In this case, we recommend creating a grouped product (shirts, as in the example) in order for all the variations to be displayed on the same page once the grouped product is being viewed by a customer. Read more about [grouped products](xref:en/running-your-store/catalog/products/grouped-products-variants). > > [!WARNING] > > Adding new or updating existing "Predefined values" does not affect products that already have the attribute. ## Used by products panel In the *Used by products* panel, you can choose which products use this attribute: ![Used by products](_static/product-attributes/used-by.jpg) ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [Grouped product](xref:en/running-your-store/catalog/products/grouped-products-variants) ## Tutorials - [Overview of conditional product attributes](https://www.youtube.com/watch?v=eIdHVcEdos8&t=55s) --- # Specification attributes Specification attributes are similar to [product attributes](xref:en/running-your-store/catalog/products/product-attributes); however, they are only used for information (visible on the product details page) and for filtering products on the category details page. They don't define product price and can't be used for inventory tracking. ## Example Let's say you are running an online computer store. What helps a customer to make a decision? - Provide a customer with comprehensive and descriptive information about your products. Although you fill the short and full descriptions of a certain computer, allow the customer to see the product's characteristics reflecting its most important details: ![Specification attributes](_static/specification-attributes/specs.jpg) This table can be displayed on the product details page if you select the **Show on product page** field when [adding a specification attribute to a product](xref:en/running-your-store/catalog/products/add-products#specification-attributes). - Allow your customers to search computers using the filter functionality. Let's say we can search in your store by CPU type and memory. Then, the category page will look as follows: ![Filtering](_static/specification-attributes/filter.jpg) Select the **Allow filtering** field when [adding a specification attribute to a product](xref:en/running-your-store/catalog/products/add-products#specification-attributes) to allow filtering by this attribute for a certain product. - Include the "Compare products" functionality in your store. This feature uses specification attributes as well. For your computer store, the "Compare products" page will look as follows: ![Compare products](_static/specification-attributes/compare.jpg) To enable the "Compare products" functionality, go to **Configuration → Settings → Catalog settings**. In the *Compare products* panel, select the **'Compare products' enabled** checkbox. The next section describes how to create specification attributes. Note that after creating a list of specification attributes, you will need to add the specification attributes to the products one by one. Learn how to add specification attributes to products in the [Add products - Specification attributes](xref:en/running-your-store/catalog/products/add-products#specification-attributes) section. ## Create a specification attribute group > [!NOTE] > > All specification attributes that don't belong to any group are in the *Default group (non-grouped specification attributes)*. To view and edit a list of specification attributes and their groups, go to **Catalog → Attributes → Specification attributes**. ![Specification attributes](_static/specification-attributes/specification_attributes.jpg) Click **Add group** to add a new group. The *Add a new specification attribute group* window will be displayed as follows: ![Add group](_static/specification-attributes/specification_group.jpg) In the *Attribute group info* panel, enter: - The **Name** of the specification attribute group. - The **Display order** number. Then save the changes. ## Create a specification attribute > [!NOTE] > > By default, there are no specification attributes precreated in nopCommerce. To view and edit a list of specification attributes, go to **Catalog → Attributes → Specification attributes**. ![Specification attributes](_static/specification-attributes/specification_attributes.jpg) On this page, you can delete specification attributes by selecting them and then clicking the **Delete(selected)** button. Click **Add attribute** to add a new attribute. The *Add a new specification attribute* window will be displayed as follows: ![Add new](_static/specification-attributes/new-attribute.jpg) In the *Attribute info* panel, enter: - The **Name** of the specification attribute. - The **Display order** number. Click **Save and continue edit** to proceed to the *Options* editing panel. ### Add a new option Click the **Add a new option** button in the *Options* panel to create a new specification attribute option. The *Add a new option* window will be displayed as follows: ![Add a new option](_static/specification-attributes/add_a_new_option.jpg) Define the following option settings: - The **Name** of the specification attribute option. - Select the **Specify color** checkbox to choose the color to be used instead of the option's text name (it will be displayed as a "color square"). - Choose the **RGB color** that will be displayed to customers. - The **Display order** number. Click **Save** to save the option details. The following screenshot shows already added options: ![Options](_static/specification-attributes/options.jpg) ### Used by products If you have applied the specification attribute to products, you can see the list of these products in the *Used by products* panel: ![Used by products](_static/specification-attributes/used-by.jpg) ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [Product attributes](xref:en/running-your-store/catalog/products/product-attributes) - [YouTube tutorial: Managing Specification Attributes](https://www.youtube.com/watch?v=YmD_vHqWzQw&index=11&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) --- # Downloadable products The downloadable products functionality is useful when you are going to sell e-books or audiobooks, courses, PDFs, music, software or you want to create a picture stock, for example. ## Example Let's say you wish to sell e-books. What distinguishes an e-book store from other stores? - First of all, you should provide the customers with an easy way to download books from your store. In nopCommerce, customers can find all the downloadable products they bought in the "My account" section: ![Sample](_static/downloadable-products/my-account.jpg) - You might also wish to allow your customers to preview some parts of the books they want to buy. In this case, your customers will see the following *Download sample* button on the product details page: ![Sample](_static/downloadable-products/sample.jpg) - Or it might be useful to ask a customer to sign a *user agreement* before downloading an e-book. For example, agree to download and print one copy of each e-book chapter for personal use only. This is how a customer will see this agreement: ![Agree](_static/downloadable-products/agree.jpg) All these features can be set up when you are editing a product. Futhermore, in special cases, you can restrict downloads of a certain book by setting up the number of days during which customers keep access to the book or maximum downloads number. Or you can choose when a customer is enabled to download a book: immediately after the book is paid or after manual validation. If you have already learned how to set up a [common product](xref:en/running-your-store/catalog/products/add-products), learn how to make this product downloadable in the section below. ## Set up a downloadable product To create a downloadable product, go to **Catalog → Products**. Click **Add new**, fill in the common product fields, and select the corresponding checkbox in the *Downloadable product* panel. ![DownloadableProduct](_static/downloadable-products/DownloadableProduct.png) Define the following details: - In the **Download file** section, upload the file using the **Upload a file** button or **use download URL** by selecting the corresponding checkbox and entering the **Download URL**. - **Unlimited downloads** in case the product can be downloaded an unlimited number of times. When this option is clear, an additional field appears. - In the **Max. downloads** field, enter the maximum number of downloads given to a customer after purchasing the product. - The **Number of days** during which customers keep access to the file. Leave this field empty if you want to enable continuous downloads. - **Download activation type**: - *When order is paid* — select this option to enable the download only when the order payment status is "Paid." - *Manually* — select this option to give control to the store administrator. When this option is selected, the administrator must manually activate the download. This is performed in the *Products* panel of an *Edit order details* page. - **Has user agreement** — if a customer must sign a user agreement in order to be able to download the product. - **User agreement text** editor is then displayed, enabling you to enter/edit the user agreement text. - **Has sample download file** allows a customer to download a sample file. - If this is applicable, upload the **Sample download file** using the **Upload a file** button or **use download URL** by selecting the corresponding checkbox and entering the **Download URL**. It will be shown on the product details page and can be downloaded by any customer free of charge. > [!TIP] > > Since downloadable products require no shipping, make sure the **Shipping enabled** field is clear in the *Shipping* panel. > > [!TIP] > > Since you don't need to track inventory of downloadable products, make sure the **Inventory method** field is set to *Don't track inventory* in the *Inventory* panel. ## Customer registration Decide whether customer registration is required for downloadable products by selecting the **Require registration for downloadable products** checkbox in the *Common* panel on the **Configuration → Settings → Customer settings** page. ## Downloadable products account page If you would like to hide the 'Downloadable products' menu item from the customer account page, go to the **Configuration → Settings → Customer settings** page and select the **Hide 'Downloadable products' tab** checkbox. ## See also - [Orders](xref:en/running-your-store/order-management/orders) ## Tutorials - [Managing digital products](https://www.youtube.com/watch?v=om-HKr-B2yA) --- # Grouped products (variants) Grouped products, or products with variants, are a convenient tool to sell a product that has various supplementary items or attribute sets. Various combinations of such a product can be sold as separate products, and the price may vary. In nopCommerce, grouped products look like a single product details page displaying all the possible options. It is a convenient and SEO-friendly tool to sell complex products. > [!TIP] > > For example, a base product, such as a camera body, can be grouped with various sets of lenses. Another use case of a grouped product is selling a type of product with various attribute sets. For example, chocolate with various flavors. In this case, a customer can easily see the main product and all its options on the same page. ![Grouped](_static/grouped-products-variants/grouped.jpg) ## Adding a new grouped product To create a grouped product, go to **Catalog → Products**. There are several steps to follow: > [!TIP] > > Learn [how to fill in the product fields](xref:en/running-your-store/catalog/products/add-products). 1. Create several products with a *simple* product type. These are the variants of the main product. Use the **Visible individually** checkbox to define whether you want them to be visible separately in catalog and search results or only shown on the product page of the main product. 1. Create a **Grouped (product with variants)** product and assign these simple products you created in the previous step in the **Associated products (variants)** panel: ![variants](_static/grouped-products-variants/variants.png) > [!NOTE] > > - In the public store, a customer sees a separate **Add to cart** button for each associated product on the *grouped* product details page. > - A *simple* product can only be associated with one *grouped* product. > - *Grouped* products are **not orderable directly**. However, *simple* products are associated with them. For example, a customer cannot order the Creative Sound Card product directly. Instead, they must order an OEM or Retail version of the Creative Sound Card. In this case, the *grouped* product is the Creative Sound Card, and there are two associated *simple* products for this *grouped* product: OEM and Retail, each with potentially different prices. ## Tutorials - [Understanding grouped products in nopCommerce](https://www.youtube.com/watch?v=B1UdxXf_jmE) - [Creating Bundled products in nopCommerce](https://www.youtube.com/watch?v=sf9jP6KFcko) --- # Recurring products Recurring product type is usually used for subscriptions or products with installment payment plans. In case your product is recurring, select the corresponding checkbox in the *Recurring product* panel. ![Recurring](_static/recurring-products/recurring.png) Define the following details: - **Cycle length**. It is a time period in which the recurring order can be repeated. - **Cycle Period** in *Days*, *Weeks*, *Months* or *Years*. It defines the units of the time period. - **Total cycles** is the number of times a customer will receive the recurring product. You can define a recurring cycle for any product in order to enable the system to create repetitive orders automatically. In this case, whenever the payment must be made, the system will use the payment details of the initial order for the subsequent recurring orders. In addition, the original shipping charges will apply to the subsequent orders. > [!NOTE] > > At least one of the active payment modules should support recurring payments. ## See also - [Payment methods](xref:en/getting-started/configure-payments/payment-methods/index) --- # Rental products The rental products functionality is useful when you want to create a website allowing customers to book rooms and hotels. This feature can also be used for a website that offers such clothes as wedding dresses, camping equipment, children's toys, and more for rent. ## Example Let's say you wish to create a website providing wedding dresses for rent. Which functionality will be useful in this case? - One of the most important features is to allow customers to choose the *rent period*. In nopCommerce, it is allowed to choose the start date and end date, as on the screenshot below: ![Rental example](_static/rental-products/example.jpg) - nopCommerce also allows the store administrator to choose the *rental period* and *rental period length*. For example, you want to give a wedding dress for rent for 3 days minimum. In this case, a customer will see the following on the product details page: ![Rental period](_static/rental-products/period.jpg) - Use *checkout attributes* to allow customers to specify the return time when a carrier should pick up the dress: ![Rental example](_static/rental-products/time.jpg) Read more about checkout attributes [here](xref:en/running-your-store/order-management/checkout-attributes). If you have already learned how to set up a [common product](xref:en/running-your-store/catalog/products/add-products), learn how to make this product rental in the section below. ## Set up a rental product To create a rental product, go to **Catalog → Products**. Click **Add new**, fill in the common product fields, and select the corresponding checkbox in the *Rental* panel. ![Rental panel](_static/rental-products/rental.png) Define the following details: - **Rental period length** is a rental cycle length, minimum billing period. Price is specified for this period. - **Rental period** in *Days*, *Weeks*, *Months* or *Years*. It defines the time units of the rental period. When buying rental products, customers have to specify the rental period in the public store. The amount to be paid is calculated automatically. ![Rental in public store](_static/rental-products/rental1.png) ## Tutorials - [Managing rental products](https://www.youtube.com/watch?v=tOaC6hOILZY&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4&index=24) --- # Import/export products nopCommerce supports importing from Excel format and exporting products in XML or Excel. You can download products from your catalog in PDF. You can find these options in **Catalog → Products** on the main page, top left. ![Products](_static/import-export-products/buttons.jpg) ## Exporting products You can export products in XML or Excel formats by clicking the **Export** button. After clicking the **Export** button, you will see the dropdown menu enabling you to **Export to XML (all found)** or **Export to XML (selected)** and **Export to Excel (all found)** or **Export to Excel (selected)**. ![Exporting product](_static/import-export-products/exporting_product.png) If you don't need to download all the products, use the *Search* panel to find the required products or/and checkboxes to select the needed products. A file with the products you have chosen will be downloaded. The file will consist of all the products' characteristics from product editing page panels (Product info, SEO, Pictures, and more). > [!NOTE] > > If you use product attributes, an exported Excel table will be grouped by rows. To view attribute details, click + next to your product in the table. > ![Simple product](_static/import-export-products/simple_product.png) ## Importing products If you do not want to add all the products to your catalog manually, you can use the import option. > [!NOTE] > > Before you start importing, you should download a table template for import in Excel format, as it was described in the [exporting products](#exporting-products) section. For accurate and correct import of your products, it's crucial to name all the columns in the table properly (exactly as in the downloaded table). It is not mandatory to fill all the table fields. The product will be created based on the filled fields. Imported products are distinguished by SKU. If the SKU already exists, then its corresponding product will be updated. Import requires a lot of memory resources. That's why it's not recommended to import more than 500–1000 records at once. If you have more records, it's better to split them into multiple Excel files and import them separately. ### Example For example, we want to add Dancing shoes to our catalog. Let's create a new row in the table: ![product table](_static/import-export-products/product_table.png) Then click **Import**, choose the file, and click the **Import from Excel** button. Then check if you have a new product in the catalog. ![product catalog](_static/import-export-products/product_catalog.png) ## Importing products with images hosted on external resources Sometimes it is necessary to import products with images that are hosted on external resources. nopCommerce supports such a scenario. However, this option is disabled by default for security purposes. You can enable it on the **"Catalog settings"** page in the administration area. Just enable the **"Export/import products. Allow download images"** setting. There is an address validation code provided by the .NET platform in this image loading method. This mechanism doesn't always correctly determine the correctness of addresses despite their full compliance with the [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986) specification. Our recommendation is to avoid using special characters, such as **^** or **~**, in URLs. So please ensure that all specified URLs contain Latin chars only. ## Importing product with categories and manufacturers The task of importing categories and manufacturers is specific because a product can belong to multiple categories or manufacturers. Each new value in this cell must be separated by the **;** character. Please avoid using spaces for formatting even though they should be ignored by the algorithm (for example, 1;2;3 is better than 1; 2; 3). The **Categories** and **Manufacturers** columns can contain both the identifiers of the corresponding objects and their names (you can use one approach or mix both options at your discretion). If you want to import categories by name, you may specify the name only or the entire category name hierarchy. In this case, the parent category will be separated from the child category by the **>>** symbols. For example, “Computers >> Desktops;” Importing categories and manufacturers by name is case sensitive, that is, “**T**est category/manufacturer **n**ame” is not the same as “**t**est category/manufacturer **N**ame” ## Setting up import/export The following section describes import/export settings: [Export/import](xref:en/running-your-store/catalog/catalog-settings#exportimport). ## See also * [Adding products](xref:en/running-your-store/catalog/products/add-products) --- # Product tags Product tags are keywords for product identification. They are used to sort products by a certain feature and enable a specific, narrow product search. For example, if you sell apparel and want to create tags for T-shirts, they can be, for example, "t-shirt," "cotton," "polo." To edit product tags that are displayed in the public store, go to **Catalog → Product tags**. ![Product tags](_static/product-tags/tags.jpg) On the product tags page, you can see how many products have a certain tag in the **Tagged products** column. You can edit the tag by clicking the **Edit** button beside it. Or you can also delete tags by selecting them and then clicking the **Delete(selected)** button. ## Adding product tags You can add tags on the Edit product details page when adding or editing a product. ![Add tags](_static/product-tags/product_tags2.png) Enter tags, separating them by commas. Once the tags are created, they can be used for other products as well. The more products are associated with a particular tag, the larger it will look in the *Popular tags* area displayed on the sidebar of the catalog page: ![Popular tags](_static/product-tags/popular_tags.png) ## Setting up product tags The following section describes product tag settings: [Tags](xref:en/running-your-store/catalog/catalog-settings#tags). ## See also * [Product categories](xref:en/running-your-store/catalog/categories) * [Adding products](xref:en/running-your-store/catalog/products/add-products) --- # Product reviews Product reviews are customers' comments on a product. Reviews can also include ratings. In the public store, reviews are displayed on the product details page. Customers can write reviews for various products. After a review has been written and approved by a store owner, other customers can define whether the review is helpful or not by clicking *Yes* or *No* beside the review. > [!NOTE] > > By default, the reviews must be approved by the store owner before they appear in the public store. However, in case a store owner decides that reviews do not have to be approved, this default behavior can be changed. To opt out of the obligatory product reviews' approval, go to **Configuration → Settings → Catalog settings** and clear the **Product reviews must be approved** option. ## Managing product reviews To manage product reviews, go to **Catalog → Product reviews**. The *Product reviews* window will be displayed as follows: ![Managing product reviews](_static/product-reviews/product_reviews2.png) ### Search for reviews You can search for reviews by: - Date range using **Created from** and **Created to**. In the Created from and Created to fields, enter the date range for your search. Alternatively, you can click the dropdown calendar and select the required date range. - **Message**. Can be used to find a review by title or text fragment. - **Approved**. Can be used to find a review by the "Approved" property. - **Product**. Sorts and shows the reviews related to a particular product. - **Store**. Allows viewing all reviews of a particular store's products. This field is displayed if you have more than one store. ### Approve or disapprove Select the reviews you want to approve or disapprove and click the **Approve selected** button or the **Disapprove selected** button accordingly. ## Editing product reviews To edit a product review, click **Edit** beside the review. The *Edit product review details* window will be displayed as follows: ![Editing product reviews](_static/product-reviews/edit_product_review_details.png) - See the **Product** for which this review was added. After clicking this field, you will be redirected to the edit product details window, where you can edit the product details. - See the **Store** in which this review was written. - And the **Customer** who created the review. After clicking this field, you will be redirected to the edit customer details window, where you can edit the details. - You can edit the review **Title**. - And its **Text**. - In the **Reply text** field, you can leave a reply to review; it will be visible in the public store under the review. - **Rating** displays the customer rating. It cannot be edited. - Select the **Is approved** checkbox to approve the review. - **Created on** shows the date and time when the review was created. ## Review types If you have created custom review types, you will see the *Review types* panel: ![Review types](_static/product-reviews/review-types.jpg) In this area, you can view all the additional reviews on the current product. **Rating** displays the customer rating. No columns in the table can be edited. For more information on setting up reviews, click see the [Product reviews](xref:en/running-your-store/catalog/catalog-settings#product-reviews) and [Review types](xref:en/running-your-store/catalog/catalog-settings#review-types) chapters. ## Tutorials - [Managing product reviews](https://www.youtube.com/watch?v=TBOpCoEAMnU&feature=youtu.be) - [Managing product review types](https://youtu.be/Ts7_T9sd1Do) --- # Categories Prior to adding new products, a store manager should create categories to assign these products later. To manage categories, go to **Catalog → Categories**. ![Categories](_static/categories/categories.jpg) Search for a category in the *Search* panel by entering the **Category name** or its part, by the **Published** property or among all the categories of a certain **Store** (if more than one store is enabled). > [!NOTE] > > To remove categories from the list, select the items to be deleted and click the **Delete (selected)** button. > You can export the categories to an external file for backup purposes by clicking the **Export** button. After clicking the **Export** button, you will see the dropdown menu enabling you to **Export to XML** or **Export to Excel**. ## Adding a new category To add a new category, click the **Add new** button at the top of the page. The *Add a new category* window will be displayed. ![Add a new category](_static/categories/add-new.png) This page is available in two modes: **advanced** and **basic**. Switch to the basic mode, which only displays the main fields, or use the advanced mode displaying all the available fields. ### Category info In the *Category info* panel, define the following category information: - **Name** — this is the name of the category displayed in the catalog. - **Description** — a description of the category. Use the editor for layout and fonts. - If this category is a subcategory, select the **Parent category** from the dropdown list. The new category will be placed under this category in the public store. - **Picture** — an image representing the category. Upload the image from your device. - **Restrict from vendors** - Check to restrict vendors from adding products to this category. This option is useful when you have multi-vendors enabled in your store. Once enabled vendors won't see this category on the "Add product" or "Edit product" pages in admin area. ### Display ![Display](_static/categories/display.png) In the *Display* panel, define the following category information: - Select the **Published** checkbox to make the category visible in the public store. - Select the **Show on home page** checkbox to display the category on the home page. - Select the **Include in top menu** checkbox to include the category in the top menu on the home page. - Select the **Allow customers to select page size** checkbox to enable customers to select a page size, that is, the number of products displayed on the category details page. The page size can be selected by customers from the page size list entered by the store owner in the **Page size options** field. - If the previous checkbox is selected, the **Page size options** will be displayed. Enter a comma-separated list of page size options (for example, 10, 5, 15, 20). The first option is the default page size if none are selected. - The **Page size** option will be displayed if the **Allow customers to select page size** checkbox is clear. It sets the page size for products in this category, for example, '4' products per page. > [!TIP] > > For example, when you add seven products to a category and set its page size to three, three products per page will be displayed on this category details page in the public store, and the total amount of pages will be three. - Select the **Price range filtering** checkbox if you want to enable filtering by price range. - If you want the price range to be entered manually, select the **Enter price range manually** checkbox. - If the setting above is enabled, enter the **Price 'from'**. - And the **Price 'to'**. - **Display order** — the order number for displaying the category. This display number is used to sort categories in the public store (ascending). The category with the display order 1 will be placed at the top of the list. - The **Category template** filed is visible if you have custom category templates installed on the **System → Templates** page. This template defines how this category (and its products) will be displayed. ### Mappings ![Mappings](_static/categories/mappings.jpg) In the *Mappings* panel, define the following category information: - **Discounts** — select discounts associated with this category. You can create discounts on the **Promotions → Discounts** page. Read more about discounts in the [Discounts](xref:en/running-your-store/promotional-tools/discounts) chapter. > [!NOTE] > > Note that only discounts of the *assigned to categories* type are visible here. After discounts are mapped to the category, they are applied to all products in this category. > > [!NOTE] > > If you want to use discounts, make sure the **Ignore discounts (sitewide)** setting is disabled in the **Configuration → Settings → Catalog settings → Performance** panel. - In the **Limited to customer roles** field, choose the customer roles that will be able to see the category in the catalog. Leave this field empty if this option is not required, and the category can be seen by everyone. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Configuration → Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). - Choose the stores in the **Limited to stores** field if the category is sold in specific stores. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). ### SEO ![Setting up SEO](_static/categories/setting-up-seo.png) In the *SEO* panel, define the following details: - **Search engine friendly page name** — the page name used by search engines. If you leave the field blank, then the category page URL will be formed using the category name. If you enter custom-seo-page-name, then the following custom URL will be used: `http://www.yourStore.com/custom-seo-page-name`. - **Meta title** specifies the title of the web page. It is a code inserted into the header of your webpage: ```html Creating Title Tags for Search Engine Optimization & Web Usability ``` - **Meta keywords** — category meta keywords, which represent a brief and concise list of the most important themes for the page. Meta keywords tag looks like: `` - **Meta description** — a description of the category. A meta description tag is a brief and concise summary of the page content. A meta description tag looks like: `` Click the **Save and continue edit** button to proceed to add products to the category. ### Products The *Products* panel contains a list of products related to the selected category. These products can be filtered by category in the catalog. The store owner can add new products to the category. Note that you need to save the category before you can add products. Click **Add a new product** to find a product you want to include in this category. You can search by the **Product name**, **Category**, **Vendor**, **Store**, **Product type**, and **Manufacturer**. ![Add products](_static/categories/add-product.jpg) Select products you would like to add to the category and click the **Save** button. The products will be displayed under the selected category. ![Products](_static/categories/products.png) After the product was added to the category, define the following information in the *Products* table by clicking the **Edit** button beside a product: - **Is featured product**. - **Display order**. > [!NOTE] > > By clicking **View**, you will be redirected to the *Edit product details* page. Click **Save**. The new category will be displayed in the public store under its parent category. ## Importing categories If you do not want to add all the categories to your catalog manually, you can use the import option. > [!NOTE] > > Before you start importing, you should download a table template for import in Excel format. For accurate and correct import of your categories, it's crucial to name all the columns in the table properly (exactly as in the downloaded table). It is not mandatory to fill all the table fields. The category will be created based on the filled fields. Import requires a lot of memory resources. That's why it's not recommended to import more than 500–1000 records at once. If you have more records, it's better to split them into multiple Excel files and import them separately. ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [SEO](xref:en/running-your-store/search-engine-optimization) --- # Manufacturers To manage manufacturers, go to **Catalog → Manufacturers**. ![Manufactures](_static/manufacturers/manufactures.jpg) Search for a manufacturer in the *Search* panel by entering the **Manufacturer name** or its part, by the **Published** property or among all the manufacturers of a certain **Store** (if more than one store is enabled). > [!NOTE] > > To remove manufacturers from the list, select the items to be deleted and click the **Delete (selected)** button. > You can export the manufacturers to an external file for backup purposes by clicking the **Export** button. After clicking the **Export** button, you will see the dropdown menu enabling you to **Export to XML** or **Export to Excel**. ## Adding a new manufacturer To add a new manufacturer, click the **Add new** button at the top of the page. The *Add a new manufacturer* window will be displayed. ![Add a new manufacturer](_static/manufacturers/add_a_new_manufacturer.png) This page is available in two modes: **advanced** and **basic**. Switch to the basic mode, which only displays the main fields, or use the advanced mode displaying all the available fields. ### Manufacturer info In the *Manufacturer info* panel, define the following details: - **Name** — this is the name of the manufacturer displayed in the catalog. - **Description** — a description of the manufacturer. Use the editor for layout and fonts. - **Picture** — an image representing the manufacturer. Upload the image from your device. ### Display ![Display](_static/manufacturers/display2.png) In the *Display* panel, define the following details: - Select the **Published** checkbox to enable the manufacturer to be visible in the public store. - Select the **Allow customers to select page size** checkbox to enable customers to select a page size, that is, the number of products displayed on the manufacturer details page. The page size can be selected by customers from the page size list entered by the store owner in the **Page size options** field. - If the previous checkbox is selected, the **Page size options** will be displayed. Enter a comma-separated list of page size options (for example, 10, 5, 15, 20). The first option is the default page size if none are selected. - The **Page size** option will be displayed if the **Allow customers to select page size** checkbox is clear. It sets the page size for products by this manufacturer, for example, '4' products per page. > [!TIP] > > For example, when you add seven products to a manufacturer and set its page size to three, three products per page will be displayed on this manufacturer details page in the public store, and the total amount of pages will be three. - Select the **Price range filtering** checkbox if you want to enable filtering by price range. - If you want the price range to be entered manually, select the **Enter price range manually** checkbox. - If the setting above is enabled, enter the **Price 'from'**. - And the **Price 'to'**. - **Display Order** — the order number for displaying the manufacturer. This display number is used to sort manufacturers in the public store (ascending). The manufacturer with the display order 1 will be placed at the top of the list. - The **Manufacturer template** filed is visible if you have custom manufacturer templates installed on the **System → Templates** page. This template defines how this manufacturer (and its products) will be displayed. ### GPSR In the *GPSR* panel, define the following details: - **Physical address** — the physical address of the manufacturer. This field is required for products sold in the EU to comply with the EU General Product Safety Regulation (Regulation (EU) 2023/988). - **Electronic address** — the electronic address (e.g., email) of the manufacturer for contacting purposes. - **Responsible person name** — the name of the natural or legal person established in the EU who is responsible for ensuring compliance with the GPSR requirements. This is required when the manufacturer is not established in the EU. - **Responsible person physical address** — the physical address of the responsible person. - **Responsible person electronic address** — the electronic address (e.g., email) of the responsible person for contacting purposes. ![GPSR](_static/manufacturers/gpsr.png) > [!NOTE] > > The GPSR (General Product Safety Regulation) requires that every product offer in the EU includes clear identification and contact details of the manufacturer. If the manufacturer is not established in the EU, a Responsible Person must be designated who is based in the EU and can be contacted by consumers and authorities regarding product safety. ### Mappings ![Mappings](_static/manufacturers/mappings.png) In the *Mappings* panel, define the following details: - **Discounts** — select discounts associated with this manufacturer. You can create discounts on the **Promotions → Discounts** page. Read more about discounts in the [Discounts](xref:en/running-your-store/promotional-tools/discounts) chapter. > [!NOTE] > > Note that only discounts of the *assigned to manufacturers* type are visible here. After discounts are mapped to the manufacturer, they will be applied to all products by this manufacturer. > > [!NOTE] > > If you want to use discounts, make sure the **Ignore discounts (sitewide)** setting is disabled in the **Configuration → Settings → Catalog settings → Performance** panel. - In the **Limited to customer roles** field, choose the customer roles that will be able to see the manufacturer in the catalog. Leave this field empty if this option is not required, and the manufacturer can be seen by everyone. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Configuration → Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list here](xref:en/running-your-store/customer-management/access-control-list). - Choose the stores in the **Limited to stores** field if the manufacturer's products are sold in specific stores. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality here](xref:en/getting-started/advanced-configuration/multi-store). ### SEO ![SEO](_static/manufacturers/SEO.png) In the *SEO* panel, define the following details: - **Search engine friendly page name** — the page name used by search engines. If you leave the field blank, then the manufacturer page URL will be formed using the manufacturer name. If you enter custom-seo-page-name, then the following custom URL will be used: `http://www.yourStore.com/custom-seo-page-name`. - **Meta title** specifies the title of the webpage. It is a code inserted into the header of your webpage: ```html Creating Title Tags for Search Engine Optimization & Web Usability ``` - **Meta keywords** — manufacturer meta keywords, which represent a brief and concise list of the most important themes for the page. Meta keywords tag looks like: `` - **Meta description** — a description of the manufacturer. A meta description tag is a brief and concise summary of the page content. A meta description tag looks like: `` Click the **Save and continue edit** button to proceed to add products to the manufacturer. ### Products The *Products* panel contains a list of products related to the selected manufacturer; these products can be filtered by the manufacturer in the catalog. The store owner can add new products to the manufacturer. Note that you need to save the manufacturer before you can add products. Click **Add a new product** to find a product you want to add to this manufacturer. You can search by the **Product name**, **Category**, **Vendor**, **Store**, **Product type**, and **Manufacturer**. ![Add products](_static/manufacturers/add-product.jpg) Select products you would like to add to the manufacturer and click the **Save** button. The product will be displayed under the selected manufacturer. ![products2](_static/manufacturers/products2.png) After the product has been added to the manufacturer, define the following information in the *Products* table by clicking the **Edit** button beside the product: - **Is featured product**. - **Display order**. > [!NOTE] > > By clicking **View**, you will be redirected to the *Edit product details* page. Click **Save**. ## Importing manufacturers If you do not want to add all the manufacturers to your catalog manually, you can use the import option. > [!NOTE] > > Before you start importing, you should download a table template for import in Excel format. For accurate and correct import of your manufacturers, it's crucial to name all the columns in the table properly (exactly as in the downloaded table). It is not mandatory to fill all the table fields. The manufacturer will be created based on the filled fields. Import requires a lot of memory resources. That's why it's not recommended to import more than 500–1000 records at once. If you have more records, it's better to split them into multiple Excel files and import them separately. ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [SEO](xref:en/running-your-store/search-engine-optimization) ## Tutorials - [Managing manufacturers in nopCommerce](https://www.youtube.com/watch?v=NnWD9-zi8s4&feature=youtu.be) --- # Catalog settings Catalog settings include enabling options for product sorting, changing view modes, comparing products, and more. To define catalog settings, go to **Configuration → Settings → Catalog settings**. The catalog settings page is available in *advanced* and *basic* modes (advanced mode by default). This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ## Artificial Intelligence This functionality integrates *Artificial Intelligence (AI)* services directly into the platform to automate the creation of product descriptions and Search Engine Optimization (SEO) meta tags, including Meta Title, Meta Description, and Meta Keywords. The feature is built into the core application and supports three popular AI service providers: - DeepSeek - Gemini - ChatGPT > [!NOTE] > > Only one provider can be active at a time. All related settings can be found on the *Catalog settings* page in the **Artificial Intelligence** section. ![AI](_static/catalog-settings/ai_settings.png) Key configuration options include: - **Enable artificial intelligence**: You can enable or disable the entire AI generation functionality. You can also independently enable or disable the generation of SEO fields. - **Provider type**: A dropdown menu allows you to choose which of the three supported AI providers will be used for content generation. - **Prompt Templates - AI query to generate[..]**: The templates for all API requests sent to the AI service can be edited. This allows advanced users to customize and fine-tune the prompts to better suit their specific needs. ### Generating Product Descriptions 1. Navigate to the product edit page. The **"Generate description with AI"** button is located directly beneath the product description editor. ![AI](_static/catalog-settings/ai_product_description.png) 1. Clicking the button opens a configuration window. ![AI](_static/catalog-settings/ai_product_description_generate.png) Here, you can adjust the parameters that will be sent to the AI service to generate the description. The following fields are mandatory: - **Product name** - **Target language** - **Features and keywords** - **Tone of voice** - You can also provide any **Special instructions** to guide the AI. 1. Click the **"Generate description with AI"** button in the pop-up window to send the request. - On Success: The generated text will be displayed in the window. You can then **Save** it directly to the product description field or **Copy to the clipboard**. If you are not satisfied with the result, you can click the "Generate" button again to get a new version. ![AI](_static/catalog-settings/ai_product_description_generated.png) - On Failure: If an error occurs during generation, an error message will be displayed instead of the text, often including a link to the log file for troubleshooting. ![AI](_static/catalog-settings/ai_product_description_generated_fail.png) ### Generating SEO Meta Tags 1. In the SEO section of the product edit page, each meta tag block contains a **"Generate meta tags with AI"** button. ![AI](_static/catalog-settings/ai_product_seo.png) 1. Clicking this button will automatically generate content for all SEO fields that are: - Enabled for generation in the settings. - Currently empty (the tool will not overwrite existing, manually entered data). > [!IMPORTANT] > > If you make changes to fields that are used as a basis for generation (e.g., the product name or short description) and do not save them, the system will prompt you to save your changes before sending the request to the AI service. > > ![AI](_static/catalog-settings/ai_product_seo_alert.png) ## Set up a search ![Search](_static/catalog-settings/search.jpg) The top panel on the page sets up *Search*: - Select the **Search enabled** checkbox if you want the search functionality to be enabled in the public store. - Select the **Search autocomplete enabled** checkbox to display the autocomplete search box in the public store as follows: ![Search](_static/catalog-settings/search.png) When this option is enabled, the following additional fields will be displayed: - **Number of 'autocomplete' products to display** sets up the number of results that will be visible in the autocomplete dropdown list of the search box in the public store. - Select the **Show a link to all search results in the autocomplete box** checkbox to display the link to all results in the autocomplete search box. Displayed if the number of items found is greater than the displayed quantity in the autocomplete box. - Select the **Show product images in autocomplete box** checkbox to enable displaying product images in the autocomplete search box. - **Search term minimum length** is a minimum number of chars required for the search. - Select the **Search page. Allow customers to select page size** checkbox if you want to allow customers to select the page size from the predefined list of options. - In the **Search page. Page size options** field, enter a comma-separated list of page size options for customers or the number of products that you want to display on the search products page. - If the **Search page. Allow customers to select page size** setting is disabled, the **Search page. Products per page** field will be displayed. In this field, enter the number of products you want to be displayed on the search page. - Select the **Search page. Price range filtering** checkbox if you want to enable filtering by price range. - If you want the price range to be entered manually, select the **Search page. Enter price range manually** checkbox. - If the setting above is enabled, enter the **Search page. Price 'from'**. - And the **Search page. Price 'to'**. - If the **Allow customers to search with manufacturer name** is enabled, customers can search by manufacturer name. - If the **Allow customers to search with category name** is enabled, customers can search by category name. > [!NOTE] > > Standard nopCommerce search relies on exact matches, so if you want to increase the speed and relevance of the search on your website, we recommend using Full-text Search. Unlike standard search, Full-text Search analyzes the entire website's content to retrieve the most relevant results. Auto-complete and typo tolerance optimize search speed and help users find exactly what they need. > > [Learn more](xref:en/running-your-store/catalog/catalog-settings/full-text-search/index) ## Product reviews ![Product reviews](_static/catalog-settings/product-reviews.jpg) The second panel sets up *Product reviews*. Define the following: - **Product reviews must be approved** to enforce product reviews to be approved by the store administrator prior to being published. - **One review per product from customer** to restrict customer to add just 1 review per product. - **Allow anonymous users to write product reviews** to allow anonymous users to write product reviews. - **Product review possible only after product purchasing** to allow reviewing the product only by customers who have already ordered it. - **Notify about new product reviews** to notify the store owner about new public reviews. - **Notify customer about product review reply** to notify a customer about product review reply. - **Reviews per store** allows only displaying reviews of the current store (on the product details page). Clear this checkbox if you want your customers to see the product's reviews written in all of your stores. - **Show product reviews tab on 'My account' page** to allow customers to see all their reviews on the 'My account' page. - **Product reviews page size** is the number of reviews per page. - **Sort by ascending** to sort product reviews by creation date in ascending order. ## Review types The next block sets up *Review types*. You can configure a list of review types if you think that a basic review is not enough. ![Review types](_static/catalog-settings/review_types.png) Click **Add new button** to create a new review type. ![Quality rating](_static/catalog-settings/quality_rating.png) Define the following: - Enter your review type **Name**. - Enter the review type **Description**. - Define the **Display order**. - When **Required**, customers have to choose an appropriate rating value before they can continue. - **Visible to all customers** sets the visibility of the review type to all customers. Click the **Save** button to add a new review type. Now customers will be able to fill additional ratings on the product review page in the public store. ![Product reviews](_static/catalog-settings/product_reviews.png) On this page, you can also see the feedback left by all customers (if this setting is active). On the customer personal account page, there is also an opportunity to view all the reviews left for the products. ![My account](_static/catalog-settings/my_account.png) ## Performance ![Performance](_static/catalog-settings/performance.jpg) The next panel sets up *Performance*. Having the following settings enabled can significantly improve the store performance: - **Ignore ACL rules (sitewide)** turns off the [ACL rules](xref:en/running-your-store/customer-management/access-control-list) configured for entities. - **Ignore limit per store (sitewide)** allows ignoring limit per stores rules configured for entities. It is recommended to enable this setting if you only have one store or no store-specific limitations. Read more about multi-store in the [Multi-store](xref:en/getting-started/advanced-configuration/multi-store) section. - **Ignore discounts (sitewide)**. - **Ignore featured products (sitewide)**. - **Cache product prices**. You should not enable it if you use complex discounts, discount requirement rules or coupon codes. ## Share ![Share](_static/catalog-settings/share.jpg) Sharing options in the *Share* panel allow to set up an opportunity for shoppers to share the products across their social media networks. The options will appear as small icons on product pages. To set up the sharing options: - Select the **Show a share button** to display a share button on the product details page. When this field is selected, the **Share button code** field will be displayed. - The **Share button code** field displays the page's button code. > [!NOTE] > > By default, the ShareThis service is used ([https://sharethis.com/](https://sharethis.com/)). This is what share links look like: ![Share](_static/catalog-settings/zzz.png) - Select the **'Email a friend' enabled** checkbox to allow customers to use the "Email a friend" option. - **Allow anonymous users to email a friend** if needed. ## Compare products ![Compare products](_static/catalog-settings/compare-products.jpg) Compare products option enables customers to compare various offers based on their characteristics and prices so that they can make the best shopping decisions. Set up the *Compare products* block as follows: - Select the **'Compare products' enabled** checkbox to enable customers to compare product options in your public store. The *Add to compare list* button will appear on product pages. - Select the **Include short description in compare products** checkbox to display short product descriptions on the compare products page. - Select the **Include full description in compare products** checkbox to display full product descriptions on the compare products page. ![compare_product](_static/catalog-settings/compare_product.png) ## Additional sections ![Additional sections](_static/catalog-settings/additional-sections.jpg) The *Additional sections* panel allows you to set the following options: - Select the **Remove required products** checkbox to automatically remove the required product from the cart when the main product is removed. - **Show best sellers on home page** allows you to show bestsellers on the home page. - If the previous checkbox is selected, you will be able to enter the **Number of best sellers on home page**. - Select the **'Products also purchased' enabled** checkbox to enable customers to view a list of products also purchased by those who purchased the above. - When the previous option is enabled, the **Number of also purchased products to display** field will appear. Here, the store owner can set the number of products to be displayed. - Select the **'Recently viewed products' enabled** checkbox to enable customers to see products recently viewed in your store. - In the **Number of 'Recently viewed products'** field, enter the number of recently viewed products to be displayed when the previous checkbox is selected. - Select the **'New products' page enabled** checkbox if you want the 'New products' page to be enabled in the store. - In the **'New products' page. Page size options** field, enter the number of recently added products to display when the *'New products' page enabled* is selected. - Select the **Display the date for a pre-order availability** checkbox if needed. ## Product fields ![Product fields](_static/catalog-settings/product-fields.jpg) In the *Product fields* panel, you can set the following options: - **Show SKU on product details page**. - **Show SKU on catalog pages**. - **Show GTIN** in the public store. - **Show manufacturer part number** in the public store. - **Show short description on catalog pages** in the public store. ## Product page ![Product page](_static/catalog-settings/product-page.jpg) In the *Product page* panel, you can set the following options: - **Product URL structure type**. Possible values: - /Product - /Category/Product - /Manufacturer/Product - **Show "free shipping" icon** for products with this option enabled. - **Allow viewing of unpublished product details page**. In this case, SEO will not be affected, and search crawlers will index the page, even though a product is temporarily unpublished and invisible to customers. Note that a store owner always has access to unpublished products. - Select the **Discontinued message for unpublished products** checkbox to display the "a product has been discontinued" message when customers try to access details pages of unpublished products. - Select the **Display type for attribute value when out of stock**. If the attribute combination is out of stock, you can show it as disabled or as usual. > [!NOTE] > > Note that the **Allow only existing attribute combinations** option should be enabled for a product. ## Catalog pages ![Catalog pages](_static/catalog-settings/catalog-pages.jpg) The *Catalog pages* panel enables you to set: - **Allow view mode changing** on the categories and manufacturers pages. - The **Default view mode** to either *Grid* or *List*. - **Include products from subcategories** when viewing a category details page. - To **Show number of distinct products beside each category** in the category navigation area located in the left column in the public store. - If needed, turn on the **Show the number of distinct products besides each category** setting. - **Category breadcrumb enabled**. Select to enable the category path (breadcrumb). This is the bar at the top of the screen that indicates in which categories and subcategories the product was viewed on the product pages. Each subelement of the bar is a separate hyperlink. - **Number of manufacturers to display** in the manufacturer navigation block. - **Use AJAX products loading** to load products asynchronously (applicable to 'paging,' 'filtering,' 'view modes') on catalog pages. - **Enable manufacturer filtering** to enable the manufacturer filtering on catalog pages. - **Enable price range filtering** to enable the price range filtering on catalog pages. - **Enable specification attribute filtering** on the catalog pages if needed. If turned off, the specification attribute filtering won't be displayed on the catalog pages even if you have such attributes created. - **Display all pictures on catalog pages** - On the pages of the catalog it becomes possible to view all the pictures of the product. - **Display 'From' prices** - Check to display 'From' prices on catalog pages. This will display the minimum possible price of a product based on price adjustments of attributes and combinations instead of the fixed base price. If enabled, it is also recommended to enable setting 'Cache product prices'. But please note that it can affect performance if you use some complex discounts, discount requirement rules, etc. > [!TIP] > > To display a short description of the product on the catalog pages you need to activate this setting - `catalogsettings.showshortdescriptiononcatalogpages` ## Tags ![Tags](_static/catalog-settings/tags.jpg) In the *Tags* panel, you can define: - **Number of product tags (cloud)** — the number of tags that appear in the tag cloud. - To **Allow customers to select 'Products by tag' page size** on the product tag page from a list of options predefined by the store owner. When disabled, customers will not be able to select page size, and the store owner enters it. - If the previous option is selected, the **'Products by tag' page size options** field becomes visible. You can enter values that can be selected by shop users. Numbers should be separated with commas. The first value will be the default. - If the **Allow customers to select 'Products by tag' page size** setting is disabled, the **'Products by tag' page. Products per page** field will be displayed. In this field, enter the number of products you want to be displayed on the search page. - Select the **'Products by tag' page. Price range filtering** checkbox if you want to enable filtering by price range. - If you want the price range to be entered manually, select the **'Products by tag' page. Enter price range manually** checkbox. - If the setting above is enabled, enter the **'Products by tag' page. Price 'from'**. - And the **'Products by tag' page. Price 'to'**. ## Tax ![Tax](_static/catalog-settings/tax.jpg) Some tax/shipping info options specific to Germany are available in the *Tax* panel: - **Display tax/shipping info (footer)**. - **Display tax/shipping info (product details page)**. - **Display tax/shipping info (product boxes)**. - **Display tax/shipping info (shopping cart)**. - **Display tax/shipping info (wishlist)**. - **Display tax/shipping info (order details page)**. ## Export/import ![Export/import](_static/catalog-settings/import-export.jpg) In the *Export/import* panel, you can define: - Select the **Export/import products with attributes** checkbox if you need product attributes to be exported/imported whenever you export/import the product. - Select the **Export/import products with specification attributes** checkbox if products should be exported/imported with specification attributes. - Select the **Export/import products with category breadcrumb** checkbox if products should be exported/imported with full category names including names of all its parents. - Select the **Export/import categories using name of category** checkbox if categories should be exported/imported using the category names. - Select the **Export/import products. Allow download images** checkbox if images can be downloaded from a remote server when exporting products. - Select the **Export/import products. Allow splitting file** checkbox if you want to import products from individual optimal-size files automatically created from the main file. This function will help you import a large amount of data with a smaller delay. - Select the **Export/import related entities using name** checkbox if related entities should be exported/imported using names. - Select the **Export/import products with "limited to stores"** checkbox if products should be exported/imported with their "limited to stores" properties. > [!NOTE] > > When you have two or more languages, Export/Import to Excel/XML supports multilingual data. ## Product sorting In the *Product sorting* panel, you can define: - Select the **Allow product sorting** checkbox to enable a product sorting option on the categories and manufacturers pages. You can activate/deactivate sorting by *Position*, *Name*, *Price*, and *Date of creation*. > [!NOTE] > > Selecting the value "Position" means that there will be no restrictions on the sorting of products. ![product_sorting](_static/catalog-settings/product_sorting.jpg) You can edit the **Display order** and **Is active** property of each option by clicking the **Edit** button. --- # YMM (Year-Make-Model) Filter ## Overview The YMM (Year-Make-Model) filter allows customers to find products using a structured, multi-level filtering system. While its name suggests automotive use, the feature is fully customizable and can be adapted for any product catalog requiring compatibility checks, such as electronics parts (e.g., filtering by "Make, Model, Display Size"). The core purpose is to help customers easily find parts compatible with a specific vehicle or product, enhancing the user experience and reducing the likelihood of incorrect purchases. ### Key Features - **Configurable Multi-Level Filtering:** Administrators can define up to three nested filter levels (e.g., Year → Make → Model). - **Flexible Value Management:** Easily add, edit, and bulk-manage filter values (e.g., 2023, Audi, A4) via the admin panel or Excel import/export. - **Product-to-Filter Mapping:** Assign products to one or more compatible filter combinations to ensure accurate search results. - **Seamless Storefront Integration:** Display the filter on the homepage for easy access and show detailed compatibility information on product pages. ## Admin Panel Configuration ### Filter Settings To configure the feature, navigate to **Configuration → Settings → Filter (YMM) settings**. ![YMM](_static/ymm/ymm_settings.png) - **`Enabled`**: This is the master switch to activate or deactivate the entire YMM functionality on the website. It is disabled by default. - **`Display on home page`**: Check this box to show the YMM filter block on the site's homepage. - **`Display filter values on product details page`**: When checked, a "Compatible with" table will appear on product pages listing all associated filter combinations. This is enabled by default. #### Filter Levels Grid Here you can customize the three available filter levels: ![YMM](_static/ymm/ymm_fl_edit.png) - **Enabled:** Activate or deactivate each level. - **Name:** Set a custom, localizable name for each level. > [!NOTE] > > By default, a new installation will have "Year," "Make," and "Model" configured and enabled. > [!WARNING] > > A parent level cannot be disabled if a child level is currently enabled. ### Managing Filter Values To create and manage the options for each filter level, go to **Catalog → Filter level values (YMM)**. ![YMM](_static/ymm/ymm_flv_list.png) - **Value Creation & Editing:** Administrators can add or edit combinations of values for the enabled filter levels (e.g., Year: 2024, Make: BMW, Model: X5). The system prevents the creation of duplicate combinations. ![YMM](_static/ymm/ymm_flv_edit.png) - **Product Mapping:** When creating or editing a value set, a new window appears where you can directly map products to that specific combination. This window also displays products that are already mapped. - **Management Features:** - **Filter:** The admin grid can be filtered by each active level to quickly find entries. - **Import/Export:** Bulk manage filter values using the Excel import and export utility. - **Delete Selected:** Remove multiple value combinations at once. ### Mapping from the Product Edit Page You can also manage mappings directly from a product's configuration page. 1. Navigate to **Catalog → Products** and open a product for editing. 1. Find the new **"Filter level values (YMM)"** panel (located after the "Cross-sells" panel). ![YMM](_static/ymm/ymm_product_map.png) 1. From here, you can add or remove associations between the product and existing filter value combinations. ## Public Store Functionality ### Homepage Filter If the feature is enabled to display on the homepage, customers will see a filter block with dropdown menus for each active filter level. ![YMM](_static/ymm/ymm_public.png) The dropdowns are **dependent and sequential**. A value must be selected in the first-level filter (e.g., "Year") before the second-level dropdown ("Make") becomes active, and so on. ### Search Results Page A search is executed only after the customer has selected a value for **all enabled filter levels**. Upon clicking **Search**, the user is redirected to a dedicated YMM search results page. ![YMM](_static/ymm/ymm_search.png) This page displays the selected filter criteria at the top and a paginated list of all matching products below. ### Product Details Page If the corresponding setting is active, a table titled **"Compatible with"** will be displayed on the product page. This table clearly lists all the YMM combinations that the specific product is compatible with, giving customers confidence in their purchase. ![YMM](_static/ymm/ymm_product_compatible.png) --- # Price lists ## Overview A price list is a named set of rules that changes the price of the products assigned to it. A price list can raise or lower the base product price by a percentage or a fixed amount, or set one fixed price for all its products, for example: - wholesale or B2B prices for a specific customer role; - a temporary sale applied to a selected customer group for a limited period; - negotiated prices for particular customers, such as a long-term contract customer. Price lists differ from [discounts](xref:en/running-your-store/promotional-tools/discounts) in that a price list changes the product price itself, and thus becomes the base for further calculations, while a discount is applied on top of the resulting price. ![Price lists](_static/price-lists/price_lists.png) ## How a price list affects the price A price is taken from a price list only when all the following conditions are met: - the price list is **active**; - the current moment is within the price list's start and end dates (if specified); - the customer belongs to the customer roles selected for this price list, or is one of the customers added to this price list individually; - the product is assigned to this price list. ![Price lists](_static/price-lists/price_lists_info.png) The price list price is calculated from the product base **Price** value using the selected calculation type and value: | Calculation type | Result | | --- | --- | | Percentage decrease | base price minus the specified percentage | | Percentage increase | base price plus the specified percentage | | Amount decrease | base price minus the specified amount | | Amount increase | base price plus the specified amount | | Fixed price | the specified price is used as is | For example, for a product with a base price of $100 and a price list with the *Percentage decrease* type and a value of 15, the price becomes $85. A product can have a **Manual price** set within a price list. When specified, this value is used instead of the calculated one. ![Price lists](_static/price-lists/price_lists_products.png) > [!NOTE] > > For any product you can check the result of the calculations on the price list's *Products* panel, where the **Original price**, **Calculated price**, and **Manual price** columns are displayed. ### Multiple price lists for one product If several active price lists apply to the same product and customer, the result depends on the **Price list strategy** setting, which you can find in **Configuration → Settings → Catalog settings**. - **Minimal price**: all applicable price lists are applied, and the lowest resulting price is used. - **Use by priority**: price lists are applied in ascending order of their **Priority** value, and the price of the first applicable price list is used. Price lists with a lower priority value are applied first; if several price lists share the same value, they are applied in the order they were created. This field is only displayed in the admin area when the *Use by priority* strategy is selected. > [!NOTE] > > The setting can also be configured separately for each store in a multi-store installation. ## Creating a price list To add a new price list, go to **Catalog → Price lists** and click **Add new**. Define the following values in the *Price list info* panel: - **Name** of the price list. - **Price calculation type**. The available options are *Percentage decrease*, *Percentage increase*, *Amount decrease*, *Amount increase*, and *Fixed price*. - **Price calculation value**. Its meaning depends on the selected calculation type: a percentage for the percentage types, or an amount for the amount and fixed price types. - **Active**. Inactive price lists are not applied to products, which allows you to prepare a list in advance and switch it on later. - **Customer roles**. Select the roles to which this price list is applied. If no role is selected, and no individual customers are added, the price list is applied to all customers. - **Description** of the price list. - **Start date** and **End date**. Leave these fields empty to make the price list active indefinitely. Click **Save** to save the changes, or **Save and continue edit** to proceed to the other panels. ## Assigning products to a price list Products can be added to a price list from the price list page or from the product page. ### From the price list page Go to the *Products* panel of the price list and click **Add product**. In the pop-up window, find the required products (you can search by product name, category, manufacturer, vendor, store, and product type), select them, and click **Save**. For each product in the grid, you can: - view the **Original price** (the product's base price) and the **Calculated price**; - set the **Manual price** to override the calculated value. Click **Edit**, enter the price, and save; - open the product page or remove the product from the price list. ### From the product page Go to **Catalog → Products**, open the required product, and in the *Price* panel select the price lists in the **Price lists** field. For more details, see [Add products](xref:en/running-your-store/catalog/products/add-products). ![Price lists](_static/price-lists/price_lists_product_info.png) > [!NOTE] > > A manual price set on the price list's *Products* panel takes precedence over the price calculated by the price list. Read more about this field in the [Add products](xref:en/running-your-store/catalog/products/add-products) section. ## Assigning customers to a price list Along with customer roles, you can assign a price list to specific customers. Go to the *Customers* panel of the price list and click **Add customer**. Find the required customers, select them, and click **Save**. ![Price lists](_static/price-lists/price_lists_customers.png) The price list is then applied to these customers in addition to the customers with the selected roles. > [!NOTE] > > Only registered customers can be added to a price list this way. To apply a price list to guests, use customer roles, such as the *Guests* role. ## Import and export price lists On the **Catalog → Price lists** page, you can import price lists from an Excel file or export the existing ones. To export, click **Export** and select **Export to Excel (all found)** or **Export to Excel (selected)**. To import, click **Import** and upload the Excel file. The file contains the following columns for each price list: `Id`, `Name`, `Description`, `Active`, `StartDateUtc`, `EndDateUtc`, `PriceCalculationType`, `PriceCalculationValue`, `Customers`, `CustomerRoles`, `Priority`. Each product of a price list is described in the nested rows of the same file, with the `Sku` and `ManualPrice` columns. > [!NOTE] > > Price lists are distinguished by the **Id** column. If an ID already exists in your store, the corresponding price list is updated; for new price lists, leave this column set to 0. All the SKUs specified in the file must exist in your catalog, otherwise the import is not performed. ## Permissions The price list functionality is controlled by the following permissions in **Configuration → Users → Roles**: - **View price lists**. - **Create, edit and delete price lists**. - **Import and export price lists**. Read more about how to configure permissions in the [Access control list](xref:en/running-your-store/customer-management/access-control-list) section. ## See also - [Add products](xref:en/running-your-store/catalog/products/add-products) - [Tier prices](xref:en/running-your-store/promotional-tools/tier-prices) - [Discounts](xref:en/running-your-store/promotional-tools/discounts) - [Customer roles](xref:en/running-your-store/customer-management/customer-roles) - [Multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store) --- # EU Omnibus Directive ## Introduction Please get [Omnibus Directive integration](https://www.nopcommerce.com/omnibus-directive). ### What is Omnibus? The Directive (EU) 2019/2161, also known as the [Omnibus Directive](https://eur-lex.europa.eu/eli/dir/2019/2161/oj), is a European Union directive aimed at strengthening consumer rights and promoting greater transparency by implementing sanctions to enforce these rights. The main objective of the Omnibus Directive is to enhance consumer protection rights across the entire European Union, and it applies to all e-commerce stores. ### Key Points of the Omnibus Directive * Any price reduction must be displayed on the e-commerce website by showing both the previous price and the current price after the discount. * The lowest price recorded during the 30 days preceding the promotion must be used as the reference for applying the reduction. ### How to Apply Promotions in Full Compliance Before planning a promotion or a discount period, you must ensure that all historical prices are available for at least 30 days prior to the promotion date. You should be able to prove and show your past prices from the last month if requested by your local authorities. ## nopCommerce plugin for the Omnibus Directive To comply with the Omnibus Directive, our integration tracks price changes over a configured timeframe and displays the lowest price to customers. Tracking takes into account discounts applied to products, categories, or manufacturers. The EU’s Omnibus Directive affects the way eCommerce businesses must display their product prices, particularly those on sale. The directive requires retailers to inform customers not only of the discounted price or percentage but also of the lowest price a product has been sold for in the past 30 days. These prices are known as omnibus prices. Businesses must be transparent in their pricing, making the omnibus prices stand out and be easily accessible to customers while maintaining consistency across all product pages. ![Product page](_static/product.png) ![The lowest price](_static/lowest-price.png) ### Plugin configuration ![The lowest price](_static/settings.png) On the configuration page, you can enable history refresh, configure timeframe, set the customize the display options, and more. Click the "Refresh price history data" button, and the plugin will calculate and save the normal prices (in historical data). This might take a moment depending on the amount of products, so please be patient. It’s recommended to do this after the plugin installation or when you start a new discount campaign. > [!NOTE] > > The plugin only supports standard discounts. Discounts with personalized coupon codes are not supported. The price history data is refreshed automatically every 24 hours for published products or instantly for a product when its price is changed (a product is created or edited). 1. If you want to disable scheduled refreshing of the price history data uncheck the **Enable scheduled refresh of price history data** checkbox, it’s enabled by default. This can be useful for stores with a large number of products. 1. To adjust the timeframe for calculating the lowest price enter the desired value into the **Lowest price calculation timeframe** field. By default, the integration displays the lowest price for the last 30 days prior to the current date. 1. Use the **Show lowest price** setting to select how to display the lowest price on the product details page: * **When the lowest price is lower than the current price** – to show the lowest price only when it's lower than the current one (otherwise, it'll be hidden). * **Always** – if you want to always display the lowest price (even if it's the same as the current one). * **Hide** – helpful when you've just installed the plugin and the collected data is not sufficient (it's recommended to choose this setting during the first 30 days of the plugin operation). 1. The **Hide lowest price for products with attributes** checkbox allows you to hide or show the lowest price for products with product attributes. Price history data is not saved for product attributes with price adjustments (we save standard product prices only). The plugin automatically clears outdated price history data every 24 hours (history data that dates back earlier than the configured price calculation timeframe). > [!NOTE] > > The schedule task does not delete a price history record that precedes the configured price calculation timeframe because it is taken as the initial price. ![Product list](_static/product-list.png) In the **Product list** block, you can see the current and the lowest prices, availability status, and the “View” button for editing the product. You can filter products by name, category, type, and store (if you have more than one). ![Price change history](_static/price-history.png) The **Price change history** block contains all saved product prices. Each entry in the table has a button that allows you to delete it (for example, if the entry was saved by mistake). You can filter history change data by product name, calculation period, and store (if you have more than one). ![Discount details page](_static/discount.png) On the discount details page, you can add all the discount info and list the products to which it is applied. We recommend manually refreshing the price change data by clicking the "Refresh price history data (Omnibus)" button once you’ve configured a discount promotion on the discount details page. Otherwise, this may lead to noncompliance with the Omnibus Directive between scheduled task runs (each 24 hours). ### Plugin installation This section describes how to integrate the Omnibus Directive plugin into your store. 1. [Purchase the integration](https://www.nopcommerce.com/omnibus-directive). 1. Download the plugin archive. 1. Go to **Admin area > Configuration > Local plugins**. 1. Upload the plugin archive using the "Upload plugin or theme" button. 1. Scroll down the list of plugins to find the newly uploaded plugin. 1. Click on the **Install** button to install the plugin. Please find more [information about how to install plugins](https://docs.nopcommerce.com/getting-started/advanced-configuration/plugins-in-nopcommerce.html). --- # Configure full-text search for your nopCommerce store Full-text search is a powerful technology that enables users to search through large volumes of text-based data quickly and accurately. Unlike standard nopCommerce search, which relies on exact matches, the Full-text Search analyzes the website's content to retrieve the most relevant results. Auto-complete and typo tolerance optimize search speed and help users find exactly what they need. nopCommerce Fast Full-text Search is implemented in two plugins: * [Fast Full-text Search based on Lucene](xref:en/running-your-store/catalog/catalog-settings/full-text-search/lucene-configure) * [Fast Full-text Search based on Elasticsearch](xref:en/running-your-store/catalog/catalog-settings/full-text-search/elasticsearch-configure) --- # Full-text search based on Elasticsearch Please get the [official integration with Elasticsearch](https://www.nopcommerce.com/full-text-search-elasticsearch?utm_source=docs.nopcommerce&utm_medium=documentation&utm_campaign=full-text-search-elasticsearch). Elasticsearch is a search engine based on the Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. Our integration provides a strongly-typed API and query DSL to interact with the Elasticsearch server. The plugin includes high-level operations for products, such as bulk indexing, update operations, and search. > [!NOTE] > > The integration is based on the v8 .NET client for use with Elasticsearch 8.x versions ## Available features Here is a list of supported features: * Automatic updating of product data on the elastic server (in real-time or on a schedule). * Automatic matching of the available indexing language to the current store language. * Several built-in search types: * Fuzzy search is used for the phrases that are spelled incorrectly. For example, if you type ‘test’ instead of ‘text’, results will still be found. * Wildcard search is used for matching phrase patterns instead of searching full phrases. The integration uses the `*` wildcard operator to represent word endings. * Exact search strictly matches the query to indexed tokens. * Several authentication methods to access an Elasticsearch cluster. ## Plugin installation This section describes how to integrate Elasticsearch into your store. 1. Purchase the integration at [https://www.nopcommerce.com/full-text-search-elasticsearch](https://www.nopcommerce.com/full-text-search-elasticsearch?utm_source=docs.nopcommerce&utm_medium=documentation&utm_campaign=full-text-search-elasticsearch) 1. Download the plugin archive. 1. Go to admin area > configuration > local plugins. Upload the plugin archive using the "Upload plugin or theme" plugin. 1. Scroll down through the list of plugins to find the newly installed plugin. Click on the "Install" button to install the plugin. You can find more information about [how to install plugins](https://docs.nopcommerce.com/getting-started/advanced-configuration/plugins-in-nopcommerce.html). The Elasticsearch must be configured for correct work of the plugin. Find more about the [Elasticsearch installation process](https://www.elastic.co/downloads/elasticsearch). > [!NOTE] > > The plugin belongs to the **Search provider** group. Use the **Group** field in the search panel to filter plugins for faster navigation. ![Local plugins](_static/local-plugins-elasticsearch.png) ## Plugin configuration Click the **Configure** button beside the Elastic search provider option in the list. Next, follow the steps to complete configuring the plugin: ![Lucene configuration page](_static/elasticsearch-config-page.png) 1. Enter the Node endpoint URL that the plugin will use to connect to your Elasticsearch cluster. 1. Input the index name that will be used for requests to the Elasticsearch server (*nopcommerceproducts* by default) 1. Enter your Elasticsearch server credentials: * **Authentication type**. Select the authentication method that will be used to grant access to the Elasticsearch cluster. * **Username**. This is the username you use with the Basic authentication scheme. * **Password**. This is the password you use with the Basic authentication scheme. * **Api Key**. This is the keyword you use with the bearer authentication scheme. 1. Choose a search algorithm: * The "**Fuzzy**" search is based on the Levenshtein Distance (For example, searches for a "roam" term will find terms like "foam" and "roams"). * The "**Contains**" search looks for 0 or more characters based on the wildcard searches with "*" at the end (For example, to search for "test", "tests", or "tester", you can use the "test" term). * The "**None**" option is based on exact matching. 1. Choose a rule for matching terms in a search query: * The "**Should**" operator - terms should appear in a field of the matching product, but are optional * The "**Must**" operator - terms must appear in a field of the matching product. 1. Set up the behavior of updating the search index documents. Check the **Immediately update indexes** to immediately apply changes for the mapped product (for example, their names or descriptions were changed). Otherwise, the reindexing will be scheduled. > [!NOTE] > > You may also manually click the "Rebuild index" button to start reindexing. 1. Enter the **Result limit**, if necessary. The Result limit is the maximum number of result matches that will be retrieved from the Elasticsearch server for search queries. 1. Enter additional delimiter characters to split a search query into terms. Please note that search queries are always splitted by space, in addition to the entered delimiters. 1. Enter the **Boost factor** for each indexed field, or use the checkbox to enable or disable relevance boosting. 1. Click the **Save** button > [!NOTE] > > To toggle the plugin state, use the "**Enable**" or "**Disable**" buttons. They are displayed depending on the current state. --- # Full-text search based on Lucene Please get the [Full-Text Search plugin based on Lucene](https://www.nopcommerce.com/full-text-search-lucene?utm_source=docs.nopcommerce&utm_medium=documentation&utm_campaign=full-text-search-lucene). [Apache Lucene™](https://lucene.apache.org/) is a high-performance, full-featured search engine library written entirely in Java. It is a technology suitable for nearly any application that requires structured search, full-text search, faceting, nearest-neighbor search across high-dimensionality vectors, spell correction, or query suggestions. Our integration uses [Lucene.Net](https://lucenenet.apache.org/) which is a port of the Lucene search library. Apache Lucene.NET is a .NET library providing powerful indexing, search features, and advanced analysis/tokenization capabilities. ## Available features Here is a list of supported features: * Automatic updating of product data in the stored index. * Automatic matching of the available indexing language to the current store language. * Several built-in search types: * Fuzzy search is used for the phrases that are spelled incorrectly. For example, when you type ‘test’ instead of ‘text’, results still can be found. * Wildcard search is used for matching phrase patterns instead of searching full phrases. The integration uses the `*` wildcard operator to represent word endings. * Exact search strictly matches the query to indexed tokens. ## Plugin installation This section describes how to integrate the Lucene plugin into your store. 1. Purchase the integration at [https://www.nopcommerce.com/full-text-search-lucene](https://www.nopcommerce.com/full-text-search-lucene?utm_source=docs.nopcommerce&utm_medium=documentation&utm_campaign=full-text-search-lucene) 1. Download the plugin archive. 1. Go to admin area > configuration > local plugins. 1. Upload the plugin archive using the "Upload plugin or theme" plugin. 1. Scroll down through the list of plugins to find the newly installed plugin. Click on the "Install" button to install the plugin. You can find more information about [how to install plugins](https://docs.nopcommerce.com/getting-started/advanced-configuration/plugins-in-nopcommerce.html) > [!NOTE] > > The plugin belongs to the **Search provider** group. Use the **Group** field in the search panel to filter plugins for faster navigation. ![Local plugins](_static/local-plugins-lucene.png) ## Plugin configuration Click the **Configure** button beside the Lucene search provider option in the list. Next, follow the steps to complete configuring the plugin: ![Lucene configuration page](_static/lucene-config-page.png) 1. Choose a search algorithm: * The "**Fuzzy**" search is based on the Levenshtein Distance (For example, searches for a "roam" term will find terms like "foam" and "roams"). * The "**Contains**" search looks for 0 or more characters based on the wildcard searches with "*" at the end (For example, to search for "test", "tests", or "tester", you can use the "test" term). * The "**None**" option is based on exact matching. 1. Choose a rule for matching terms in a search query: * The "**Should**" operator - terms should appear in a field of the matching product, but are optional * The "**Must**" operator - terms must appear in a field of the matching product. 1. Set up the behavior of updating the search index documents. Check the **Immediately update indexes** to immediately apply changes for the mapped product (for example, their names or descriptions were changed). Otherwise, the reindexing will be scheduled. > [!NOTE] > > You may also manually click the "Rebuild index" button to start reindexing. 1. Enter the **Result limit**, if necessary. The Result limit is the maximum number of result matches that will be retrieved from the index for search queries. 1. Enter additional delimiter characters to split a search query into terms. Please note that search queries are always splitted by space, in addition to the entered delimiters. 1. Enter the **Boost factor** for each indexed field, or use the checkbox to enable or disable relevance boosting. 1. Click the **Save** button > [!NOTE] > > To toggle the plugin state, use the "**Enable**" or "**Disable**" buttons. They are displayed depending on the current state. --- # Order management Order management functionality is the "hub" of your store: all operational data, such as orders, payments, shipment processing, inventory updates, return requests, are collected and managed here. Learn how to get the most out of the order management in the following chapters: * [Orders](xref:en/running-your-store/order-management/orders) * [Shipping management](xref:en/running-your-store/order-management/shipping-management) * [Requests for quote (RFQ)](xref:en/running-your-store/order-management/rfq) * [Return requests](xref:en/running-your-store/order-management/return-requests) * [Shopping carts and wishlists](xref:en/running-your-store/order-management/shopping-carts-and-wishlists) * [Inventory management](xref:en/running-your-store/order-management/inventory-management) * [Checkout attributes](xref:en/running-your-store/order-management/checkout-attributes) * [Order settings](xref:en/running-your-store/order-management/order-settings) --- # Orders To view and manage orders, go to **Sales → Orders**. The orders page lists all current orders. After a customer completes a transaction, a new order appears on the orders page. The top area of the page enables a store owner to search for orders. Enter specific search criteria and use a variety of filters to find any order placed in the store. Whenever a search is completed, the results of the search will be displayed in the lower half of the screen. You can click **View** to view the order details. ![Order list](_static/orders/search.png) ## Search for orders To search for orders, enter one or more of the following search criteria: * **Start date** and **End date** to define a period of orders' creation. * **Warehouse** to load orders with products from a specified warehouse. * **Product** — enter a product name * **Order statuses** – select one of the following: *All*, *Pending*, *Processing*, *Complete*, *Cancelled*. * **Payment statuses** — select a specific payment status to search by: *All*, *Pending*, *Authorized*, *Paid*, *Partially refunded*, *Refunded*, *Voided*. * **Shipping statuses** — select a specific shipping status to search by: *All*, *Shipping not required*, *Not yet shipped*, *Partially shipped*, *Shipped*, *Delivered*. * **Store** — set a specific store in which orders were placed. * **Vendor** — search by a specific vendor. You'll see orders with products by a specified vendor. * **Billing phone number** — customer's phone number. * **Billing email address** — customer's email address. * **Billing last name** — customer's last name. * **Billing country** — customer's country. * **Payment method** — set a specific payment method that was used during checkout. * **Order notes** — search in order notes. Leave empty to load all orders. * **Go directly to order #** — enter the order number and click **Go** to display the required order. ### Export orders You can export orders to an external file by clicking the **Export** button at the top of the page. After clicking the **Export** button, you will see the dropdown menu enabling you to **Export to XML (all found)** or **Export to XML (selected)** and **Export to Excel (all found)** or **Export to Excel (selected)**. ### Import orders You can import orders from Excel by clicking the **Import**, choose the file, and click the **Import from Excel** button. Imported orders are distinguished by order GUID. If the order GUID already exists, then its details will be updated. > [!WARNING] > > Import requires a lot of memory resources. That's why it's not recommended to import more than 500 - 1,000 records at once. If you have more records, it's better to split them to multiple Excel files and import separately. ## Order details To view the full order information, click **View** beside the order in the list. Click the **Invoice (PDF)** button in the top right corner to generate an invoice for the order in PDF. Click **Delete** if you want to delete the order. ### Info In the **Info** panel, a store owner can perform the following: * View the **Order #**, which is a unique order number. * View the **Created on** — the date/time the order was placed/created. * View the **Customer** who placed the order. * View the **Order status**. The order status will only be *Completed* when the payment status is set to *Paid* and the shipping status is set to *Delivered*. The order status can be changed manually by clicking the **Change status** button. However, this option is only recommended for advanced users because all appropriate actions (such as inventory adjustment, sending notification emails, reward points, gift card activation/deactivation) must be performed manually in this case. * **Cancel order**. A confirmation message will be displayed; click **Yes** to remove the order from the system. > [!NOTE] > > When a customer uses the Manual Credit Card payment method, which enables storing credit card information in the database, the **Edit credit card** button becomes visible. If a different payment method is used, this button will not be visible. * View the **Order subtotal**, **Order shipping**, **Order tax**, **Order total**, **Profit**. If you click the **Edit order totals** button, you will be able to edit the order totals as on the screenshot below: ![Order totals](_static/orders/edit-totals.jpg) * View the **Payment method** used for this order. * View the **Payment status**. Can be one of the following: *Pending*, *Authorized*, *Paid (captured)*, *Refunded*, *Partially refunded*, or *Voided*. > [!NOTE] > > Not all of the payment gateways support all of these statuses. Read more about payment methods in the [Payment methods](xref:en/getting-started/configure-payments/payment-methods/index) chapter. If the payment status is *Authorized*, the relevant buttons will be available to **Void** and **Capture** the order. **Capture** is used to collect the funds from the customer. **Void** cancels an order that has not been captured. If the payment status is *Pending*, the owner can click **Mark as paid** to indicate the payment has been issued for the order. If the payment status is *Paid*, the **Refund** and **Partial refund** buttons will be available. After clicking **Refund**, a confirmation window will be displayed. After clicking the **Partial refund** button, the *Partial refund* window will be displayed. This window enables the owner to refund part of the total order as follows: ![Refund](_static/orders/refund.png) * View the **Store** in which this order was placed. * View the **Order GUID** displayed for internal usage. * View the **Customer IP address**, which a customer used when placing the order. ### Billing & shipping In the **Billing & shipping panel**, view and edit the billing and shipping information if needed. * View the **Billing address** and **Shipping address**. Optionally, you can click the **View address on Google maps** link to locate the required shipping address. Click the **Edit** button in order to edit the billing or shipping address. * View and edit the **Shipping method** if needed. * View the **Shipping status**. > [!NOTE] > > Store owners can create several shipments per order. If you create a shipment but do not ship all products, then the shipping status of the order will be **Partially shipped**. Once all the products are shipped, the status changes to **Shipped**. Once all the shipments are delivered, the status changes to **Delivered**. * View the list of **Shipments**. ![Shipments panel](_static/orders/shipments.jpg) Click **View** beside the shipment to view its details. The shipment information window will be displayed: ![Shipment details](_static/orders/shipment-details.jpg) **Add shipment** button enables creating several shipments per order and is visible when there is at least one unshipped product in the order. Click **Add shipment** button to add a new shipment to the order, and you will see the **Add a new shipment to order** window: ![Add shipment](_static/orders/add-shipment.jpg) * In the **Tracking number** field, enter the tracking number of the shipment. A tracking number enables your customers and you to check up on the progress of a shipment via telephone or online system operated by your shipping agent (post office or a private courier service, such as FedEx or UPS). Whenever a shipment passes certain points along its route, it will be identified by the shipping agent's system, and the tracking database will be updated with the new location and time information. * Fill the **Admin comment** field if needed. * Select the **Shipped** checkbox to mark the shipment as shipped using the current date. * If the previous checkbox is selected, the **Delivered** checkbox will be available. Select this checkbox to mark the shipment as delivered using the current date. * In the **Products shipped** panel: in the **Qty to ship** column, enter the required quantity of the specific order item to ship. ### Products In the **Products** panel, a store owner can: * **View the product information**, including price, quantity, and total price. * Click the **Product name** link to view a product details page. If the product is downloadable, click **Reset** to reset the number of downloads or **Upload license file**. In addition, when the *Download activation type* of a product is set to *Manually*, the administrator has the option to click **Activate** to enable downloading the product from the site or **Deactivate** to disable downloading the product from the site. * **Edit** the product's **Price**, **Quantity**, **Discount**, and **Total**. * **Delete** a product from the system. ![Products](_static/orders/products.jpg) * Click **Add product**. Select the product from the list. Then, in the *Add a new product to order* window, find the required product. Then proceed to fill the required values and click **Add product**. Do not forget to update order totals after adding a new product to the order. ![Add product](_static/orders/add-product.jpg) ### Order notes In the **Order notes** panel, a store owner can view the notes that were added to the order for information purposes, delete notes, and add new ones. A note may contain an **Attached file** and can be **Displayed to a customer** in the public store. ![Products](_static/orders/note.jpg) ## See also * [Adding products](xref:en/running-your-store/catalog/products/add-products) * [Shipments](xref:en/running-your-store/order-management/shipping-management) * [YouTube tutorial on managing orders](https://www.youtube.com/watch?v=z6TUJOO3gVg&index=5&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) --- # Shipping management To search for shipments and view them, go to **Sales → Shipments**. ## Shipment list ![Shipment list](_static/shipping-management/order-shipment-list.jpg) The top area of the page enables you to search for a shipment by various search criteria: * **Start date** and **End date** for shipments created between these dates. * Enter the **Tracking number** if you want to find shipment with a certain tracking number. * Select the **Warehouse** for shipments sent from a specific warehouse. * Click the **Load not delivered** checkbox if you do not want to load already delivered items. * Use **Country, State/province, County/region, City** to search by a shipment destination. * Click the **Load not shipped** checkbox if you do not want to load already shipped items. * Check the **Load not ready for pickup** checkbox if you want to load items that are not ready for pickup. Select certain shipments to **Set as shipped (selected)** or **Set as delivered (selected)** or **Set as ready for pickup (selected)**. You can also **Print packaging slips (selected)** or **Print Packaging slips (all)** to print packaging receipts. In the list of shipments, a store owner can view all items of a shipment by clicking ![expand](_static/shipping-management/order-shipment-expand.png) in the first column of the shipment. ## Shipment details If you click **View**, the *View shipment details* window will be opened as follows: ![Shipment details](_static/shipping-management/shipment-details.jpg) In this window, you can: * Proceed to the order. * Set a **Tracking number** for the shipment. * Add an **Admin comment** for internal use. * See the **Shipment total weight**. * Mark the shipment as **Shipped**. * Edit the **Date shipped**. * Mark the shipment as **Delivered**. * Edit the **Date delivered**. * **Print packaging slip**. * **Delete** the shipment. If a customer chose the "Pick up in store" shipping method during the checkout process, you will be able to mark the shipment as "ready for pickup". On the *View shipment details* page, this button looks as follows: ![Shipment details](_static/shipping-management/ready-for-pickup.jpg) ## Shipping settings To set up shipping, visit the [Configure shipping](xref:en/getting-started/configure-shipping/index) section. ## See also * [Orders](xref:en/running-your-store/order-management/orders) * [Adding products](xref:en/running-your-store/catalog/products/add-products) --- # Request for Quote (RFQ) & Quote Support ## Overview This functionality is implemented as a standalone plugin that allows customers to submit a **Request for Quote (RFQ)** for products in their shopping cart. It is particularly useful for negotiating bulk discounts or special pricing that is not otherwise available on the site. In response, site administrators can create and send a formal **Quote** to the customer, outlining a special offer. ## Setup & Configuration The plugin's configuration is straightforward: - **Activation**: The entire feature can be enabled or disabled with a single setting. ![Image](_static/rfq/configure.png) - **Access Control**: Access Control List (ACL) permissions can be configured separately for the public-facing storefront and the admin panel to control who can use the feature. ![Image](_static/rfq/acl.png) ## Usage ### Customer Workflow 1. **Initiating an RFQ**: If the plugin is active and permitted by ACLs, a new button appears on the shopping cart page. ![Image](_static/rfq/sc_request.png) Clicking it takes the user to the RFQ creation form. ![Image](_static/rfq/sc_request_form.png) 1. **Editing the RFQ**: On this form, the user can adjust the request before submitting it. The RFQ is not saved to the database until it is sent. - Add comments to the request. - Propose a custom quantity and price per unit for each item. - The user can return to the cart by clicking **"Back to shopping cart"**. 1. **Submitting the RFQ**: Once the user clicks **"Send request"**, the RFQ is submitted and can no longer be edited by the user. The only available actions are to cancel or delete it. ![Image](_static/rfq/sc_request_form_create.png) 1. **Managing RFQs and Quotes**: After submitting a request, two new menu items appear in the user's account section: - **"Requests for quote"**: A list of all submitted RFQs. ![Image](_static/rfq/sc_request_list.png) - **"Quotes"**: A list of all offers received from the store administrator. The user receives an email notification when a new quote is sent. ![Image](_static/rfq/customer_q_list.png) 1. **Creating an Order from a Quote**: If a received quote is acceptable and not expired, the user can click **"Create the order"**. ![Image](_static/rfq/customer_q_create_order.png) This action performs the following: - The user's current shopping cart is cleared. - A new cart is created containing the exact items and prices from the quote. - The user proceeds to the standard checkout process. 1. **Quote Mode Limitations**: - Once a cart has been generated from a quote, it is considered in "quote mode". - The user cannot add any other items to the cart or modify the items from the quote. Attempting to do so will cancel the quote mode and empty the cart. - The user can click **"Exit quote mode"** to clear the cart and return to the main store page. ![Image](_static/rfq/sc_by_q.png) ### Administrator Workflow 1. **Notification and Management**: When a user submits an RFQ, the store owner receives an email notification. Two new menu items appear in the admin panel for managing RFQs and Quotes, leading to their respective lists. ![Image](_static/rfq/admin_rfq.png) 1. **Reviewing an RFQ**: From the RFQ list, an admin can view the details of a user's request. On the edit page, the admin can: - Modify any product line item. - Delete an item from the request. - Cancel or delete the entire RFQ. ![Image](_static/rfq/admin_rfq_edit.png) 1. **Creating a Quote**: - **From an RFQ**: The admin can directly convert an RFQ into a quote by clicking the **"Create the quote"** button on the RFQ detail page. ![Image](_static/rfq/admin_rfq_create_q.png) - **From Scratch**: A new quote can also be created independently from the main quotes list page. 1. **Editing a Quote**: On the quote editing page, the admin can: - Modify existing product data. - Add new products via a two-step process: - first search for the product; ![Image](_static/rfq/admin_create_q.png) - then set the desired quantity and price; ![Image](_static/rfq/admin_create_q_product.png) - Set an expiration date for the offer. After this date, the user can no longer create an order from it. 1. **Sending a Quote**: The quote is saved in the database but remains hidden from the user until the admin clicks **"Send quote"**. Upon sending, the user receives an email notification. 1. **Post-Submission Rules**: - Once a quote has been sent to the user, it can no longer be edited by the administrator. - A sent quote can only be deleted if the user has not yet created an order from it. --- # Return requests The return request feature enables customers to request a return on items previously purchased. These are also known as RMA requests. This option is only available for completed orders. Return requests settings are managed in **Configuration → Settings → Order settings** in the *Return request settings* panel. To enable return requests, select the **Enable returns system** checkbox. When this option is enabled, a **Return item(s)** button is displayed for completed orders on the order details page in the public store. To proceed to the [return request settings section, click here](#return-request-settings). In the next sections, we will describe how the return request functionality can be used by your customers and how to manage return requests in the admin area. ## Submit a return request To submit a return request, a customer should take the following steps: 1. In the public store, go to the *My account* window and click **Orders**. The following page will be displayed: ![My account - Orders](_static/return-requests/my-account-orders.jpg) 1. Click the **Return Item(s)** button beside the completed order to be returned. The *Return item(s) from order #* window will be displayed as shown in the following example: ![Return items](_static/return-requests/return-items.jpg) * The **Qty to return** dropdown list allows selecting the number of items to be returned. * The **Return reason** dropdown list allows selecting the reason for requesting a return. For example, the wrong product ordered, wrong product received, and more. Read [below](#return-request-settings) about how to manage return reasons. * The **Return action** dropdown list allows selecting the required return action to take. For example, repair a product, replace a product, issue credit, and more. Read [below](#return-request-settings) about how to manage return actions. * Use the **Upload a file** option if you want to attach some additional documents or pictures to your request. > [!NOTE] > > This option is only available when the **Allow file uploads** checkbox is selected. Read [below](#return-request-settings) about how to set this up. * In the **Comments** field, a customer can enter an optional comment for information purposes. 1. After using the return request feature, the customer can see the created return requests and their statuses on the *My Account* page in the public store by clicking **Return requests**: ![Return requests public](_static/return-requests/return-requests.jpg) ## Manage return requests The store owner can now manage this return request in the administration area. To view and edit return requests, go to **Sales → Return requests**. All return requests will be displayed as follows: ![Return requests admin](_static/return-requests/return-requests-admin.jpg) Click **Edit** beside the return request; the *Edit return request details* window will be displayed: ![Edit return request](_static/return-requests/edit-return-request.jpg) The store administrator is allowed to: * View the return request **ID**. * View the **Order #**. Clicking the order number redirects to the associated order details page. * View the **Customer**. Clicking the customer email redirects to the associated customer details page. * View the **Product**. Clicking the product name redirects to the associated product details page. * Enter the **Quantity** of the returned product. * Fill the **Quantity returned to stock** field. It represents the number of items that should be returned to stock. * Select the **Return request status**: * *Pending* * *Received* * *Return authorized* * *Item(s) repaired* * *Item(s) refunded* * *Request rejected* * *Cancelled* * In the **Reason for return** field, edit the reason for return if necessary. * In the **Requested action** field, edit the requested action if necessary. * In the **Customer comments** field, edit the comment entered by the customer if necessary. * In the **Staff notes** field, enter an optional note for information purposes. These notes will not be displayed to a customer. * View the **Date** when the return request was submitted. > [!NOTE] > > Click the **Notify customer about status change** button to send an email to the customer informing them on the return request status change. ![Control buttons](_static/return-requests/control-elements.png) ## Return request settings To define the return request settings, go to **Configuration → Settings → Order settings**. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). Go to the *Return request settings* panel: ![Return request settings](_static/return-requests/return-request-settings.jpg) In this panel, you can define: * **Enable returns system** to enable your customers to submit return requests for purchased items. * In the **Return request number mask** field, specify a custom return request number if needed. * **Number of days that the return request is available** to set the number of days that the return request link will be available in the customer area. > [!TIP] > > For example, if the store owner allows returns within 30 days after the purchase, this field will be set to 30. When the customer logs into the website and looks at "My account," orders completed earlier than 30 days ago will have no **Return item(s)** button. * Select the **Allow file uploads** checkbox if you want to allow uploading files (pictures, for example) when submitting a return request. This option is especially useful for customers who face some problems with their orders, such as receiving damaged items or wrong products. ### Return request reasons This panel represents a list of reasons a customer can choose from when submitting a return request. ![Return request reasons](_static/return-requests/return-request-reasons.jpg) Click **Add new** to add a new request reason. The *Add new return request reason* window will be displayed as follows: ![Add a return request reason](_static/return-requests/add-reason.jpg) Enter the return request reason **Name** and **Display order** number (1 represents the first item in the list). Click **Save** to save the changes. ### Return request actions This panel represents a list of actions a customer can choose from when submitting a return request. ![Return request actions](_static/return-requests/return-request-actions.jpg) Click **Add new** to add a new request action. The *Add new return request action* window will be displayed as follows: ![Add a return request action](_static/return-requests/add-action.jpg) Enter the return request action **Name** and **Display order** number (1 represents the first item in the list). Click **Save** to save the changes. ## See also * [YouTube tutorial: managing return requests](https://www.youtube.com/watch?v=VqF2GZ2ip_0&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4&index=17) * [Order settings](xref:en/running-your-store/order-management/order-settings) * [Orders](xref:en/running-your-store/order-management/orders) --- # Shopping carts and wishlists The "Shopping carts and wishlists" section enables store owners to view all the existing shopping carts and wishlists of all the customers in all stores on one page. To access this page, go to **Sales → Shopping carts and wishlists**. ![Shopping carts and wishlists](_static/shopping-carts-and-wishlists/list.jpg) In the *Search* area at the top of the page, select the desired **Shopping cart type**: *Shopping cart* or *Wishlist*. You can expand the products by clicking the following icon in the first column: ![Expand](_static/shopping-carts-and-wishlists/icon.jpg). From the list, you can proceed to the customer details page by clicking the customer link. You can also visit the edit product details page by clicking the name of the product or delete the product from the cart by clicking the **Delete** button. ## Shopping cart Select the *Shopping cart* from the **Shopping cart type** dropdown list on the **Sales → Shopping carts and wishlists** and click **Search** to view the shopping cart list. This list contains all products that were placed in carts but not purchased. The following screenshot shows how a customer sees a shopping cart page in the public store: ![Shopping carts public](_static/shopping-carts-and-wishlists/shopping-cart-public.jpg) There are a few elements on the shopping cart page. Some of them can be disabled if needed: 1. The button in the **Remove** column allows removing an item from the shopping cart. 1. The button in the **Qty.** column allows a customer to change a product's quantity by entering the appropriate number in the **Qty** field. 1. The **Continue shopping** button allows a customer to proceed to the catalog. 1. The **Estimate shipping** button allows a customer to estimate shipping. After clicking this button, the following pop-up window will be displayed: ![Estimate shipping](_static/shopping-carts-and-wishlists/estimate-shipping.jpg) In this window, the customer can enter the shipping address and see the appropriate shipping options. You can disable shipping estimation on the shopping cart page by clearing the **Estimate shipping enabled (cart page)** checkbox on the **Configuration → Settings → Shipping settings** page. 1. You can see the **Gift wrapping** dropdown on the shopping cart screenshot provided above. This is a checkout attribute. Read more about how to manage checkout attributes in the [Checkout attributes](xref:en/running-your-store/order-management/checkout-attributes) chapter. 1. The **Discount code** section allows a customer to enter a discount code. You can disable this by clearing the **Show discount box** checkbox on the **Configuration → Settings → Shopping cart settings** page. Read more about discounts in the [Discounts](xref:en/running-your-store/promotional-tools/discounts) chapter. 1. The **Gift cards** section allows a customer to use a gift card. You can disable this by clearing the **Show gift card box** checkbox on the **Configuration → Settings → Shopping cart settings** page. Read more about gift cards in the [Gift cards](xref:en/running-your-store/promotional-tools/gift-cards) chapter. 1. In the shopping cart totals section, a customer sees the shipping fee. Read about how to set up shipping in the [Configure shipping](xref:en/getting-started/configure-shipping/index) section. 1. In the same section, a customer sees the tax info. Read about how to set up taxes in the [Configure taxes](xref:en/getting-started/configure-taxes/index) section. 1. In the same section, a customer sees how many reward points will be earned. Read about how to set up reward points in the [Reward points](xref:en/running-your-store/promotional-tools/reward-points) section. 1. In the same section, a customer sees terms of service. You can disable this by clearing the **Terms of service (shopping cart page)** checkbox on the **Configuration → Settings → Order settings** page. > [!NOTE] > > In case you don't want to allow customers to add a certain product to shopping cart, select the **Disable buy button** checkbox in the *Prices* panel of the product edit page. Read more about adding a product in the [Add products](xref:en/running-your-store/catalog/products/add-products) chapter. > > [!NOTE] > > Check out our [marketplace](http://www.nopcommerce.com/marketplace) for plugins that help you manage abandoned carts and recover lost sales. ## Wishlist Select the *Wishlist* option from the **Shopping cart type** dropdown list on the **Sales → Shopping carts and wishlists** page and click **Search** to view the wishlists. A wishlist is a list of products that a customer can share with friends or save to transfer to the cart later. If adding to wishlist is enabled for a product, the **Add to wishlist** button appears on the product details page in the public store. When a product of different variants is added to a wishlist, all variants chosen by the customer will be included in the wishlist. > [!TIP] > > For example, if a customer adds the same shirt in 2 different colors, each shirt will appear as a separate item in the wishlist. In the case a customer adds the same product to the wishlist multiple times, the product only appears once but with an updated quantity that reflects the number of times it was added. The following screenshot illustrates how a customer sees the wishlist page in the public store: ![Wishlist public](_static/shopping-carts-and-wishlists/wishlist-public.jpg) There are a few elements on the wishlist page: 1. The button in the **Remove** column allows removing an item from the wishlist. 1. The **Update wishlist** button allows a customer to change a product's quantity by entering the appropriate number in the **Qty** field. 1. The **Add to cart** button allows a customer to add the selected products to the cart. 1. The **Email a friend** button allows a customer to send the wishlist to a friend via email. You can disable this by clearing the **Allow customers to email their wishlists** checkbox on the **Configuration → Settings → Shopping cart settings** page. 1. **Your wishlist URL for sharing** allows a customer to share the wishlist. > [!NOTE] > > In case you don't want to allow a customer to add a certain product to wishlist, select the **Disable wishlist button** checkbox in the *Prices* panel of the product edit page. Read more about adding a product in the [Add products](xref:en/running-your-store/catalog/products/add-products) chapter. ### Multiple wishlist Registered customers can create and manage multiple wishlists, allowing for better organization of desired products. By default, each customer has a "Wishlist" which cannot be renamed or deleted. Core concepts: - **Default Wishlist:** Every registered customer has one default wishlist named "Wishlist". This list is permanent and cannot be altered or removed. - **Custom Wishlist:** Registered users can create additional, personalized wishlists. These can be named, managed, and deleted by the user. User scenarios: 1. Viewing Wishlists ![Viewing Wishlists](_static/shopping-carts-and-wishlists/viewing-wishlists.png) - Upon navigating to the main Wishlist page, the products contained within the default "Wishlist" are displayed. - A list of all created custom wishlists is also visible on this page. - Selecting a custom wishlist will update the view to display only the products contained within that specific list. 1. Creating a Custom Wishlist ![image](_static/shopping-carts-and-wishlists/add-custom-wishlist.png) - Only registered users have the ability to create new wishlists. - On the main Wishlist page, an option to "Create New Wishlist" is available. - Users can provide a custom name for their new wishlist. 1. Deleting a Custom Wishlist ![image](_static/shopping-carts-and-wishlists/delete-custom-wishlist.png) - When viewing the contents of a custom wishlist, a "Delete" button will be present. - A confirmation prompt will be displayed to the user before the wishlist is permanently deleted. > [!NOTE] > The default "Wishlist" cannot be deleted. 1. Adding Products to a Wishlist The process for adding products to a wishlist (e.g., by clicking a 'heart' icon on a product or catalog page) differs based on whether the user has created custom wishlists. **Scenario 1: No Custom Wishlists Exist** - When a user adds a product to their wishlist, it is automatically added to the default "Wishlist". **Scenario 2: At Least One Custom Wishlist Exists** ![image](_static/shopping-carts-and-wishlists/add-to-list.png) - The product is still immediately added to the default "Wishlist". - Following the addition, a notification will appear, confirming the product has been added. This notification will contain a link, such as "Move it to a custom wishlist". - Clicking this link opens a pop-up window where the user can: - Select an existing custom wishlist to move the product to. - Choose to create a new wishlist, which will then contain the product. - After selecting a destination, the user can be redirected to the chosen wishlist or continue shopping. 1. Moving Products Between Wishlists ![image](_static/shopping-carts-and-wishlists/move-to-list.png) - This functionality is available only when a user has created at least one custom wishlist. - On the Wishlist page, each product item will feature a dropdown menu. - This menu lists all available wishlists (including the default "Wishlist"). - Selecting a wishlist from the dropdown will move the product from its current list to the selected one. ## Shopping cart and wishlist settings To change the shopping cart and wishlist settings, go to the **Configuration → Settings → Shopping cart settings** page. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ### Common settings In the *Common* panel, you can define: ![Common](_static/shopping-carts-and-wishlists/common.png) - **Show discount box** displaying the discount coupon box on the shopping cart page. - **Show gift card box** displaying the gift card box on the shopping cart page. - **Allow cart item editing** to enable customers to edit items in the cart. This feature is useful when products have values entered by customers. - **Maximum shopping cart items** — the maximum number of products allowed to be added to the shopping cart. - Select the **Carts shared between stores** checkbox to share shopping carts (and wishlists) between stores. - **Show product images on cart** to display product images in the store shopping carts. - **Display cart after adding a product** to the display the shopping cart page immediately after a product is added to the cart. When this checkbox is clear, the customer will remain on the page where the product was added to the cart. - **Number of cross-sells** that you want to display on the checkout page of the shopping cart in the public store. Enter 0 if you do not want to display cross-sells. ### Mini shopping cart settings In the *Mini shopping cart* panel, you can define: ![mini-shopping-cart](_static/shopping-carts-and-wishlists/mini-shopping-cart.png) - **Show mini-shopping cart** – a dropdown menu that appears at the top right corner of the main window, when hovering over the "Shopping cart" link as shown below: ![Cart](_static/shopping-carts-and-wishlists/cart.png) When this field is selected, the following fields will be displayed: - **Number of products in mini-shopping cart** — the maximum number of products displayed in the mini shopping cart dropdown menu in the public store. - **Show product images in mini shopping cart** to determine whether images are displayed in the mini shopping cart dropdown menu. ### Wishlist settings In the *Wishlist* panel, you can define: ![Wishlist](_static/shopping-carts-and-wishlists/wishlist.png) - **Maximum wishlist items** — the maximum number of different products allowed to be added to the wishlist. - **Show product images on wishlist** to display product images in customers' wishlists. - **Allow customers to email their wishlist** to friends. When this field is enabled, the following field will be displayed: - **Allow guests to email their wishlist** to friends. - **Allow multiple wishlists** specifies whether customers can use multiple wishlists. - **Maximum number of custom wishlists** indicates the number of custom wishlists a customer can use. - **Allow 'out of stock' items to be added to the wishlist**. - Select the **Move items from wishlist to cart** checkbox to move products from wishlist to the cart when clicking the "Add to cart" button. Otherwise, they are copied. - **Display wishlist after adding a product** to display the wishlist page immediately after a product is added to the wishlist. When this checkbox is clear, the customer will remain on the page, where the product was added to the wishlist. ## See also - [Orders](xref:en/running-your-store/order-management/orders) - [Promotional tools](xref:en/running-your-store/promotional-tools/index) ## Tutorials - [Overview of wishlists in nopCommerce](https://www.youtube.com/watch?v=9EN7oZSwIVE) --- # Inventory management Inventory management is a system of stock level control. In nopCommerce, it consists of setting up the inventory and tracking low stocks. To set up inventory, go to **Catalog → Products → Edit a product**. In the *Edit product details* window, go to the *Inventory* panel. In this panel, you can choose one of the three inventory methods: 1. [Don't track inventory](#dont-track-inventory) 1. [Track inventory](#track-inventory) 1. [Track inventory by product attributes](#track-inventory-by-product-attributes) In the next sections, we will see the difference between these methods. ## Don't track inventory Some products might not require inventory tracking. For example, services, second hand or custom-made goods. In this case, a store owner can opt for no tracking by choosing the *Don't track inventory* option in the **Inventory method** field. ![Don't track inventory](_static/inventory-management/inventory.png) In this case, the store owner can define: - **Warehouse** that will be used when calculating shipping rates. Read more in the [Warehouses](xref:en/getting-started/configure-shipping/advanced-configuration/warehouses) chapter. - **Minimum cart qty** is a quantity allowed in a customer's shopping cart, for example, set to 3 to only allow customers to purchase 3 or more items of this product. - **Maximum cart qty** is a quantity allowed in a customer's shopping cart, for example, set to 5 to only allow customers to purchase 5 or fewer items of this product. - In the **Allowed quantities** field, enter a comma-separated list of quantities you want this product to be restricted to. Instead of a quantity textbox that allows them to enter any quantity, they will receive a dropdown list of the values you enter here. - Select the **Not returnable** checkbox if this product is not returnable. In this case, a customer won't be allowed to submit a return request. ## Track inventory In case inventory tracking is required, the shop owner can select an **Inventory method** between two options: *Track inventory* (by product) or *Track inventory by product attributes*. The *Track inventory* option is for those who don't have product variants and simply need to know how many items are left. In this section, we will describe the *Track inventory* option. Once this option is chosen, the section expands, displaying new fields: ![Track inventory](_static/inventory-management/track-inventory.jpg) Set up inventory as follows: - **Stock quantity** is the total quantity. It is reduced whenever an order is shipped. - Choose the **Warehouse** that will be used when calculating shipping rates. You can manage warehouses on the **Configuration → Shipping → Warehouses** page. For further details, refer to the [Warehouses](xref:en/getting-started/configure-shipping/advanced-configuration/warehouses) page. - Select the **Multiple warehouses** checkbox if you want to support shipping and inventory management from multiple warehouses. This way, you can manage inventory per warehouse: ![Multiple warehouses](_static/inventory-management/multiple-warehouses.jpg) Click **Use** in the appropriate row if you want to use this warehouse for the product. - Enter the **Stock qty**, which is the total quantity. It is reduced whenever an order is shipped. - Enter the **Reserved qty**, which is the product quantity that is ordered but not shipped or added to a shipment yet. - The **Planned qty** is the product quantity that is ordered and already added to a shipment but not shipped yet. - To prevent customers from placing orders and then finding out that the product is out of stock, you can take certain actions. Select the **Display availability** checkbox to display stock availability in the public store. - If required, select the **Display stock quantity** checkbox to enable customers to see a product stock quantity on the product details page (this checkbox is only displayed when the **Display availability** checkbox is selected). The following screenshot demonstrates what a customer will see in the public store: ![Availability](_static/inventory-management/stock-quantity.png) - In the **Minimum stock qty** field, enter the minimum value below which further actions will be taken. - From the **Low stock activity** dropdown list, select the action to be taken when the stock quantity falls below the minimum stock quantity value, as follows: - **Nothing**: store owners can still choose to take no action. It means that customers can continue to order products. - **Disable buy button**: the buy button becomes disabled when stock is low. Therefore, customers cannot buy this product but can still see it existing in the store. - **Unpublish**: the product is not visible in the store anymore. Used when the product is going to be stopped entirely. - In the **Notify for qty below** field, enter the value below which a notification email will be sent to the administrator. - Store owners can set up **Backorders**, that is, orders that can not be fulfilled at the moment of purchase. From the backorders dropdown list, select the required backorder mode as follows: - **No backorders**: customers can't purchase this product when there is no stock available. - **Allow qty below 0**: customers can purchase this product even when there is no stock available. - **Allow qty below 0 and notify customer**: customers can purchase this product even when there is no stock available. In addition, they get a notification with the following message: *Out of stock - on backorder and will be dispatched once in stock (**Display availability** option should also be enabled in this case)*. - Select **Allow back in stock subscriptions**, to enable customers to subscribe for notifications about product availability, as on the screenshot below: ![Subscribe](_static/inventory-management/stock-subscription.png) - Choose the **Product availability range** that will be displayed for customers when the product is not available at the moment. You can set up availability ranges in the *Product availability ranges* panel of the **Configuration → Shipping → Dates and ranges** page. For further details, refer to the [Dates and ranges](xref:en/getting-started/configure-shipping/advanced-configuration/dates-and-ranges) page. - **Minimum cart qty** is a quantity allowed in a customer's shopping cart, for example, set to 3 to only allow customers to purchase 3 or more items of this product. - **Maximum cart qty** is a quantity allowed in a customer's shopping cart, for example, set to 5 to only allow customers to purchase 5 or fewer items of this product. - In the **Allowed quantities** field, enter a comma-separated list of quantities you want this product to be restricted to. Instead of a quantity textbox that allows them to enter any quantity, they will receive a dropdown list of the values you enter here. - Select the **Not returnable** checkbox if this product is not returnable. In this case, a customer won't be allowed to submit a return request. ## Track inventory by product attributes In the case you have various product attribute combinations and need to track their stock quantity, select the *Track inventory by product attributes* inventory method. Once this option is chosen, the section expands, displaying new fields: ![Track inventory by product attributes](_static/inventory-management/track-inventory-attributes.jpg) - Choose the **Warehouse** that will be used when calculating shipping rates. You can manage warehouses on the **Configuration → Shipping → Warehouses** page. For further details, refer to the [Warehouses](xref:en/getting-started/configure-shipping/advanced-configuration/warehouses) page. - To prevent customers from placing orders and then finding out that the product is out of stock, you can take certain actions. Select the **Display availability** checkbox to display stock availability in the public store. - If required, select the **Display stock quantity** checkbox to enable customers to see a product stock quantity on the product details page (this checkbox is only displayed when the **Display availability** checkbox is selected). The following screenshot demonstrates what a customer will see in the public store: ![Availability](_static/inventory-management/stock-quantity.png) - Choose the **Product availability range** that will be displayed for customers when the product is not available at the moment. You can set up availability ranges in the *Product availability ranges* panel of the **Configuration → Shipping → Dates and ranges** page. For further details, refer to the [Dates and ranges](xref:en/getting-started/configure-shipping/advanced-configuration/dates-and-ranges) page. - **Minimum cart qty** is a quantity allowed in a customer's shopping cart, for example, set to 3 to only allow customers to purchase 3 or more of items this product. - **Maximum cart qty** is a quantity allowed in a customer's shopping cart, for example, set to 5 to only allow customers to purchase 5 or fewer items of this product. - In the **Allowed quantities** field, enter a comma-separated list of quantities you want this product to be restricted to. Instead of a quantity textbox that allows them to enter any quantity, they will receive a dropdown list of the values you enter here. - Select **Allow only existing attribute combinations** to only allow adding to the cart/wishlist existing attribute combinations with stock quantities greater than 0. In this case, you have to create all product attribute combinations that you have in stock. - Select the **Not returnable** checkbox if this product is not returnable. In this case, a customer won't be allowed to submit a return request. > [!NOTE] > > To set **Stock quantity** for different attribute combinations, go to the **Attribute combinations** tab of the *Product attributes* panel on the edit product details page. In this tab, you can define whether to **Allow out of stock** for a certain attribute combination to enable orders to be approved even when the product is out of stock. ![Attribute combinations](_static/inventory-management/atribute-combinations.jpg) > > [!TIP] > > To track products currently under stock, go to **Reports → Low stock**. > A low stock report contains a list of products that are currently under stock, that is, the stock quantity is equal to or less than the minimum stock quantity set in the *Inventory* section on the product details page. ![Low stock](_static/inventory-management/low-stock.png) Click **View** to view the product details page, where these stock settings can be changed. For more details about reports in nopCommerce, visit the [Reports](xref:en/running-your-store/reports) page. ## See also - [Product attributes](xref:en/running-your-store/catalog/products/product-attributes) - [Warehouses](xref:en/getting-started/configure-shipping/advanced-configuration/warehouses) ## Tutorials - [Managing backorders in nopCommerce](https://www.youtube.com/watch?v=CMhQ39clCKM) --- # Checkout attributes Checkout attributes represent additional order information that is gathered during the final stage of the shopping process. > [!TIP] > > Using the checkout attributes, shop owners can specify, for example, whether a bought product requires gift wrapping or careful handling, as in the case of fragile goods. Checkout attributes are displayed on the shopping cart page and enable users to select them, if required, before the checkout. To set up or edit checkout attributes, go to **Catalog → Attributes → Checkout attributes**. ![Checkout attributes](_static/checkout-attributes/list.jpg) You can select checkout attributes and click the **Delete (selected)** button to delete them. ## Add a new checkout attribute To create a new checkout attribute, click **Add new**. The *Add a new checkout attribute* window will be displayed as follows: ![Add a new checkout attributes](_static/checkout-attributes/add-new.jpg) This page is available in two modes: **advanced** and **basic**. Switch to the basic mode, which only displays the main fields, or use the advanced mode displaying all the available fields. In the *Attribute info* panel, define the following information: - **Name** — the attribute name. - **Text prompt** — a question or a comment that will be displayed in the checkout area on the shopping cart page. - From the **Control type** dropdown list, select the required method for displaying the attribute value, such as *Dropdown list*, *Radio button list*, *Checkboxes*, *Textbox*. > [!NOTE] > > Dropdown lists, radio lists, checkboxes and color squares require the store owner to define values (such as Green, Blue, Red, and more). *Textbox* and *Date picker* control types do not require the store owner to define values since customers will be requested to fill these textbox fields. In addition, for some control types, you can specify validation rules. For example, for the *Textbox* attribute, you can define the **Minimum length**, **Maximum length**, and **Default value**. For the *File upload* attribute, you can define the **Allowed file extension** and **Maximum file size (KB)**. - Select the **Required** checkbox if selecting an attribute value is required before completing the purchasing process. - **Display order** — display order number of the checkout attribute. - Select the **Shippable product required** checkbox in case this attribute should only be displayed for the product that needs to be shipped. - Selected **Tax exempt** checkbox indicates that no tax will be applied to this checkout attribute. - In the case a tax is applied, from the **Tax category** dropdown list, select the checkout attribute tax category. - **Limited to stores** enables you to limit the attribute to one or more stores. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save and continue edit** to proceed to the *Attribute values* panel (if applicable). ### Add a new checkout attribute value In the *Attribute values* panel, click **Add a new checkout attribute value** to create a new attribute value. ![Add a new checkout attribute value](_static/checkout-attributes/value.jpg) In the *Add a new checkout attribute value* window, define the following information: - **Name** — the attribute value name. > [!TIP] > > For example, *Yes* or *No*, for such questions as "Do you require fragile care handling"? - **Price adjustment** will add the entered amount to a total purchase sum in case the attribute value is selected. - **Weight adjustment** will change an order weight by the entered amount in case the attribute value is selected. - Select the **Pre-selected** checkbox to indicate the attribute value is preselected for a customer. - **Display order** — display order number of the attribute value. You can **Edit** and **Delete** attribute values by clicking the corresponding buttons beside the attributes in the *Attribute values* panel. ![attribute_values](_static/checkout-attributes/attribute_values.png) ## Add a condition In the *Condition* panel, a store owner can specify a condition for the checkout attribute to be visible (depending on other attributes). A conditional attribute only appears if the previous attribute is selected. ![condition](_static/checkout-attributes/condition.png) Click **Save**. The new attribute will be displayed on the shopping cart page in the public store. ## Tutorials - [Adding checkout attributes](https://www.youtube.com/watch?v=sJcZP1qjHmY&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4&index=3) - [Overview of conditional checkout attributes](https://www.youtube.com/watch?v=z3UiXgK8Jgo&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4&index=18) --- # Order settings To define order settings, go to **Configuration → Settings → Order settings**. The *Order settings* window will be displayed. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). In this window, you can define the following order settings: ## Checkout Define the following settings in the *Checkout* panel: ![Checkout](_static/order-settings/checkout.jpg) * **Checkout disabled** to disable the checkout process. * **Anonymous checkout allowed** to enable customers to purchase products without registration/logging in. * **Use one page checkout**, which is a single webpage your customers would use to buy a product or a service from you. * **Order totals on payment info tab** to display a product list and order totals in the payment info tab (one-page checkout). * Whether to require customers to accept the **Terms of service** before processing the order (**on the shopping cart page**). * Whether to require customers to accept the **Terms of service** before processing the order (**on the confirm order page**). * **Disable "Billing address" step** during checkout. The billing address will be pre-filled and saved using the default registration data (cannot be used with guest checkout selected). In **Configuration → Settings → Customer settings**, ensure the appropriate address fields that cannot be prefilled are not required (or disabled). * **Disable "Order completed" page** to automatically redirect a customer to the order details page after an order is placed. * **Display "Pickup in store" on "Shipping method" page** or on the shipping address page. ## Order totals Define the following settings in the *Order totals* panel: ![Totals](_static/order-settings/totals.jpg) * **Min order sub-total amount**. Orders below this amount will not be issued. * **Calculate "Min order sub-total amount" including tax**. In this case, an order subtotal will be calculated including tax when validating **Min order sub-total amount field** specified in the previous step. * **Min order total amount**. Orders below this amount will not be issued. * **Auto update order totals** to have the order totals automatically updated on editing an order in the admin area (currently in BETA testing). ## Common Define the following settings in the *Common* panel: ![Common](_static/order-settings/common.jpg) * The **Order ID** counter. This is useful if you want your orders to start with a certain number. This only affects orders created after defining. The value must be greater than the current maximum order ID. * In **Order number mask**, you can create a custom order number. For example, starting with {YYYY} — the year of the order creation date. * **Is re-order allowed** to enable customers to re-order. The re-order mechanism automatically adds all items that were in a previous order to the shopping cart. * **Complete order when delivered** to set order status to "Complete" only when its shipping status is "Delivered." Otherwise, the "Shipped" status will be enough. * **Export orders with products**. * **Allow admins to buy "Call for price" products** to allow administrators (in impersonation mode) to buy products marked as "Call for price." * **Show product thumbnail in order details page** to show product thumbnail in order details page. ## PDF invoice Define the following settings in the *PDF invoice* panel: ![PDF invoice](_static/order-settings/pdf-invoice.jpg) * **To Attach PDF invoice ("order placed" email)**. * **To Attach PDF invoice ("order paid" email)**. * **Attach PDF invoice ("order processing" email)**. * **To Attach PDF invoice ("order completed" email)**. > [!TIP] > > Learn how to set up PDF in the [PDF settings](xref:en/getting-started/advanced-configuration/pdf-settings) chapter. ## Gift cards Define the following settings in the *Gift cards* panel: ![Gift cards](_static/order-settings/gift-cards.jpg) * **Activate gift cards after completing of an order** to activate related gift cards when an order is completed. * **Deactivate gift cards after cancelling of an order** to deactivate related gift cards when an order is canceled. * **Deactivate gift cards after deleting of an order** to deactivate related gift cards when an order is deleted. * **Delete gift card usage history after order cancellation** to delete gift card usage history after an order is canceled. ## Return request settings In the *Return request settings* panel, you can set up return requests. For more details, see the [Return request settings](xref:en/running-your-store/order-management/return-requests#return-request-settings) section. ## See also * [Orders](xref:en/running-your-store/order-management/orders) * [Return requests](xref:en/running-your-store/order-management/return-requests) * [PDF settings](xref:en/getting-started/advanced-configuration/pdf-settings) --- # Customer management Customers in nopCommerce is a broad group that includes all users. This chapter describes how to manage customer profiles, track the activities in the system, and view online users. Learn how to get the most out of the customer management in your nopCommerce store in the following chapters: * [Managing customers](xref:en/running-your-store/customer-management/managing-customers) * [Customer roles](xref:en/running-your-store/customer-management/customer-roles) * [Access control list](xref:en/running-your-store/customer-management/access-control-list) * [Activity log](xref:en/running-your-store/customer-management/activity-log) * [Online customers](xref:en/running-your-store/customer-management/online-customers) * [Customer settings](xref:en/running-your-store/customer-management/customer-settings) --- # Managing customers The customer list contains details of all existing customers and allows adding new ones. The customer list contains details of all existing customers and allows adding new ones. This and other customer management configurations makes nopCommerce an eCommerce platform with built-in [omnichannel feature](https://www.nopCommerce.com/omnichannel-commerce). In nopCommerce, customers include all users, such as administrators, vendors, and buyers. In nopCommerce, customers include all users, such as administrators, vendors, and buyers. To manage customers, go to **Customers → Customers**. The following window will be displayed: ![Customers](_static/managing-customers/customers.png) To search for customers, in the *Customers* window, enter one or more of the following search criteria: - **Email**. - **Username**, if enabled in the [customer settings](xref:en/running-your-store/customer-management/customer-settings). - **First name**. - **Last name**. - **Is active**. Search customers by an account status. - **Date of birth**, if enabled in the [customer settings](xref:en/running-your-store/customer-management/customer-settings). - **Company**, if enabled in the [customer settings](xref:en/running-your-store/customer-management/customer-settings). - **Phone**, if enabled in the [customer settings](xref:en/running-your-store/customer-management/customer-settings). - **Zip code**, if enabled in the [customer settings](xref:en/running-your-store/customer-management/customer-settings). - **IP address**. - **Customer roles** — you can select one or more customer roles to be displayed. - **Registration date from** and **Registration date to** - **Last activity from** and **Last activity to** > [!NOTE] > > You can export the customer data to an external file by clicking **Export to XML (all)** or **Export to Excel (all)**. You can export selected customer data to an external file by clicking **Export to XML (selected)** or **Export to Excel (selected)**. Then click the **Search** button. ## Add a new customer To add a new customer, in the *Customers* window, click **Add new**. The *Add a new customer* window will be displayed. Define the following customer details: ## Customer info The *Customer info* panel allows to enter customers' personal and account information, for example, change a password, assign/remove customer roles. ![Customer details](_static/managing-customers/add-new.png) You can edit the following fields: - **Email** address. - **Password**. - **First name**. - **Last name**. - **Gender**. - **Date of birth**. - **Company name**. - **Is tax exempt** indicates whether the customer is exempted from taxes. - **Customer roles** — one or multiple customer roles. Note that any role that needs to log in to the system (for example, administrator, vendor) should have the "Registered" customer role among others. You can set up customer roles in the [Customer roles](xref:en/running-your-store/customer-management/customer-roles) section. - From the **Manager of vendor** dropdown list, if required, select a vendor associated with this customer account. When associated, this customer will be able to log in to the selected vendor portal and manage its products and orders. Note that if you have a vendor associated with this customer, you should ensure this customer record is in the [Vendors](xref:en/running-your-store/vendor-management) list. - Select the **Active** checkbox to activate the customer. - **Customer must change password** - Check to require the customer to change their password. - **Admin comment** — administrator comments for internal use if required. Click the **Save** button to save the changes or **Save and continue edit** button to proceed for more customer information. In this case, you will see the newly added panels on the customer details page. You will also see the **Send email**, **Send private message** (if [forums](xref:en/running-your-store/content-management/forums) are enabled), and **Delete** buttons. ![Buttons](_static/managing-customers/edit_customer_details.png) After clicking the **Send email** button, the *Send email* window will be displayed, enabling the store owner to send an email to the customer. After clicking the **Send private message** button, the *Send private message* window will be displayed, enabling to send a message to the customer. To use private messaging, allow private messages in [forum settings](xref:en/running-your-store/content-management/forums). ## Orders In the *Orders* panel, you can view the customer's orders' details. ![customer_info](_static/managing-customers/customer-orders.png) ## Addresses In the *Addresses* panel, you can view, edit, and create new addresses of the customer. ![addresses](_static/managing-customers/customert-adresses.png) Click the **Add new address** button to add a new customer address. Fill in the appropriate fields and click **Save**. The new address will be added to the customer. ## Current shopping cart and wishlist In the *Current shopping cart and wishlist* panel, you can view the customer's shopping cart and wishlist. ## Activity log In the *Activity log* panel, you can view the customer's activity log. See how to manage activity types in the [Activity log - Customer activity types](xref:en/running-your-store/customer-management/activity-log#customer-activity-types) section. ## Place order (impersonate) In the *Place order (impersonate)* panel, store owners can create orders for their customers without password information. This is useful for customers who do not want to register or for large sites using CSRs to place orders over the phone. The panel contains the **Place order** button. After clicking this button, you will be redirected to the public store. Select the products the customer wants, add them to the cart exactly as the customer would do in the public store, then use the **Checkout** button to proceed through the usual checkout process, and then click the **Finish session** link at the top of the page to finish this session. ## Back in stock subscriptions In the *Back in stock subscriptions* panel, see the products the customer is subscribed to. ## Reward points In the *Reward points* panel, store owners can add reward points to the customer or view their reward points usage history. This panel is visible when the reward points program is enabled. Refer to the [Reward points](xref:en/running-your-store/promotional-tools/reward-points) section for more information. ### Add (reduce) points ![Reward points](_static/managing-customers/customer-reward-points.png) In this panel: - Enter the number of **Points**. To reduce points, enter a negative value. - In the **Points validity** field, specify the number of days the awarded points will be valid (only for a positive number of points). - Enter a **Message** or comment. - Select the **Activate points immediately** checkbox if you want to enable customers to use reward points right after earning them. If you don't select this checkbox, one more option will appear: - If the previous checkbox is clear, in the **Reward points activation** field, specify the period (number of days/hours) after which reward points will be activated. ## See also - [Customer roles](xref:en/running-your-store/customer-management/customer-roles) - [Vendors](xref:en/running-your-store/vendor-management) ## Tutorials - [Customer management in nopCommerce](https://www.youtube.com/watch?v=DOl-g-NNFEM&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4&index=1) - [Re-assigning a deleted email address](https://www.youtube.com/watch?v=lqmrWJdXZEE&t=1s) - [Overview of impersonation mode](https://www.youtube.com/watch?v=KQi-CDVawJ4) --- # Customer roles The customer roles in nopCommerce enable you to form groups of your web store users. You can create various groups, such as store admins, shoppers, [vendors](xref:en/running-your-store/vendor-management), and others. You can also grant these groups certain rights, such as discounted pricing and other special statuses (such as tax exemption, free shipping, and more) using the [access control list](xref:en/running-your-store/customer-management/access-control-list). To manage customer roles, go to **Customers → Customer roles**. The *Customer roles* window will be displayed as follows: ![Customer roles](_static/customer-roles/customerroles1.png) Click **Add new** to add a new customer role. The *Add a new customer role* window will be displayed: ![Add a new customer role](_static/customer-roles/customerroles2.png) Define the following information: * **Name** of the customer role. * Select **Active** to make this role active. * Select the **Free shipping** checkbox to enable customers with this role to get free shipping on their orders. * Select the **Tax exempt** checkbox to enable customers with this role to make tax-free purchases. * Select the **Override default tax display type** and select one of the tax types from the **Default tax display type** dropdown list: * *Including tax* * *Excluding tax* * Select the **Enable password lifetime** to force customers to change their passwords after a specified time. * **Purchased with product**. Click the **Choose product** button to choose a special product. A customer is added to this customer role once this product is purchased (paid). > [!NOTE] > > In the case of refund or order cancellation, you must manually remove a customer from this role. * **Is system role**. This setting shows whether this role is used in the code. It is predefined and cannot be modified. * **System name** of the customer role. Click **Save**. ## Tutorials * [Overview of customer roles](https://www.youtube.com/watch?v=3vdIDNIYFIQ) * [Recovering back a deleted admin user](https://www.youtube.com/watch?v=D45WkrbaA38) --- # Access control list Access Control List (ACL) restricts or grants users access to certain areas of the site. This list is managed by administrators. Therefore, the user must have administrator rights to be able to access it. The access list has the following characteristics: * Access control list is role-based, that is, manages roles, such as *Global administrators*, *Content managers*, and others. This list of roles can be managed on the **Customers → Customer roles** page. For further details, refer to [Customer roles](xref:en/running-your-store/customer-management/customer-roles). * Access control list appears in the administration area. Make sure a user has to be an administrator in order to access the ACL. * There are some predefined administrator actions. These include *Manage orders*, *Manage customers*, and much more. To manage the access control list, go to **Configuration → Access control list**. The *Access control list* window will be displayed: ![Access control list](_static/access-control-list/acl.png) Click **Edit** and select the required roles beside the *Permission* items. The selected roles will have access to the selected actions accordingly. ![Access control list](_static/access-control-list/acl_edit.png) Click **Save**. > [!TIP] > > Example: We need a role called *Content manager*. The *Content manager* must have access to new products and manufacturers management, editing reviews on the site, blogs, campaigns, and no access to shopping carts. > To do this: > > 1. Create a **Customer role** called *Content manager* on the **Customers → Customer roles** page. > 1. In the access control list, add the desired customer roles for the following permissions: *Access Admin Area, Admin Area. Manage Blog, Admin Area. Manage Campaigns, Admin Area. Manage Forums, Admin Area. Manage News, Admin Area. Manage Newsletter Subscribers, Public Store. Allow Navigation, Public Store. Display Prices*. > 1. Save the changes. --- # Activity log Activity log is used to track user activity in the system. By default, all *activity types* are enabled for tracking in nopCommerce. A store owner can disable them by clearing the relevant checkboxes. Most of the activity types listed are only for the administrator and record actions in the administration area. However, some are for the public store and track actions of shoppers (such as adding to cart/wishlist or placing an order). ## Customer activity types To enable/disable activity types, go to **Customers → Activity types**. ![Activity types](_static/activity-log/activity-type.png) Select the **Is enabled** checkbox beside the activity type you want to be enabled. Then click **Save** in the top right. ## Customer activity log To search for activity logs, go to **Customers → Activity log**. ![Activity log](_static/activity-log/activity-log.jpg) Define the search criteria using one or more of the following fields: - To search by date range, enter the date range in the **Created from** and **Created to** fields. Alternatively, you can click the dropdown calendar and select the required date ranges. - **Activity log type** for customer's activity. - **IP address** to search for a customer by IP address. You can clear a certain activity log item by clicking the **Delete** button beside it or clear the whole log of activities by clicking the **Clear activity log** button in the top right. --- # Online customers The Online customers section enables store owners to view customers that were online within the last 20 minutes. This information is useful for store owners as it shows the last visited page and helps to decide upon actions required to convert visitors into buyers. To access this window, go to **Customers → Online customers**. ![Online customers](_static/online-customers/list.png) The store owner can filter users by **Customer roles**. The *Online customers* window includes the following columns: - **Customer info** — you can view and edit customer information by clicking the link. - **IP Address** — current IP address of the customer - **Location** — IP-address-wise location of the customer. - **Last activity** — date and time the online customer last logged in. - **Last visited page** — the page the customer visited last time. > [!NOTE] > > To see the last visited page, you need to enable the **Store last visited page** setting on the **Configuration → Settings → Customer settings** page (*Account* panel). This page includes GeoLite2 data created by MaxMind available from [http://www.maxmind.com](http://www.maxmind.com) --- # Customer settings Customer settings include enabling customers to upload an avatar, showing customer location, changing name format or joining date, and more. To define customer settings, go to **Configuration → Settings → Customer settings**. The customer settings window will be displayed. This window contains six panels: Common, Password and security, Account, Profile, Customer form fields, and Address form fields. 1. The **Common** panel contains general customer settings. 1. The **Password and security** panel contains fields that can be used to configure security settings and password complexity. 1. The **Account** panel contains fields for setting up a customer account. 1. The **Profile** panel contains fields for configuring the customer profile. 1. The **Customer form fields** panel contains fields that are used on the customer registration page. 1. The **Address form fields** panel contains fields for detailing the customer's address during checkout. ## Common ![common](_static/customer-settings/customersettings1.png) Define the common customer settings as follows: * Select the **Registration method** as follows: * **Standard account creation**: users are enabled to register; no approval is required. * **Email validation is required after registration**: users are enabled to register; however, they must accept the confirmation email sent to them before their account is approved. * **A customer should be approved by administrator**: users are enabled to register; administrator approval is required. * **Registration is disabled**: select this option to disable registration. * Select the **Notify about new customer registration** checkbox to enable the store owner to get an email notification whenever a new customer is registered. * Select the **Require registration for downloadable products** checkbox if customers have to complete registration in order to purchase downloadable products. * Use the **Allow customers to check gift card balance** field to allow customers to check gift card balance. > [!NOTE] > > If the **Allow customers to check gift card balance** field is selected, then the CAPTCHA setting must be enabled in the admin area (**Configuration → Settings → General settings → CAPTCHA panel**). This feature is potentially not safe, and CAPTCHA is needed to prevent and complicate brute force. For more details, refer to the [CAPTCHA settings](xref:en/getting-started/advanced-configuration/security-settings#captcha). * Choose whether to **Allow customers to select time zone** in the public store on the accounts page. Otherwise, the default time zone is used. * Select the **Default store time zone** from the dropdown list. > [!NOTE] > > The current time zone is displayed automatically. * Select the **Allow customers to remove associations** to allow customers to remove external authentication associations. ## Password and security ![password](_static/customer-settings/customersettings2.png) * Set the **Password minimum length, Password maximum length, Password must have at least one lowercase, Password must have at least one uppercase, Password must have at least one non alphanumeric character, Password must have at least one digit** to change password complexity. * **Unduplicated passwords number** is a number of passwords that mustn't be the same as the previous ones. * Select the **Default password format** as follows: * *Clear* * *Hashed* * *Encrypted* > [!NOTE] > > This setting is for storing customers' passwords and will only be applied to newly registered customers. * In **Password lifetime**, enter the number of days for password expiration. > [!NOTE] > > To use the **Password lifetime** feature, don't forget to select **Enable password lifetime** property on the customer role edit page (**Customers → Customer roles**) for those roles that need to change passwords. For more details, refer to [Customer roles](xref:en/running-your-store/customer-management/customer-roles). * In the **Password recovery link. Days valid** field, enter the number of days for the password recovery link. Set it to 0 if you don't want the link to expire. * Enter the **Maximum login failures** number. Set 0 to disable this feature. * In **Lockout time (login failures)**, enter the number of minutes to lockout users. * Select the **Force entering email twice** checkbox if you want your customers to enter email twice during the registration. * **Force multi-factor authentication**. Force activation of multi-factor authentication for customer roles specified in Access control list (at least one MFA provider must be active). * Select the **'Login by phone' enabled** checkbox to allow customers to sign in to the store with a phone number instead of an email address or a username. ![password](_static/customer-settings/customersettings3.png) > [!IMPORTANT] > > This feature has the following prerequisites, all of them are defined on the same *Customer settings* page: > > * **'Phone number' enabled** and **'Phone number' required** in the *Customer form fields* panel. Otherwise, customers will not be able to specify the number the code is sent to. > * A configured and enabled SMS provider, since the verification code is sent as an SMS message. Read more about it in the [Twilio SMS provider](xref:en/getting-started/advanced-configuration/sms-providers/twilio) chapter. When the **'Login by phone' enabled** checkbox is selected, the following options will be displayed: * **OTP code time to live**: the time (in seconds) during which the one-time password (OTP) code remains valid. Set to 0 if the code should not expire. * **OTP code send attempts**: the maximum number of times a customer can request a new code for the same phone number. * **OTP code verification attempts**: the number of failed attempts allowed for OTP code verification. * **OTP code resend time**: the time (in minutes) that must pass before a customer can request the code again. * **OTP code length**: the number of digits in the generated code. > [!NOTE] > > The verification code is sent by SMS and is valid only once. If the code has expired, the number of attempts to send it is exceeded, or the code is requested again before **OTP code resend time** has passed, the customer is asked to request a new one. * **Phone number validation is enabled**. This setting ensures that numbers entered by customers always follow a consistent format and can be used for verification. ## Account ![Account](_static/customer-settings/account.jpg) * Select the **'Usernames' enabled** checkbox to enable using usernames for login and registration instead of emails. > [!NOTE] > > It is not recommended to change this option in the production environment. When the **'Usernames' enabled** checkbox is selected, the following options will be displayed: * **Allow customers to change their usernames**: select this option if customers are allowed to change their usernames. * **Allow customers to check the availability of usernames**: select this option to allow customers to check the username availability before clicking the *Save* button on the *My account - Customer info* page. The **Check availability** button will be displayed in this case; see the example below. ![Check availability button](_static/customer-settings/check-availability-button.jpg) * Select the **Username validation is enabled** field if you want to enable username validation (when registering or changing on the "My account" page in the public store). When this checkbox is selected, the following options will be displayed: * **Username validation rule**: set the validation rule for a username in this field. You can specify a list of allowed characters or a regular expression. If you use a regular expression, select the **Use regex for username validation** field described below. * Select the **Use regex for username validation** field to use a regular expression for username validation (when registering or changing on the "My account" page in the public store). * Select the **Customer name format** as follows: * *Show emails* * *Show usernames* * *Show full names* * *Show first name* The customer name will be shown in the store next to the customer's news and blog comments, on the forum pages, and more. * Select the **Phone number validation is enabled** checkbox if you want to enable phone number validation (when registering or changing on the "My account" page in the public store). When this checkbox is selected, the following options will be displayed: * **Phone number validation rule**: set the validation rule for a phone number in this field. You can specify a list of allowed characters or a regular expression. If you use a regular expression, select the **Use regex for username validation** field described below. * Select the **Use regex for phone number validation** field to use a regular expression for phone number validation (when registering or changing on the "My account" page in the public store). * **Allow customers to upload avatars**: the customers' avatars will be shown in the store next to their news and blog comments, on the forum pages, and more. If this option is selected, the following checkbox will be displayed: * Select the **Default avatar enabled** checkbox to display the default user avatars. * Select the **Hide 'Downloadable products' tab** checkbox to hide this tab on the "My account" page. * Select the **Hide 'Back in stock subscriptions' tab** checkbox to hide this tab on the "My account" page. * Select the **Hide newsletter box** checkbox if you do not want to display the newsletter subscription box. * Select the **Newsletter box. Allow to unsubscribe** checkbox to display the "unsubscribe" option in the newsletter block. For example, it's required in Germany. * Select the **Store last visited page** checkbox to store the customer's last visited page. You can then view the pages last visited by customers on the **Customers → Online customers** page. You can clear this checkbox to improve the site performance. * Select the **Store IP address** checkbox to store the last IP addresses of customers. When disabled, it can improve performance. ## Profile ![profile](_static/customer-settings/customersettings4.png) * **Allow viewing of customer profiles**: this setting enables to see the details of other customers in the public store. * Select the **Show customers location** checkbox if required. * Select the **Show customers join date** checkbox if required. ## Customer form fields In the *Customer form fields* panel, define whether the following form fields are enabled in the system: ![customerformfields](_static/customer-settings/customersettings5.png) * **'Gender' enabled** * **'Neutral' option enabled**. If this option is enabled, you will be able to specify one of three gender options: - Male, female, neutral (as per German laws). * **'First name' enabled**. When enabled, you can also decide whether this field should be required. * **'Last name' enabled**. When enabled, you can also decide whether this field should be required. * **'Date of Birth' enabled.** When enabled, you can also decide whether this field should be required and enter a minimum allowed age (for example, to ensure that a customer is above 18). * **'Company' enabled.** When enabled, you can also decide whether this field should be required. * **'Street address' enabled.** When enabled, you can also decide whether this field should be required. * **'Street address 2' enabled** if the second street address is enabled. When enabled, you can also decide whether this field should be required. * **'Zip/postal code' enabled**. When enabled, you can also decide whether this field should be required. * **'City' enabled.** When enabled, you can also decide whether this field should be required. * **'County/region' enabled.** When enabled, you can also decide whether this field should be required. * **'Country' enabled.** When enabled, you can also decide whether this field should be required. * **'State/province' enabled.** When enabled, you can also decide whether this field should be required. Note: This field only is visible when the **Country** field is enabled. * **'Phone number' enabled.** When enabled, you can also decide whether this field should be required. * **'Fax number' enabled.** When enabled, you can also decide whether this field should be required. * Select the **'Accept privacy policy' enabled** checkbox to request customers to accept the privacy policy during the registration. * Select the **'Newsletter' enabled** checkbox to offer customers a newsletter subscription during the registration. ### Custom customer attributes If the default form fields are not enough for your requirements, you can manage additional customer attributes using this table. Customer attributes are created in the same manner as checkout attributes. For further details, refer to [Checkout attributes](xref:en/running-your-store/order-management/checkout-attributes). ![Custom customer attributes](_static/customer-settings/customersettings6.png) ## Address form fields In the *Address form fields* panel, a store owner can manage the address form fields available during the registration. You can select which fields are enabled and required among the following: ![Address form fields](_static/customer-settings/customersettings7.png) * **'Company' enabled.** When enabled, you can also decide whether this field should be required. * **'Street address' enabled.** When enabled, you can also decide whether this field should be required. * **'Street address 2' enabled** if the second street address is enabled. When enabled, you can also decide whether this field should be required. * **'Zip/postal code' enabled**. When enabled, you can also decide whether this field should be required. * **'City' enabled.** When enabled, you can also decide whether this field should be required. * **'County/region' enabled.** When enabled, you can also decide whether this field should be required. * **'Country' enabled.** When enabled, you can also decide whether this field should be required. * **'State/province' enabled.** When enabled, you can also decide whether this field should be required. Note: This field is only visible when the **Country** field is enabled. * **'Phone number' enabled.** When enabled, you can also decide whether this field should be required. * **'Fax number' enabled.** When enabled, you can also decide whether this field should be required. ### Custom address attributes > [!NOTE] > > If the default address fields are not enough for your requirements, you can manage additional address attributes using this table. Address attributes are created in the same manner as checkout attributes. For further details, refer to [Checkout Attributes](xref:en/running-your-store/order-management/checkout-attributes). ![Custom address attributes](_static/customer-settings/customersettings8.png) Click **Save** at the top of the page. ## Tutorials * [Configuring password settings](https://www.youtube.com/watch?v=TwWArXNi0CA) --- # Vendor management *Vendors* represent a special category of customers that should be considered separately. nopCommerce has tools for [multi-vendor](https://www.nopcommerce.com/multi-vendor-marketplace) and drop shipping that enable you to sell online without having to keep stocks or ship orders. In this case, each product is assigned to a particular vendor whose details (including email address) are stored. Whenever an order is placed, an email is sent to the vendor of each product in the order. The email includes the products, quantities, and more information if required. The vendor ships the item to the customer on behalf of the merchant, who typically pays each of their vendors at the end of the month. Products from multiple independent vendors appear in the common product catalog, and your website visitors can shop at one web store even if your products are supplied by hundreds of vendors from all over the world. Each vendor can be provided with administrator panel access to manage their products, review sales reports and order details regarding their products. Vendors can't see each other's activities. The money goes to the merchant account of the store administrator, who then manually distributes funds among the vendors according to the order history, which is tracked and managed separately for each provider. In this manner, the customer only sees one charge from the main company. The following procedure describes how to set up and provide a vendor record with access to the vendor portal site. ## Set up a vendor account Go to **Customers → Vendors**. The *Vendors* window will be displayed: ![Vendors](_static/vendor-management/vendor1.png) Click **Add new**. ### Vendor info ![Add vendor](_static/vendor-management/vendor2.png) In the *Vendor info* panel, define the following vendor's details: * **Name** of the vendor. * **Description** for the vendor. * Vendor's **Email**. "Order placed" notifications will be sent to this email. * Select the **Active** checkbox to activate the vendor. * Upload a vendor **Picture**. * **Admin comment** — an optional comment or information for internal use. > [!NOTE] > > Some vendor message templates, such as *OrderPaid.VendorNotification* and *OrderPlaced.VendorNotification*, are disabled by default. See how to change this in the [Message templates](xref:en/running-your-store/content-management/message-templates) section. ### Vendor attributes When you create some additional vendor attributes, the *Vendor attributes* panel will be displayed as well. A store owner is able to create attributes for a vendor, much like for a product. This would allow multi-vendor stores to collect and display more information about a vendor to customers. Learn more about vendor attributes and how to create them in the [Vendor attributes](#vendor-attributes) section below. ### Address (optional) In the *Address (optional)* panel, enter the vendor's address. ![Address (optional)](_static/vendor-management/address.jpg) ### Display In the *Display* panel, define the following display parameters: ![Display](_static/vendor-management/vendor4.png) * **Allow customers to select page size** from a predefined list of options. * If the previous checkbox is selected, define **Page size options** (comma-separated). * If the previous checkbox is clear, enter the **Page size**. * **Display order** of the vendor. ### SEO Refer to the [SEO panels](xref:en/running-your-store/search-engine-optimization#seo-panels) section in order to set up SEO. ![SEO](_static/vendor-management/seo.jpg) ## Assigning a vendor to a customer record This step is optional and only required if you want your vendors to be able to log in to their administration portal and manage their products, orders and/or other data. If you do not want vendors to have access to the admin area, ignore this step to allow the store owner to manage all vendor mappings. Go to **Customers → Customers**. The *Customers* window will be displayed: ![Customers](_static/vendor-management/vendor7.png) Create a new customer or click **Edit** beside a customer record you want to assign a vendor to. For more information about creating a customer, refer to [Add a new customer](xref:en/running-your-store/customer-management/managing-customers#add-a-new-customer). * In the *Customer info* panel, ensure the *Vendors* customer role is selected in the **Customer roles** field. > [!NOTE] > > A vendor customer account cannot belong to the default *Administrators* customer role. * In the *Customer info* panel, find the **Manager of vendor** field. Select the vendor record created previously. ![Edit customer](_static/vendor-management/edit-customer.jpg) After the vendor's customer account is set up, the vendor can use this customer account to manage products, orders, shipments and view reports. The *Administration* link at the top of the public store will be displayed after logging in. > [!TIP] > > [YouTube tutorial: Managing vendors](https://www.youtube.com/watch?v=MH6r6tqfLF8&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4&index=9) ## Vendor settings This section describes how to define the vendor settings of your store. This includes the number of vendors to display, whether or not to show the vendor on the product details pages of the store, and more. Go to **Configuration → Settings → Vendor settings**. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ### Common In the *Common* panel, define the following vendor settings: ![Common](_static/vendor-management/vendorsettings1.png) * **Allow customers to apply for vendor account**. Firstly, a vendor request is filled by a user, thus creating a vendor account. Then, the request is presented to the store owner (via email notification) to be accepted. > [!NOTE] > > A store owner has to add an appropriate customer record to the "Vendors" role manually in order to grant access to the admin area. Read about it in the [Assigning a vendor to a customer record](#assigning-a-vendor-to-a-customer-record) section above. * If the previous checkbox is selected, you can select **Terms of service** to require vendors to accept terms of service during registration. > [!NOTE] > > To edit these terms of service, go to **Content management → Topics (pages)**. Find the **VendorTermsOfService** item and click **Edit**. Read more about it in the [Topics (pages)](xref:en/running-your-store/content-management/topics-pages) section. * **Allow vendors to edit info** allows vendors to provide personal information in the public store. * Choose whether to **Notify about vendor information changes** to notify the admin about vendor information changes. * **Maximum number of products** per vendor. * **Allow vendors to import products** allows vendors to import products. ### Catalog In the *Catalog* panel, define the following vendor settings: ![Catalog](_static/vendor-management/vendorsettings2.png) * **Allow customers to contact vendors** (send emails using contact forms). This functionality is available on a vendor details page in the public store. * **Allow search by vendor** to customers on an advanced search page. * Choose whether to **Show vendor on product details page** (if associated). * Choose whether to **Show vendor name on order details page** (if associated). * **Number of vendors to display** in the vendor navigation block in the public store. ### *Vendor attributes* You can create any number of vendor attributes, such as business name or website. ![Vendor attributes](_static/vendor-management/vendorsettings3.png) #### Add a new attribute Click **Add new** to create a new vendor attribute and its values. The *Add new vendor attribute* window will be displayed as follows: ![Add new](_static/vendor-management/vendorsettings4.png) In the *Attribute info* panel, define the following information: * **Name** — the name of the vendor attribute. * **Required** — when an attribute is required, vendors must choose an appropriate attribute value before they can continue. * From the **Control type** dropdown list, select the required method for displaying the attribute value: *Drop-down list, Radio button list, Checkbox, Textbox, Multiline textbox, Read-only checkbox*. * **Display order** — the vendor attribute display order. > [!NOTE] > > Dropdown lists, radio lists, checkboxes, and read-only checkboxes require the store owner to define values. Textbox and multiline textbox control types do not require the store owner to define values since vendors will be required to fill these textbox fields. Click **Save and continue edit** to proceed to the *Values* panel. #### Add a new attribute value In the *Values* panel, click **Add a new attribute value** to create a new attribute value. ![Add a new attribute values](_static/vendor-management/vendorsettings5.png) In the *Add a new attribute value* window, define the following information: * **Name** — the attribute value name. * Select the **Pre-selected** checkbox to indicate the attribute value is preselected for a customer. * **Display order** — display order number of the attribute value. You can edit and remove attribute values by clicking the corresponding buttons beside the attribute values in the *Values* panel. Click **Save**. The new attribute will be displayed in the *Edit vendor details* page. ## Vendor reviews The catalog on the vendor detail page shows reviews that have been aggregated to calculate the overall rating for each vendor. You'll find the list of reviews on the vendor page, which is created by aggregating reviews of all the vendor's products, sorted by date. ![Vendor reviews](_static/vendor-management/vendor_reviews.png) > [!NOTE] > > The default number of reviews on a vendor reviews page is 6. You can change this value in the *VendorProductReviewsPageSize* setting. ## Allow customers to PM vendors (private messages) Currently customers can contact vendors (`vendorsettings.allowcustomerstocontactvendors` setting). However, it is possible to send private messages to vendors. To do this, you need to select on the vendor details page to which customer the private message will be sent. ![Customer for PM](_static/vendor-management/customer_for_pm.png) You can only choose one customer. ![Vendor private message choose](_static/vendor-management/vendor_pm_choose.png) If the *forumsettings.allowprivatemessages* setting is **true**, then an additional button for sending a private message will appear in the catalog on the vendor page. ![Vendor private message](_static/vendor-management/vendor_pm.png) You can now fill out the form below to send a private message. ![Vendor send private message](_static/vendor-management/vendor_pm_send.png) > [!NOTE] > > Currently, customers can contact suppliers via a contact form. (`vendorsettings.allowcustomerstocontactvendors` setting). --- # Promotional tools nopCommerce allows you to use a lot of promotional tools to market your store. They can help you raise customer awareness of your brand, encourage your partners and vendors to participate in affiliate programs, offer your customers some good deals (like discounts, tier prices), generate sales, and create loyalty to your store. Learn more in the following chapters: - [Discounts](xref:en/running-your-store/promotional-tools/discounts) - [Gift cards](xref:en/running-your-store/promotional-tools/gift-cards) - [Reward points](xref:en/running-your-store/promotional-tools/reward-points) - [Affiliates](xref:en/running-your-store/promotional-tools/affiliates) - [Tier prices](xref:en/running-your-store/promotional-tools/tier-prices) - [Cross-sells and related products](xref:en/running-your-store/promotional-tools/cross-sells-and-related-products) - [Email campaigns](xref:en/running-your-store/promotional-tools/email-campaigns) - [Brevo integration](xref:en/running-your-store/promotional-tools/brevo-integration/index) - [Facebook Pixel](xref:en/running-your-store/promotional-tools/facebook-pixel) - [Omnisend integration](xref:en/running-your-store/promotional-tools/omnisend) - [Reminders](xref:en/running-your-store/promotional-tools/reminders) --- # Discounts In nopCommerce, you can use discounts to enable access to special offers. They can be applied to certain categories, products, the total amount, and more. You can use various requirements available out of the box and via plugins from the [nopCommerce marketplace](http://www.nopcommerce.com/marketplace) for your discounts. Products in nopCommerce can have any number of discounts attached. In the case of several discounts applied, nopCommerce will automatically calculate the best possible price for the customer based on all the available discounts and group memberships. The most common way of using discounts is a coupon code. A coupon code is entered by your customer on the shopping cart page just before checking out. To see the list of discounts, go to the **Promotions → Discounts** page: ![Discounts](_static/discounts/list.jpg) The top area of the page enables you to search for discounts by various search criteria: - **Start date** and **End date** for discounts created between these dates. - **Discount type**. - **Vendor** to search by a specific vendor. - **Coupon code**. - **Discount name** is a full discount name or its fragment. - **Is Active**. > [!NOTE] > > By default, there are no discounts available in nopCommerce, so you can create them from scratch and follow your own marketing strategy. ## Adding a new discount To add a new discount, go to **Promotions → Discounts** and click **Add new**. ![Add a new discount](_static/discounts/add-new.jpg) This page is available in two modes: advanced and basic. Stay in the basic mode, which only displays the main fields, or switch to the advanced mode displaying all the available fields. - Select the **Is active** checkbox if you want to set active this discount. - Enter the **Name** of the discount. - From the **Discount type** dropdown list, assign the discount to the required option as follows: - *Assigned to order total*: these discounts are applied to the entire customer order (order total). - *Assigned to products*: after this discount is created, the store owner can assign it to a product on the product details page or add products in the *Applied to products* panel, which will be displayed below after you save the new discount. - *Assigned to categories*: after this discount is created, the store owner can assign it to a category on the category edit page or add categories in the *Applied to categories* panel, which will be displayed below after you save the new discount. This enables applying the discount to all products in this category. - If selected, the **Apply to subcategories** field will be displayed to allow applying this discount to subcategories. - *Assigned to manufacturers*: after this discount is created, the store owner can assign it to a manufacturer on the manufacturer edit page or add the manufacturer in the *Applied to manufacturer* panel, which will be displayed below after you save the new discount. This enables applying the discount to all products by this manufacturer. - *Assigned to shipping*: these discounts are applied to the shipping fee. - *Assigned to order subtotal*: these discounts are applied to order subtotal values. - Select **Vendor**. You can manage [vendors](xref:en/running-your-store/vendor-management) in **Customers → Vendors**. The only support disocunt type for vendors will be "Assigned to products". No other discount types could be created. Then a vendor will be able to assigned his own products only to this discounts (the "Applied to products" tab). - Select the **Use percentage** checkbox if you want to apply a percentage discount. - If the previous checkbox is selected, the **Discount percentage** field will be displayed. - You can also set the **Maximum discount amount**. Leave this field empty to allow any discount amount. If you're using *Assigned to products* discount type, then it will be applied to each product separately. - You can apply **Discount amount** to the order or SKU if the **Use percentage** checkbox is clear. - Select the **Requires coupon code** checkbox to enable a customer to apply a coupon code to get the discount. - After selecting the checkbox, the **Coupon code** option appears. You can enter the required coupon code in this field. This enables customers to enter the coupon code during checkout to apply the discount. > [!NOTE] > > A customer can apply an unlimited number of coupon codes to an order if they fit it. - If you want to specify the **Start date** and **End date** for your discount, select them in the calendar field in Coordinated Universal Time (UTC). - The **Cumulative with other discounts** option allows customers to use several discounts at the same time. If selected, this discount can be used simultaneously with other ones. > [!NOTE] > > This feature only works for discounts of the same type. Right now, discounts of distinct types are already cumulative. - You can also limit the number of times the discount will be used. From the **Discount limitation** dropdown list, select the required limitation regarding the discount: - *Unlimited*. - *N times only*: select this option and enter the number of times this discount will be available. - *N times per customer*: select this option and enter the number of times this discount will be available for one customer. - In the **Maximum discounted quantity** field (only visible when the **Discount type** is set to *Assigned to products*, *categories* or *manufacturers*), specify the maximum product quantity that can be discounted. It can be used for scenarios like "buy 2 and get 1 for free." - Enter the **Admin comment** if needed. It won't be visible to customers. Click **Save** to save the changes or **Save and continue edit** to proceed to editing other panels. ## Adding discount requirements After creating the discount, it's allowed to add discount requirements if you want some specific rules to be applied to the discount. Set up requirements if you want to limit the discount to certain user categories depending on a customer role, the amount spent or others. You can use a single requirement type or group several types and apply them simultaneously. To add discount requirements, go to the *Requirements* panel: ![Requirements](_static/discounts/requirements.jpg) To add a new requirement, select the **Discount requirement type** from the dropdown list. - There is one requirement type available in nopCommerce out of the box: *Must be assigned to a customer role*. This allows you to configure discounts for certain customer groups (roles). Other requirements are available as plugins on our [marketplace](https://www.nopcommerce.com/en/extensions?searchterm=discount+requirement&category=discounts-promotions). - Also, you can create a group of requirements to deal with complex requirements with multiple rules. Requirement group is a useful feature for creating discount requirement templates. You can create a requirement group just once and then use it whenever you want this limitation to be applied. You can include one requirement group into another if needed. The requirements are set using Boolean logic. For instance, if you want the discount to be assigned to a particular customer role or in case a customer had spent a certain amount. Such requirements and more are available as plugins on our [marketplace](https://www.nopcommerce.com/en/extensions?searchterm=discount+requirement&category=discounts-promotions). ![Group requirements](_static/discounts/discount-requirenents-group.png) You can set an unlimited number of requirement groups, one inside another. For example, more complex case, when you want your customers to get a discount if they are vendors and have spent a certain amount or if they are forum moderators and they put a certain product to the cart at the same time. When customers apply a discount while proceeding to the checkout, it will be displayed as follows: ![discount-in-shopping-cart](_static/discounts/discount-in-shopping-cart.png) ![coupone-code](_static/discounts/coupone-code.png) ## Common type of discounts ### Black Friday sale Black Friday is always the day after Thanksgiving. It's a quite common discount campaign; almost every online store has a Black Friday sale. ![Black Friday](_static/discounts/Black-friday.png) - **Name** — you can enter any name; it's internal only. - **Discount type** — here, it's *Assigned to subtotal* type when a discount is applied to the entire order amount before all the fees are added (like shipping fee and taxes). It's relevant here because we want all the products in the cart to be discounted. - We can apply the discount in % or just enter the amount in chosen currency. We have 10% here. - The **Maximum discount amount** can be limited as well, so even if the total cost of products in the cart is $300, a customer will only have a $10 discount anyway. - This discount will require a **Coupon code**. You can apply discounts without entering coupon codes, but it's not recommended considering marketing purposes. Coupon codes allow you to check campaigns' results. - Discounts are often time-based. Here, we entered Black Friday weekend dates in the **Start date** and **End date** fields. - **Cumulative with other discounts** option allows customers to use several discounts at the same time. - The last setting is for **Discount limitation** usage. For instance, this discount can be applied once per customer. ### Buy one item and get 50% off the second Often, you need to sell more items of a certain product. In this case, to encourage your customers to buy several items, you can offer them a discount. Let's see how to use the discount "Buy one item and get 50% off the second" in your nopCommerce store. ![Edit discount details](_static/discounts/buy_1.png) - The **Discount type** is *Assigned to products*. In the *Applied to products* panel, you can add them; here, it will be an "Oversized T-shirt." - We want our customers to get a 50% discount on the 2nd T-shirt. - This discount can be used once per customer, so the **Maximum discounted quantity** is 1. - You can set up requirements for the product quantity in the *Requirements* panel. Add a requirement type *Customer has all of these products* and add a T-shirt with a quantity 2. This requirement type can be [downloaded as a plugin](https://www.nopcommerce.com/en/has-all-products-discount-requirement-rule). Read about how to install plugins in the [Plugins](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) section. ![Buy one item and get 50% on the second](_static/discounts/buy_2.png) You can use this scenario to set up another popular discount, "Buy one and get the second for free," if you set up a 100% discount. ## See also - More plugins on discount types and discount requirement types on the [nopCommerce marketplace](http://www.nopcommerce.com/marketplace) - How to [install plugins](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) ## Tutorials - [Using discounts in nopCommerce](https://www.youtube.com/watch?v=cAXxnV79dzw&index=7&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) - [Configuring discounts with boolean logic](https://www.youtube.com/watch?v=gBtZG3OcjnQ) --- # Gift cards In nopCommerce, you have an opportunity to sell gift cards among other types of products. Gift cards are a good marketing tool, enabling you to reach more customers and stimulate additional purchases. Gift cards are a highly targeted instrument as the receivers are certainly motivated to use them because it is like a personal proposal to them. ![nopCommerce gift card](_static/gift-cards/gift_main.png) ## Add a new gift card You can create gift card products, defining a product as a gift card by selecting the **Is gift card** checkbox when creating the product in the **Catalog → Products → Add new → Gift card** panel. ![Is gift card](_static/gift-cards/is_gift_card.png) In this panel, you also need to specify the **Gift card type**: *Virtual* or *Physical*. > [!WARNING] > > It is not recommended to change the gift card type in a "live" store. ## Activating a gift card After your customers complete purchases with the gift card products, you can then search and view the list of all the purchased gift cards in **Sales → Gift cards**. ![Gift cards](_static/gift-cards/gift-cards.jpg) To see the gift card details, click the **Edit** button beside it. The *Edit gift card details* window will be displayed: ![Edit gift card](_static/gift-cards/gift-card-edit.jpg) You should select the **Is gift card activated** checkbox to activate the gift card. Then generate the **Coupon code**. > [!NOTE] > > In order to activate a gift card automatically after completing an order, go to the **Configuration → Settings → Order settings** page. Find the *Gift cards* panel and select the **Activate gift cards after completing of an order** checkbox. In this case, the **Coupon code** will be generated automatically as well. > Note that this page has other settings related to gift card activation as well. You can also define the following gift card information: - In **Gift card type**, select whether it's *Virtual* or *Physical*. - Beside the **Order** field, click **View** to view the order in which the gift card was purchased. - In the **Initial value** field, edit the initial value of the card if needed. - The **Remaining amount** field allows to see the remaining amount of this gift card. - The **Is gift card activated** field determines whether this gift card is activated and can be used. - The **Coupon code** field represents the gift card coupon code (used during checkout). - If required, edit the **Recipients name**, **Recipient's email** (if the gift card type is *Virtual*), **Sender's name**, and **Sender's email** (if the gift card type is *Virtual*) in the relevant fields. - Enter an optional message in the **Message** area. - Click **Notify recipient**. An email containing the gift card details will be sent to the recipient. This button is only relevant for virtual gift cards and not physical ones. ## Usage history In the *Usage history* panel, you can see the list of orders for which this gift card coupon was used. After the gift card is activated and the sender receives a coupon code, they can use it during checkout. ![Gift card usage history](_static/gift-cards/gift-usage.jpg) ## Using gift cards A gift card is used in the public store by entering the serial number in the box on the shopping cart page. ![Using gift card](_static/gift-cards/using-geft-cards.jpg) > [!NOTE] > > You can disable the gift card box on the shopping cart page by clearing the **Show gift card box** checkbox on the **Configuration → Settings → Shopping cart settings** page (*Common* panel). You can also allow your customers to check the gift card balance. To do this, select the **Allow customers to check gift card balance** checkbox on the **Configuration → Settings → Shopping cart settings** page (*Common* panel). > [!NOTE] > > This feature requires CAPTCHA to be enabled because it is potentially not safe, and CAPTCHA is needed to prevent and complicate brute force. To activate CAPTCHA, go to the **Configuration → Settings → General settings** page and select the **CAPTCHA enabled** checkbox in the *CAPTCHA* panel. To learn how to set up CAPTCHA, refer to the [Security settings - CAPTCHA](xref:en/getting-started/advanced-configuration/security-settings#captcha) section. ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [YouTube tutorial on managing gift cards](https://www.youtube.com/watch?v=4SJ7uBZGas0&index=4&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) --- # Reward points The "Reward points" functionality enables you to create and implement a loyalty program for improving customer experience and increasing customer loyalty. A "Reward points" program allows customers to earn points for certain actions they take on the site, like registering and making purchases. Reward points can be used as one of the payment methods. This option is displayed in the payment method area of the checkout. Exchangeable reward points can be used together with other payment options, such as credit cards, gift cards, and more. The points can also be canceled if a customer cancels an order or sends a return request. ## Managing reward points To manage the reward points program, go to **Configuration → Settings → Reward points**. This page is available in two modes: *basic* and *advanced*. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). To set up your reward point program, define these settings: ## Common ![Reward points common](_static/reward-points/settings-common.jpg) - Select the **Enabled** checkbox to make the reward points program active. - In the **Exchange rate** field, specify the reward points exchange rate (for example, 1 point = $1). - In the **Minimum reward points to use** field, enter the minimum number of reward points required before customers can use them. Enter 0 if you do not need to define this setting. - If you specify the **Maximum reward points to use per order** field, customers won't be able to use more than X reward points per order. Set to 0 if you do not want to use this setting. - The **Maximum redeemed rate** setting limits the maximum order total that can be paid by reward points (percentage). For example, if set to 0.6, then only 60% of order total can be paid using reward points but not more than the **Maximum reward points to use per order**. Set to 0 if you do not want to use this setting. ## Earning reward points ![Reward points earning](_static/reward-points/settings-earning.jpg) - In the **Points for purchases** field, specify the number of points granted for purchases. - In the **Purchases points validity** field, specify the number of days the points awarded for purchases will be valid. The default value is `45` days. If you specify a value of `0`, then the reward points will expire indefinitely. - In the **Minimum order total** field, specify the minimum order total (excluding shipping cost) to award points for purchases. - In the **Points for registration** field, specify the number of points granted for customer registration. - In the **Registration points validity** field, specify the number of days the points awarded for registration will be valid. - Select the **Activate points immediately** checkbox if you want to enable customers to use reward points right after earning them. If you clear this checkbox, one more option will appear: - In the **Reward points activation** checkbox, specify the period (number of days/hours) after which reward points will be activated. - Select the **Display how much will be earned** checkbox to show your customers how many points will be earned. It will be visible on the checkout page. - Select the **Points accumulated for all stores** checkbox to accumulate all the reward points in one balance for all stores so that they can be used in any store. - In the **Page size** field, set the page size for the history of reward points on the *My account* page Click **Save**. > [!NOTE] > > Reward points are applied to registered users only. When a customer uses reward points during checkout, it looks like this: ![reward_points_checkout](_static/reward-points/reward_will_earn.png) ![reward_points_checkout](_static/reward-points/reward_pints_checkout.png) ## See also - [Managing reward points tutorial](https://www.youtube.com/watch?v=lE4-xDUKkd0&index=14&list=PLnL_aDfmRHwsbhj621A-RFb1KnzeFxYz4) --- # Affiliates Affiliate marketing is an internet-based marketing practice in which affiliates are rewarded for the website traffic generated (each visitor or customer). It is a web-based pay-for-performance program designed to compensate affiliate partners for driving qualified leads or sales from their websites to the merchant's website. Affiliates are third parties who refer customers to your site. The nopCommerce software can track those referrals so that the store administrator can determine the commission to be paid to affiliates. Once a customer is assigned an affiliate ID, every order they place will also be tagged with that ID. In nopCommerce, an affiliate partner link looks as follows: `http://www.yourstore.com/?AffiliateID=N` (where N is an affiliate ID). A store owner can also specify the *friendly URL* name field for marketing purposes: `http://www.yourstore.com/?affiliate=your_friendly_name_here`. This URL is displayed when you visit the affiliate details page. Whenever this hyperlink is clicked on the affiliate site, nopCommerce looks for an affiliate ID query string parameter. ![nopCommerce affiliates](_static/affiliates/affiliates.jpg.png) ## Add a new affiliate To add an affiliate, go to **Promotions → Affiliates** and click **Add new**. ![Add a new affiliate](_static/affiliates/affiliate_new.png) Define the affiliate details: - Select the **Active** checkbox to activate the affiliate. - **First name**. - **Last name**. - **Email**. - **Company** name. - Select the **Country** from the dropdown list. - If the selected country is the USA, specify the **State/province** as well. - **County/region**. - **City**. - **Address 1**. - **Address 2**. - **Zip/postal code**. - **Phone number**. - **Fax number**. - In the **Admin comment** field, you can enter an optional comment or information for internal use. - You can specify the **Friendly URL name**, which is a friendly affiliate URL link for marketing purposes, or you can leave this field empty, then the default URL will be used. By default, affiliate partners have URLs like: `http://www.yourstore.com/?AffiliateID=N` (where N is an affiliate ID). If you click **Save and continue edit**, you will see two more panels where you can check how effective this affiliate is: - The *Affiliated customers* panel shows a list of all affiliated customers. - The *Affiliated orders* panel shows a list of all affiliated orders. When an affiliated customer places an order, you can see the order in this panel. ## See also - [Order management](xref:en/running-your-store/order-management/index) - [Customer management](xref:en/running-your-store/customer-management/index) --- # Tier prices Tier prices are a promotional tool that allows a store owner to offer special prices when customers buy larger amounts of a particular product. This tool is typically used in wholesales, but retailers can apply it as well to incentivize buyers and drive more sales. Tier prices can be applied to a product on the product edit page. Go to **Catalog → Products**, select a product to which you want to add a tier price, and click **Edit**. Find the *Tier prices* panel to add a new tier price: ![Tier prices](_static/tier-prices/tier.png) > [!NOTE] > > You need to save the product before you can add tier prices for the product page. ## Adding tier prices Click the **Add new tier price** button to add a new tier price. The *Add new tier price* window will be displayed: ![Adding tier prices](_static/tier-prices/add-new.jpg) - In the **Quantity** and **Price** fields, define the price applicable to a certain quantity of the product. - In the case you run several stores, from the **Store** dropdown list, select the one in which you plan to apply the tier prices. - From the **Customer role** dropdown list, select the customer role based on which the tier price will be defined, for example, *All* customers, *Registered*, *Guests*. - In the **Start date** and **End date** fields, enter the period of tier prices availability. Leave these fields empty if not applicable. Click **Save**. The *Tier prices* table will be updated with the new data. You can now view the updated product details page in the public store: ![Tier price example](_static/tier-prices/TierPriceExample.jpg) When a customer adds a certain quantity of a product to their cart, the price will automatically change to reflect the discount. ## Tutorials - [Managing tier pricing](https://www.youtube.com/watch?v=ERE08UEDU58&t=10s) --- # Cross-sells and related products "Cross-sells" and "Related products" are marketing tools in nopCommerce that can be used to offer your customers additional products they may like based on their shopping behavior (viewing and adding certain products to the cart). It is also a good opportunity for you to up-sell some products. You can use both these tools simultaneously. You can set up cross-sells and related products when creating or editing a product on the product edit page. Go to **Catalog → Products**, select a product, and click **Edit**. Find the *Cross-sells* and *Related products* panels. > [!NOTE] > > You need to save the product before you can add cross-sells and related products. ## Cross-sells The "cross-sell products" option provides an opportunity to sell additional products that are usually bought with the selected product; however, you can add any product from your catalog, even those not complementary to the product in the cart. Cross-sells are displayed at the bottom of the checkout page. For example, when your customer is buying a CPU, they might need a monitor and something else. You can add an unlimited number of cross-sell products to a product. ![Cross-sells](_static/cross-sells-and-related-products/Cross-sells.png) ### Adding new cross-sells Click **Add new cross-sell product** and choose product(s) from the catalog. You can use the following criteria: **Product name**, **Category**, **Vendor**, **Store**, **Product type**, and **Manufacturer** to find a product easily. ![Adding new cross-sells](_static/cross-sells-and-related-products/add-new-cross-sells.png) After you have chosen a cross-sell product and saved it, you can check how cross-sells will be displayed on the checkout page: ![Cross-sells on the checkout page](_static/cross-sells-and-related-products/Cross-sells_on_checkout.png) ## Related products The Related Products option provides an opportunity to advertise and up-sell other products to your customers together with the chosen one. These products are displayed below the selected product on the product details page. You can add an unlimited number of related products to a product. ![Related_products](_static/cross-sells-and-related-products/Related.png) ### Adding new related products Click **Add new related product** and choose product(s) from the catalog. You can use the following criteria: **Product name**, **Category**, **Vendor**, **Store**, **Product type**, and **Manufacturer** to find a product easily. ![Adding a new related product](_static/cross-sells-and-related-products/adiing-new-related.png) After you have chosen a related product and saved it, you can check how related products will be displayed on the product details page: ![Related products on the product details page](_static/cross-sells-and-related-products/rel-product-on-the-prod-det-page.png) ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [Tier prices](xref:en/running-your-store/promotional-tools/tier-prices) ## Tutorials - [Understanding cross-sells in nopCommerce](https://www.youtube.com/watch?v=J_6OlVarIFc) - [Managing related products](https://www.youtube.com/watch?v=FGuozvhyqYE&t=6s) --- # Email campaigns During registration, a customer can select the *Newsletter* option to receive newsletters from your store. Or it's possible to subscribe to a newsletter later using the form in the footer (in the Default Clean nopCommerce theme). The other way of filling in email subscribers is to import a list of subscribers from an external CSV file to nopCommerce. You can also export the list of subscribers to an external CSV file from nopCommerce. See how to manage newsletter subscribers in the [Newsletter subscribers](#multiple-newsletter-lists) section below. Use your subscribers list to create email campaigns to easily and quickly reach the target audience with no additional marketing activities. Campaigns help to promote trust and loyalty to a company while also increasing sales. There are several examples of email marketing campaigns you can use for your store: start with a welcome email that thanks for the subscription, regularly send out announcements, news regarding your company, coupons for future purchasing, and much more. > [!NOTE] > > There are no campaigns available by default, so you can create them from scratch in order to follow your own marketing strategy. To manage campaigns, go to **Promotions → Campaigns**. ![Manage campaigns](_static/email-campaigns/manage-campaigns.png) ## Add a new email campaign To create a new campaign, click **Add new**. ![Add a campaign](_static/email-campaigns/add_new.png) Define the following campaign details: - Campaign **Name**. - **Subject** of the campaign. - Enter the **Body** text of the email you want to send out. - In **Allowed message tokens**, you can see the list of allowed message tokens you can use in your email campaign. You can see all of them if you click **Show**. - Enter the **Planned date of sending** and time. - From the **Limited to store** dropdown list, select which store's subscribers will get this email. - From the **Limited to customer role** dropdown list, select the roles of subscribers that will receive this email. - From the **Limited to subscription types** dropdown list, choose a subscription type to which this email will be sent. Click **Save** or **Save and continue editing** to proceed to send your campaign. ## Send the campaign After the campaign is saved, you can send it to customers. You will see the new panel at the top of the page: ![Test email](_static/email-campaigns/test.jpg) > [!NOTE] > > Make sure you've tested the campaign before sending it out to multiple customers. First of all, send a test email to check if everything is done properly. To do this, choose the **Email account** that will be used to send the campaign. See how to create an email account in the [Email accounts](xref:en/getting-started/email-accounts) section. Then enter your email address in the **Send test email to** field and click **Send test email**. After you make sure that everything is OK, send your campaign to customers using the **Send mass email** button. ## Multiple Newsletter Lists The **Multiple Newsletter Lists** feature allows store owners to create and manage multiple newsletter subscription options for their customers. Previously, only a single default newsletter was available. With this feature, customers can now choose which newsletters they want to subscribe to, giving them more control over the communications they receive. By default, one newsletter list named **"Newsletter"** is provided. Store owners can create additional lists, such as **"Partner Newsletter"**, **"Special Offers"**, or **"Promo Newsletter"**, and manage them from the admin panel. ### Customer Experience When multiple newsletter lists are configured, customers will see all available lists on: - The **registration page** - The **customer information page** Customers can select the newsletters they wish to subscribe to using checkboxes. ![Customers subscribing](_static/email-campaigns/customer_subs.png) Alternatively, customers can subscribe later using the form in the footer (in the Default Clean nopCommerce theme): ![Newsletter box](_static/email-campaigns/newsletter-box.jpg) ### Managing subscribers On the **Promotions → Newsletter subscribers** page you can search for subscribers using the following fields: ![Newsletter subscribers](_static/email-campaigns/subscribers.png) - **Email** – Enter a subscriber’s email to find them, or leave empty to load all subscribers. - **Start date / End date** – Filter by the subscription date. - **Active** – Choose between *Active*, *Not active*, or *All* subscribers. - **Store** – Select the store. - **Customer roles** – Select a customer role. - **Subscription type** – Select the type of subscription. Click **Search** to apply filters. The function of creating and editing subscriptions is available through the administration panel. ![NewsLetterSubscription](_static/email-campaigns/newsletter_subscription_create.png) You can also manage newsletter subscribers by importing a list from an external CSV file into nopCommerce or exporting subscribers to a CSV file. To export or import newsletter subscribers: - Click **Import from CSV** to import subscriber lists in CSV format. - Click **Export to CSV** to export the existing subscriber list. ### Managing Subscription Types In addition to managing subscribers, store owners can view and edit **subscription types**. This allows full control over what kinds of newsletters are available for customers. - From the admin panel, navigate to **Promotions → Subscription types**. - You can add, edit, or delete subscription types. - These types will be displayed as options to customers when subscribing. **Examples:** Manage existing subscription types: ![NewsLetterSubscription](_static/email-campaigns/newsletter_subscription_types.png) Edit or create subscription type details: ![NewsLetterSubscription](_static/email-campaigns/newsletter_subscription_type_create.png) ### Campaign Management When creating an email campaign, store owners can: - Select a **specific newsletter list** to target - Choose **"all newsletter lists"** to send the campaign to all customers subscribed to at least one newsletter This functionality is fully integrated with email plugins, such as **Brevo**, ensuring seamless campaign delivery. ## Tutorials - [Managing campaigns in nopCommerce](https://youtu.be/iW2m8LQyyWM) --- # Brevo integration ## What Brevo is [Brevo](https://get.brevo.com/5f897rrc6cwa) is an all-in-one digital marketing toolbox capable of taking care of the entirety of your marketing needs. Brevo empowers to build and grow relationships using email campaigns, SMS messages, and sophisticated automation of marketing workflows. The Brevo integration for nopCommerce allows a store owner to: * design clear and professional newsletters * build and target the audience * automate the marketing (for example, abandoned cart recovery) Discover the following chapters and learn how to: * [Set up Brevo plugin](xref:en/running-your-store/promotional-tools/brevo-integration/set-up-brevo-plugin) * [Recover abandoned carts](xref:en/running-your-store/promotional-tools/brevo-integration/recover-abandoned-carts) * [Send an order confirmation email](xref:en/running-your-store/promotional-tools/brevo-integration/send-an-order-confirmation-email) --- # Set up Brevo plugin This section describes how to integrate Brevo into your store. ## Install and enable the plugin The Brevo plugin is an out-of-the-box nopCommerce plugin. You can find it here: **Configuration → Local plugins**. To find the plugin faster, use the **Group** field in the search panel to filter the plugins by *Misc* type: ![Find the plugin](_static/set-up-brevo-plugin/plugin-list.jpg) Install the plugin using the **Install** button if it is uninstalled. Then enable it by clicking the **Edit** button. You will see the *Edit plugin details* window in this case. Mark the plugin as enabled using the **Is enabled** checkbox and click the **Save** button. ## How to configure the plugin 1. Click the **Configure** button. You will see the *Configure - Brevo* window: ![Configure - Brevo](_static/set-up-brevo-plugin/configure-window.jpg) 1. You will need to create a free Brevo account using [this link](https://get.brevo.com/5f897rrc6cwa). 1. Enter your **API v3 key** from your Brevo account on the [SMTP & API](https://account.brevo.com/advanced/api/) page. 1. Click the **Save** button. 1. Once you have done this, you should be able to see your account details. ![After th first save](_static/set-up-brevo-plugin/general-panel.jpg) 1. Go to the **Contacts** panel to synchronize your nopCommerce customers with your Brevo account. ![Contacts](_static/set-up-brevo-plugin/contacts-panel.jpg) * To create a new Brevo list, click the **Create a list** button to be redirected to your Brevo account. * From the dropdown list, select the list where your nopCommerce subscribers and their contact data will be added. Click the **Save** button. ### What data is synced? The following form fields are synced as contact attributes: * EMAIL * FIRSTNAME * LASTNAME * SMS * STORE_ID * USERNAME * PHONE * COUNTRY * GENDER * DATE_OF_BIRTH * COMPANY * ADDRESS_1 * ADDRESS_2 * ZIP_CODE * CITY * COUNTY * STATE * FAX > [!NOTE] > > For the sync, note that these form fields need to be enabled for customers. Go to **Configuration → Settings → Customer settings → Customer form fields**. Order data is synced as transactional attributes: * ORDER_ID: ID of the order * ORDER_PRICE: amount of the order * ORDER_DATE: date of the order > [!NOTE] > > Orders are synced when their payment status is "Paid." ### How often are contacts synced? After the initial sync, a task is scheduled to run every 6000 seconds to automatically add your new subscribers to your Brevo list. Click the **Sync now** button to sync right away. To change the sync frequency, go to **System → Schedule tasks**. ![Schedule tasks](_static/set-up-brevo-plugin/configure-task.jpg) ## Sending transactional emails Go to the **Transactional emails** panel to send your transactional emails via brevo SMTP. ![Sending transactional emails](_static/set-up-brevo-plugin/email-panel.jpg) 1. Select the **Use Brevo SMTP** checkbox. 1. Paste your SMTP password, which can be found in [brevo account page](https://account.brevo.com/advanced/api). 1. From the dropdown list, select the sender you wish to send your emails from. 1. Click the **Save** button. You should then be able to see the email notification list. This lists all the transactional emails (like order confirmation ones) that you send. ![Notification list](_static/set-up-brevo-plugin/email-list.jpg) For each template, you can: * Choose if it is active or inactive. * Choose between the default nopCommerce template and a Brevo template. To do this: 1. Click the **Edit** button 1. From the dropdown, choose your template 1. Click **Update** * Edit its content. > [!NOTE] > > If you *have selected* the **Brevo email template**, then click **Edit template** to edit the content of your template on your Brevo account. If you *haven't selected* the **Brevo email template**, then clicking **Edit template** will redirect you to the message template edit page in the nopCommerce admin area. Read more about the [message template editing process](xref:en/running-your-store/content-management/message-templates). You can also send a test email from that page to check the content. Note that an email credit will be used for each test email. ## Sending SMS Go to the **SMS** panel to send SMS notifications to your customers in addition to emails. ![Sms panel](_static/set-up-brevo-plugin/sms-panel.jpg) 1. Select the **Use SMS notifications** checkbox. 1. Enter an alphanumerical sender (maximum of 11 characters). 1. Type your telephone number. 1. Click the **Save** button. To send an SMS campaign to a Brevo list: ![Sms panel](_static/set-up-brevo-plugin/sma-campaigns.jpg) 1. Go to the **SMS campaigns** block. 1. Choose a **List** of contacts to send the SMS campaign. 1. Enter the name of the sender to the **Send SMS campaign from** field. The number of characters is limited to 11 (alphanumeric format). 1. Specify the SMS campaign content using the **Text** field. The number of characters is limited to 160 for one message. 1. Click **Save campaign**. The plugin is now configured. You can access all your transactional email stats directly from Brevo. ## Setting up Marketing Automation workflows > [!NOTE] > > A customer has to be identified by their email address to trigger a workflow, that is, a customer should be logged in to their account on the nopCommerce store or enter their email address during checkout. Go to the **Marketing Automation** panel to install the marketing automation tracking script to track the activity of shoppers in your store. You will be able to automate your marketing by sending a series of emails or SMS once a visitor has signed up, a prospect has abandoned their cart, a customer has made a purchase or in case of other event. ![Marketing automation](_static/set-up-brevo-plugin/marketing-automation.jpg) 1. Select the **Use Marketing Automation** checkbox. 1. If the *Marketing Automation platform* is enabled on your Brevo account, then the plugin will automatically fill your **Tracker ID**. 1. Paste the tracking script generated by Brevo to the **Tracking script** field. {TRACKING_ID} and {CUSTOMER_EMAIL} will be dynamically replaced. 1. Make sure that the Brevo widget is activated on the **Configuration → Widgets** page. 1. Click the **Save** button. Once Marketing Automation is enabled and functioning properly, you will find the following logs in your Brevo account under *Automation → Logs → Event logs*: * Page * Identify * Track events The plugin will automatically track the activity of shoppers for you to set up workflows to recover lost sales and order confirmation workflows. 3 track events are passed: * cart_updated is passed when an item is added to a cart. * cart_deleted is passed when a cart is emptied. * order_completed is passed when an order has been made. This means that the payment status is "Paid." ![Logs](_static/set-up-brevo-plugin/logs.png) ## Learn more * Learn how to [create an abandoned cart email](xref:en/running-your-store/promotional-tools/brevo-integration/recover-abandoned-carts). * Learn how to [create an order confirmation email](xref:en/running-your-store/promotional-tools/brevo-integration/send-an-order-confirmation-email). --- # Recover abandoned carts In this tutorial, you will learn how to create abandoned cart email and how to set up the workflow to recover lost sales. You will also learn which nopCommerce order data is compatible with the Brevo platform. ## Before getting started You will need the following: * Brevo account credentials. If you don't have one, [sign up for free](https://get.brevo.com/v70whp). * Make sure that Brevo's [*New Template Language*](https://get.brevo.com/eg4z2v) for emails is enabled on your account. * Follow [these steps](xref:en/running-your-store/promotional-tools/brevo-integration/set-up-brevo-plugin) to set up the brevo plugin. ## Create an abandoned cart email template First, log into your Brevo account then go to the Automation platform > [Email Templates](https://get.brevo.com/e8j7a). Click on the **New Template** button at the top right. The email template can be personalized with several types of data: * [contact attributes saved in your Brevo list](#personalize-your-email-with-contact-attributes) * [abandoned item details](#personalize-your-email-with-the-abandoned-items-details) * [abandoned cart details](#personalize-your-email-with-the-abandoned-cart-details) ### Personalize your email with contact attributes Let's start by [personalizing with contact attributes](https://get.brevo.com/bynyff). In the example below, we have included a personalization of: * the recipient's first name using {{ contact.FIRSTNAME }} * the recipient's last name using {{ contact.LASTNAME }} > [!NOTE] > > FIRSTNAME and LASTNAME should be existing attributes in your Brevo account. ![Attribute personalization](_static/recover-abandoned-carts/attribute-personalization.gif) Now let's personalize the email template with order variables such as the name of the items left behind, their images, price etc. To do so, we will use the *New Template Language* to insert a dynamic list. ### Personalize your email with the abandoned items details The following variables may be included directly from a dynamic list within your Brevo template content: | Items data | Insert this placeholder in your template | | ------------- | ------------- | | Name | {{ item.name }} | | SKU | {{ item.sku }} | | Category | {{ item.category }} | | ID | {{ item.id }} | | ID of the item variation | {{ item.variant_id }} | | Name of the item variation | {{ item.variant_name }} | | Price | {{ item.price }} | | Quantity | {{ item.quantity }} | | Storefront link of the purchased item | {{ item.url }} | | Image | {{ item.image }} | In the *Drag & Drop Editor*, select your desired block that will display the abandoned items. 1. Click the **pencil icon** to edit the settings for the design block. 1. Enable the **dynamic list** option. 1. In the **parameter** field, write `items`. 1. In the **variable** field, write `item`. 1. Set the limit for the number of items that will be displayed. For example, if there are 5 items left in the cart, and you set 3 as the limit, only 3 items will be shown in the email. ![Email editor](_static/recover-abandoned-carts/items.jpg) Now add the variables to your email template. In the example above, we have added: * `{{ item.name }}` - the name of the item * `{{ item.quantity }}` - the quantity of the item * `{{ item.price | floatformat: 2 }}` - the price of the item To add the link of the item, select the **Call-To-Action (CTA)** button. On the right sidebar, under *Link*, type `{{ item.url }}`. ![item.url](_static/recover-abandoned-carts/item-url.jpg) To add the image of the item, select the image. On the right sidebar, under *Image source*, choose *From URL* then type `{{ item.image }}`. ![item.image](_static/recover-abandoned-carts/item-image.jpg) Once your design is complete, click the green **Save & Quit** button. Then click the **Save & Activate** button. ### Personalize your email with the abandoned cart details The following variables may be included directly within your Brevo template content: | Cart details | Insert this placeholder | | ------------- | ------------- | | Affiliation | {{ params.affiliation }} | | Currency | {{ params.currency }} | | Discount | {{ params.discount }} | | Shipping | {{ params.shipping }} | | Subtotal | {{ params.subtotal }} | | Tax | {{ params.tax }} | | Total before tax | {{ params.tax }} | | Total | {{ params.total_before_tax }} | | Link to cart | {{ params.url }} | > [!NOTE] > > Items shown in the link to cart page will be different based on where the session is opened from. For example, let's say a customer is browsing from their laptop. If they click on the abandoned cart email from their phone, it will not show their abandoned cart. In the *Drag & Drop Editor*, select your desired block that will display the abandoned cart information then add the order variables you want. We recommend formatting numbers by using [floatformat](https://get.brevo.com/ogcn5b). In the example below, we have added: * `{{ params.currency }}` - the currency of the abandoned cart * `{{ params.subtotal | floatformat: 2 }}` - the subtotal of the abandoned cart * `{{ params.discount | floatformat: 2 }}` - the discount of the abandoned cart * `{{ params.total | floatformat: 2 }}` - the total of the abandoned cart ![Cart](_static/recover-abandoned-carts/cart.jpg) To add the link of the abandoned cart, select the **Call-To-Action (CTA)** button. On the right sidebar, under *Link*, type `{{ params.url }}`. ![params.url](_static/recover-abandoned-carts/url.jpg) Once your design is complete, click the green **Save & Quit** button. Then click the **Save & Activate** button. ## Creating the abandoned cart workflow > [!NOTE] > > A customer has to be identified by their email address to trigger the workflow, i.e. a customer should be logged into their account on your nopCommerce store or input their email address during checkout. Navigate to the [Automation](https://get.brevo.com/tvl7ng) tab of your Brevo account. Click on **+ CREATE A NEW WORKFLOW**, then select **Detailed Abandoned Cart** and follow the steps. ![Detailed Abandoned Cart](_static/recover-abandoned-carts/detailed-abandoned-cart.jpg) At the *Send an email* step, select the email template you have just created and activated from the dropdown list. When your workflow is complete, click on **DONE** to save and activate it. Feel free to read this tutorials to help you creating the workflow: * [Recovering abandoned carts: automatically send the emails (step 3)](https://get.brevo.com/gqqwh) ## Example Let's say that customer Jean Blue has visited your store but the following 3 items have been left in the cart. ![Cart example](_static/recover-abandoned-carts/cart-example.jpg) Your template will look like this: ![Cart example](_static/recover-abandoned-carts/template.jpg) The email received by Jean Blue will look like this: ![Cart example](_static/recover-abandoned-carts/email.jpg) ## Learn more * [Send an order confirmation email](xref:en/running-your-store/promotional-tools/brevo-integration/send-an-order-confirmation-email) --- # Send an order confirmation email In this tutorial, you will learn how to create an order confirmation email template and set up a workflow to keep buyers engaged. You will also learn which nopCommerce order data are compatible with the Brevo platform. ## Before getting started You will need the following: * Brevo account credentials. If you don't have one, [sign up for free](https://get.brevo.com/v70whp). * Make sure that Brevo [*New Template Language*](https://get.brevo.com/eg4z2v) for emails is enabled in your account. * Follow [these steps](xref:en/running-your-store/promotional-tools/brevo-integration/set-up-brevo-plugin) to set up the brevo plugin. ## Create the order confirmation email template First, log in to your Brevo account, then go to the Automation platform > [Email Templates](https://get.brevo.com/e8j7a). Click the **New Template** button in the top right. The email template can be personalized with several types of data: * [contact attributes saved in your Brevo list](#personalize-your-email-with-contact-attributes) * [order details](#personalize-your-email-with-the-order-details) * [ordered item details](#personalize-your-email-with-the-ordered-items-details) ### Personalize your email with contact attributes Let's start by personalizing with [contact attributes](https://get.brevo.com/bynyff). In the example below, we have included personalization of: * the recipient's first name using `{{ contact.FIRSTNAME }}` * the recipient's last name using `{{ contact.LASTNAME }}` > [!NOTE] > > FIRSTNAME and LASTNAME should be existing attributes in your Brevo account. ![Attribute personalization](_static/send-an-order-confirmation-email/attribute-personalization.gif) ### Personalize your email with the order details The following variables can be included directly within your Brevo template content: | Order data | Shipping address data | Billing address data | | ------------- | ------------- | ------------- | | {{ params.url }} | {{ params.shipping_address.firstname }} | {{ params.billing_address.firstname }} | | {{ params.currency }} | {{ params.shipping_address.lastname }} | {{ params.billing_address.lastname }} | | {{ params.date }} | {{ params.shipping_address.company }} | {{ params.billing_address.company }} | | {{ params.discount }} | {{ params.shipping_address.phone }} | {{ params.billing_address.phone }} | | {{ params.id }} | {{ params.shipping_address.address1 }} | {{ params.billing_address.address1 }} | | {{ params.revenue }} | {{ params.shipping_address.address2 }} | {{ params.billing_address.address2 }} | | {{ params.shipping }} | {{ params.shipping_address.city }} | {{ params.billing_address.city }} | | {{ params.subtotal }} | {{ params.shipping_address.country }} | {{ params.billing_address.country }} | | {{ params.tax }} | {{ params.shipping_address.state }} | {{ params.billing_address.state }} | | {{ params.total_before_tax }} | {{ params.shipping_address.zipcode }} | {{ params.billing_address.zipcode }} | In the *Drag & Drop Editor*, select your desired block that will display the order information, then add your variables. We recommend formatting numbers using [floatformat](https://get.brevo.com/ogcn5b). In the example below, we have added: * `{{ params.currency | floatformat: 2 }}` - the currency of the order * `{{ params.subtotal | floatformat: 2 }}` - the subtotal of the order * `{{ params.discount | floatformat: 2 }}` - the discount of the order * `{{ params.total | floatformat: 2 }}` - the total of the order ![Order summary](_static/send-an-order-confirmation-email/order.jpg) Now let's personalize the email template with ordered items. To do so, we're using the *New Template Language* to insert a dynamic list. ### Personalize your email with the ordered items details The following variables can be included directly from a dynamic list within your Brevo template content: | Items data | Insert this placeholder in your template | | ------------- | ------------- | | Name | {{ item.name }} | | SKU | {{ item.sku }} | | Category | {{ item.category }} | | ID | {{ item.id }} | | ID of the item variation | {{ item.variant_id }} | | Name of the item variation | {{ item.variant_name }} | | Price | {{ item.price }} | | Quantity | {{ item.quantity }} | | Storefront link to the purchased item | {{ item.url }} | | Image | {{ item.image }} | In the *Drag & Drop Editor*, select your desired block that will display the ordered items. 1. Click the **pencil icon** to edit the settings for the design block. 1. Enable the **dynamic list** option. 1. In the **parameter** field, type `items`. 1. In the **variable** field, type `item`. 1. Set the limit for the number of items that will be displayed. For example, if there are 5 items, and you set 3 as the limit, only 3 items will be shown in the email. ![Items](_static/send-an-order-confirmation-email/items.jpg) Now add the variables to your email template. In the example above, we have added: * `{{ item.name }}` - the name of the item * `{{ item.quantity }}` - the quantity of the item * `{{ item.price | floatformat: 2 }}` - the price of the item To add the link to the item, select the **Call-To-Action (CTA)** button. On the right sidebar, under *Link*, type `{{ item.url }}`. ![Item](_static/send-an-order-confirmation-email/item.jpg) To add the image of the item, select the image. On the right sidebar, under *Image source*, choose *From URL*, then type `{{ item.image }}`. ![Image](_static/send-an-order-confirmation-email/image.jpg) Once your design is complete, click the green **Save & Quit** button. Then click the **Save & Activate** button. ## Creating the order confirmation workflow > [!NOTE] > > A customer has to be identified by their email address to trigger the workflow, that is, a customer should be logged in to their account on your nopCommerce store or enter their email address during checkout. Navigate to the [Automation](https://get.brevo.com/tvl7ng) tab of your Brevo account. Click **+ CREATE A NEW WORKFLOW**, then select **Product Purchase** and follow the steps. 1. **Step 1/3** — An event happens * Select *Custom Event (Track Event)*. * Type `order_completed`. * Click **NEXT**. 1. **Step 2/3** — Add a delay * Choose a delay. For example, 5 seconds. * Click **NEXT**. 1. **Step 3/3** — Send an email * From the dropdown list, select the email template you have just created and activated. * Select **Use my event data to customize the email**. * Select **The event data which triggered the workflow**. * Click **FINISH**. ![Create workflow](_static/send-an-order-confirmation-email/create-workflow.gif) When your workflow is complete, click **DONE** to save and activate it. ## Example Let's say that customer Jean Blue has purchased the following 3 items from your store. ![Order items](_static/send-an-order-confirmation-email/order-items.jpg) Your template will look like this: ![Template](_static/send-an-order-confirmation-email/template.jpg) The email received by Jean Blue at will look like this: ![Email](_static/send-an-order-confirmation-email/email.jpg) ## Learn more * [Recover abandoned carts](xref:en/running-your-store/promotional-tools/brevo-integration/recover-abandoned-carts) --- # Facebook Pixel plugin This section describes how to integrate the Facebook pixel into your store. ## What the Facebook pixel is The Facebook pixel allows you to receive information about the actions taken in your store to make your Facebook ads more relevant to your audience. The Facebook pixel can help you understand the behavior of visitors to your store and which advertising strategy works best to reach your business goals. Tracked conversions appear in the [Facebook Ads Manager](https://www.facebook.com/adsmanager) and [Facebook Analytics](https://business.facebook.com/analytics) dashboard, where they can be used to measure the effectiveness of your ads, define custom audiences for ad targeting or dynamic ads campaigns, and to analyze the effectiveness of your website's conversion funnels. ## What the Facebook Pixel plugin does The Facebook Pixel plugin for nopCommerce pasts a snippet of JavaScript code that allows you to track visitor activity on your website. It works by loading a small library of functions used whenever a customer takes action. ## Install and enable the plugin The Facebook Pixel plugin is an out-of-the-box nopCommerce plugin. You can find it here: **Configuration → Local plugins**. To find the plugin faster, use the **Group** field in the search panel to filter the plugins by *Widgets* type: ![Find the plugin](_static/facebook-pixel/plugin-list.jpg) Install the plugin using the **Install** button if it is uninstalled. Then enable it by clicking the **Edit** button. You will see the *Edit plugin details* window in this case. Mark the plugin as enabled using the **Is enabled** checkbox and click the **Save** button. ## How to configure the plugin 1. Click the **Configure** button. You will see the *Configure - Facebook Pixel* page window: ![Configure - Facebook Pixel](_static/facebook-pixel/configure-window.jpg) 1. Click the **Add new configuration** button. 1. Fill in the following form to set up the plugin: ![Form](_static/facebook-pixel/form.jpg) * Select the **Enabled** checkbox to enable this Facebook pixel configuration. * Enter your **Pixel ID**, which you can find in the [Ads Manager → Events Manager](https://business.facebook.com/events_manager). If you have not created a pixel, [follow these instructions](https://www.facebook.com/business/help/952192354843755) to create one — all you need is the pixel's ID. * **Advanced Matching**: if selected, some of the visitors' data (in the hashed format) will be collected by the Facebook pixel. If you implement advanced matching automatically using the Events Manager, clear this setting. * **Include User properties**: select to include *User properties*, data about the User, in a pixel. Then, you can view User properties in the Facebook Analytics dashboard under People → User Properties. Next, you will see the list of events. Standard events are predefined visitor actions that correspond to common, conversion-related activities, such as searching for a product, viewing a product, or purchasing a product. * **Track "PageView" event**: select to enable tracking of the standard event when a person lands on the website pages. * **Track "AddToCart" event**: select to enable tracking of the standard event when a product is added to the shopping cart. * **Track "Purchase" event**: select to enable tracking of the standard event when an order is placed. * **Track "ViewContent" event**: select to enable tracking of the standard event when a person lands on a product details page. * **Track "AddToWishlist" event**: select to enable tracking of the standard event when a product is added to the wishlist. * **Track "InitiateCheckout" event**: select to enable tracking of the standard event when a person enters the checkout flow prior to completing the checkout flow. * **Track "Search" event**: select to enable tracking of the standard event when a search is made. * **Track "Contact" event**: select to enable tracking of the standard event when a person person submits a question via contact us form. * **Track "CompleteRegistration" event**: select to enable tracking of the standard event when a registration form is completed. > [!NOTE] > > As an additional parameter, some events include product SKU or product combination SKU; make sure that they are filled in correctly in your catalog. * **Disable for users not accepting Cookie Consent**: select to disable the Facebook pixel for users not accepting Cookie Consent. You may want this if you conduct business in countries subject to General Data Protection Regulation (GDPR). You also need to activate the **DisplayEuCookieLawWarning** setting on the **Configuration → Settings → General settings** page in order to display Cookie Consent for users. > [!NOTE] > > The General Data Protection Regulation (GDPR) took effect on May 25, 2018, and creates consistent data protection rules across Europe. Businesses that advertise with Facebook companies can continue to use Facebook platforms and solutions in the same way they do today. ## Configure custom events > [!NOTE] > > You can only see this panel after you have already created and saved the current configuration! If the predefined standard events aren't suitable for your needs, you can track your own custom events, which can also be used to define custom audiences for ad optimization. You can configure them below. Specify the name and choose widget zones in which the custom event will be tracked. If you don't know which zone to use for your custom event, you can ask in our [forums](https://www.nopcommerce.com/boards). ![Configure custom events](_static/facebook-pixel/custom-events.jpg) ## See also [What data does the Facebook Pixel collect?](https://developers.facebook.com/docs/facebook-pixel/support#pixelcollect) --- # Omnisend integration This section describes how to integrate the Omnisend plugin into your store. The plugin supports all versions of nopCommerce, including minor versions from 4.30 to 4.70. ## What the Omnisend is Omnisend is an email & SMS marketing automation platform that helps ecommerce stores to connect and engage with their customers. You can create popups and signup forms to collect new subscribers. Engage with them by taking advantage of channels like email and SMS. Use your store data to segment customers and drive sales with personalized automation. ## What the Omnisend plugin does Omnisend plugin for nopCommerce allows the store owner: * Synchronize contacts - performs synchronization of customers subscribed to the newsletter. * Synchronize products - synchronizes categories and products. ## Install and enable the plugin The Omnisend plugin is an out-of-the-box nopCommerce plugin. You can find it here: **Configuration → Local plugins**. To find the plugin faster, use the **Group** field in the search panel to filter the plugins by *Misc* type: ![Find the plugin](_static/omnisend/plugin-list.jpg) Install the plugin using the **Install** button if it is uninstalled. Then enable it by clicking the **Edit** button. You will see the *Edit plugin details* window in this case. Mark the plugin as enabled using the **Is enabled** checkbox and click the **Save** button. ## How to configure the plugin 1. Click the **Configure** button. You will see the *Configure - Omnisend* window: ![Configure - Omnisend](_static/omnisend/configure-window.jpg) To use Omnisend with nopCommerce, you will need to [create an account](https://your.omnisend.com/g1K9y2) with Omnisend. You can start with the free plan to explore platform features, no credit card needed. > [!NOTE] > > If you have been using Omnisend and already have an account connected to another store, make sure to [create a new empty store](https://support.omnisend.com/en/articles/3022953-managing-multiple-stores?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGdTU12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1#register-a-new-store-under-the-owners-account) first. 1. To connect Omnisend to your store: [Log into](https://app.omnisend.com/login?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGf2o12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1) your Omnisend account. 1. Click *Connect store* in the dashboard or in your account navigation menu ![Connect store - Omnisend](_static/omnisend/connect-store.jpg) 1. Generate an API key and paste it into the appropriate field on the plugin configuration page. ![API key - Omnisend](_static/omnisend/store-api-key.jpg) 1. Click the **Save** button. 1. Go to the **Synchronization** panel to synchronize your nopCommerce customers and products with your Omnisend account. ![Sync](_static/omnisend/sync.jpg) ### What features are supported? * [Email](https://support.omnisend.com/en/articles/6070131-building-an-email-campaign?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGqRM12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1) and [SMS campaigns](https://support.omnisend.com/en/articles/1918472-sms-in-campaigns?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGqQs12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). * [Omnisend Signup forms](https://support.omnisend.com/en/articles/1061792-types-of-signup-forms?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVJfyY12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). * [Other 3rd party integrations](https://support.omnisend.com/en/collections/35918-integrations-with-3rd-party-apps?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGM2w12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). * These Automation workflows: * [Order Confirmation](https://support.omnisend.com/en/articles/1421803-order-confirmation-automation?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMw012dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1) (Paid for Order and Placed order events), * [Cancellation Confirmation](https://support.omnisend.com/en/articles/1649441-cancellation-confirmation-automation?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMyw12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1) (Order Cancelled event), * [Birthday](https://support.omnisend.com/en/articles/1061790-birthday-email-automation?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMRM12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1), * [Welcome email](https://support.omnisend.com/en/articles/1061818-welcome-email-automation?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMTk12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1), * [Contact enters/exits segment](https://support.omnisend.com/en/articles/2398171-contact-enters-exits-a-segment-automation?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMQI12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1), * [Browse Abandonment](https://support.omnisend.com/en/articles/1692754-browse-abandonment?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMXU12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1), * [Product Abandonment](https://support.omnisend.com/en/articles/1690227-product-abandonment?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGMSM12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1), * [Abandoned Checkout & Abandoned Cart](https://support.omnisend.com/en/articles/6659889-abandoned-cart-and-abandoned-checkout?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGJx812dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). * [Segmentation](https://support.omnisend.com/en/articles/5945163-using-omnisend-segmentation?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGJzE12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). Most of the filters in the segmentation are available, except the order statuses events: Paid for order, Cancelled order, Had order shipped, Had partially shipped order, Refunded order, Had partially refunded order. However, you can still utilize 'Placed order' filter. * [Live activity](https://support.omnisend.com/en/articles/1689912-live-view-tracking-store-activity?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGJwY12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). * Adding your [Brand Assets](https://support.omnisend.com/en/articles/6099524-brand-assets-management?irclickid=VWt1B4VIXxyPTkbVXw2OtWsaUkHVGJ3w12dV0g0&irpartnerid=5274744&irprogramid=21260&irgwc=1). ### What data is synced? The following store data will now be synced to Omnisend: * Customer details * Products and viewed categories * Order-related events * Abandoned cart-related events > [!NOTE] > > Manual synchronization should be performed only once, with multiple synchronization, batch insert will report data insert errors. Further synchronization will go automatically and will not require the participation of an administrator ## Contacts sync Two types of contacts synchronization are implemented in the plugin: * Initial import of all existing contacts. Performed when the user has just installed the plugin and wants to import all existing store contacts into the Omnisend account. * Contact synchronization when subscribing/subscribing. ## Customer tracking events (JS snippet) To track user actions in the store, a JS script is installed on all pages of the site. By default, the script tracks visits to all pages, including tracking visits to the product page. An additional script is also used to notify user identification. ## Cart events, Order events In the plugin track a number of events to notify the Omnisend service: * Adding a product to cart. * Placing an order. * Payment of an order. * Order refunded. * Canceling an order. * Finalizing the order processing. * Starting the checkout process. * Changing a product in the cart (increasing the quantity, discounts, etc.). * Deleting the last product from the cart. * Changing the order status. * Restoring cart. The user has the option to follow the link from the email Omnisend (abandoned cart reminder) to the store. ## Products sync The plugin implements import of categories and products. When you click the **Sync products** button, the synchronization process is performed. > [!NOTE] > > If there are many categories (>300), the user will be shown a warning that the import may take a long time. In addition to the initial import, real-time synchronization of products is implemented, but only changes in the `StockQuantity` parameter are tracked to keep the product status (*inStock*, *outOfStock*, *notAvailable*) up to date. --- # Reminders The **Reminders** feature allows sending email notifications to users about their abandoned carts, incomplete registrations, and unfinished orders. This functionality helps improve user engagement and conversion by reminding users to complete their actions. ## Available Reminders There are three types of reminders that can be sent to users: 1. **Abandoned Cart** - Up to **3 reminders** can be sent for an abandoned cart. - Reminders are sent sequentially based on the time of the user's last interaction with the cart. - A reminder is sent only if the delay configured for that reminder has passed since the last interaction. 1. **Abandoned Order** - Up to **2 reminders** are sent, but only for the **earliest incomplete order**. - If a reminder has been sent for an order, reminders for other orders are not sent until the current order is completed. 1. **Incomplete Registration** - Only **one reminder** is sent. - This reminder is triggered only for users whose **Registration Method** is set to *"Email validation is required after registration"*. > [!Note] > All reminders starting from the second one are sent only if the previous reminder has already been sent. ## Administration Administrators can manage reminders in the **Reminders** page under the **Promotions** section: ![Reminders](_static/reminders/reminders-config.png) - Reminders can be enabled or disabled for the entire group or individually. - Each reminder has a configurable **delay**, which determines when the reminder will be sent. - Each reminder is associated with a **Message Template**. ![Reminders](_static/reminders/reminders-message-templates.png) - And the delay directly affects the **Delay Send** setting in the template. ![Reminders](_static/reminders/reminders-message-template-1.png) ## Tokens for Cart Reminders Two tokens are available for cart reminders: - `%Customer.Cart%` – Inserts a table of products from the user's cart. - `%Customer.ShoppingCartUrl%` – URL linking directly to the user's cart (including login if required). ## Scheduled Tasks Each type of reminder is handled by a scheduled task: - **Process incomplete registrations** – runs **hourly**. - **Process incomplete orders** – runs **hourly**. - **Process abandoned carts** – runs **every 20 minutes**. These tasks ensure timely processing and sending of reminders according to the configured delays. ![Reminders](_static/reminders/reminders-tasks.png) --- # Content management Content management is a set of processes and technologies that support the collection, managing, and publishing of the information on your site. nopCommerce allows you to use all the tools needed to make your online store more informative and your communication with customers better. ## Learn more - [Blog](xref:en/running-your-store/content-management/blog) - [News](xref:en/running-your-store/content-management/news) - [Forums](xref:en/running-your-store/content-management/forums) - [Polls](xref:en/running-your-store/content-management/polls) - [Topics (pages)](xref:en/running-your-store/content-management/topics-pages) - [Menu](xref:en/running-your-store/content-management/menu) - [Message templates](xref:en/running-your-store/content-management/message-templates) - [SEO](xref:en/running-your-store/search-engine-optimization) - [Email campaigns](xref:en/running-your-store/promotional-tools/email-campaigns) --- # Blog A blog is a great way to connect with your existing customers, keeping them informed about the latest product offerings or educating them, and to find new customers. To manage blog posts, go to **Content management → Blog posts**. ![Blog posts](_static/blog/blog1.jpg) ## Add a new blog post Click **Add new** and fill in the information about the new blog post. ![Add a new blog post](_static/blog/add-new.jpg) ### Info In the *Info* panel, define the following blog post details: * If more than one language is enabled, from the **Language** dropdown list, select the language of this blog post. Customers will only see blog posts in their selected language. * Enter the **Title** of this blog post. * Enter the **Body** text of this blog post. * You can specify the **Body overview** if you want only a part of the text to be visible on the main blog page where all blog posts are listed. * Enter **Tags** to be displayed on the blog page in the public store. Tags are keywords that this blog post can also be identified by. Enter a comma-separated list of the tags associated with this blog post. The more blog posts are associated with a particular tag, the larger size it has in the "Popular tags" area displayed on the sidebar on the blog page. ![p3](_static/blog/Blog3.png) * Select the **Allow comments** checkbox to enable customers to add comments to this blog post. * Select the **Include in sitemap** checkbox to include the blog post in the sitemap. * Enter the **Start date** and **End date** for displaying this blog post in Coordinated Universal Time (UTC). > [!NOTE] > > You can leave these fields empty if you do not want to define the blog post's start and end dates. * Choose the stores in the **Limited to stores** field to enable this blog post for specific stores only. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). While editing an existing blog post or after clicking the **Save and continue edit** button for a new one, you can click the **Preview** button in the top right to see how the blog post will appear on the site. ### SEO In the *SEO* panel, define the following blog post details: ![SEO for blog posts](_static/blog/blog4.jpg) * Define the **Search engine friendly page name**. For example, enter "the-best-news" to make your URL `http://yourStore.com/the-best-news`. Leave this field empty to generate it automatically based on the title of the blog post. * Override the page title in the **Meta title** field (the default title is the title of the blog post). * Enter **Meta keywords** to be added to the blog post's header. They represent a brief and concise list of the most important themes on the page. * Enter **Meta description** to be added to the blog post's header. The meta description tag is a brief and concise summary of the page content. ## Manage blog comments To manage blog comments, select **Content management → Blog comments**. ![Blog comments](_static/blog/blog5.jpg) Use the **Approve selected** button to approve the selected comments and **Disapprove selected** to disapprove ones. You can also edit or delete a blog comment. If deleted, the comment will be removed from the system. ## Blog settings You can manage blog settings in **Configuration → Settings → Blog settings**. This page is available in 2 modes: *advanced* and *basic*. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ![Blog settings](_static/blog/Blog-Setting.png) ### Common Define the following *Common* settings: * Select the **Blog enabled** checkbox to enable the blog functionality in your store. * In the **Posts page size** field, set the number of posts per page. * In the **Number of tags (cloud)** field, enter the number of tags that appear in the tag cloud. * Select the **Display blog RSS feed link in the browser address bar** checkbox to show the blog RSS feed link in the browser address bar. ### Blog comments Define the following *Blog comments* settings: * Select the **Allow guests to leave comments** checkbox to enable nonregistered users to add comments to the blog. * Select the **Blog comments must be approved** checkbox if blog comments must be approved by the administrator. * Select the **Notify about new blog comments** checkbox to notify the store owner about new blog comments. * Select the **Blog comments per store** checkbox to display blog comments written in the current store only. Click **Save**. > [!NOTE] > > You can enable CAPTCHA for blog comments for security purposes. For more information, proceed to the [CAPTCHA](xref:en/getting-started/advanced-configuration/security-settings#captcha) section. --- # News nopCommerce allows you to post news in your store. There can be any important tidings, like nopCommerce latest release information, your company updates, and more. In nopCommerce, the feature is implemented as the *News* plugin (system name *Misc.News*), available since nopCommerce 5.00. The plugin belongs to the *Misc* group. ## How it works News will be displayed in your store on the home page or in the site footer menu. ![p1](_static/news/news_1.png) To manage news, go to **Content management → News items**. The list of all news will be displayed as follows: ![News](_static/news/list.png) ## Adding news To add a new news item, click the **Edit** button and fill in the information about the news item. ![Adding news](_static/news/add-new.png) ### Info In the *Info* panel, define the following news item details: - If more than one language is enabled, from the **Language** dropdown list, select the language of this news item. Customers will only see news in their selected language. - Enter the **Title** of this news item. For example: "The launch of our new nopCommerce store." - In the **Short description** field, enter an abstract of this news item. This is the text your visitors will see on the news list in the public store. - In the **Full description** field, enter the text of this news item. - Select the **Allow comments** checkbox to enable customers to add comments to the news item. - Enter the **Start date** and **End date** for displaying this news item in Coordinated Universal Time (UTC). > [!NOTE] > > You can leave these fields empty if you do not want to define the news item's start and end dates. - Choose the stores in the **Limited to stores** field to enable this news item for specific stores only. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). - Select the **Published** checkbox to publish this news item in your store. While editing an existing news item or after clicking the **Save and continue edit** button for a new one, you can click the **Preview** button in the top right to see how the news item will appear on the site. ### SEO In the *SEO* panel, define the following news item details: ![SEO for news item](_static/news/seo.png) - Define the **Search engine friendly page name**. For example, enter "the-best-news" to make your URL `http://yourStore.com/the-best-news`. Leave this field empty to generate it automatically based on the title of the news item. - Override the page title in the **Meta title** field (the default title is the title of the news item). - Enter **Meta keywords** to be added to the news item's header. They represent a brief and concise list of the most important themes for the page. - Enter **Meta description** to be added to the news item's header. The meta description tag is a brief and concise summary of the page content. ## Managing news comments To manage news comments, go to **Content management → News comments**. ![News comments](_static/news/news-comments.png) Use the **Approve selected** button to approve the selected comments and **Disapprove selected** to disapprove ones. You can also edit or delete a comment. If deleted, the comment will be removed from the system. ## News settings To configure the plugin, go to **Configuration → Local plugins** and click **Configure** beside *News*. This page is available in 2 modes: *advanced* and *basic*. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ![News settings](_static/news/news-settings.png) ### Common Define the following *Common* settings: - Select the **News enabled** checkbox to enable the news functionality in your store. - Select **Show on home page** to display your news items on your store home page. - Enter the **Number of items to display** on the home page. - Enter the **News archive page size**. It's the number of news displayed on one page. - Select **Display news RSS feed link in the browser address bar** to enable the news RSS feed link in customers' browser address bar. - Select the **Sitemap includes news items** if you want to include news items in sitemap. - Select the **sitemap.xml includes news items** if you want to include news items in sitemap.xml file. - Select the **Show CAPTCHA on news page (comments)** to show CAPTCHA on news page when writing a comment. ### News comments Define the following *News comments* settings: - Select the **Allow guests to leave comments** checkbox to enable nonregistered users to add comments to news. - Select the **News comments must be approved** checkbox if news comments must be approved by the administrator. - Select the **Notify about new news comments** checkbox to notify the store owner about new news comments. - Select the **News comments per store** checkbox to display news comments written in the current store only. Click **Save**. ## Tutorials - [Managing news in nopCommerce](https://www.youtube.com/watch?v=ztLlRXvBQK4) --- # Forums A forum is an online discussion site where people can hold conversations in the form of posted messages. A forum may contain a number of subforums, each having several topics. In nopCommerce, the feature is implemented as the *Forums* plugin (system name *Misc.Forums*), available since nopCommerce 5.00. The plugin belongs to the *Misc* group. > [!NOTE] > > Since version 4.90, you have to [manually add](xref:en/running-your-store/content-management/menu) a menu or footer item after enabling forums, if needed. ## How it works To manage forum groups and forums (inside forum groups), go to **Content management → Forums**. ![Manage forums](_static/forums/list.png) ## Add a new forum group Click the **Add new forum group** button. ![Add a new forum group](_static/forums/forums2.png) - Define a new forum group **Name**. - In the **Display order** field, enter the display order of the forum group. A value of 1 represents the top of the list Click **Save**. ## Add a new forum ![Add a new forum](_static/forums/forums3.png) - From the **Forum group** dropdown list, select the required forum group. - Enter the **Name** of the new forum. - Enter the **Description** of the new forum. - Select the **Display order** for the forum group. A value of 1 represents the top of the list Click **Save**. To view an example of how forums should work, go to . ![nopCommerce forums](_static/forums/example.png) ## Forum settings To configure the plugin, go to **Configuration → Local plugins** and click **Configure** beside *Forums*. This page is available in 2 modes: *advanced* and *basic*. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ### Common ![Common settings](_static/forums/common.png) Define the following forum settings in the *Common* panel: - Enable forums by selecting the **Forums enabled** checkbox. - Select the **Show CAPTCHA on forum** checkbox to show CAPTCHA on forum, when editing and creating a topic or post. - Select the **Relative date and time formatting** checkbox to enable the relative date and time (for example, 2 hours ago, 1 day ago). - You can give an opportunity to specify customers' signatures by selecting **Signature enabled**. - Select the **Show customers post count** checkbox to enable showing the number of posts created by a customer. - From the **Forum editor** dropdown list, select the forum editor type to use: - Simple textbox. - BBCode editor. - Markdown editor > [!NOTE] > > It is not recommended to change the forum editor type in the production environment. ### Permissions ![Permissions settings](_static/forums/permissions.png) Define the following forum settings in the *Permissions* panel: - **Allow guests to create posts**. - **Allow guests to create topics**. - **Allow customers to edit posts**. - **Allow customers to delete posts**. - **Allow customers to manage forum subscriptions**. - Select the **Allow users to vote for posts** checkbox to enable voting. - The **Maximum votes per day** field sets the number of votes a user can do per day if the previous setting is enabled. ### Page sizes ![Page sizes settings](_static/forums/page-sizes.png) Define the following forum settings in the *Page sizes* panel: - **Topics page size** — the page size for topics in forums, for example, `10` topics per page. - **Posts page size** — the page size for posts in topics, for example, `10` posts per page. - **Search results page size** — the page size for search results, for example, `10` results per page. - **Active discussions page size** – the page size for the active discussions page, for example, `50` results per page. ### Feeds ![Feeds settings](_static/forums/feeds.png) Define the following forum settings in the *Feeds* panel: - Select the **Forum feeds enabled** checkbox to enable RSS feeds for each forum. - In the **Forum feed count** field, set the number of topics to be included in each feed. - Select the **Active discussions feed enabled** checkbox to enable RSS feeds for active discussion topics. - In the **Active discussions feed count** field, set the number of discussions to be included in the "Active discussions" feed. ## Tutorials - [Managing forums in nopCommerce](https://www.youtube.com/watch?v=wW2QvC4WA_8) --- # Polls Polls functionality in nopCommerce allows you to make your e-commerce site more interactive. There are many ways you can use polls for an e-commerce site. One popular way is to use them as a short customer satisfaction survey. People like being asked for feedback, and this is a good opportunity to see how you are doing as an online merchant. In nopCommerce, the feature is implemented as the *Polls* plugin (system name *Misc.Polls*), available since nopCommerce 5.00. The plugin belongs to the *Misc* group. The poll on the home page of the Default Clean nopCommerce theme looks like: ![Home page poll](_static/polls/polls_3.png) To view all the polls and add new ones, go to **Content management → Polls**. ![Polls list](_static/polls/polls_1.png) To search for polls that were used in a certain store, select the store name from the list. ## Polls settings To configure the plugin, go to **Configuration → Local plugins** and click **Configure** beside *Polls*. This page is available in 2 modes: *advanced* and *basic*. This page enables multi-store configuration; it means that the same settings can be defined for all stores or differ from store to store. If you want to manage settings for a certain store, choose its name from the multi-store configuration dropdown list and select all the checkboxes needed on the left to set custom values for them. For further details, refer to [Multi-store](xref:en/getting-started/advanced-configuration/multi-store). ## Adding polls To add a new poll, click the **Add new** button in the top right. ![Add a new poll](_static/polls/add-new.png) ### Poll info Define the following details for the new poll: - If more than one language is enabled, from the **Language** dropdown list, select the language of this poll. Customers will only see polls in their selected language. - Enter the descriptive **Name** of this poll. This is the text the customers will see. For example, "What do you think about our store?" - Select the **Published** checkbox to make this poll active. - Select the **Show polls on home page** checkbox if you want to show the poll on the home page. - Select the **Show in the left-side columne** checkbox if you want to show poll on the left-side column. - Select the **Allow guests to vote** checkbox to enable nonregistered users to vote in the poll. - Enter the **Start date** and **End date** in Coordinated Universal Time (UTC). > [!NOTE] > > You can leave these fields empty if you do not want to define the poll's start and end dates. - Choose the stores in the **Limited to stores** field to enable this poll for specific stores only. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). - Enter the **Display order** of the poll. A value of 1 represents the top of the list. Click **Save and continue edit** to proceed to the *Poll answers* panel. ### Poll answers Fill in the following poll answer info: - The **Name** that will be displayed to a customer. - The **Display order**. A value of 1 represents the top of the list. Then click the **Add new record** button to save the answer. The complete list of answers can look as follows: ![Poll answers](_static/polls/answers.png) You can then **Edit** records and **Delete** them if required. ## Tutorials - [Managing polls in nopCommerce](https://www.youtube.com/watch?v=RJP45cUhuZQ) --- # Topics (pages) Topics (pages) are free-form content blocks that can be displayed on your site, either embedded within other pages or on a separate page. These are often used for FAQ pages, policy pages, special instructions, and more. To create a custom page, you should create a new topic and enter your custom page content on the topic details page. Content can be written for each language separately. ## Topic list To view the topics, go to **Content management → Topics (pages)**. Search for topics in the topics list by entering the topic text or its fragment in the **Search keywords** field or among all the topics of a certain store. ![p1](_static/topics-pages/topic-list.jpg) ## Adding topics To add a new topic, go to **Content management → Topics (pages)**. Click **Add new** and fill in the information about the new topic. ![p2](_static/topics-pages/new-topic.jpg) ### Info In the *Info* panel, define the following topic details: * Enter the **Title** for the topic. * Add the topic content using the editor provided in the **Body** field. * The **URL** field is there for information only. It is the URL of the topic in the public store. You can edit this by editing the **Search engine friendly page name** field below. ### Display In the *Display* panel, define the following topic details: * Select the **Published** checkbox to make this topic published. * You can include this topic in the **top menu**, **footer (column 1)**, footer (column 2), footer (column 3), and **sitemap**. Do this by selecting the corresponding checkbox. * Select the **Password protected** checkbox if this topic is password-protected. The **Password** field will be displayed on the topic page in the public store. A customer will need to enter the password to access the content of this topic. * From the **Customer roles** dropdown list, select a customer role or roles that can access this topic. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Configuration → Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * In the **Limited to stores** dropdown list, select stores in which the topic will be displayed. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). * Use the **Accessible when store closed** field to make this topic accessible when the store is closed. * Select the topic's **Display order**. For example, 1 represents the first item in a list. * Enter the **System name** of this topic. > [!NOTE] > > It is possible to use the same system name for different topics. For example, you can create two different topics with the same system name and make them accessible for different customer roles. For example, *Guest* and *Registered* customer roles. This means that guests and registered customers will see the different content on the site. > [!NOTE] > > While editing an existing topic or after clicking the **Save and continue edit** button for a new one, you can click the **Preview** button to see how the topic will appear on the site. ### SEO In the *SEO* panel, define the following topic details: * In the **Search engine friendly page name** field, enter the name of the page used by search engines. If you enter nothing, then the web page URL will be formed using the page name. If you enter *custom-seo-page-name*, then the following URL will be used: `http://www.yourStore.com/custom-seo-page-name`. * In the **Meta title** field, enter the required title. The title tag specifies the title of your web page. It is a code inserted into the header of your webpage, and it is in the following format: ```html Creating Title Tags for Search Engine Optimization & Web Usability <title> </head> ``` * Enter the required category **Meta keywords**, which represents a brief and concise list of the most important themes of your page. The meta keywords tag is in the following format: ```html <meta name="keywords" content="keywords, keyword, keyword phrase, etc."> ``` * In the **Meta description** field, enter a description of the category. The meta description tag is a brief and concise summary of your page's content. The meta description tag is in the following format: ```html <meta name="description" content="Brief description of the contents of your page."> ``` Click **Save**. The topic will be displayed in the public store. ## See also * [SEO](xref:en/running-your-store/search-engine-optimization) ## Tutorials * [Adding new topic template](https://www.youtube.com/watch?v=M-g4Ux2GCaY) --- <!-- page: Menu | url: http://nopdocs.service.hedr.dev/en/running-your-store/content-management/menu.html | source: en/running-your-store/content-management/menu.md --> # Mega Menu Starting with version 4.90, the main menu and the footer navigation can be fully customized by the administrator in the admin panel. ![Menu](_static/menu/public.png) ## Accessing Menu Management To manage menus, navigate to **Content management -> Menus**. From this page, you can either edit an existing menu or create a new one. ![Menu](_static/menu/admin.png) ## Creating and Managing Menus When creating a new menu, you must specify its location using the **Menu type**: - **Main menu**: The primary navigation bar. - **Footer**: The navigation links in the site's footer. ![Menu](_static/menu/add_menu.png) > [!WARNING] > > While you can create multiple `Main menu` instances, only one will be displayed on the storefront at any given time, determined by its availability and creation order. The **'Display all categories'** setting automatically generates top-level menu items based on your store's categories and their sub-categories. If this checkbox is enabled, these category links will appear before any manually created menu items. After a menu is successfully created, you can begin adding items to it. ![Menu](_static/menu/menu_items.png) ## Adding and Configuring Menu Items The following parameters are available when creating or editing a menu item. ![Menu](_static/menu/menu_items_add.png) > [!WARNING] > > For menus with the `Footer` type, the **'Parent menu item'** property is unavailable, as footer navigation supports only a single level with no nesting. ### Menu Item Type This parameter determines the behavior and available settings for the menu item. ![Menu](_static/menu/menu_item_type.png) - **Standard page**: Links to a predefined system page with a pre-configured route. - **Category**: - Display all categories (in a grid or list layout). - Display a single category (as a grid, list, or simple link). - **Manufacturer**: - Display all manufacturers (in a grid or list layout). - Link to the "All manufacturers" page. - Link to a specific manufacturer's page. - **Product**: Links directly to a selected product page. - **Vendor**: - Display all vendors (in a grid or list layout). - Link to the "All vendors" page. - Link to a specific vendor's page. - **Topic (page)**: Links to a selected topic page. - **Custom link**: A simple link where you manually specify the Text and URL. - **Text without link**: Displays non-clickable text. This is useful for parent-level items that serve as headers and do not need to link anywhere. ### Additional Settings for Grid/List Layouts For menu items that use a grid or list template (e.g., displaying all categories), the following options are available: - **Number of elements per row (grid)**: Sets the maximum number of items to display in a single row of the grid. - **Number of subcategories per category item (grid)**: Sets the maximum number of sub-category links to display within each grid tile. - **Maximum number of elements**: Sets the total maximum number of child items to display. ![Menu](_static/menu/menu_items_add_grid.png) --- <!-- page: Message templates | url: http://nopdocs.service.hedr.dev/en/running-your-store/content-management/message-templates.html | source: en/running-your-store/content-management/message-templates.md --> # Message templates Message templates define the layout, content, and formatting of automated messages sent from your store. They are called transactional emails because each one is associated with a specific type of transaction. There are several message templates available in nopCommerce by default to notify users and the store owner about order statuses and more. To access message templates, go to **Content management → Message templates**. ![MessageTemplate1](_static/message-templates/list.png) Filtering: * You can search for message templates by keywords or store. Keywords are used to search in the name, body or subject of a message template. The list of available stores is shown if you have more than one store and the **Performance → Ignore "limit per store" rules (sitewide)** setting on the *Catalog settings* page is not active. * **Email account**. This drop-down list appears if the store has two or more email accounts. * You can also filter message templates by **Is active**. ## Edit a message template Find the message template you want to edit and click **Edit**. The *Edit message template details* window will be displayed as follows: ![Editing message templates](_static/message-templates/edit.jpg) If you have more than one language installed, select the required **language tab**. > [!TIP] > > By default, only the English language is used in the system. You can manage languages in **Configuration → Language**. Read more about languages in nopCommerce in the [Localization](xref:en/getting-started/advanced-configuration/localization) section. Edit the message template details as follows: * Edit the **Subject** of the message. You can include tokens in the subject. You can see the list with all the tokens allowed at the top of the page. * Edit the **Body** of the message. * In the **BCC** field, enter the blind copy recipients of this email message if needed. * From the **Email account** dropdown list, select the email account used to send this message template. * You can test this message template by clicking the **Test template** button. When clicked, the *Send test email* will be displayed as follows: ![Send test email](_static/message-templates/test-template.jpg) Enter your email in the **Send email to** field, fill the tokens with some test values, then click the **Send** button. > [!TIP] > > Email accounts are configured in **Configuration → Email accounts**. Read more about it in the [Emails accounts](xref:en/getting-started/email-accounts) section. * Select the **Is active** option to indicate this message should be sent. * Select the **Send immediately** checkbox if you want this email to be sent immediately. * If the previous checkbox is clear, the **Delay send** field will be displayed. * Select the **Attached static** file checkbox to upload a file that will be attached to each email sent. * Choose the stores in the **Limited to stores** field if the message template is for specific stores only. Leave the field empty in case this functionality is not required. > [!NOTE] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save**. > [!NOTE] > > To create a full copy of the message template, click **Copy template** in the top right. This is useful if you have several stores configured and want to create distinct templates for each of your stores. ## See also * [Email accounts](xref:en/getting-started/email-accounts) * [Languages](xref:en/getting-started/advanced-configuration/localization) ## Tutorials * [Adding conditions in message templates](https://www.youtube.com/watch?v=5chrb1yH1v4&feature=youtu.be) --- <!-- page: Search engine optimization | url: http://nopdocs.service.hedr.dev/en/running-your-store/search-engine-optimization.html | source: en/running-your-store/search-engine-optimization.md --> # Search engine optimization SEO stands for search engine optimization; it is a process of getting traffic from "free," "organic," "editorial" or "natural" search results on search engines. All major search engines have primary search results where webpages and other content, such as videos or local listings, are shown and ranked based on what the search engine considers most relevant for users. nopCommerce supports SEO techniques for various types of pages in your store. Find them listed in the [See also](#see-also) section. ## SEO settings There are some general SEO settings in nopCommerce that can be applied to the entire store. To edit SEO settings, go to **Configuration → Settings → General settings**. Then proceed to the *SEO* panel: ![SEO settings](_static/search-engine-optimization/seo1.png) - In the **Default page title** field, enter the default title for the pages in your store. - In the **Page title SEO adjustment** field, select the required page title's SEO adjustment as follows: - The page name comes after the store name in the title: `YOURSTORE.COM` | PAGENAME - The store name comes after the page name in the title: PAGENAME | `YOURSTORE.COM` - Specify the **Page title separator**. - Enter the **Default meta keywords** for the pages in your store. This can be overridden for individual categories, manufacturers, products, and some other pages. - Enter the **Default meta description** for the pages in your store. This can be overridden for individual categories, manufacturers, products, and some other pages. - Enter the **Home page title** for the home page of your store. - Enter the **Home page meta description** for the home page of your store. - Select **Generate product meta description** to automatically generate the product META descriptions (if not specified on the product details page) based on the product's short description. - Choose the **WWW prefix requirement**. For example, `http://yourStore.com/` can be automatically redirected to `http://www.yourStore.com/`. Select one of the following options: - *Doesn't matter* - *Pages should have WWW prefix* - *Pages should not have WWW prefix* - Select the **Convert non-western chars** checkbox to remove the accents in SEO names. For example, convert é to e. - Select the **Enable canonical URLs** checkbox to transform a URL into a canonical URL to enable determining whether two syntactically different URLs may lead to a page with the equivalent content. - Select the **Twitter META tags** checkbox to generate Twitter META tags on the product details page. - Select the **Open Graph META tags** checkbox to generate Open Graph META tags on the product details page. - Select the **Microdata tags** checkbox to generate Microdata tags on the product details page. - Enter the **Custom <head> tag**. For example, some custom <meta> tag. Or leave empty to ignore this setting. ## SEO panels There are several types of pages in nopCommerce for which you can set up individual SEO settings, including meta keywords, meta description, meta title, and search engine friendly page names. This is done on SEO panels of the corresponding admin area sections. ![SEO panel](_static/search-engine-optimization/seo-panel.jpg) - In the **Search engine friendly page name** field, enter the name of the page used by search engines. If you enter nothing, then the webpage URL will be formed using the page name. If you enter *custom-seo-page-name*, then the following custom URL will be used: `http://www.yourStore.com/custom-seo-page-name`. - In the **Meta title** field, enter the required title. The title tag specifies the title of your webpage. It is retrieved by web browsers and also used by search engines, such as Google, to display a webpage in search results: ![Meta title](_static/search-engine-optimization/meta-title.jpg) - Enter the required **Meta keywords**. They describe the content of a webpage concisely and are therefore important indicators of a website's content to search engines. Meta keywords help tell search engines what the topic of the page is. The keywords are generally lowercase. - In the **Meta description** field, enter a description of the page. The meta description provides a summary of the webpage. Search engines, such as Google, often display the meta description in search results, which can influence click-through rates: ![Meta description](_static/search-engine-optimization/meta-description.jpg) A meta description can be any length, but Google generally truncates snippets to ~155–160 characters. It's best to keep meta descriptions long enough to be sufficiently descriptive, so it's recommended to write descriptions between 50–160 characters. Note that the "optimal" length will vary depending on the situation, and your primary goal should be to provide value and drive clicks. ## Search engine friendly page names To see all search engine friendly page names used in the store, go to **System → Search engine friendly page names**. ![Search engine friendly page names](_static/search-engine-optimization/seo-page-names-list.jpg) Here, you can filter search engine friendly page names by **Name**, **Language** or **Is active** property. You can also delete one or multiple selected search engine friendly page names using the **Delete selected** button. In the **Edit page** column, you can see the button used to navigate to the appropriate page. ## See also - [Adding products](xref:en/running-your-store/catalog/products/add-products) - [Product categories](xref:en/running-your-store/catalog/categories) - [Manufacturers](xref:en/running-your-store/catalog/manufacturers) - [Vendors](xref:en/running-your-store/vendor-management) - [Topics (pages)](xref:en/running-your-store/content-management/topics-pages) - [News](xref:en/running-your-store/content-management/news) - [Blog](xref:en/running-your-store/content-management/blog) ## Tutorials - [Understanding SEO settings in nopCommerce](https://youtu.be/UxqM_nJyv1Q) --- <!-- page: Reports | url: http://nopdocs.service.hedr.dev/en/running-your-store/reports.html | source: en/running-your-store/reports.md --> # Reports Reports are important for management; they allow for monitoring store's performance, tracking key metrics, and supporting decision-making. nopCommerce reports provide access to sales and customer information. ## Dashboard The dashboard is the first page you see when accessing the admin area. It enables you to view your store statistics, including the total number of orders processed over the chosen period (year, month, week), registered customers, low-stock products, and the most popular products in your store. ![Dashboard](_static/reports/dashboard.png) The dashboard consists of several blocks: ### nopCommerce news Displays general nopCommerce news like new version releases. ![News](_static/reports/news.png) ### Common statistics ![Common](_static/reports/common.png) Here, you can find links to more detailed reports: - Sales → Orders - Sales → Return requests - Customers → Registered customers - Reports → Low stock ### Orders This diagram shows the number of orders processed in the last week, month, year. ![Orders](_static/reports/orders.jpg) ### New customers This diagram shows the number of customers registered in the last week, month, year. ![New customers](_static/reports/customers.jpg) ### Order totals This section shows the total of orders processed in the last day, week, month, year. Orders are shown by order status. ![Order totals](_static/reports/order-totals.png) ### Incomplete orders This section shows the number of orders that are currently incomplete. ![Orders incomplete](_static/reports/order-incomplete.png) ### Latest orders The Latest orders section shows you the latest placed orders. ![Latest orders](_static/reports/order-latest.png) ### Popular search keywords This block displays the most used keywords. ![Keywords](_static/reports/keywords.png) ### Bestsellers reports This section displays the bestsellers by quantity and by amount. ![Bestsellers](_static/reports/bestsellers.png) ## Sales summary This report represents the total orders summary. To generate a report, you can use the following filters: - **Start date** for the search. - **End date** for the search. - **Order status** to search by a specific order status, for example, "Complete." - **Payment status** to search by a specific payment status, for example, "Paid." - **Category** to search in a specific category. - **Manufacturer** to search by a specific manufacturer. - **Billing country** to filter by order billing country. - **Vendor** to search by a specific vendor. - **Product** to search by a specific product. - **Group by** for grouping by time periods. When this option is set to "Day," it will display a list of dates for a selected period (start/end date). For example, "Nov 8th, 2020," "Nov 7th, 2020," etc. When it is set to "Week", it will display a list of weeks (for example, "December 7th, 2020 - December 12th, 2020," etc.). When it is set to "Month", it will display a list of months (for example, "December 2020," "November 2020," etc.). Then click **Run report**. ![Sales summary](_static/reports/sales-summary.jpg) ## Low stock report A low stock report contains a list of products currently under stock. In the example shown below, the min stock quantity was set to 20, and the stock quantity is 0; therefore a low stock report is generated for this product. You can set up low stock settings when adding the product. To view low stock reports, go to **Reports → Low stock**. The *Low stock* report window will be displayed as follows: ![Low stock report](_static/reports/low-stock-reports.png) The low stock reports can be filtered by the **Published** property, which represents the *Published* property of products. In the displayed table, click **View** to view the product details page where the stock quantity can be updated. ## Bestsellers and never purchased Knowing the best-selling products and products never purchased is essential for any shop owner. First of all, this can help in making better purchasing decisions: you can scale up on your popular items and exclude unpopular ones from your product list. When analyzing, consider, for example, whether certain colors sell faster or whether your product sales depend on a season. Secondly, defining most and least selling goods can help you *re-evaluate product design and marketing*. Maybe your best items go faster just because of their placement in your webstore or better description. Come up with various options and test them. To do it more effectively, engage with your customers. *Conduct various surveys* to find out why the best-selling items are preferred, what makes them special for your buyers. Use the insights to improve your marketing and increase sales. ### Bestsellers To view bestsellers in nopCommerce, go to **Reports → Bestsellers**. Enter one or more of the following search criteria to run the report: - **Start date** and/or **End date**. - **Store** if you want to select one of your stores. - **Order status**, such as *All*, *Pending*, *Processing*, *Complete* or *Cancelled*. - **Payment status**, such as *All*, *Pending*, *Authorized*, *Paid*, *Refunded*, *Partially refunded* or *Voided*. - Choose the **Category**. - Choose the **Manufacturer**. - Choose the **Billing country**. - Choose the **Vendor**. Then click **Run report**. The report will break down your best-selling products based on both units sold and revenue: ![Bestsellers](_static/reports/bestsellers.jpeg) ### Products never purchased To view products never purchased, go to **Reports → Products never purchased**. Enter one or more of the following search criteria to run the report: - Choose the **Category**. - Choose the **Manufacturer**. - **Store** if you want to select one of your stores. - Choose the **Vendor**. - **Start date** and/or **End date**. Then click **Run report**. ![Products never purchased](_static/reports/never-purchased.jpg) ## Country sales A country report contains a list of orders that includes the number of orders and the total order sum in each country. This enables store owners to view the orders per country. To view a country sales report, go to **Reports → Country sales**. ![Country sales](_static/reports/country-report.png) To set up the report, enter one or more of the following search criteria: - **Start date** for the search. - **End date** for the search. - **Order status**, such as *All*, *Pending*, *Processing*, *Complete* or *Cancelled*. - **Payment status**, such as *All*, *Pending*, *Authorized*, *Paid*, *Refunded*, *Partially refunded* or *Voided*. - **Store** if you want to select one of your stores. Then click **Run report**. ## Customer reports Customer reports give a store owner general information about registered customers and their orders. You can find various reports in the **Reports → Customer reports** menu. ### Registered customers To run this report, go to **Reports → Customer reports → Registered customers**. This report displays the number of registered customers for a certain period. You can track the number of users registered within the last day, week, two weeks, month, and year. ![Registered customers](_static/reports/customer-registered.png) ### Customers by order total To run this report, go to **Reports → Customer reports → Customers by order total**. In this report, you can see the order totals spent and number of orders made by customers. ![Customers by order total](_static/reports/Customers-by-order-total.png) Enter one or several search criteria to compile a report: - Registration **Start date**. - Registration **End date**. - **Order status**, such as *All*, *Pending*, *Processing*, *Complete* or *Cancelled*. - **Payment status**, such as *All*, *Pending*, *Authorized*, *Paid*, *Refunded*, *Partially refunded* or *Voided*. - **Shipping Status**, such as *All*, *Shipping not required*, *Not yet shipped*, *Partially shipped*, *Shipped*, *Delivered*. Then click **Run report**. ### Customers by number of orders To run this report, go to **Reports → Customer reports → Customers by number of orders**. This report displays the top 20 customers based on the total number of orders issued. ![Customers by number of orders](_static/reports/Customers-by-number-of-orders.png) Enter one or several search criteria to compile a report: - Registration **Start date**. - Registration **End date**. - **Order status**, such as *All*, *Pending*, *Processing*, *Complete* or *Cancelled*. - **Payment status**, such as *All*, *Pending*, *Authorized*, *Paid*, *Refunded*, *Partially refunded* or *Voided*. - **Shipping Status**, such as *All*, *Shipping not required*, *Not yet shipped*, *Partially shipped*, *Shipped*, *Delivered*. Then click **Run report**. ## Tutorials - [Running reports in nopCommerce](https://www.youtube.com/watch?v=IbfoppTG9tM) ## See also - [Microsoft Power BI](xref:en/running-your-store/reports/microsoft-power-bi) --- <!-- page: Microsoft Power BI | url: http://nopdocs.service.hedr.dev/en/running-your-store/reports/microsoft-power-bi.html | source: en/running-your-store/reports/microsoft-power-bi.md --> # Microsoft Power BI Please [get the official integration with Power BI](https://www.nopcommerce.com/microsoft-power-bi). ## Introduction Power BI is a collection of software services, apps, and connectors that work together to turn your unrelated sources of data into coherent, visually immersive, and interactive insights. Power BI lets you easily connect to your data sources, visualize and discover what's important, and share that with anyone or everyone you want. The content isn't static, so you can dig in and look for trends, insights, and other business intelligence. Slice and dice the content, and even ask it questions in your own words. Or, sit back and let your data discover interesting insights, send you alerts when data changes, or email reports to you on a schedule that you set. All your content is available to you anytime, in the cloud or on-premises, from any device. That's just the beginning of what Power BI can do. Learn more about [Power BI](https://learn.microsoft.com/en-us/power-bi/fundamentals/power-bi-overview). ## Available reports A Power BI report is a multi-perspective view into a dataset, with visuals that represent different findings and insights from that dataset. A report can have a single visual or pages full of visuals. > [!TIP] > > Since the plugin comes with the source code, you can add new reports or change the data model, customizing the integration for your specific requirements. You can [find out more about how reports are created](https://learn.microsoft.com/en-us/power-bi/consumer/end-user-experience). The basic plugin package includes 13 reports covering different analytical aspects of the available information. A detailed description of each of them is presented below. ### Sales Summary The Sales Summary is a commonly used report that shows detailed sales data for your chosen date range. ![Sales summary](_static/microsoft-power-bi/Sales_summary.png) For all cards in the report, several filtering fields are available - here and henceforth we will call them general filters. > [!TIP] > > Each element of the report, be it a table, graph, or chart, is interactive and can act as an additional filter for the overall summary of information. The Sales Summary report has few sections, or “cards”, that display different sales information for your selected date range. - **Sales by Category and Product** - This table displays information about how many products were sold by category. The report gives an overall picture of sales. - **Bestsellers** - The table shows the products that had the highest sales amount. You can also change the sort order and display the best selling products by number of sales. - **Sales by customers** - The report provides an understanding of which customers make the most purchases. - **Quantity and sales by month** - This graph shows how sales were distributed over time. Records are kept not only of the amount of revenue, but also of the units of goods sold. Sales by Day of Week ![Sales by Day of Week](_static/microsoft-power-bi/Sales_by_Days.png) The report shows the distribution of sales by day of the week. This can be useful when planning sales or some one-time discounts. ### Sales History ![Sales History](_static/microsoft-power-bi/Sales_History.png) This report allows to analyze the sales history of both an individual product and an entire category throughout the history of the store. This information is useful for studying the demand for certain goods and signals whether the chosen product shows a tendency toward obsolescence or going out of fashion. ### Sales by Shipping Address ![Sales by Shipping Address](_static/microsoft-power-bi/Sales_by_Shipping_Address.png) If you are interested in the geography of shipment of your goods, then this report provides a fairly detailed description of how many products were sent to specific locations for the selected period of time. ### Average Order Value ![Average Order Value](_static/microsoft-power-bi/Average_order_value.png) The report helps to estimate the average order price by category, region and vendor. This information can be useful in assessing the purchasing power of customers from different regions and understanding which vendors influence this indicator. ### Order Overview ![Order Overview](_static/microsoft-power-bi/Orders_overview.png) The report consists of several sections, let's look at each of them: - **Order Total by Customer role** - The graph displays the distribution of orders by user roles. Keep in mind, though, that a user can have several roles, therefore information about orders will be displayed for each role of this user, respectively. In the example above, administrators are also registered users, so their orders are displayed for both summaries. - **Sales by Categories** - This report allows you to evaluate the sales share of product categories. - **Sales and Number of orders by Year and Month** - This chart is auxiliary and helps to understand the dynamics of sales growth over several time periods. This information can be used to analyze seasonal sales of a particular product category. Orders by Status ![Orders_by_status](_static/microsoft-power-bi/Orders_by_status.png) This report is intended to show the distribution of orders according to their statuses. This is important for understanding how many orders are being processed for the selected time period, how many of them have already been paid and how many have been completed. ### Monthly Performance ![Monthly_performance](_static/microsoft-power-bi/Monthly_performance.png) The report collects information about sales for a specified month in comparison with the previous month. This allows merchants to track best performing and underperforming products compared to the previous month. - **Order Total by Category** - The report collects all product sales by category for a specified month and compares them with the previous one. - **Best performing products** - The report includes only those products whose sales in the current month exceeded the sales in the previous one. - **Underperforming products** - The report includes only those products whose sales in the current month were lower than those in the previous month. ### Year to year comparison ![Year_to_year_comparison](_static/microsoft-power-bi/Year_to_year_comparison.png) The report asks you to compare sales for a given year with sales in the previous year. An interesting feature is the implementation of a cumulative sales schedule. This will allow you to analyze the dynamics of profit generation and predict an increase in sales for the future. ### Top Products ![Top_products](_static/microsoft-power-bi/Top_products.png) The report allows you to identify sales leaders in a specified category. Data is analyzed over the entire sales history. The report consists of several sections, let's look at each of them: - **Top Products by Order Total** - This chart displays the product rating based on the total order amount. - **Top Products by Number of Orders** - The chart ranks products, whose number of orders is presented in descending order. It helps you track your most frequently ordered products. - **Top Products by Quantity** - This chart shows the rating of products that were purchased in large numbers. - **Top Products by Customers Count** - The chart visualizes how many people purchased a particular product. The product rating is compiled regardless of repeat purchases from the same buyer. This way you can reach the audience that is interested in the product. - **Product list** - This general report represents all previous graphs in a table. ### Latest 20 Orders ![Latest_20_orders](_static/microsoft-power-bi/Latest_20_orders.png) The report allows you to track information on the latest 20 orders. This can be a convenient tool for the administrator to monitor the current store’s workload. ### Customers ![Customers](_static/microsoft-power-bi/Customers.png) Information about the number of registered users, the amount and number of their orders. The report can be built depending on the status of the order, shipment or payments, and all this can be seen for a selected period of time. ### Advanced Product Search ![Advanced_product_search](_static/microsoft-power-bi/Advanced_product_search.png) A report that provides an advanced product search option. ## Plugin installation This section describes how to integrate the Power BI service into your store. 1. [Purchase the integration](https://www.nopcommerce.com/microsoft-power-bi). 1. Download the plugin archive. 1. Go to admin area > configuration > local plugins. 1. Upload the plugin archive using the "Upload plugin or theme" plugin. 1. Scroll down through the list of plugins to find the newly installed plugin. And click on the "Install" button to install the plugin. ## Pre-configuration The following will describe the necessary and sufficient steps to set up the Power BI integration with nopCommerce. 1. [Register](https://app.powerbi.com/singleSignOn) or [log in](https://app.powerbi.com/home) to the Power BI service. The account must be your company’s account. ### Power BI Gateway 1. [Install](https://powerbi.microsoft.com/en-us/gateway/) a standard gateway **Power BI Gateway**. ![Install_Gateway](_static/microsoft-power-bi/Install_Gateway.png) 1. Launch the **Gateway**, to do this, launch the **On-premises data gateway** application. 1. Enter the email address for your account that you used when you signed up for the Power BI service. > [!NOTE] > > Your account is stored in the **Azure AD** tenant. ![OnPremisses_data_gateway](_static/microsoft-power-bi/OnPremisses_data_gateway.png) 1. Select the **Register a new gateway on this computer** ![Register_Gateway](_static/microsoft-power-bi/Register_Gateway.png) 1. Enter the gateway name. The name must be unique within the client. Also enter your recovery key. You will need this key to restore or move the gateway. ![Gateway_name](_static/microsoft-power-bi/Gateway_name.png) 1. Check that your gateway is ready for use. ![Check_Gateway](_static/microsoft-power-bi/Check_Gateway.png) ### Register your app Registering your application in Microsoft Entra establishes a trust relationship between your app and the Microsoft identity platform. Follow these steps to create the app registration: 1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). 1. If you have access to multiple tenants, use the *Settings* icon in the top menu to switch to the tenant in which you want to register the application. 1. Browse to **Identity > Applications > App registrations** and select *New registration*. 1. Enter a meaningful **Name** for your. 1. Under **Supported account types**, specify who can use the application. We recommend you select *Accounts in this organizational directory only* for your applications. 1. Select **Register** to complete the app registration. ![Azure_portal](_static/microsoft-power-bi/register_app.png) 1. The application's **Overview** page is displayed. Record the **Application (client) ID**, which uniquely identifies your application and is used in your plugin settings as part of validating the security tokens it receives from the Microsoft identity platform. ![Azure_portal](_static/microsoft-power-bi/app_id.png) > [!IMPORTANT] > > New app registrations are hidden to users by default. When you're ready for users to see the app on their My Apps page you can enable it. To enable the app, in the Microsoft Entra admin center navigate to **Identity > Applications > Enterprise applications** and select the app. Then on the **Properties** page, set **Visible to users?** to *Yes*. > ![Azure_portal](_static/microsoft-power-bi/properties.png) 1. Grant admin consent. To add permissions to your Azure AD app, follow these steps: - From the left, under *Manage*, select **API permissions**. - Select **Add a permission**. > ![Azure_portal](_static/microsoft-power-bi/request_api.png) - In the Request API permissions window, select Power BI Service. - Select **Delegated permissions**. A list of APIs is displayed. > ![Azure_portal](_static/microsoft-power-bi/delegated_permission.png) - Expand the API you want to add permissions to, and select the permissions you want to add to it. - Select **Add permissions**. > ![Azure_portal](_static/microsoft-power-bi/all_permission.png) 1. From the left, under Manage, select **Authentication**. 1. In **Advanced settings** > **Allow public client flows** > **Enable the following mobile and desktop flows:**, select **Yes**. > ![Allow_public_client_flows](_static/microsoft-power-bi/Allow_public_client_flows.png) 1. Go to the plugin configuration page and paste the resulting **Application ID**. > [!WARNING] > > Publishing a report is only possible if you use an MSSQL database. Connection configurations with other types of databases are not currently supported. ## Publish reports In this section, we'll look at the process of publishing a report to Power BI. If you do not plan to change the content of the report or modify its data model, then this procedure should be performed only once. After this, the integration of your store with the Power BI service will be permanent. All you need to do is to update the data either on a schedule or manually from your Power BI account. After this, all the reports described in this article will be available to you. 1. You must specify the name under which the report will be uploaded to the Power BI service. The Dataset will be named similarly. ![Publish-PBIX](_static/microsoft-power-bi/Publish-PBIX.png) 1. Next, a verification code will be generated to pass user verification. By default, it is copied to the clipboard for later pasting. Click the **Verify user** button. ![Verify](_static/microsoft-power-bi/Verify.png) 1. Paste the received code in the pop-up window. ![Enter_code](_static/microsoft-power-bi/Enter_code.png) 1. Next, select your account in PowerBI. ![Pick_an_account](_static/microsoft-power-bi/Pick_an_account.png) 1. Next, confirm that you are connecting to your application in Power BI. Click **Continue**. ![Confirm_connect](_static/microsoft-power-bi/Confirm_connect.png) 1. If you have successfully logged into your application, the following window will appear. Just wait until it closes on its own. ![Signed_on_device](_static/microsoft-power-bi/Signed_on_device.png) 1. At this step, you have an option to overwrite an existing report in Power BI under an already existing name. In this case, the following message appears: ![Replacing_dataset](_static/microsoft-power-bi/Replacing_dataset.png) 1. Next, you will need to choose which gateway to use to communicate with the data. Select the one you created earlier. ![Select_gateway](_static/microsoft-power-bi/Select_gateway.png) 1. Next, the report file will be published. ![Publish_complete](_static/microsoft-power-bi/Publish_complete.png) 1. You can now set up a data refresh schedule for your report in the dataset settings panel. ![Refresh_schedule](_static/microsoft-power-bi/Refresh_schedule.png) ## Troubleshooting ### Issue - The request body must contain the following parameter: 'client_assertion' or 'client_secret' If you encounter this error during the authorization process of your application, then to solve this problem you need to follow several steps described below: 1. In the [Microsoft Entra admin center](https://entra.microsoft.com/), select your app in **App registrations**, and then select **Authentication**. 1. In **Settings** > **Allow public client flows**, select **Enabled**. ![Allow_public_client_flows](_static/microsoft-power-bi/Allow_public_client_flows.png) ### Checking the correct connection and settings (in case of problems) - To verify that the gateway is correctly connected to your data source, you can check the connection status in the **Manage connections and gateways** section. ![Manage_connections_and_gateways](_static/microsoft-power-bi/Manage_connections_and_gateways.png) - Connecting to the gateway You need to make sure that the gateway is linked to your server. The machine name is indicated in the "Device" column. ![Connecting_to_the_gateway](_static/microsoft-power-bi/Connecting_to_the_gateway.png) - Connecting to the database ![Connecting_to_the_database](_static/microsoft-power-bi/Connecting_to_the_database.png) You can check your connection, which server and database it is configured to. ![Connection_Gateway](_static/microsoft-power-bi/Connection_Gateway.png) - (Optional) To verify that your data binding to the gateway settings are correct, log into your Power BI account and open your dataset settings. ![Dataset_settings](_static/microsoft-power-bi/Dataset_settings.png) - Check the connection to gateway from the drop-down list: If the status column says "Running on [Your_Server_Name]", then the connection to the gateway is configured correctly. You can check the details in the "Actions" column. ![Check_gateway_connection](_static/microsoft-power-bi/Check_gateway_connection.png) ## View reports Published reports can be viewed in several ways: 1. Directly in your Power BI account under the **My Workspace** [tab](https://app.powerbi.com/groups/me/list?experience=power-bi). 1. Directly on the Power BI plugin configuration page in the **View reports** panel using Power BI embedded analytics. Let's take a closer look at the second scenario, since it is part of the integration. > [!TIP] > > More information about [Power BI embedded analytics](https://learn.microsoft.com/en-us/power-bi/developer/embedded/embedded-analytics-power-bi). The process for viewing reports is similar to the publishing process. After successful user verification, all reports in your Workspace will be available in the **View reports** panel of the plugin. > [!WARNING] > > Each time you view reports, you must go through a user authorization process, this is due to the fact that the Power BI service issues an access token for a limited time. > ![Report_list](_static/microsoft-power-bi/Report_list.png) The default currency is the *US dollar*. For technical reasons, the integration does not use the main currency of the store and if it is necessary to change it in reports, then this must be done manually. To change the currency, you need to edit the format of all numeric indicators in the measures. ![Currency](_static/microsoft-power-bi/Currency.png) By default, the currency format is set to "*Currency General*", which should cause the currencies to be reformatted when the regional settings for the report are changed. ## License The Power BI plugin is licensed under the following [terms](https://www.nopcommerce.com/microsoft-power-bi-license-terms). --- <!-- page: System administration | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/index.html | source: en/running-your-store/system-administration/index.md --> # System administration This chapter covers the technical aspects of running a nopCommerce store. It describes how to expand the store functionality by technical means, such as additional external plugins, external authentication for easier checkout process, configuration of widgets, and setting up email accounts. This chapter focuses more on the back end; the front end is covered in the [Design](xref:en/getting-started/design-your-store/index) chapter. ## See here * [System information](xref:en/running-your-store/system-administration/system-information) * [Log](xref:en/running-your-store/system-administration/log) * [Warnings](xref:en/running-your-store/system-administration/warnings) * [Maintenance](xref:en/running-your-store/system-administration/maintenance) * [Message queue](xref:en/running-your-store/system-administration/message-queue) * [Schedule tasks](xref:en/running-your-store/system-administration/schedule-tasks) * [Templates](xref:en/running-your-store/system-administration/templates) --- <!-- page: System information | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/system-information.html | source: en/running-your-store/system-administration/system-information.md --> # System information The following procedure describes how to view the system information of the store and system server. To view system information, go to the **System** menu, select **System Information**. The *System information* will be displayed as follows: ![System information](_static/system-information/system-information.png) --- <!-- page: Log | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/log.html | source: en/running-your-store/system-administration/log.md --> # Log The system log report displays a list of all the errors, warnings, and information messages created in the system. To view the log, go to **System → Log**. The *Log* window will be displayed as follows: ![Log](_static/log/log.png) A log item includes the log type, description of the error, and date. You can click the **Delete selected** button to remove the selected log items or click the **Clear log** button to clear the entire log. To search for a system log, enter one or more of the following pieces of information: * In the **Created from** field, select the start date for the search. * In the **Created to** field, select the end date for the search. * In the **Message** field, select the message or its fragment to search by. * From the **Log level** dropdown list, select the type of log information to display as follows: * *All* * *Debug* * *Information* * *Warning* * *Error* * *Fatal* Click **Search**. The log system window will be displayed based on the search criteria. ## View system log details Clicking **View** displays additional details of the error that occurred, as follows: ![Log entry - Details](_static/log/log-details.jpg) You can click **Delete** to remove a log from the system if required. --- <!-- page: Warnings | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/warnings.html | source: en/running-your-store/system-administration/warnings.md --> # Warnings The following procedure describes how to view all the warnings that currently exist in the store. To view store warnings, go to **System → Warnings**. The *Warnings* window will be displayed as follows: ![Warnings](_static/warnings/warnings.jpg) We recommend that you fix all the existing warnings. Otherwise, they will affect your store's efficiency and performance. Refer to the following articles in order to fix the existing warnings: * [Your store information](xref:en/getting-started/advanced-configuration/your-store-information) * [Currencies](xref:en/getting-started/configure-payments/advanced-configuration/currencies) * [Measures](xref:en/getting-started/configure-shipping/advanced-configuration/measures) * [Payment methods](xref:en/getting-started/configure-payments/payment-methods/index) * [Plugins in nopCommerce](xref:en/getting-started/advanced-configuration/plugins-in-nopcommerce) --- <!-- page: Maintenance | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/maintenance.html | source: en/running-your-store/system-administration/maintenance.md --> # Maintenance In the **System** menu, select **Maintenance**. ## Delete guest customer records ![Maintenance](_static/maintenance/deleting_guest_customers.png) In the *Deleting guest customers* panel, click the **Delete** button. This option enables you to delete customer records created for guest visitors. > [!NOTE] > > Only guests without orders or written customer content (such as product reviews or news comments) will be deleted. ## Deleting old exported files ![Maintenance](_static/maintenance/old_export.png) In the *Deleting old exported files* panel, click the **Delete** button. All the exported and generated files (such as PDF and Excel files) will be deleted and removed from the database. ## Delete abandoned shopping carts and wishlists ![Maintenance](_static/maintenance/deleting_abandoned_sc.png) In the *Deleting abandoned shopping carts* panel, click the **Delete** button. All shopping cart and wishlist items created before the specified date will be deleted. ## Re-index database tables ![Maintenance](_static/maintenance/re-index.png) In the *Re-index database tables* panel, click the **Re-index** button. This procedure modifies existing tables by rebuilding the index. When you execute re-indexing in a table, only the statistics associated with the indexes are updated. Automatic or manual statistics created in the table (instead of an index) are not updated. ## Database backups ![Maintenance](_static/maintenance/db_backup.png) In the *Database backups* panel, click the **Backup now** button to create a database backup. > [!NOTE] > > Database backup functionality only works when your nopCommerce application is deployed on the same server as the database. Otherwise, you will have to take care of the backup yourself (contact your system administrator). ## Delete already sent emails ![Maintenance](_static/maintenance/delete_already_sent_emails.png) ## Delete minification files ![Maintenance](_static/maintenance/delete_min_files.png) ## Shrink database ![Maintenance](_static/maintenance/shrink.png) ## Delete image thumbs ![Maintenance](_static/maintenance/delete_image_thumbs.png) ## Clear search history ![Maintenance](_static/maintenance/clear_search_history.png) ## Tutorials [Overview of system maintenance options](https://www.youtube.com/watch?v=CNgTJZoWHTA) --- <!-- page: Message queue | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/message-queue.html | source: en/running-your-store/system-administration/message-queue.md --> # Message queue Emails are not sent immediately in nopCommerce. They are queued. A message queue contains all emails already sent or not yet sent. To load the message queue, in the **System** menu, select **Message queue**. The *Message queue* window will be displayed as follows: ![Message queue](_static/message-queue/message-queue.png) Enter one or more of the following criteria to search for messages: * In the **Start date** field, select the start date. * In the **End date** field, select the end date. * In the **From address** field, enter the source address of a message. * In the **To address** field, enter the target address of a message. * Select the **Load not sent emails only** checkbox to only load emails that have not been sent yet. * In the **Maximum send attempts** field, enter the maximum number of attempts to send a message. * In the **Go directly to email #** field, enter the email number and click **Go** to display the required email. Click **Search** to load the message queue matching the criteria. On this page, you can click the **Delete selected** button to delete selected emails from the grid. You can click **Delete all** to remove all emails. ## Message queue item details To view the message queue item details, click the **Edit** button beside the message. The *Edit message queue item* window will be displayed: ![Message queue item details](_static/message-queue/edit.png) In this window, you can delete the message by clicking the **Delete** button. Or you can requeue the message using the **Requeue** button. On this page, you can edit the following message details: * **From** email address. * **From name**. * **To** email address. * **To name**. * **ReplyTo** email address. * **ReplyTo name**. * **Cc** email address. * **Bcc** email address. * Email message **Subject**. * Email message **Body**. * Select the **Send immediately** checkbox to send this message immediately. * Enter the number of **Sent attempts**. This is the number of attempts to send this message. Click **Save** or **Save and continue edit** to save the message details. --- <!-- page: Schedule tasks | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/schedule-tasks.html | source: en/running-your-store/system-administration/schedule-tasks.md --> # Schedule tasks The *Schedule tasks* window enables the store owner to schedule a task to run during certain periods in the background and to view useful information regarding the task and whether it was completed successfully. For example, nopCommerce sends queued emails periodically. The tasks run on a separate thread coming from the ASP.NET thread pool. To view the scheduled tasks, in the **System** menu, select **Schedule tasks**. The *Schedule tasks* window will be displayed as follows: ![Schedule tasks](_static/schedule-tasks/schedule-tasks.png) To edit a scheduled task, click the **Edit** button beside the task. The window will expand as follows: ![Schedule tasks - Edit](_static/schedule-tasks/schedule-tasks-edit.png) You can edit the scheduled task as follows: * Edit the **Name**. * Edit the number of **Seconds (run period)**. A task period should not exceed 24 days. * Select the **Enabled** checkbox in order to enable the task. * Select the **Stop on error** checkbox in order to stop the task when an error occurs. Click **Update** to save your changes. > [!NOTE] > > Do not forget to restart the application once a task has been modified. If required, you can click **Run now** to run a scheduled task on demand. --- <!-- page: Templates | url: http://nopdocs.service.hedr.dev/en/running-your-store/system-administration/templates.html | source: en/running-your-store/system-administration/templates.md --> # Templates In nopCommerce, you can specify an alternate layout template for a category, manufacturer, product, and topic. You can see a list of the existing templates on the **System → Templates** page: ![Templates](_static/templates/templates.jpg) By default, there is one category template, one manufacturer template, one topic template, and two product templates in the system. Each category, manufacturer, product, and topic details page in the admin area allow you to choose the template when editing an entity. For example: ![Category templates](_static/templates/category-templates.jpg) > [!NOTE] > > You will only see the template dropdown list if you have more than one template created for categories, manufacturers, and topics. > > [!NOTE] > > Since we have two product types, *Simple* and *Grouped (product with variants)*, we have two appropriate product templates created by default: > ![Product templates list](_static/templates/product-templates-list.jpg) > > Therefore, to see the template dropdown list on the product details page, you need to create two product templates that fit the chosen product type. Read about how to do this below. ## Add a new template Let's see how to create a template on the product template example. Let's say you want to create it for the *Simple* product type. 1. First of all, you need to create an appropriate template file. Skip this step if you already have one placed in the right folder. - Go to the `Views\Product` folder. - Copy the `ProductTemplate.Simple.cshtml` file and rename it. Let's say it will be `ProductTemplate.MyNewOne.cshtml`. - Modify the code of the `ProductTemplate.MyNewOne.cshtml` file to fit your needs. 1. Go to the **System → Templates** page and proceed to the *Product templates* panel: ![Create a product template](_static/templates/product-templates-with-form.jpg) 1. In the *Add new record* block, fill in the following form: - Enter the **Name** of the template. In our case, it's `My New One`. - Enter the **View path**. In our case, it's `ProductTemplate.MyNewOne`. - Enter the **Display order** of this template. 1 represents the top of the list. - *For the product template only. Not applicable for other templates:* Enter the **Ignored product type IDs (advanced)**. By default, we have two product types and appropriate product type IDs: *Simple* (ID 5) and *Grouped (ID 10)*. Since we are creating a template for the *Simple* product type, we should ignore the *Grouped* product type with ID 10. So the form will look as follows: ![Form](_static/templates/form.jpg) 1. Click the **Add new record** button to save the new template. After you save the new template, you will see it on the product details page, and now you can choose from two product templates: ![Product details page](_static/templates/choose.jpg) > [!NOTE] > > It's not required to restrict a product template using the **Ignored product type IDs (advanced)** field. If you leave this field empty, you will be able to use the product template for all types of products. --- <!-- page: Developers guide | url: http://nopdocs.service.hedr.dev/en/developer/index.html | source: en/developer/index.md --> # Developers guide The nopCommerce developer documentation is here to help you through the process of nopCommerce customization. Here you will find several sections: * [Developer tutorials](xref:en/developer/tutorials/index) * [Creating a nopCommerce plugin](xref:en/developer/plugins/index) * [Designer's Guide](xref:en/developer/design/index) * [Web API documentation](xref:en/developer/web-api/index) * [Mobile app documentation](xref:en/developer/mobile-app/index) * [Microsoft Dynamics 365](xref:en/developer/ms-dynamics-365/index) --- <!-- page: Developer tutorials | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/index.html | source: en/developer/tutorials/index.md --> # Developers tutorials The following is a list of common questions asked by developers working with nopCommerce. It also describes some of the architectural choices the nopCommerce team made. * [System Requirements for Development](xref:en/developer/tutorials/system-requirements-for-developing) * [Coding Standards](xref:en/developer/tutorials/coding-standards) * [Architecture of nopCommerce](xref:en/developer/tutorials/architecture-of-nopCommerce) * [Source Code Organization](xref:en/developer/tutorials/source-code-organization) * [Getting Started with nopCommerce Development](xref:en/developer/tutorials/instruction-on-how-to-start-developing-on-nopcommerce) * [Default Database Schema](xref:en/developer/tutorials/db-schema) * [Updating an Existing Entity (how to add a new property)](xref:en/developer/tutorials/update-existing-entity) * [Database Migrations](xref:en/developer/tutorials/migrations) * [Inversion of Control and Dependency Injection](xref:en/developer/tutorials/inversion-of-control) * [Registering New Routes](xref:en/developer/tutorials/register-new-routes) * [Introduction to Plugin System](xref:en/developer/tutorials/description-of-plugin-system) * [Develop a New Plugin](xref:en/developer/tutorials/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin) * [Using DataTables](xref:en/developer/tutorials/guide-to-creating-a-page-containing-a-reporting-table-of-datatables) * [Data Validation](xref:en/developer/tutorials/data-validation) * [Exposing and Handling Events](xref:en/developer/tutorials/events) * [Settings API](xref:en/developer/tutorials/settings) * [Settings in appsettings.json](xref:en/developer/tutorials/appsettings-json-file) * [Settings in web.config](xref:en/developer/tutorials/description-of-the-web-config-file-in-project) * [Extending Permissions](xref:en/developer/tutorials/permissions) * [Scheduled Tasks](xref:en/developer/tutorials/scheduled-tasks) * [ITypeFinder Interface](xref:en/developer/tutorials/type-finder) * [Deployment on Azure with Git and Automatic Builds](xref:en/developer/tutorials/azure-deploy) * [Using Docker](xref:en/developer/tutorials/docker) * [Deploy nopCommerce to an Azure VM](xref:en/developer/tutorials/azure-publish) * [Content Security Policy (CSP) Headers](xref:en/developer/tutorials/csp-headers) * [Unit Testing](xref:en/developer/tutorials/unit-tests) --- <!-- page: System Requirements for Development | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/system-requirements-for-developing.html | source: en/developer/tutorials/system-requirements-for-developing.md --> # System Requirements for Development ## Operating System ### Windows | OS | Version | | ----------------- | ---------------------------------------- | | Windows 11 | 26H1, 25H2, 24H2 (IoT), 24H2 (E), 24H2, 23H2 (E) | | Windows 10 Client | 21H2 (E), 21H2 (IoT), 1809 (E), 1607 (E) | | Windows Server | 2025, 23H2, 2022, 2019, 2016 | | Nano Server | 2025, 2022, 2019 | ### Linux | OS | Version | | ---------------------------- | ------------------- | | Red Hat Enterprise Linux | 10, 9, 8 | | Fedora | 44, 43 | | Debian | 13 | | Ubuntu | 26.04, 24.04, 22.04 | | openSUSE Leap | 16.0 | | SUSE Enterprise Linux | 16.0, 15.7 | | Alpine Linux | 3.24, 3.23, 3.22, 3.21 | Other distributions are supported at best effort, per [.NET Support and Compatibility for Linux Distributions](https://github.com/dotnet/core/blob/main/linux.md). ### Apple | OS | Version | | -------- | ---------- | |iOS |27, 26, 18 | |iPadOS |27, 26, 18 | |macOS |27, 26, 15 | |tvOS |27, 26 | ### Android | OS | Version | | -------- | ---------- | |Android |17, 16, 15, 14| > [!NOTE] > > Find a complete [list of supported operation systems](https://github.com/dotnet/core/blob/main/release-notes/10.0/supported-os.md). > > [!IMPORTANT] > > The **Windows Client 7 SP1, 8.1** operating systems are no longer supported, starting with .NET 7.0. > > For more information about supported OS versions please visit [this page](https://github.com/dotnet/core/blob/main/release-notes/10.0/supported-os.md). ## Supported Browsers * Microsoft Edge. Microsoft Internet Explorer 9 and above (IE6 and IE7 were supported in versions prior 3.60, IE8 was support in versions prior 4.10) * Mozilla Firefox 2.0 and above * Google Chrome 1.x and above * Apple Safari 12.x and above ## Tools Required for Development Since it is based on Microsoft's .NET 10 we need to install a few tools before starting development on top of nopCommerce. ### .NET 10 runtime & .NET 10 SDK Since nopCommerce 5.00 is based on .NET 10. We need to install [.NET 10 runtime](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-aspnetcore-10.0.12-windows-x64-installer) and [.NET 10 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-10.0.401-windows-x64-installer) before we start development on nopCommerce. ### Visual Studio Visual Studio 2026 (v18.0) or Above / Visual Studio Code As we know, nopCommerce is based on "Microsoft .NET 10" and *Visual Studio IDE* is best for developing .Net based applications. Since .NET Core is platform independent, we can develop and deploy a .Net based application on any platform. But we can use *Visual Studio Code* as an alternative to *Visual Studio* for developing on Windows as well as other platforms. > [!NOTE] > > If you are using *Visual Studio Code*, you will need to install the **C# Dev Kit** official C# extension from Microsoft. ### Microsoft SQL Server 2016 or Above / MySql Server 8 or Above / PostgreSQL 15 or Above Starting from the 4.30 version, nopCommerce uses *Linq2DB* as an ORM Framework. *Linq2DB* is an object-relational mapper (ORM) that enables .NET developers to work with a database using .NET objects. It can map .Net objects to various numbers of Database providers. You may choose between MS SQL Server, MySql Server, and PostgreSQL. > [!NOTE] > > For more information about supported databases please visit [this page](https://linq2db.github.io/articles/general/databases.html) ### Internet Information Service (IIS) 7.0 or above One option for hosting a nopCommerce app/project is IIS, a Microsoft technology that hosts web-based applications on Windows. However, nopCommerce can also run on Linux and MacOS, which do not support IIS. In that case, you can use alternative tools like Apache or Nginx to host your application on a Linux server. --- <!-- page: Coding Standards | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/coding-standards.html | source: en/developer/tutorials/coding-standards.md --> # Coding Standards nopCommerce has specific coding guidelines that developers should follow when creating source code. The [.editorconfig](https://github.com/nopSolutions/nopCommerce/blob/develop/.editorconfig) file in Visual Studio helps to enforce the desired code style. There are three supported .NET coding convention categories: - Language conventions - Formating conventions - Naming conventions ## Language conventions ### .NET code style settings #### "this." qualifiers This style rule can be applied to fields, properties, methods, or events. - Prefer the code element *not* to be prefaced with `this.` - Prefer fields *not* to be prefaced with `this.` ```csharp //Right capacity = 0; ``` ```csharp //Wrong this.capacity = 0; ``` - Prefer properties *not* to be prefaced with `this.` ```csharp //Right ID = 0; ``` ```csharp //Wrong this.ID = 0; ``` - Prefer methods *not* to be prefaced with `this.` ```csharp //Right Display(); ``` ```csharp //Wrong this.Display(); ``` - Prefer events *not* to be prefaced with `this.` ```csharp //Right Elapsed += Handler; ``` ```csharp //Wrong this.Elapsed += Handler; ``` #### Language keywords instead of framework type names for type references This style rule can be applied to local variables, method parameters, and class members, or as a separate rule to type member access expressions. - Prefer the language keyword for local variables, method parameters, and class members, instead of the type name, for types that have a keyword to represent them. ```csharp //Right private int _member; ``` ```csharp //Wrong private Int32 _member; ``` - Prefer the language keyword for member access expressions, instead of the type name, for types that have a keyword to represent them. ```csharp //Right var local = int.MaxValue; ``` ```csharp //Wrong var local = Int32.MaxValue; ``` #### Modifier preferences The style rules in this section concern modifier preferences, including requiring accessibility modifiers, specifying the desired modifier sort order, and requiring the read-only modifier. - Prefer accessibility modifiers to be declared except for public interface members. ```csharp //Right class MyClass { private const string thisFieldIsConst = "constant"; } ``` ```csharp //Wrong class MyClass { const string thisFieldIsConst = "constant"; } ``` - Prefer the specified ordering: *`public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async:silent`* ```csharp //Right class MyClass { private static readonly int _daysInYear = 365; } ``` #### Parentheses preferences The style rules in this section concern parentheses preferences, including the use of parentheses for arithmetic, relational, and other binary operators. - Prefer parentheses to clarify arithmetic operator (*, /, %, +, -, <<, >>, &, ^, |) precedence ```csharp //Right var v = a + (b * c); ``` ```csharp //Wrong var v = a + b * c; ``` - Prefer parentheses to clarify relational operator (>, <, <=, >=, is, as, ==, !=) precedence ```csharp //Right var v = (a < b) == (c > d); ``` ```csharp //Wrong var v = a < b == c > d; ``` - Prefer parentheses to clarify other binary operators (&&, ||, ??) precedence ```csharp //Right var v = a || (b && c); ``` ```csharp //Wrong var v = a || b && c; ``` - Prefer to not have parentheses when operator precedence is obvious ```csharp //Right var v = a.b.Length; ``` ```csharp //Wrong var v = (a.b).Length; ``` #### Expression-level preferences The style rules in this section concern expression-level preferences, including the use of object initializers, collection initializers, explicit or inferred tuple names, and inferred anonymous types. - Prefer objects to be initialized using object initializers when possible ```csharp //Right var c = new Customer() { Age = 21 }; ``` ```csharp //Wrong var c = new Customer(); c.Age = 21; ``` - Prefer collections to be initialized using collection initializers when possible ```csharp //Right var list = new List<int> { 1, 2, 3 }; ``` ```csharp //Wrong var list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); ``` - Prefer tuple names to ItemX properties ```csharp //Right (string name, int age) customer = GetCustomer(); var name = customer.name; ``` ```csharp //Wrong (string name, int age) customer = GetCustomer(); var name = customer.Item1; ``` - Prefer inferred tuple element names ```csharp //Right var tuple = (age, name); ``` ```csharp //Wrong var tuple = (age: age, name: name); ``` - Prefer explicit anonymous type member names ```csharp //Right var anon = new { age = age, name = name }; ``` ```csharp //Wrong var anon = new { age, name }; ``` - Prefer auto-properties over properties with private backing fields ```csharp //Right private int Age { get; } ``` ```csharp //Wrong private int age; public int Age { get { return age; } } ``` - Prefer using a null check with pattern-matching over *`object.ReferenceEquals`* ```csharp //Right if (value is null) return; ``` ```csharp //Wrong if (object.ReferenceEquals(value, null)) return; ``` - Prefer assignments with a ternary conditional over an if-else statement ```csharp //Right string s = expr ? "hello" : "world"; ``` ```csharp //Wrong string s; if (expr) { s = "hello"; } else { s = "world"; } ``` - Prefer return statements to use a ternary conditional over an if-else statement ```csharp //Right return expr ? "hello" : "world"; ``` ```csharp //Wrong if (expr) { return "hello"; } else { return "world"; } ``` - Prefer compound assignment expressions ```csharp //Right x += 1; ``` ```csharp //Wrong x = x + 1; ``` #### Null-checking preferences The style rules in this section concern null-checking preferences. - Prefer null coalescing expressions to ternary operator checking ```csharp //Right var v = x ?? y; ``` ```csharp //Wrong var v = x != null ? x : y; // or var v = x == null ? y : x; ``` - Prefer to use a null-conditional operator when possible ```csharp //Right var v = o?.ToString(); ``` ```csharp //Wrong var v = o == null ? null : o.ToString(); // or var v = o != null ? o.String() : null; ``` ### C# code style settings #### Implicit and explicit types The style rules in this section concern the use of the var keyword versus an explicit type in a variable declaration. This rule can be applied separately to built-in types, when the type is apparent, and elsewhere. - Prefer *`var`* is used to declare variables with built-in system types such as *`int`* ```csharp //Right var x = 5; ``` ```csharp //Wrong int x = 5; ``` - Prefer *`var`* when the type is already mentioned on the right-hand side of a declaration expression ```csharp //Right var obj = new Customer(); ``` ```csharp //Wrong Customer obj = new Customer(); ``` - Prefer *`var`* over explicit type in all cases, unless overridden by another code style rule ```csharp //Right var f = this.Init(); ``` ```csharp //Wrong bool f = this.Init(); ``` #### Expression-bodied members The style rules in this section concern the use of [expression-bodied members](https://docs.microsoft.com/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) when the logic consists of a single expression. This rule can be applied to methods, constructors, operators, properties, indexers, and accessors. - Prefer block bodies for methods ```csharp //Right public int GetAge() { return this.Age; } ``` ```csharp //Wrong public int GetAge() => this.Age; ``` - Prefer block bodies for constructors ```csharp //Right public Customer(int age) { Age = age; } ``` ```csharp //Wrong public Customer(int age) => Age = age; ``` - Prefer block bodies for operators ```csharp //Right public static ComplexNumber operator + (ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } ``` ```csharp //Wrong public static ComplexNumber operator + (ComplexNumber c1, ComplexNumber c2) => new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); ``` - Prefer expression bodies for properties when they will be a single line ```csharp //Right public int Age => _age; ``` ```csharp //Wrong public int Age { get { return _age; }} ``` - Prefer expression bodies for indexers ```csharp //Right public T this[int i] => _values[i]; ``` ```csharp //Wrong public T this[int i] { get { return _values[i]; } } ``` - Prefer expression bodies for accessors ```csharp //Right public int Age { get => _age; set => _age = value; } ``` ```csharp //Wrong public int Age { get { return _age; } set { _age = value; } } ``` - Prefer expression bodies for lambdas ```csharp //Right Func<int, int> square = x => x * x; ``` ```csharp //Wrong Func<int, int> square = x => { return x * x; }; ``` #### Pattern matching The style rules in this section concern the use of [pattern matching](https://docs.microsoft.com/dotnet/csharp/pattern-matching) in C#. - Prefer pattern matching instead of is expressions with type casts ```csharp //Right if (o is int i) {...} ``` ```csharp //Wrong if (o is int) {var i = (int)o; ... } ``` - Prefer pattern matching instead of *`as`* expressions with null checks to determine if something is of a particular type ```csharp //Right if (o is string s) {...} ``` ```csharp //Wrong var s = o as string; if (s != null) {...} ``` #### Inlined variable declarations This style rule concerns whether out variables are declared inline or not. Starting in C# 7, you can [declare an out variable in the argument list of a method call](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/out-parameter-modifier#calling-a-method-with-an-out-argument), rather than in a separate variable declaration. - Prefer *`out`* variables to be declared inline in the argument list of a method call when possible ```csharp //Right if (int.TryParse(value, out int i)) {...} ``` ```csharp //Wrong int i; if (int.TryParse(value, out i)) {...} ``` #### C# expression-level preferences This style rule concerns using the [default literal for default value expressions](https://docs.microsoft.com/dotnet/csharp/programming-guide/statements-expressions-operators/default-value-expressions#default-literal-and-type-inference) when the compiler can infer the type of the expression. - Prefer *`default`* over *`default(T)`* ```csharp //Right void DoWork(CancellationToken cancellationToken = default) { ... } ``` ```csharp //Wrong void DoWork(CancellationToken cancellationToken = default(CancellationToken)) { ... } ``` #### C# null-checking preferences These style rules concern the syntax around null checking, including using throw expressions or throw statements, and whether to perform a null check or use the conditional coalescing operator (?.) when invoking a [lambda expression](https://docs.microsoft.com/dotnet/csharp/lambda-expressions). - Prefer to use throw expressions instead of throw statements ```csharp //Right this.s = s ?? throw new ArgumentNullException(nameof(s)); ``` ```csharp //Wrong if (s == null) { throw new ArgumentNullException(nameof(s)); } this.s = s; ``` - Prefer to use the conditional coalescing operator (?.) when invoking a lambda expression, instead of performing a null check ```csharp //Right func?.Invoke(args); ``` ```csharp //Wrong if (func != null) { func(args); } ``` #### Code block preferences This style rule concerns the use of curly braces { } to surround code blocks. - Prefer no curly braces if allowed ```csharp //Right if (test) this.Display(); ``` ```csharp //Wrong if (test) { this.Display(); } ``` ## Formatting conventions ### .NET formatting settings ### Organize using directives These formatting rules concern the sorting and display of *`using`* directives and *`Imports`* statements. - Sort `System.*` *`using`* directives alphabetically, and place them before other using directives. ```csharp //Right using System.Collections.Generic; using System.Threading.Tasks; using Octokit; ``` ```csharp //Wrong using System.Collections.Generic; using Octokit; using System.Threading.Tasks; ``` - Do not place a blank line between using directive groups. ```csharp //Right using System.Collections.Generic; using System.Threading.Tasks; using Octokit; ``` ```csharp //Wrong using System.Collections.Generic; using System.Threading.Tasks; using Octokit; ``` ### C# formatting settings The formatting rules in this section apply only to C# code. #### New-line options These formatting rules concern the use of new lines to format code. - Require braces to be on a new line for all expressions ("Allman" style). ```csharp //Right void MyMethod() { if (...) { ... } } ``` ```csharp //Wrong void MyMethod() { if (...) { ... } } ``` - Place else statements on a new line. ```csharp //Right if (...) { ... } else { ... } ``` ```csharp //Wrong if (...) { ... } else { ... } ``` - Place catch statements on a new line. ```csharp //Right try { ... } catch (Exception e) { ... } ``` ```csharp //Wrong try { ... } catch (Exception e) { ... } ``` - Require finally statements to be on a new line after the closing brace. ```csharp //Right try { ... } catch (Exception e) { ... } finally { ... } ``` ```csharp //Wrong try { ... } catch (Exception e) { ... } finally { ... } ``` - Require members of object initializers to be on separate lines ```csharp //Right var z = new B() { A = 3, B = 4 } ``` ```csharp //Wrong var z = new B() { A = 3, B = 4 } ``` - Require members of anonymous types to be on separate lines ```csharp //Right var z = new { A = 3, B = 4 } ``` ```csharp //Wrong var z = new { A = 3, B = 4 } ``` - Require elements of query expression clauses to be on separate lines ```csharp //Right var q = from a in e from b in e select a * b; ``` ```csharp //Wrong var q = from a in e from b in e select a * b; ``` #### Indentation options These formatting rules concern the use of indentation to format code. - Indent *`switch`* case contents ```csharp //Right switch(c) { case Color.Red: Console.WriteLine("The color is red"); break; case Color.Blue: Console.WriteLine("The color is blue"); break; default: Console.WriteLine("The color is unknown."); break; } ``` ```csharp //Wrong switch(c) { case Color.Red: Console.WriteLine("The color is red"); break; case Color.Blue: Console.WriteLine("The color is blue"); break; default: Console.WriteLine("The color is unknown."); break; } ``` - Indent *`switch`* labels ```csharp //Right switch(c) { case Color.Red: Console.WriteLine("The color is red"); break; case Color.Blue: Console.WriteLine("The color is blue"); break; default: Console.WriteLine("The color is unknown."); break; } ``` ```csharp //Wrong switch(c) { case Color.Red: Console.WriteLine("The color is red"); break; case Color.Blue: Console.WriteLine("The color is blue"); break; default: Console.WriteLine("The color is unknown."); break; } ``` - Labels are placed at the same indent as the current context ```csharp //Right class C { private string MyMethod(...) { if (...) { goto error; } error: throw new Exception(...); } } ``` ```csharp //Wrong class C { private string MyMethod(...) { if (...) { goto error; } error: throw new Exception(...); } } ``` ```csharp //Wrong class C { private string MyMethod(...) { if (...) { goto error; } error: throw new Exception(...); } } ``` #### Spacing options These formatting rules concern the use of space characters to format code. - Remove space between the cast and the value ```csharp //Right int y = (int)x; ``` ```csharp //Wrong int y = (int) x; ``` - Place a space character after a keyword in a control flow statement such as a *`for`* loop ```csharp //Right for (int i;i<x;i++) { ... } ``` ```csharp //Wrong for(int i;i<x;i++) { ... } ``` - Place a space character before the colon for bases or interfaces in a type declaration ```csharp //Right interface I { } class C : I { } ``` ```csharp //Wrong interface I { } class C: I { } ``` - Place a space character after the colon for bases or interfaces in a type declaration ```csharp //Right interface I { } class C : I { } ``` ```csharp //Wrong interface I { } class C :I { } ``` - Insert space before and after the binary operator ```csharp //Right return x * (x - y); ``` ```csharp //Wrong return x*(x-y); ``` ```csharp //Wrong return x * (x-y); ``` - Remove space characters after the opening parenthesis and before the closing parenthesis of a method declaration parameter list ```csharp //Right void Bark(int x) { ... } ``` ```csharp //Wrong void Bark( int x ) { ... } ``` - Remove space within empty parameter list parentheses for a method declaration ```csharp //Right void Goo() { Goo(1); } void Goo(int x) { Goo(); } ``` ```csharp //Wrong void Goo( ) { Goo(1); } void Goo(int x) { Goo(); } ``` - Remove space characters between the method name and opening parenthesis in the method declaration ```csharp //Right void M() { } ``` ```csharp //Wrong void M () { } ``` - Remove space characters after the opening parenthesis and before the closing parenthesis of a method call ```csharp //Right MyMethod(argument); ``` ```csharp //Wrong MyMethod( argument ); ``` - Remove space within empty argument list parentheses ```csharp //Right void Goo() { Goo(1); } void Goo(int x) { Goo(); } ``` ```csharp //Wrong void Goo() { Goo(1); } void Goo(int x) { Goo( ); } ``` - Remove space between method call name and opening parenthesis ```csharp //Right void Goo() { Goo(1); } void Goo(int x) { Goo(); } ``` ```csharp //Wrong void Goo() { Goo(1); } void Goo(int x) { Goo (); } ``` - Insert space after a comma ```csharp //Right int[] x = new int[] { 1, 2, 3, 4, 5 }; ``` ```csharp //Wrong int[] x = new int[] { 1,2,3,4,5 }; ``` - Remove space before a comma ```csharp //Right int[] x = new int[] { 1, 2, 3, 4, 5 }; ``` ```csharp //Wrong int[] x = new int[] { 1 , 2 , 3 , 4 , 5 }; ``` - Insert space after each semicolon in a for statement ```csharp //Right for (int i = 0; i < x.Length; i++) ``` ```csharp //Wrong for (int i = 0;i < x.Length;i++) ``` - Remove space before each semicolon in a for statement ```csharp //Right for (int i = 0; i < x.Length; i++) ``` ```csharp //Wrong for (int i = 0 ; i < x.Length ; i++) ``` - Remove extra space characters in declaration statements ```csharp //Right int x = 0; ``` ```csharp //Wrong int x = 0 ; ``` - Remove space before opening square brackets *`[`* ```csharp //Right int[] numbers = new int[] { 1, 2, 3, 4, 5 }; ``` ```csharp //Wrong int [] numbers = new int [] { 1, 2, 3, 4, 5 }; ``` - Remove space between empty square brackets *`[]`* ```csharp //Right int[] numbers = new int[] { 1, 2, 3, 4, 5 }; ``` ```csharp //Wrong int[ ] numbers = new int[ ] { 1, 2, 3, 4, 5 }; ``` - Remove space characters in non-empty square brackets *`[0]`* ```csharp //Right int index = numbers[0]; ``` ```csharp //Wrong int index = numbers[ 0 ]; ``` #### Wrap options These formatting rules concern the use of single lines versus separate lines for statements and code blocks. - Leave statements and member declarations on different lines ```csharp //Right int i = 0; string name = "John"; ``` ```csharp //Wrong int i = 0; string name = "John"; ``` - Leave code block on a single line ```csharp //Right public int Foo { get; set; } ``` ```csharp //Wrong public int MyProperty { get; set; } ``` ## Naming conventions - Constants are named only in capital letters with a delimiter *`_`* ```csharp //Right const int TEST_CONSTANT = 1; ``` ```csharp //Wrong const int Test_Constant = 1; ``` - Fields with *`public`* access are referred to as PascalCase notation ```csharp //Right public int TestField; ``` ```csharp //Wrong public int testField; ``` - Interface names must be in PascalCase notation and have the prefix *`I`* ```csharp //Right public interface ITestInterface; ``` ```csharp //Wrong public interface testInterface; ``` - The names of classes, structures, methods, enums, events, properties, namespaces, and delegates should be in PascalCase notation ```csharp //Right public class SomeClass; ``` ```csharp //Wrong public class someClass; ``` - Use a descriptive name in PascalCase for the parameter of a generic type, unless a single letter is sufficient and a descriptive name adds no value. ```csharp //Right public interface ISessionChannel<TSession> { /*...*/ } public delegate TOutput Converter<TInput, TOutput>(TInput from); public class List<T> { /*...*/ } ``` - Use the name of the type *`T`* parameter for types that contain only a single letter type parameter ```csharp //Right public int IComparer<T>() { return 0; } public delegate bool Predicate<T>(T item); public struct Nullable<T> where T : struct { /*...*/ } ``` - Use the prefix *`T`* for descriptive names of type parameters ```csharp //Right public interface ISessionChannel<TSession> { TSession Session { get; } } ``` Specify the constraints associated with the type parameter in its name. For example, an *`ISession`* constraint parameter may be called *`TSession`*. - Private and protected class fields must begin with the prefix *`_`* ```csharp //Right private int _testField; protected int _testField; ``` ```csharp //Wrong private int testField; protected int testField; ``` - All other code elements such as variables, method parameters, and class fields (except open ones) are named in camelCase notation. ```csharp //Right var testVar = new Object(); public void Foo(int firstParam, string secondParam) ``` ```csharp //Wrong var TestVar = new Object(); public void Foo(int FirstParam, string SecondParam) ``` --- <!-- page: Architecture of nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/architecture-of-nopCommerce.html | source: en/developer/tutorials/architecture-of-nopCommerce.md --> # Architecture of nopCommerce ## Introduction nopCommerce is a highly customizable and flexible, multi-store, multi-vendor, SEO friendly, full-featured open-source E-Commerce solution. Which is built on top of Microsoft `ASP.NET Core` framework. nopCommerce is always up to date with the latest technology and follows best practices. ## Overview This document provides a comprehensive architectural overview of the nopCommerce system. This documentation is targeted at new nopCommerce developers. In this documentation, we will be exploring each project in nopCommerce solution, dependencies between those projects, etc. ## Overview of nopCommerce Architecture nopCommerce is one of the most popular and successful `Dot NET based` open-source `E-Commerce` solutions. The success of nopCommerce is not only because it contains most of the features required by a modern E-Commerce solution, out of the box and its UI is highly customizable and User friendly, but also because the nopCommerce solution is equally organized and developer-friendly. The main strength of nopCommerce is its flexible, extendable architecture and well-organized source code. The nopCommerce architecture is very close to the onion architecture. Which is mainly focused on controlling the code coupling. According to this architecture, all code can depend on layers more central, but code cannot depend on layers further out from the core. In other words, all coupling is toward the center. ![nopCommerceArchitecturalDiagram](_static/architecture-of-nopCommerce/nopCommerceArchitecture.png) This means projects can only have a dependency on the other projects that reside inward from the current project. For example, if you see the above diagram `Nop.Data` project can depend on the `Nop.Core` project and can have `Nop.Core` as a dependency, but `Nop.Core` cannot depend on `Nop.Data` similarly `Nop.Services` can have `Nop.Data` and `Nop.Core` as it's dependencies but neither `Nop.Core` nor `Nop.Data` can have `Nop.Service` as their dependency. This means projects can only have another project as a dependency only if it resides inward or more center from the layer the current project resides. Which is the key to code decoupling. The main advantage of this approach/architecture is that, now if we want to test the Application Core then we can do so even if we do not have any `UI` for our application. Because the Application core does not depend on `UI layer`. Or we can change our `UI framework` from `Razor` view engine and `JQuery` to `Angular` or `React` or `Vue` without affecting our Application Core and can use the same core to build Mobile Applications or Desktop Applications. All of this without changing a bit of code in our Application Core. ## Projects in nopCommerce Solution ### Application Core This is the innermost layer in the nopCommerce architecture. It is the core of the application. All the data access logic and business logic classes reside inside this layer. In the nopCommerce solution, we can find all of the projects for this layer inside the "Libraries" directory. This layer contains three projects. #### Nop.Core This project contains a set of core classes for nopCommerce. This project is at the center of the architecture and does not have any dependencies on other projects in the solution. This project contains core classes that are shared with the entire solution like Domain Entities, Caching, Events, and other Helper classes. #### Nop.Data The `Nop.Data` project depends on the `Nop.Core` project, which is in the middle of the architecture. It does not depend on any other project in the solution. The `Nop.Data` project has classes and functions for reading and writing to a database or other data store. It separates data-access logic from business objects. #### Nop.Services The `Nop.Services` project is the outermost layer of the Application Core in nopCommerce architecture. It depends on the other two projects in the Application Core. It has core services, business logic, validations, and calculations for the data. Some people call it the Business Access Layer (BAL) or Business Logic Layer (BLL). It serves as the facade for all the other layers. It has service classes and uses a repository pattern to expose its features and functionalities. This approach decouples the core from the other layer outside the core. It also prevents or reduces code changes in the other layers if the logic for the Application Core changes. This approach is ideal for dependency injection. ### UI Layer This layer resides outside the "Application Core". In the nopCommerce solution, we can find all of the projects for this layer inside the "Presentation" directory. All the presentation logic and UI resides in this layer. This is the layer where the UI which users can interact with, presents. In nopCommerce, this layer breaks into two other layers. #### Nop.Web.Framework The `Nop.Web.Framework` project is the inner layer of the Presentation layer and depends on the Application Core layer. It is a class library project that serves as a framework for the Presentation layer. It has shared logic for both the nopCommerce public website and the admin panel. #### Nop.Web The `Nop.Web` project is the outermost layer of the Presentation layer in nopCommerce architecture. It has the E-Commerce front-end website user interface that users can interact with. It is an ASP.NET Core application that depends on `Nop.Web.Framework` and the Application Core. It uses `Nop.Web.Framework` for the shared logic between this and the Admin panel. It uses the Application Core for data access and manipulation. #### Admin In nopCommerce, it belongs in the same layer as the `Nop.Web` project. This lives inside the `Nop.Web` project as an area. It is also a UI(User Interface), but this part of the Presentation contains UI for the Admin panel. Admin panel is where all the contents for a public website are maintained and from where we can monitor the activities of our public website. A public website can be accessed without any restriction but the "Admin panel" requires some Authentication and Authorization to access it since it contains information that only the site admin has the right to access. ### Test Layer This layer resides in the same layer as the "Presentation Layer", right outside the "Application Core" This layer is all about testing the different parts of the application. Testing in nopCommerce is easy and more reliable due to the architecture it follows for its system design. In the nopCommerce solution, we can find all of the projects for this layer inside the "Tests" directory. nopCommerce uses **NUnit** testing framework for *Unit Testing*. #### Nop.Tests This layer is the inner layer of the "Test layer" and has a dependency on the "Application Core" layer. This project contains the core logic for testing. #### Nop.Core.Tests These tests are built for *Unit Testing* the `Nop.Core` project, it tests for cashing, domain entities, and so on. #### Nop.Data.Tests These tests are created for *Unit Testing* the `Nop.Data` project, they test the work of various data providers with operations on an entity, such as insert delete, etc. #### Nop.Services.Tests These tests are built for *Unit Testing* the `Nop.Service` project. It contains logic to test every service class for every operation. #### Nop.Web.Tests These tests can be used to test the Presentation layer of the nopCommerce, which contains "Public website" and "Admin Panel". --- <!-- page: Source Code Organization | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/source-code-organization.html | source: en/developer/tutorials/source-code-organization.md --> # Source code organization This document is a developer's guide to the structure of the nopCommerce solution and is intended to help new developers learn the source code. First of all, nopCommerce is an open-source application, so you can download it for free from [GitHub](https://github.com/nopSolutions/nopCommerce). Projects and folders are listed in the order in which they are sorted in *Visual Studio*. We recommend that you open your nopCommerce solution in *Visual Studio* and view projects and files as you read this document. ![Source code organization](_static/source-code-organization/structure_of_projects.jpg) Most of the projects, directories, and files are named so that you can get a rough idea of their purpose. For example, you don't even have to look inside the project called `Nop.Plugin.Payments.PayPalStandard` to guess what it does. ## `\Libraries\Nop.Core` The `Nop.Core` project contains a set of core classes for nopCommerce, such as caching, events, helpers, and business objects (for example, `Order` and `Customer` entities). ## `\Libraries\Nop.Data` The `Nop.Data` project contains a set of classes and functions for reading from and writing to a database or other data store. The `Nop.Data` library helps separate data-access logic from your business objects. nopCommerce uses the *Linq2DB* Code-First approach. Code-First allows a developer to define entities in the source code (all core entities are defined in the `Nop.Core` project), and then use *Linq2DB* and *FluentMigrator* to generate the database from the C# classes. That's why it's called Code-First. You can then query your objects using LINQ, which translates to SQL behind the scenes and is executed against the database. nopCommerce uses [Fluent API](https://fluentmigrator.github.io/articles/technical/fluent-api-create.html) to fully customize the persistence mapping. ## `\Libraries\Nop.Services` This project contains a set of core services, business logic, validations, or calculations related to the data if needed. Some people call it *Business Access Layer* (BAL). ## Projects in the `\Plugins\` solution folder `Plugins` is a *Visual Studio* solution folder that contains plugin projects. Physically it's located at the root of your solution. But plugins DLLs are automatically copied in the `\Presentation\Nop.Web\Plugins` directory which is used for already deployed plugins because the build output paths of all plugins are set to `..\..\Presentation\Nop.Web\Plugins\{Group}.{Name}`. This allows plugins to contain some external files, such as static content (CSS or JS files) without having to copy files between projects to be able to run the project. ## `\Presentation\Nop.Web` `Nop.Web` is an MVC web application project, a presentation layer for the public store which also contains an administration panel included as an area. If you haven't used `ASP.NET` before, please find more info [here](http://www.asp.net/). This is the application that you run. It is the startup project of the application. ## `\Presentation\Nop.Web.Framework` `Nop.Web.Framework` is a class library project containing some common presentation things for the `Nop.Web` project. ## `\Test\Nop.Tests` `Nop.Tests` is a class library project containing some common test classes and helpers for other test projects. It does not have any tests itself. Read more about UNIT testing in nopCommerce in the following article: [UNIT testing](xref:en/developer/tutorials/unit-tests). ### `\Nop.Core.Tests` Nop.Core.Tests is the test project for the Nop.Core project. ### `\Nop.Services.Tests` Nop.Services.Tests is the test project for the Nop.Services project. ### `\Nop.Web.Tests` `Nop.Web.Tests` is the test project for the presentation layer projects. ## Tutorials - [The Architecture behind the nopCommerce eCommerce Platform](https://www.youtube.com/watch?v=6gLbizzSA9o&list=PLnL_aDfmRHwtJmzeA7SxrpH3-XDY2ue0a) --- <!-- page: Getting Started with nopCommerce Development | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/instruction-on-how-to-start-developing-on-nopcommerce.html | source: en/developer/tutorials/instruction-on-how-to-start-developing-on-nopcommerce.md --> # Getting Started with nopCommerce Development nopCommerce is an open-source Microsoft ASP.NET-based eCommerce solution. This is a basic guide for developers on how to start developing on nopCommerce. ## 1. Tools Required for Development You can learn about technology and system requirements from the **"[Tools Required for Development](xref:en/developer/tutorials/system-requirements-for-developing#tools-required-for-development)"** article. ## 2. Stack of technologies used in nopCommerce The best part of nopCommerce is that its source code is fully customizable and its pluggable architecture makes it easy to develop custom functionality and follow any business requirements by using a plugin system. It follows well-known software architectures, patterns, and best security practices. And above all that, it runs on the latest technologies to offer the best experience possible to end-users. So, to achieve all of this nopCommerce uses a stack of technologies in its architecture. * Application Layer * Razor View Engine It is to render an HTML page on the client side. Razor View engine is a markup syntax that helps us to write HTML and server-side code in web pages using C# or VB.NET. * JQuery It is a javascript library used to extend the UI & UX functionality of HTML pages. * Business Layer * Fluent Validation It is a validation library for .NET that uses a fluent interface and lambda expressions for building validation rules. * Mapster Mapster is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. * ASP.NET Core internal dependency injection ASP IOC manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. * Linq2DB Linq2DB is an open-source ORM framework for .NET applications. It is a .NET Foundation project. It enables developers to work with data using objects of domain-specific classes without focusing on the underlying database tables and columns where this data is stored. So, it is the bridge between the Business Layer and the Data Layer. * FluentMigrator Fluent Migrator is a migration framework for .NET. Migrations are a structured way to alter the database schema and are an alternative to creating lots of SQL scripts that have to be run manually by every developer involved. Migrations solve the problem of evolving a database schema for multiple databases (for example, the developer's local database, the test database, and the production database). Database schema changes are described in classes written in C# that can be checked in to a version control system. * Data Layer * Microsoft SQL Server SQL Server is Microsoft's full-featured relational database management system (RDBMS). * MySQL MySQL is the world's most popular open-source database. With its proven performance, reliability, and ease of use, MySQL has become the leading database choice for web-based applications. * PostgreSQL PostgreSQL is a powerful, open-source object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance. * Redis (cache) Redis is an open-source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. In nopCommerce, Redis is used to store old data as an in-memory cache dataset. Which boosts the speed and performance of an application. * Microsoft Azure(Optional) Azure is a public cloud computing platform with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual computing, storage, networking, and much more. ## 3. How to download the project and run it on the local machine Before we begin to work with nopCommerce we need to ensure that our local machine is configured and all the required tools are installed properly and working correctly. Now, let us go to step-by-step instructions on how to download and run nopCommerce on our local machine. ### Step 1: Download nopCommerce source code To download please visit [www.nopcommerce.com](https://www.nopcommerce.com/download-nopcommerce). There you can see two download buttons one with a source code and one without a source code as shown in the picture below. ![image1](_static/instruction-on-how-to-start-developing-on-nopcommerce/image1.png) Since we are downloading nopCommerce for development purposes we need to download the one that says "Package with source code" which contains the source code of nopCommerce. To download nopCommerce you need to be logged in or register a new account. Now you can download nopCommerce as a RAR file, and extract it to your desired folder location. ### Step 2: Open nopCommerce solution * Open in Microsoft Visual Studio Open the folder. Inside that folder, you will see a bunch of files and folders that form the source code for nopCommerce. ![image2](_static/instruction-on-how-to-start-developing-on-nopcommerce/image2.png) There, you will also see a solution file with the `.sln` extension, double click that solution file to open the nopCommerce project in your Microsoft Visual Studio. * Open in Visual Studio Code When starting, specify the root directory: ![image4](_static/instruction-on-how-to-start-developing-on-nopcommerce/image4.jpg) ### Step 3: Running the nopCommerce project nopCommerce does not require you to have any further configuration to run the project. nopCommerce is ready to run out of the box. * Run Microsoft Visual Studio So, now you can run a project using *Microsoft Visual Studio* by hitting `ctrl+F5` or just `F5` to run a project in debugging mode, or you can run using a button with a play icon in *Microsoft Visual Studio*. * Run Visual Studio Code The **launch.json** file is used to set up the debugger in *Visual Studio Code*. This file contains information about how the project will be launched. When you first start *Visual Studio Code*, it will generate this file according to the standard template along the path `.vscode/launch.json`. In addition to the *launch.json* file, configure launch settings using the launchSettings.json file. The advantage of the **launchSettings.json** file is that it allows settings to be shared between *Visual Studio Code* and the full version of *Visual Studio*. This file is already shipped with the nopCommerce source code. We just need to specify which profile we will use when starting the project. ```json "launchSettingsProfile": "Nop.Web", ``` > [!NOTE] > > Only profiles with `"commandName": "Project"` are supported. The `"IIS Express"` profile cannot be used in this case. By default, the project will run at `https://localhost:5001` because it is listed first in the profile. If you want to change this and not use SSL, then you need to specify this in the settings of the **launch.json** file: ```json "serverReadyAction": { "action": "openExternally", "pattern": "\\bNow listening on:\\s+http://\\S+:([0-9]+)", "uriFormat": "http://localhost:%s" }, ``` Now you can run a project using *Visual Studio Code* by hitting `ctrl+F5` or just `F5` to run a project in debugging mode. After you run the project for the first time you will see an installation page like below: ![image3](_static/instruction-on-how-to-start-developing-on-nopcommerce/nop_install.jpg) Here you need to fill in all required information to complete your installation. #### Store information Here you are required to provide an email address and password which then be used as your administrator account in your nopCommerce shop. #### Database information Here you need to provide the information you want to use for this project. Here you have to choose your database storage. You can use `MS SQL Server` or `MySQL` or `PostgreSQL`. It is your decision which one you want to use. For the sake of this tutorial, we will be using `MS SQL Server`. Also, you will see the checkbox asking if you want to create a database if not exist, please check the checkbox. Moving further you need to set up your connection string. For that, you have two options. One is to fill a form with "**Server name**" and "**Database name**". In "Server name" you need to provide your server's name and in "Database name" you need to provide a database name you want to create or if you already have one then it will not create but use the existing one. However, you also can choose the option "**Enter raw connection string (advanced)**" then you need to write the whole connection string by yourself. After that, you need to provide your SQL server's credentials for authentication. After you fill in all of this information you need to press the "install" button, it will take about 1 minute to complete the installation, then you will be redirected to the online shop homepage. ### 4. How to configure nopCommerce to run on HTTPS * Microsoft Visual Studio To set SSL/HTTPS for your nopCommerce you need to go to the property window of the `Nop.Web` project under the *Presentation* folder since it is the startup project for nopCommerce. To open the property window right-click on the `Nop.Web` project and at the bottom of the context menu you will see a menu named "Properties", just click on that menu then a property window will appear. In the property, window navigate to the "**Debug**" tab. ![image3](_static/instruction-on-how-to-start-developing-on-nopcommerce/image3.jpg) Check the "**Use SSL**", and enter the HTTPS URL beside it. Then save this project. Now run your project again and navigate to the given URL and you can see that it is running on SSL/HTTPS now. So this is the one way for configuring HTTPS in your WebProject but there is also another way to configure SSL. For that go to your `Nop.Web` project and expand the project, you will see a virtual file named "Properties" in your project structure just below "Dependencies". Inside Properties you will find a JSON file called **launchSetting.json**. Open that file and you will see a bunch of configuration settings already written in that file. Inside that file, you may have a section as shown in the figure above. So to enable SSL you just need to replace 0 under the "**sslPort**" property to the port you want to run for SSL connection, make sure the port is available. To test, run your project and navigate to `https://localhost:{yourPort}`. * Visual Studio Code To launch the project via the *SSL* protocol, you need to make sure that the following setting is specified in the **launch.json** file: ```json "serverReadyAction": { "action": "openExternally", "pattern": "\\bNow listening on:\\s+(https?://\\S+)" } ``` > [!NOTE] > > Settings in **launch.json** will take precedence over settings in **launchSettings.json**, so for example, if args is already set to something other than an empty string/array in launch.json then the launchSettings.json content will be ignored. --- <!-- page: Default Database Schema | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/db-schema.html | source: en/developer/tutorials/db-schema.md --> # Default Database Schema In this article, we will look at the database schema that is installed during initial installation and which remains unchanged in 90% of cases. We won't bring the entire schema as a whole but will describe the default installation that provides for the creation of 126 tables. To understand such a schema easily let's split it into parts. Below, we grouped the tables most naturally and understandably: * [Customers info](#customers-info) * [Products info](#products-info) * [Product attributes](#product-attributes) * [Tier price](#tier-price) * [Inventory by warehouses](#inventory-by-warehouses) * [Orders](#orders) * [Shipments](#shipments) * [Discounts](#discounts) * [Shopping cart](#shopping-cart) * [Addresses](#addresses) * [Database naming convention](#database-naming-convention) ## Customers info ![Customers info](_static/db-schema/customers-info.jpg) This diagram shows a set of tables that contain basic customer information. It also indicates the direction of links. We won't delve into the purpose of tables and fields, since their names are self-descriptive enough. ### Features (Customers info) * In the **Customer** table we have three fields which in fact should be defined as foreign keys but in practice, they are not: 1. AffiliateId 1. VendorId 1. RegisteredInStoreId This is done intentionally so as not to overload the system with unnecessary connections, since these fields are not used in every online store. * Some of the user data is stored in the **GenericAttribute** table. You can find all of them at `\src\Libraries\Nop.Core\Domain\Customers\NopCustomerDefaults.cs`. The structure of this table is presented below: ![GenericAttribute](_static/db-schema/generic-attribute.jpg) Besides the mentioned customer data, this table can store any data for other entities as well. We added this table on purpose so that you could extend any entity without changing the structure of the tables. Additionally, this table stores custom **Customer attributes** and **Vendor attributes** with the chosen values for vendors and customers in the XML format. See the following rows to understand what it looks like: ![Xml](_static/db-schema/xml.jpg) On the example of the XML string from the *Value* column we can see how exactly the attribute values are stored for a certain vendor: ```csharp <Attributes><VendorAttribute ID="2"><VendorAttributeValue><Value>1</Value></VendorAttributeValue></VendorAttribute></Attributes> ``` As you can see the vendor with ID 1 has only one vendor attribute filled. This attribute has ID 2 and its value is 1. Custom customer attributes have the same structure as vendor attributes. The following screenshot represents the relationships between **Customer attributes** and **Vendor attributes** and their values: ![Xml](_static/db-schema/attributes.jpg) ## Products info ![Products info](_static/db-schema/products-info.jpg) In the diagram, you can see the base data for the product (the schema of the product information table below). As a rule, this data is used in 99% of cases. ![Product table](_static/db-schema/product.png) ### Features (Products info) Depending on the store settings, additional tables may be connected to this schema. For example, to distribute product quantity among multiple warehouses. ![Product table](_static/db-schema/warehouse.jpg) Or if you want to use the product reviews functionality: ![Product table](_static/db-schema/product-review.jpg) ### Product attributes Then let's consider the schema of attributes and their combinations presented below: ![Product attributes](_static/db-schema/product-attributes.jpg) ### Tier price If you use tier pricing for products you should also pay attention to the following schema: ![Tier price](_static/db-schema/tier-price.jpg) ### Inventory by warehouses Although this feature is not used often, it might be useful to give a schema for accounting for goods in a particular warehouse: ![Inventory by warehouses](_static/db-schema/stock-quantity-history.jpg) ## Orders ![orders](_static/db-schema/orders.jpg) In this diagram, we can see the tables related to the order data. The **Order** table has the following structure: ![order](_static/db-schema/order.png) There is no need to comment on anything since everything should be clear from the diagram and the names of the fields are self-descriptive enough. It should only be noted that the **RewardPointsHistory** table is used only if the *Reward points system* is activated for the store. ## Shipments ![shipments](_static/db-schema/shipments.jpg) The purpose of all tables in the diagram, as before, raises no questions. Nevertheless, let's dwell on a few points. The **ShippingMethod** table is used to manage the list of connected plugins, and the specific shipping method is stored in the *ShippingRateComputationMethodSystemName* and *ShippingMethod* fields of the **Order** table. The *OrderItemId* field of the **ShipmentItem** table is essentially a reference to the **OrderItem** table. ## Discounts ![discounts](_static/db-schema/discounts.jpg) From the diagram above, we can see that discounts can be applied to three groups: **Products**, **Manufacturers**, **Categories** And can be configured with various rules which are controlled by plugins (``IDiscountRequirementRule``). In the **DiscountRequirement** table, the *InteractionTypeId* field must contain one of the values specified in the ``RequirementGroupInteractionType`` enumeration: ```csharp /// <summary> /// Represents an interaction type within the group of requirements /// </summary> public enum RequirementGroupInteractionType { /// <summary> /// All requirements within the group must be met /// </summary> And = 0, /// <summary> /// At least one of the requirements within the group must be met /// </summary> Or = 2 } ``` ## Shopping cart Another important part of the store is a shopping cart. In our case the schema of this mechanism is very simple: ![Shopping cart](_static/db-schema/shopping-cart-item.jpg) The only thing worth noting is that this schema is also used for a wishlist. To separate these two types, the *ShoppingCartTypeId* field is used. The values in this field must match the values from the **ShoppingCartType** enumeration: ```csharp /// <summary> /// Represents a shopping cart type /// </summary> public enum ShoppingCartType { /// <summary> /// Shopping cart /// </summary> ShoppingCart = 1, /// <summary> /// Wishlist /// </summary> Wishlist = 2 } ``` ## Addresses Perhaps you will also be interested in the table schema involved in storing addresses, both delivery and customer addresses: ![addresses](_static/db-schema/addresses.jpg) As you understand, the standard installation includes much more tables. We don't describe them all, since many of them have no connections and serve only for a specific purpose, while others are used very rarely. ## Database naming convention You may have noticed that the database uses a mixed approach to the naming of tables and columns (with `_` char, without `_`, CamelCase). A long time ago we used `_` char. But now we've completely switched to using **PascalCase** notation. We chose not to change the names of the existing tables or columns, as many of our users had already written custom scripts that would break otherwise. To maintain backward compatibility with the new standards, we introduced the `INameCompatibility` interface. It lets you rename the tables and columns to map the objects correctly with the tables that follow the old naming standards. The [BaseNameCompatibility](https://github.com/nopSolutions/nopCommerce/blob/develop/src/Libraries/Nop.Data/Mapping/BaseNameCompatibility.cs) class in the `Nop.Data.Mapping` namespace has the full list of overrides. --- <!-- page: Updating an Existing Entity (how to add a new property) | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/update-existing-entity.html | source: en/developer/tutorials/update-existing-entity.md --> # Updating an existing entity (How to add a new property) This tutorial covers how to add a property to the "Category" entity that ships with the nopCommerce source code. ## The data model Entities will have two classes that are used to map records to a table. The first class defines the properties, fields, and methods consumed by the web application. ```sh File System Location: [Project Root]\Libraries\Nop.Core\Domain\Catalog\Category.cs Assembly: Nop.Core Solution Location: Nop.Core.Domain.Catalog.Category.cs ``` The second class is used to map the properties defined in the class above to their respective SQL columns. The mapping class is also responsible for mapping relationships between different SQL tables. ```sh File System Location: [Project Root]\Libraries\Nop.Data\Mapping\Builders\Catalog\CategoryBuilder.cs Assembly: Nop.Data Solution Location: Nop.Data.Mapping.Builders.Catalog.CategoryBuilder.cs ``` But we recommend you to use it only for your entity classes. In our case, we'll use the migration mechanism instead of the mapping class. Add the following property to the `Category` class. ```csharp public string SomeNewProperty { get; set; } ``` Add the new class `Nop.Data.Migrations.AddSomeNewProperty` with following code: ```csharp using FluentMigrator; using Nop.Core.Domain.Catalog; namespace Nop.Data.Migrations [NopSchemaMigration("2024-04-20 00:00:00", "Category. Add some new property")] public class AddSomeNewProperty: ForwardOnlyMigration { /// <summary> /// Collect the UP migration expressions /// </summary> public override void Up() { var categoryTableName = nameof(Category); if (!Schema.Table(categoryTableName).Column(nameof(Category.SomeNewProperty)).Exists()) Alter.Table(categoryTableName) .AddColumn(nameof(Category.SomeNewProperty)).AsInt32().AsString(255).Nullable(); } } ``` > [!NOTE] > > The procedure for updating migrations is carried out during the initialization of the database. > >```csharp >public virtual void InitializeDatabase() >{ > var migrationManager = EngineContext.CurrenResolve<IMigrationManager>(); > migrationManager.ApplyUpMigrations(typeof(NopDbStartup).Assembly); >} >``` ## The presentation model The presentation model is used to transport information from a controller to the view (read more at asp.net/mvc). Models have another purpose; defining requirements. We configured our database to only store 255 characters for the `SomeNewProperty`. If we try and save a `SomeNewProperty` with 300 characters the application will break (or truncate the text). We want the application to protect users from failures the best we can, and our view models help enforce requirements like string length. ```sh File System Location: [Project Root]\Presentation\Nop.Web\Areas\Admin\Models\Catalog\CategoryModel.cs Assembly: Nop.Admin Solution Location: Nop.Web.Areas.Admin.Models.Catalog.CategoryModel.cs ``` The validator class is used to validate the data stored inside of the model class (e.g. required fields, max length, and required ranges). ```sh File System Location: [Project Root]\Presentation\Nop.Web\Areas\Admin\Validators\Catalog\CategoryValidator.cs Assembly: Nop.Web Solution Location: Nop.Web.Areas.Admin.Validators.Catalog.CategoryValidator.cs ``` Add the property to our view model. ```csharp // The NopResourceDisplayName provides the "key" used during localization [NopResourceDisplayName("Admin.Catalog.Categories.Fields.SomeNewProperty")] public string SomeNewProperty { get; set; } ``` The requirements code will be added to the constructor of the validator. ```csharp //I think this code can speak for itself RuleFor(m => m.SomeNewProperty).Length(0, 255); ``` ## The view ```sh File System Location: [Project Root]\Presentation\Nop.Web\Areas\Admin\Views\Category\_CreateOrUpdate.Info.cshtml Assembly: Nop.Web ``` Views contain the HTML for displaying model data. Place this HTML under the "PictureId" section. ```csharp <div class="form-group"> <div class="col-md-3"> <nop-label asp-for="SomeNewProperty" /> </div> <div class="col-md-9"> <nop-editor asp-for="SomeNewProperty" /> <span asp-validation-for="SomeNewProperty"></span> </div> </div> ``` ## The controller In this case, the controller is responsible for mapping the domain data model to our view model and vice versa. The reason we chose the category model to update is because of its simplicity. ```sh File System Location: [Project Root]\Presentation\Nop.Web\Areas\Admin\Controllers\CategoryController.cs Assembly: Nop.Admin Solution Location: Nop.Web.Areas.Admin.Controllers.CategoryController.cs ``` We're going to make three updates to the CategoryController class. * Data Model → View Model * Create View Model → Data Model * Edit View Model → Data Model Normally we would write tests for the following code and verify that model mapping is working correctly, but we'll skip unit testing for now to keep it simple. In the appropriate methods ("Create", "Edit", or "PrepareSomeModel") add the code to set this property. In most cases, it's not required because it's automatically handled by *Mapster* in the `.ToModel()` method. In the public method to save entity (usually: "Create" or "Edit" methods with `[HttpPost]` attribute) ```csharp // Edit View Model → Data Model category.SomeNewProperty = model.SomeNewProperty; ``` ## Troubleshooting * Recreate the database. Either your custom SQL script or use the nopCommerce installer. * Stop the development web server between schema changes. * Post a detailed comment on [our forums](http://www.nopcommerce.com/boards/). --- <!-- page: Database Migrations | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/migrations.html | source: en/developer/tutorials/migrations.md --> # Database Migrations ## Short description of the changes made in the approach to working with the database The work with the database was significantly reworked in the nopCommerce version 4.30. The first change that could be noticed is a complete rejection of navigation properties. We may think and argue about the usefulness of this approach but it has a couple of positive points: 1. Simplify the understanding and maintenance of the code. > [!NOTE] > > During the code refactoring, we found and corrected several inaccuracies affecting both performance and functionality. 1. Full control over the queries and the moment of their execution (which positively affects the performance of the entire solution). 1. Possibility to simplify the migration process to any database framework (most importantly). Since nopCommerce completely switched to .Net Core (version 4.10) and became a cross-platform solution, supporting several databases has become a more and more important aspect. The nopCommerce team has conducted considerable research and analysis and decided to abandon the use of the standard Entity Framework Core. At the same time, we decided not to work with the database through LINQ queries using the OOP approach (which is the most common approach used by C#-developers). The final choice fell on a bundle of Linq2DB and FluentMigrator. Below, I will describe the role of each of these frameworks in detail. ## Linq2DB > [!NOTE] > > Started from 4.30 version nopCommerce uses Linq2DB as an ORM Framework. Linq2DB is an object-relational mapper (ORM) that enables .NET developers to work with a database using .NET objects. It can map .Net objects to various numbers of Database providers. In nopCommerce, Linq2DB is used as a database-access level. Currently, nopCommerce supports three of the most popular databases: MS SQL Server, MySQL, and PostgreSQL. If we analyze the code, we can easily see that each database is supported by its class that implements the INopDataProvider interface. But if you do not plan to create your database access provider, you can ignore the implementation details altogether. For most development tasks, understanding just a few points will be sufficient: 1. You need an object corresponding to the table in the database (POCO class). 1. All work with table data is carried out through the `IRepository<TEntity>` interface. You do not even need to take care of its placement into the IoC, since it is registered through a call to the appropriate factory method. 1. You need to control the creation of the table in the database. To address the last issue, we need to deal with the second framework from the bundle, namely FluentMigrator. ## FluentMigrator > [!NOTE] > > Fluent Migrator is a migration framework for .NET much like Ruby on Rails Migrations. *Migrations* are a structured way to alter your database schema and are an alternative to creating lots of SQL scripts that have to be run manually by every developer involved. Migrations solve the problem of evolving a database schema for multiple databases (for example, the developer's local database, test database, and production database). Database schema changes are described in classes written in C#. These classes can be checked into a version control system. The detailed plan for adding your entities is described in the following article: [Plugin with data access](xref:en/developer/plugins/how-to-write-plugin-4.70). Therefore, we will remain only on general theoretical points: 1. Migrations are supported at the level of the nopCommerce code itself. 1. You can create any migrations inherited from the abstract class **MigrationBase**. 1. To simplify version control for migrations we added the **NopMigrationAttribute** attribute inherited from **MigrationAttribute** to the code. Now you can simply specify the date and time when the migration was created instead of the usual long number. 1. We also added the **SkipMigrationOnUpdateAttribute** attribute that indicates if migration should be skipped during the update process. 1. You can create a table in the database in two ways: * Use **Create.Table** method in the **Up** method of your migration class and specify all details using the extension methods. * Use **IMigrationManager.BuildTable\<T\>** method in the **Up** method of your migration class and specify all details, if needed, using the implementation of the **IEntityBuilder** and **INameCompatibility** interfaces (in nopCommerce we use this approach). > [!IMPORTANT] > > In order to run new migrations you have to increase the version in your plugin.json file. --- <!-- page: Inversion of Control and Dependency Injection | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/inversion-of-control.html | source: en/developer/tutorials/inversion-of-control.md --> # Inversion of Control and Dependency Injection Inversion of Control and Dependency Injection are two related ways to break apart dependencies in your applications. [Inversion of Control (IoC)](https://en.wikipedia.org/wiki/Inversion_of_control) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source. [Dependency Injection (DI)](http://en.wikipedia.org/wiki/Dependency_injection) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and sets properties. Martin Fowler has written a great description of Dependency Injection or *Inversion of Control*. We're not going to duplicate his work here,you can find his article [here](https://martinfowler.com/articles/injection.html). nopCommerce uses ASP.NET Core's built-in DI container, which is represented by the `IServiceProvider` interface. This container is responsible for mapping dependencies to specific types and for injecting dependencies into various objects. Once a service and an appropriate interface, which the service implements, are written you should register them in any class implementing the `INopStartup` interface (`Nop.Core.Infrastructure` namespace). The `ConfigureServices` method is responsible for installing services in the application. Services are added to the project through the `IServiceCollection` parameter. ```csharp public class NopStartup : INopStartup { public virtual void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.AddScoped<IWebHelper, WebHelper>(); ... } public void Configure(IApplicationBuilder application) { } public int Order => 2000; } ``` You can create as many dependency registrar classes as you need. Note that each class implementing the **INopStartup** interface has an **Order** property. It allows you to replace existing dependencies. To override nopCommerce dependencies, set the `Order` property to something greater than 0. nopCommerce orders dependency classes and runs them in ascending order. The higher the number the later your objects will be registered. This way you will register both built-in ASP.NET Core services and your own, the same registration mechanism applies to registering services in plugins. --- <!-- page: Registering New Routes | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/register-new-routes.html | source: en/developer/tutorials/register-new-routes.md --> # Registering New Routes [ASP.NET Core routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing) is responsible for mapping incoming browser requests to particular MVC controller actions. nopCommerce has an `IRouteProvider` interface which is used for route registration during application startup. All main routes are registered in the `RouteProvider` and `GenericUrlRouteProvider` classes located in the *`Nop.Web`* project. You can create as many `RouteProvider` classes as you need. For example, if your plugin has some custom routes which you want to register, then create a new class implementing the `IRouteProvider` interface and register the routes specific to your new plugin. ```csharp /// <summary> /// Represents plugin route provider /// </summary> public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { endpointRouteBuilder.MapControllerRoute(PayPalCommerceDefaults.ConfigurationRouteName, "Admin/PayPalCommerce/Configure", new { controller = "PayPalCommerce", action = "Configure" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` --- <!-- page: Introduction to Plugin System | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/description-of-plugin-system.html | source: en/developer/tutorials/description-of-plugin-system.md --> # Introduction to Plugin System ## How to initialize a new Plugin system (How to create a new plugin project) nopCommerce uses a plugins system to extend the functionality of the nopCommerce store. Plugins are a set of independent programs or components that can be added to an existing system to extend some specific functionality and also can be removed from the system without affecting the main system during the process. > [!NOTE] > > For more information about how to create a plugin you can visit [**this page**.](xref:en/developer/plugins/index) ## How to Search and use plugins from the nopCommerce store nopCommerce already has several plugins pre-built and available to use, out of the box. You can also search and find several plugins already available from the nopCommerce official marketplace and see if someone has already created a plugin that suits your needs. If not, then you always can build your own plugin according to your requirements. But here let's see how to find and use plugins from the nopCommerce store. For that nopCommerce has a marketplace where we can find different themes and plugins. You can find it at [nopCommerce Marketplace](https://www.nopcommerce.com/marketplace). ![image4](_static/description-of-plugin-system/image4.png) Here you can see three tabs. The **All** tab contains all themes and extensions, the **Themes** tab contains all nopCommerce themes which are for nopCommerce website skin, and lastly, the **Extensions** tab where we can find plugins. So go to the Extensions tab. Here you can find all free and commercial plugins. To find a specific plugin you want, you can search from here. On the right side, you can find the filtration section from where you can narrow down your filtering. After you find your searched plugin just download and install. Each plugin has a full description about how to use the plugin, on its download page, so don't forget to read those descriptions. ## Interface `IPlugin` `IPlugin` is an interface that exposes the functionalities used while installing or uninstalling the plugin. Every plugin project must have a class inherited from this interface for nopCommerce to treat that project as a plugin. ### Method `GetConfigurationPageUrl` ```cs string GetConfigurationPageUrl() ``` This should return the URL for the configuration view. When we install the plugin we will see a `Configuration` button, so if we implement this method in our class then the string value we return to from this method will be used as the URL for that `configuration` button. ### Property `PluginDescriptor` ```cs PluginDescriptor PluginDescriptor{ get; set; } ``` This property is used to get or set the information that describes the current plugin. When we write a new plugin or widget we need to create a **plugin.json** file. nopCommerce uses the same file to initialize the value for this property. ### Method `InstallAsync` ```cs Task InstallAsync(); ``` The method is executed when the plugin is installed, this logic usually implements the initialization of settings, locales, and other infrastructure for the correct configuration of the plugin. ### Method `UninstallAsync` ```cs Task UninstallAsync(); ``` The method is the opposite of "InstallAsync", it should completely delete all resources allocated to the plugin after it is uninstalled. ### Method `UpdateAsync` ```cs Task UpdateAsync(string currentVersion, string targetVersion); ``` The method is used to update the plugin to the specified version. ### Method `PreparePluginToUninstallAsync` ```cs Task PreparePluginToUninstallAsync() ``` This method will be invoked when we click the `UninstallAsync` button for the plugin. Code inside this method will be executed before the nopCommerce uninstalls the plugin from the system. In this method, we may want to write the logic to validate our plugin for uninstallation. For example, here we can check if there are other plugins which are depending on the plugin we are trying to uninstall. If so we may not want users to uninstall the plugin until the plugin depending on the current plugin is uninstalled. ## Class `PluginDescriptor` This class as the name implies holds the information that describes the plugin. If you compare the *properties* from this class to *key* from the **plugin.json** file, you will see a similar structure. That is because this class **PluginDescriptor.cs** is used to map that **plugin.json** file to a C# class so that the information provided in **plugin.json** can be used by nopCommerce. Except for those properties `PluginDescriptor` class contains some more properties and helper methods. ### Property `Installed` ```cs public virtual bool Installed { get; set; } ``` This property is used to verify if a plugin is installed in our nopCommerce application or not. ### Property `PluginType` ```cs public virtual Type PluginType { get; set; } ``` It is used to get or set the type of the plugin. This type references the class that implements the `IPlugin` interface in the plugin project. ### Property `OriginalAssemblyFile` ```cs public virtual string OriginalAssemblyFile { get; set; } ``` It is used to get or set the original assembly file that a shadow copy was made from. ### Property `ReferencedAssembly` ```cs public virtual Assembly ReferencedAssembly { get; set; } ``` It is to get or set the assembly that has been shadow copied that is active in the application. ### Property `ShowInPluginsList` ```cs public virtual bool ShowInPluginsList { get; set; } = true; ``` This property is used to indicate whether we want to show the plugin in the plugin list or not. ### Method GetPluginDescriptorFromText ```cs public static PluginDescriptor GetPluginDescriptorFromText(string text) ``` This method takes *json string* as input and parses the *json string* to type `PluginDescriptor`. And returns `PluginDescriptor` parsed from the *json string*. ### Method `Save` ```cs public virtual void Save() ``` It is to save the plugin description from `PluginDescriptor` to the **plugin.json** file. ### Method `CompareTo` ```cs public int CompareTo(PluginDescriptor other) ``` It compares the current instance of `PluginDescriptor` with other instances of `PluginDescriptor` supplied as the parameter by comparing the property *FriendlyName* And returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified parameter. ### Method `Instance` ```cs public virtual TPlugin Instance<TPlugin>() where TPlugin : class, IPlugin ``` This method is used to get the instance of *Plugin* of type `PluginType` property from the current `PluginDescriptor`. ## Interface `IPluginManager` `IPluginManager` is a generic interface of type class. It contains method decelerations used for loading plugins using different filter parameters. We can find the implementation of this interface in `PluginManager` located under namespace `{Nop.Services.Plugins}`. --- <!-- page: Develop a New Plugin | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin.html | source: en/developer/tutorials/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin.md --> # Develop a New Plugin ## Overview nopCommerce uses the plugins system to extend the functionality of the admin panel and uses a widget system to extend the functionality of the website. Plugins and Widgets are a set of independent programs or components that can be added to an existing system to extend some specific functionality and also can be removed from the system without affecting the main system during the process. So by using the concept of Plugins and widgets we can add more functionality to our system and we can build them without altering or editing the core source code of the nopCommerce solution. This enables us to upgrade or downgrade our nopCommerce solution to the latest version or older version as we desire without having to rewrite plugins and widgets we already created. ## Plugins vs. Widgets As we know both plugins and widgets are for extending the functionality of the nopCommerce solution. Well, then you may ask "What is the difference between them". Ultimately in nopCommerce, you can think of widgets as a plugin but with an extra feature. To create a widget the process is mostly the same as creating a plugin, but by using widgets we can show some UI (User Interface) to the nopCommerce public website in some specific areas predefined by nopCommerce which are known as widget-zones. Which we cannot achieve only via a plugin. You may think of a Widget as a subset of a Plugin. >[!NOTE] > >All available widget zones can be found in the `Nop.Web.Framework.Infrastructure` namespace: > >- The admin panel widget-zones can be found in the **AdminWidgetZones.cs** file. > >- The public store widget-zones can be found in the **PublicWidgetZones.cs** file. You must be a bit more clear about what widgets and plugins are when they can be used and what is the benefits of using them. So, now let's go and create a simple widget that shows a "Hello World" message to the public site, to understand how to create a widget in nopCommerce. ## Initialize Plugin Project ### Step 1: Create a new project Go to the nopCommerce official website and download the latest nopCommerce source code. Open your nopCommerce solution in your favorite IDE (Microsoft Visual Studio is recommended). If you want to know more about the structure of the project, then first check out the article ["Source code organization"](xref:en/developer/tutorials/source-code-organization). On the top of the solution, you will see a *Plugins* folder, expand that folder and you will see a list of plugin projects shipped with nopCommerce by default. ![image1](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image1.png) In order to create a new Widget project, Right-click on *Plugins* folder: **Add** -> **New Project**, and the "add new project" window will appear. ![image2](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image2.png) Select the **Class Library** project template and go to the next step, where you will need to specify the name of the project. ![image2_1](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image2_1.png) nopCommerce follows some standard naming conventions, which you can get more information from nopCommerce documentation. I have chosen `Nop.Plugin.Widget.HelloWorld` as my project name by following the naming convention of nopCommerce. And the location should be inside the */src/Plugins* directory. Now click **Next**. ![image2_2](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image2_2.png) This should create a new project inside the Plugin directory. And you may see in your solution like this: ![image3](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image3.png) ### Step 2: Configure your new project to be used as a Widget We need to configure a couple of things in our project for it to be used as a *Plugin* or a *Widget*. After you create your project successfully open its `.csproj` file, for that right-click on your project, and click the `{Your_Project_Name.csproj}` menu from the context menu and replace its content with the following code. ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>$(SolutionDir)\Presentation\Nop.Web\Plugins\{PLUGIN_OUTPUT_DIRECTORY}</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(SolutionDir)\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(SolutionDir)\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` Here replace `{Plugin_Output_Directory}` with your project name, in my case *Widget.HelloWorld*. What this will do is it copies all DLL files related to this project into the `Nop.Web/Plugin/{Plugin_Output_Directory}`, because *Plugin* directory inside `Nop.Web` is the location where nopCommerce searches from plugins and widgets to display in *Plugin* or *Widget* list in the admin panel. ### Step 3: Create a plugin.json file This file is required for every *Plugin* or *Widget* we create for nopCommerce. This file contains meta information about our plugin that describes our plugin. It contains information like the name of our plugin, which version of nopCommerce it is target/built for, some description about our plugin, version of our plugin, and so on. For more information please see the article [plugin.json file](xref:en/developer/plugins/plugin_json). ### Step 4: Create a class that inherits from BasePlugin Class We need to have a class that inherits from the `IPlugin` interface so that nopCommerce treats our project as a plugin. But nopCommerce already has a class `BasePlugin` that inherits from the `IPlugin` interface and implements all methods from that interface. So, instead of inheriting from the `IPlugin` interface, we can extend the `BasePlugin` class. If we have some logic that needs to be executed during our plugin/widget installation and uninstallation process then we can override the `InstallAsync` and `UninstallAsync` methods from the `BasePlugin` class to our class. Finally, the class should look like this ```cs public class HelloWorldPlugin: BasePlugin { public override async Task InstallAsync() { //Logic during installation goes here... await base.InstallAsync(); } public override async Task UninstallAsync() { //Logic during uninstallation goes here... await base.UninstallAsync(); } } ``` Now build your project and run. Navigate to the admin panel and under **Configuration** there is a **Local plugins** menu click that menu. Here you will see all plugins listed that are present in our `Nop.Web/Plugins` directory. There you will see your newly created plugin. If you do not see it, then click on the **Reload list of plugins** button, after that, it will restart your application and list all plugins available. Now you should see your plugin. Click the green **Install** button in your plugin's row. ![image5](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image5.png) Now after you click the install button, click the **Restart your application to apply changes** button. It will restart your application and install your plugin. After installation completes you will see a *Configure* and *Edit* button and an *Uninstall* button like this. ![image6](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image6.png) Now your plugin is installed. But the *Configure* button will not work, since we don't have any configure page in our plugin. ## Create a widget to show some UI on our public Site As previously mentioned, a *Widget* is the same as a plugin but with extra features. So we can use this same plugin project to convert it to a widget and render some UI to our public site. So let's see how we can extend this plugin and make it into a widget. First, we need to create a `ViewComponent`. Create a directory *Components* in the root of the project and create a **`ViewComponent`** class. We need to inherit this class from the `NopViewComponent` base class. ```cs public class ExampleWidgetViewComponent: NopViewComponent { public IViewComponentResult Invoke(string widgetZone, object additionalData) { return Content("Hello World"); } } ``` Now go to the previous class that extends `BasePlugin` we have previously created and is inherited from the `IWidgetPlugin` interface. This interface has two function declarations `GetWidgetZones` and `GetWidgetViewComponent` which we need to implement in our class. ```cs public class HelloWorldPlugin: BasePlugin, IWidgetPlugin { /// <summary> /// Gets a value indicating whether to hide this plugin on the widget list page in the admin area /// </summary> public bool HideInWidgetList => false; /// <summary> /// Gets a type of a view component for displaying widget /// </summary> /// <param name="widgetZone">Name of the widget zone</param> /// <returns>View component type</returns> public Type GetWidgetViewComponent(string widgetZone) { return typeof(ExampleWidgetViewComponent); } /// <summary> /// Gets widget zones where this widget should be rendered /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the widget zones /// </returns> public Task<IList<string>> GetWidgetZonesAsync() { return Task.FromResult<IList<string>>(new List<string> { "home_page_before_categories" }); } public override async Task InstallAsync() { //Logic during installation goes here... await base.InstallAsync(); } public override async Task UninstallAsync() { //Logic during uninstallation goes here... await base.UninstallAsync(); } } ``` Now if you build your project, navigate to the admin panel, and go to **Configuration -> Widgets**, you will be able to view your widget in the list. ![image7](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image7.png) Here you may notice that this widget does not have the *Configure* button. That is because we did not create a configuration view file for this widget and did not override the `GetConfigurationPageUrl` method from the `BasePlugin` class. Since we have already installed our plugin we do not have to install it again, but here you can see that widget is not active right now. We can activate this by clicking the *Edit* button. ![image8](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image8.png) Now after we set the widget to active our widget should work as expected. If we go to our home page before the category we must see the "Hello World" message as shown in the picture (highlighted in yellow). ![image9](_static/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin/image9.png) --- <!-- page: Using DataTables | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/guide-to-creating-a-page-containing-a-reporting-table-of-datatables.html | source: en/developer/tutorials/guide-to-creating-a-page-containing-a-reporting-table-of-datatables.md --> # Using DataTables In this tutorial, we will be learning about how to extend the functionality of nopCommerce with custom functionality for the admin panel and create a page containing a table with some data as a report. Before starting this tutorial, you need to have some prior knowledge and understanding of some of the topics. * [nopCommerce architecture](xref:en/developer/tutorials/source-code-organization). * [nopCommerce Plugin](xref:en/developer/tutorials/guide-to-expanding-the-functionality-of-the-basic-functions-of-nop-commerce-through-a-plugin). * [nopCommerce routing](xref:en/developer/tutorials/register-new-routes). If you are not familiar with the above topics, we highly recommend you learn about them first. This tutorial will show you how to create a table that displays information about the distribution of users by country (based on billing address). Let's walk through the step-by-step process of creating the aforementioned functionality. ## Create a nopCommerce plugin project We are assuming that you already know where and how to create a nopCommerce plugin project and configure the project according to nopCommerce standards. If you don't know then you can visit [this page](xref:en/developer/plugins/how-to-write-plugin-4.70) to learn how to create and configure the nopCommerce plugin project. If you have followed the above-provided link to create and configure your plugin project then you may end up with a folder structure like this. ![image1](_static/guide-to-creating-a-page-containing-a-reporting-table-of-datatables/image1.png) ### Models/CustomersDistribution.cs First, let's create a model named **CustomersDistribution** inside the **Models** folder. ```cs public record CustomersDistribution : BaseNopModel { /// <summary> /// Country based on the billing address. /// </summary> public string Country { get; set; } /// <summary> /// Number of customers from a specific country. /// </summary> public int NoOfCustomers { get; set; } } ``` Also, let's add the search model named `CustomersByCountrySearchModel` inside the *Models* folder. ```cs public record CustomersByCountrySearchModel : BaseSearchModel { } ``` nopCommerce uses the repository pattern for data access which is ideal for dependency injection mechanism. ### Services/ICustomersByCountry.cs Now let us create a service that fetches required data from a database. For service, we will create an interface and a service class implementing that interface. ```cs public interface ICustomersByCountry { Task<List<CustomersDistribution>> GetCustomersDistributionByCountryAsync() } ``` ### Services/CustomersByCountry.cs Here we are creating a class named **CustomersByCountry** which implements the **ICustomersByCountry** interface. ```cs public class CustomersByCountry : ICustomersByCountry { private readonly IAddressService _addressService; private readonly ICountryService _countryService; private readonly ICustomerService _customerService; public CustomersByCountry(IAddressService addressService, ICountryService countryService, ICustomerService customerService) { _addressService = addressService; _countryService = countryService; _customerService = customerService; } public async Task<List<CustomersDistribution>> GetCustomersDistributionByCountryAsync() { return await _customerService.GetAllCustomersAsync() .Where(c => c.ShippingAddressId != null) .Select(c => new { await (_countryService.GetCountryByAddressAsync(_addressService.GetAddressById(c.ShippingAddressId ?? 0))).Name, c.Username }) .GroupBy(c => c.Name) .Select(cbc => new CustomersDistribution { Country = cbc.Key, NoOfCustomers = cbc.Count() }).ToList(); } } ``` We implemented the method of the interface that retrieves data from the database. We used this approach so that we'll be able to use dependency injection techniques to inject this service into the controller. ### Infrastructure/PluginNopStartup.cs To register our interface and its implementation in the dependency injection (DI) container, we need to create a class that implements the INopStartup interface. This interface includes two methods and one property. Our primary focus is on implementing the ConfigureServices method, where we will register our interface with the DI container. ```cs /// <summary> /// Represents object for the configuring services on application startup /// </summary> public class PluginNopStartup : INopStartup { /// <summary> /// Add and configure any of the middleware /// </summary> /// <param name="services">Collection of service descriptors</param> /// <param name="configuration">Configuration of the application</param> public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { //register custom services services.AddScoped<ICustomersByCountry, CustomersByCountry>(); } /// <summary> /// Configure the using of added middleware /// </summary> /// <param name="application">Builder for configuring an application's request pipeline</param> public void Configure(IApplicationBuilder application) { } /// <summary> /// Gets order of this startup configuration implementation /// </summary> public int Order => 3000; } ``` ### Controllers/CustomersByCountryController.cs Now let's create a controller class. A good practice to name plugin controllers is like *{Group}{Name}Controller.cs*. For example, TutorialCustomersByCountryController, here *{Tutorial}{CustomersByCountry}Controller*. But remember that it is not a requirement to name the controller with *{Group}{Name}* it is just the recommended way by nopCommerce for naming but the Controller part in the name is the requirement of .Net MVC. ```cs [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action public class DistOfCustByCountryPluginController : BasePluginController { private readonly ICustomersByCountry _service; public DistOfCustByCountryPluginController(ICustomersByCountry service) { _service = service; } [HttpGet] public IActionResult Configure() { CustomersByCountrySearchModel customerSearchModel = new CustomersByCountrySearchModel { AvailablePageSizes = "10" }; return View("~/Plugins/Tutorial.DistOfCustByCountry/Views/Configure.cshtml", customerSearchModel); } [HttpPost] public async Task<IActionResult> GetCustomersCountByCountry() { try { return Ok(new DataTablesModel { Data = await _service.GetCustomersDistributionByCountryAsync() }); } catch (Exception ex) { return BadRequest(ex); } } } ``` In the controller, we are injecting the **ICustomersByCountry** service we created previously to get data from the database. Here we have created two Actions one is of type `HttpGet` and another of type `HttpPost`. The `Configure` action returns a view named "Configure.cshtml" which we haven't created yet. And `GetCustomersCountByCountry` action which uses an injected service to retrieve data and return data in the JSON format. This action is going to be called by the data table which expects a response as `DataTablesModel` object. So, here we set the data property which is the data that will be rendered in the table. ### Views/Configure.cshtml Now let's create a view with *DataTables* where we can display our data which then can be viewed by our users. ```cs @using Nop.Web.Framework.Models.DataTables @{ Layout = "_ConfigurePlugin"; } @await Html.PartialAsync("Table", new DataTablesModel { Name = "customersDistributionByCountry-grid", UrlRead = new DataUrl("GetCustomersCountByCountry", "TutorialCustomersByCountry"), Paging = false, ColumnCollection = new List<ColumnProperty> { new ColumnProperty(nameof(CustomersDistribution.Country)) { Title = "Country", Width = "300" }, new ColumnProperty(nameof(CustomersDistribution.NoOfCustomers)) { Title = "Number Of Customers", Width = "100" } } }) ``` ### Views/_ViewImports.cshtml The *_ViewImports.cshtml* file contains code to import all required references for our view files. ```cs @inherits Nop.Web.Framework.Mvc.Razor.NopRazorPage<TModel> @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, Nop.Web.Framework @using Microsoft.AspNetCore.Mvc.ViewFeatures @using Nop.Web.Framework.UI @using Nop.Web.Framework.Extensions @using System.Text.Encodings.Web @using Nop.Plugin.Tutorial.DistOfCustByCountry.Models @using Nop.Web.Framework.Models.DataTables; @using Microsoft.AspNetCore.Routing; ``` * In `Configure.cshtml` we are using a partial view named **`Table`**. This is the nopCommerce implementation of *JQuery DataTables*. We can find this file under `Nop.Web/Areas/Admin/Views/Shared/Table.cshtml`. There you can see the code for the implementation of *DataTables*. This view model takes a `DataTablesModel` class for the configuration of *DataTables*. Let's explain the properties that we have set for the `DataTablesModel` class. * **Name:** This will be set as an id for *DataTables*. * **UrlRead:** This is the URL from where *DataTables* is going to fetch data to render in the table. Here we are setting the URL to **`GetCustomersCountByCountry`** Action of the `TutorialCustomersByCountry` controller from where we are getting data for *DataTables*. * **Paging:** This property is used to enable or disable pagination for DataTables. * **ColumnCollection:** This property holds the column configuration property. There are several other properties that you can play around with to understand what each of the properties is used for. ### Infrastructure/RouteProvider Now the last step is to register our route for the Action "GetCustomersCountByCountry" of Controller "TutorialCustomersByCountry". We do not need to register the route for "Configure" Action because we have already registered that in the `DistOfCustByCountryPlugin` class. ```cs /// <summary> /// Represents plugin route provider /// </summary> public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { //add route for the access token callback endpointRouteBuilder.MapControllerRoute("CustomersDistributionByCountry", "Plugins/Tutorial/CustomerDistByCountry/", new { controller = "TutorialCustomersByCountry", action = "GetCustomersCountByCountry" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` >[!NOTE] > > To learn more about nopCommerce routing please visit [this page](xref:en/developer/tutorials/register-new-routes) Now just build your project and run it. Log in as an Admin user and go to the *LocalPlugins* menu under *Configuration*, there you will see your newly created plugin. Install that plugin. After installation is complete you will see a *configuration* button in your plugin. If you have followed correctly through this tutorial then you will see the output, something like the image below: ![image2](_static/guide-to-creating-a-page-containing-a-reporting-table-of-datatables/image2.png) --- <!-- page: Data Validation | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/data-validation.html | source: en/developer/tutorials/data-validation.md --> # Data Validation Data validation is the process of ensuring that a program operates on clean and correct data. Most .NET developers use `Data Annotation Validators`. But nopCommerce uses **`Fluent Validation`**. It's a small validation library for .NET that uses a fluent interface and lambda expressions for building validation rules for your business objects. To add validation for a model in nopCommerce, you need to do the following: Create a class derived from the `AbstractValidator` class and put all required logic there. ```csharp public partial class AddressValidator : BaseNopValidator<AddressModel> { public AddressValidator(ILocalizationService localizationService) { RuleFor(x => x.FirstName) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("AddressFields.FirstName.Required")); } } ``` ASP.NET Core will execute the appropriate validator when a view model is posted to a controller. --- <!-- page: Exposing and Handling Events | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/events.html | source: en/developer/tutorials/events.md --> # Exposing and Handling Events Events are notifications broadcast to interested parties. Events are triggered on data changes like inserts, updates, and deletes. nopCommerce allows developers to "listen" for events they might be interested in. There are two ways a developer will work with events. A developer will either want to publish events for listeners to consume, or subscribe to events other developers will have programmatically published. 1. To publish an event a developer will need to obtain an instance of **IEventPublisher** and call the **PublishAsync** method with the appropriate event data. ```csharp await _eventPublisher.PublishAsync(new OrderPlacedEvent(order)); ``` The event class looks like this: ```csharp public class OrderPlacedEvent { public OrderPlacedEvent(Order order) { Order = order; } public Order Order { get; } } ``` 1. To listen for an event the developer will want to create a new implementation of the generic **IConsumer** interface. Once a new consumer implementation has been created nopCommerce uses reflection to find and register the implementation for event handling. ```csharp public class EventConsumer : IConsumer<OrderPlacedEvent> { public async Task HandleEventAsync(OrderPlacedEvent eventMessage) { if (eventMessage?.Order != null) { //do something } } } ``` --- <!-- page: Settings API | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/settings.html | source: en/developer/tutorials/settings.md --> # Settings API Like any other website platform, nopCommerce has settings such as "Store name" or "One page checkout enabled". There are two ways to manage settings in nopCommerce. 1. You can use **GetSettingByKeyAsync** and **SetSettingAsync** methods of **ISettingService** implementation for loading and saving individual settings. ```csharp var setting = await GetSettingByKeyAsync<string>(key); ... await _settingService.SetSettingAsync(key, value); ``` 2. The preferred approach for handling settings in nopCommerce is to create a new implementation of the **ISettings** interface. Each setting will be represented by a C# property and developers should rely on setting classes to be injected via the constructor when they are required. Below is an example settings class. ```csharp public partial class MediaSettings : ISettings { public int AvatarPictureSize { get; set; } public int ProductThumbPictureSize { get; set; } public int ProductDetailsPictureSize { get; set; } public int ProductThumbPictureSizeOnProductDetailsPage { get; set; } public int AssociatedProductPictureSize { get; set; } public int CategoryThumbPictureSize { get; set; } public int ManufacturerThumbPictureSize { get; set; } public int VendorThumbPictureSize { get; set; } public int CartThumbPictureSize { get; set; } public int OrderThumbPictureSize { get; set; } public int MiniCartThumbPictureSize { get; set; } public int AutoCompleteSearchThumbPictureSize { get; set; } public int ImageSquarePictureSize { get; set; } public bool DefaultPictureZoomEnabled { get; set; } public bool AllowSVGUploads { get; set; } public int MaximumImageSize { get; set; } public int DefaultImageQuality { get; set; } public bool MultipleThumbDirectories { get; set; } public bool ImportProductImagesUsingHash { get; set; } public string AzureCacheControlHeader { get; set; } public bool UseAbsoluteImagePath { get; set; } public string VideoIframeAllow { get; set; } public int VideoIframeWidth { get; set; } public int VideoIframeHeight { get; set; } public int ProductDefaultImageId { get; set; } } ``` --- <!-- page: Settings in appsettings.json | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/appsettings-json-file.html | source: en/developer/tutorials/appsettings-json-file.md --> # Settings in appsettings.json ## Overview This article contains the description of the *appsettings.json* file. In this article, we will explain what settings are available in this file, what they are used for, and how to use these settings to change the functionality/behavior of the nopCommerce project. >[!IMPORTANT] > >All settings can be overridden in environment variables. ## The appsettings.json file overview If you have worked on the *ASP.NET Core* project previously or you are familiar with `ASP.NET Core` then you might have used the *appsettings.json* file and have some understanding of what this file is and what this file is used for. >[!NOTE] > >You can also edit this file from the **Configuration → Settings → App settings** page. The *appsettings.json* file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information. Actually, in *ASP.NET Core*, the application configuration settings can be stored in different configuration sources such as *appsettings.json* file, **`appsettings.{EnvironmentName}.json`** file (where the `{Environment}` is the application's current hosting environments such as Development, Staging or Production), `User Secrets` (where we used to store sensitive information), etc. ## Settings available in the appsettings.json file ### DataConfig The connection to the database is configured through this section. * **ConnectionString** This setting expects a string value. >[!NOTE] > >The connection string will have a format specific to the selected database provider. > For example connection string for **SqlServer** look like this: > >```powershell >Data Source={localhost};Initial Catalog={your_data_base_name}};Integrated >Security=False;Persist Security Info=False;User ID={your_user_id}};Password={your_password}};>Trust Server Certificate=True >``` * **DataProvider** You can specify one of the supported data providers: * [**SqlServer**](https://www.microsoft.com/sql-server) * [**MySql**](https://www.mysql.com/) * [**PostgreSQL**](https://www.postgresql.org/) * **SQLCommandTimeout** Sets the wait time (in seconds) before terminating the attempt to execute a command and generating an error. By default, timeout isn't set and a default value for the current provider is used. Set **`0`** to use an infinite timeout. * **WithNoLock** Indicates whether to add NoLock hint to SELECT statements (Relates to SQL Server only) ### AzureBlobConfig >[!IMPORTANT] > >This settings section is relevant for version 4.80 and below. For nopCommerce version 4.90 and above, [Azure settings are described here](xref:en/developer/plugins/cloudflare-images). We can use *Azure Blob Storage* to store blob data. nopCommerce already has a feature integrated for that, we just need to set the following information correctly to use this feature. Values for these settings can be obtained for *Azure* while you create the storage account. * **ConnectionString** This setting expects a string value. Here you need to add your `AzureBlobStorage` connection string * **ContainerName** Value for this setting is also of type string. In this setting, we set the container name for *Azure BLOB storage*. * **EndPoint** This setting also expects a string value. Here we need to set the endpoint for *Azure BLOB storage*. * **AppendContainerName** This setting expects a boolean value. Set the value to **`true`** or **`false`** based on whether the Container Name is appended to the `EndPoint` when constructing the URL. * **StoreDataProtectionKeys** This setting expects a boolean value. Set the value to **`true`** if you want to use the *Windows Azure BLOB storage* for *Data Protection Keys*. * **DataProtectionKeysContainerName** This setting expects a string value. Here you need to set up an Azure container name for storing *Data Protection Keys* (this container should be separate from the container used for media and should be Private) * **DataProtectionKeysVaultId (optional)** This setting also expects a string value. Set the `Azure key vault ID` if you need to encrypt the *Data Protection Keys* ### CacheConfig Cache configuration. * **DefaultCacheTime** This setting determines the lifetime of the cached data. The default is **`60`** minutes. * **LinqDisableQueryCache** Indicates whether to disable LINQ expressions caching for queries. This cache reduces time, required for query parsing but have several side-effects. For example, cached LINQ expressions could contain references to external objects as parameters, which could lead to memory leaks if those objects are not used anymore by other code. Or cache access synchronization could lead to bigger latencies than it saves. ### CommonConfig *CommonConfig* contains settings used to configure the behavior of nopCommerce itself. It is a JSON object and contains some settings that can be tweaked to change the behavior of nopCommerce. * **DisplayFullErrorStack** This setting expects a boolean value. The default value is **`false`**. You can set the value to **`true`** if you want to see the full error in the production environment. Which is not what we usually suggest. But if you have a good reason to show full error during the production environment then you can do it from this setting. For the development environment this setting is ignored and whatever the value you set for this setting full error will be shown. We can say that this setting is always enabled for a development environment. * **UserAgentStringsPath** This setting stores the path to the `Browscap.xml` file, `Browscap.xml` is, as the filename might indicate, a browser capabilities database. It's essentially a list of all known browsers and bots, along with their default capabilities and limitations. ```powershell ~/App_Data/browscap.xml ``` >[!NOTE] > > In computing, a user agent is software (a software agent) that is acting on behalf of a user, such as a web browser that "retrieves, renders and facilitates end-user interaction with Web content". For more information please visit [UserAgent](https://en.wikipedia.org/wiki/User_agent). * **CrawlerOnlyUserAgentStringsPath** This setting stores the location/path for `browscap.crawlersonly.xml`. It stores user agents only for "CrawlerOnly". ```powershell ~/App_Data/browscap.crawlersonly.xml ``` * **CrawlerOnlyAdditionalUserAgentStringsPath** This setting stores the location/path for `additional.crawlers.xml`. It stores user agents only for "Сrawlers". ```powershell ~/App_Data/additional.crawlers.xml ``` * **UseSessionStateTempDataProvider** This setting expects a boolean value. The default value for this setting is **`false`**. You might want to set the value to **`true`** if you want to store `TempData` in the session state. By default, the cookie-based `TempData` provider is used to store `TempData` in cookies. * **ScheduleTaskRunTimeout** allows you to set up a running schedule task timeout in milliseconds. Set **`null`** to use a default value. * **StaticFilesCacheControl** specifies the value of the 'Cache-Control' header for static content (in seconds). ```powershell public,max-age=31536000 ``` * **ServeUnknownFileTypes** setting specifies the value indicating whether to serve files that don't have a recognized content type. The default value is **`false`**. * **UseAutofac**. The value indicating whether to use *Autofac IoC container*. If disabled, then the default *.Net IoC container* will be used. * **PermitLimit**. Maximum number of permit counters that can be allowed in a window (1 minute). Must be set to a value `> 0` by the time these options are passed to the constructor of `FixedWindowRateLimiter`. If set to **`0`** than limitation is off. * **QueueCount**. Maximum cumulative permit count of queued acquisition requests. Must be set to a value `>= 0` by the time these options are passed to the constructor of `FixedWindowRateLimiter`. If set to **`0`** than Queue is off. * **RejectionStatusCode**. Default status code to set on the response when a request is rejected. ### DistributedCacheConfig A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm. * **DistributedCacheType** You can choose one of the implementations: * **Memory** - This is a framework-provided implementation of `IDistributedCache` that stores items in memory. The Distributed Memory Cache isn't a distributed cache. Cached items are stored by the app instance on the server where the app is running. * **SQL Server** - The Distributed SQL Server Cache implementation allows the distributed cache to use a SQL Server database as its backing store. To create a SQL Server cached item table in a SQL Server instance, you can use the SQL-cache tool. The tool creates a table with the name and schema that you specify. It is recommended to use a separate database for this purpose. ```sh dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;" dbo nopCache ``` * **Redis** - nopCommerce supports *Redis* out of the box. To enable the *Redis* in your application you must set the corresponding settings. For more information about [Redis](https://azure.microsoft.com/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache). * **Redis Synchronized Memory** - nopCommerce version 4.70 introduces a new way of caching with synchronization through the message mechanism in *Redis*. This option has very high performance since the cache itself is stored in memory and *Redis* is used only as a synchronizer. To enable this option in your application you must set the same settings as and for the base *Redis* cache. * **Enabled** This setting expects a boolean value. Set the value to **`true`** if you want to enable `Distributed cache`. The system uses In-Memory caching, so this setting is used to indicate whether we should use `Distributed Cache` for caching, instead of the default `in-memory caching`. So, use this setting if you want to use for example *Redis* for caching. * **ConnectionString (optional)** This setting is only used in conjunction with *Redis* or *SQL Server*. This setting expects a string value. The default value for this setting is ```powershell 127.0.0.1:{PORT},ssl=False ``` * **SchemaName (optional)** This setting is only used in conjunction with `SQL Server`. * **TableName (optional)** This setting is only used in conjunction with `SQL Server`. SQL Server database name. * **InstanceName (optional)** Specify the instance name (by default "nopCommerce"). * **PublishIntervalMs (optional)** Specify the interval to publish key change events, in milliseconds. ### HostingConfig Hosting contains settings used to configure the hosting behavior. It is a JSON object and contains some properties settings which can be tweaked to change the behavior for hosting. * **UseProxy** This setting expects a boolean value. Enable this setting to apply forwarded headers to their matching fields on the current HTTP request. * **ForwardedProtoHeaderName** This setting expects a string value. Specify a custom HTTP header name for identifying the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer. * **ForwardedForHeaderName** This setting expects a string value. Specify a custom HTTP header name to determine the originating IP address (e.g., **`CF-Connecting-IP`**, **`X-ProxyUser-Ip`**). * **KnownProxies** This setting expects a string value. Specify a list of IP addresses (comma separated) to accept forwarded headers. * **KnownNetworks** This setting expects a string value. Specify a list of IP CIDR notations (comma separated) to accept forwarded headers. e.g. 172.64.0.0/13,162.158.0.0/15 ### InstallationConfig It contains settings that are used to configure the behavior of nopCommerce during the nopCommerce installation. * **DisableSampleData** This setting expects a boolean value. This setting indicates whether a store owner can install sample data during installation. If you don't want the store owner to install sample data during installation then just set the value for this setting to **`true`**. * **DisabledPlugins** This setting expects a string value. Specify a list of plugins (comma separated) ignored during installation. * **InstallRegionalResources** This setting expects a boolean value. This setting enables the selection of additional language resources during installation. The choice of the country determines the settings that will be applied to the store (exchange rates, taxes, units of measurement, etc. regional features). ### PluginConfig * **UseUnsafeLoadAssembly** This setting expects a boolean value. You might want to set the value to **`true`** if you want to load an assembly into the load-from context, bypassing some security checks. ### WebOptimizer We use the [WebOptimizer](https://github.com/ligershark/WebOptimizer) tool for minification and bundling of *CSS* and *JavaScript* code, which is an *ASP.NET Core* middleware. Optimization is performed at runtime with server-side and client-side caching for high performance. * **EnableJavaScriptBundling** This setting expects a boolean value. You can set it to **`true`** if you want JS file bundling and minification to be enabled. * **EnableCssBundling** This setting expects a boolean value. You can set it to **`true`** if you want CSS file bundling and minification to be enabled. * **JavaScriptBundleSuffix** This setting expects a string value. You can set a suffix for the js-file name of generated bundles (by default **`.scripts`**). * **CssBundleSuffix** This setting expects a string value. You can set a suffix for the CSS-file name of generated bundles (by default **`.styles`**). * **EnableCaching** This setting expects a boolean value. You can set a value indicating whether server-side caching is enabled (by default **`true`**). * **EnableMemoryCache** This setting expects a boolean value. You can set a value indicating whether *Microsoft.Extensions.Caching.Memory.IMemoryCache* based caching is enabled (by default **`true`**). * **EnableDiskCache** This setting expects a boolean value. Determines if the pipeline assets are cached to disk. This can speed up application restarts by loading pipeline assets from the disk instead of re-executing the pipeline. Can be helpful to disable while in development mode. * **EnableTagHelperBundling** This setting expects a boolean value. You can set whether bundling is enabled (by default **`false`**). * **CdnUrl** This setting expects a string value. You can set the CDN URL used for TagHelpers (by default **`null`**). * **CacheDirectory** This setting expects a string value. Sets the directory where assets will be stored if **EnableDiskCache** is **`true`** (by default **`{ContentRootPath}\\wwwroot\\bundles`**). * **AllowEmptyBundle** This setting expects a boolean value. You can set whether the empty bundle is allowed to generate instead of throwing an exception (by default **`true`**). * **HttpsCompression** This setting expects an integer value. You can set a value Indicating if files should be compressed for HTTPS requests when the Response Compression middleware is available. The default value is **`2`**. You can choose one of the implementations: * **1** - Opts out of compression over HTTPS. * **2** - Opts into compression over HTTPS. >[!NOTE] > > Enabling compression on HTTPS requests for remotely manipulable content may expose security problems. * **MemoryCacheTimeToLive** If *EnableMemoryCache* memory caching is enabled, control how long an entry is stored in memory. Default is 60 minutes. --- <!-- page: Settings in web.config | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/description-of-the-web-config-file-in-project.html | source: en/developer/tutorials/description-of-the-web-config-file-in-project.md --> # Settings in web.config ## What is the web.config file `web.config` file is an XML-based configuration file used in ASP.NET-based applications to manage various settings that are concerned with the configuration of our website. In this way, we can separate our application logic from configuration logic. And the main benefit of this is, if we want to change some configuration settings then we do not need to restart our application to apply new changes, ASP.NET automatically detects the changes and applies them to the running ASP.NET application. The ASP.NET framework uses a hierarchical configuration system. You can place a `web.config` file in any subdirectory of an application. The file then applies to any pages located in the same directory or any subdirectories. ## web.config for nopCommerce nopCommerce uses the `web.config` in the `Nop.Web` project which can be found inside the Presentation directory. In the root of the project directory, you can see a web.config file. If your solution is fresh installation of nopCommerce then the content of that file looks something like this: ```xml <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <modules> <!-- Remove WebDAV module so that we can make DELETE requests --> <remove name="WebDAVModule" /> </modules> <handlers> <!-- Remove WebDAV module so that we can make DELETE requests --> <remove name="WebDAV" /> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <!-- When deploying on Azure, make sure that "dotnet" is installed and the path to it is registered in the PATH environment variable or specify the full path to it --> <aspNetCore requestTimeout="23:00:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" forwardWindowsAuthToken="false" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600" hostingModel="InProcess"> </aspNetCore> <httpProtocol> <customHeaders> <remove name="X-Powered-By" /> <!-- Protects against XSS injections. ref.: https://www.veracode.com/blog/2014/03/guidelines-for-setting-security-headers/ --> <add name="X-XSS-Protection" value="1; mode=block" /> <!-- Protects against Clickjacking attacks. ref.: http://stackoverflow.com/a/22105445/1233379 --> <add name="X-Frame-Options" value="SAMEORIGIN" /> <!-- Protects against MIME-type confusion attack. ref.: https://www.veracode.com/blog/2014/03/guidelines-for-setting-security-headers/ --> <add name="X-Content-Type-Options" value="nosniff" /> <!-- Protects against Clickjacking attacks. ref.: https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet --> <add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains" /> <!-- CSP modern XSS directive-based defence, used since 2014. ref.: http://content-security-policy.com/ --> <add name="Content-Security-Policy" value="default-src 'self'; connect-src *; font-src * data:; frame-src *; img-src * data:; media-src *; object-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline';" /> <!-- Prevents from leaking referrer data over insecure connections. ref.: https://scotthelme.co.uk/a-new-security-header-referrer-policy/ --> <add name="Referrer-Policy" value="same-origin" /> <!-- Permissions-Policy is a new header that allows a site to control which features and APIs can be used in the browser. ref.: https://w3c.github.io/webappsec-permissions-policy/ --> <add name="Permissions-Policy" value="accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=*, usb=()" /> </customHeaders> </httpProtocol> </system.webServer> </configuration> ``` ```xml <configuration> ... </configuration> ``` Every configuration rule goes inside the "`<configuration>`" element. ```xml <system.webServer> ... </system.webServer> ``` The `<system.webServer>` element specifies the root element for many of the site-level and application-level configuration settings for IIS, and contains configuration elements that define the settings used by the Web server engine and modules. ```xml <modules> <!-- Remove WebDAV module so that we can make DELETE requests --> <remove name="WebDAVModule" /> </modules> ``` The `<modules>` element defines the native-code modules and managed-code modules that are registered for an application. We commonly use modules to implement customized functionality. The `<modules>` element contains a collection of `<add>`, `<remove>` and `<clear>` elements. Here nopCommerce is using the `<remove>` element to remove the WebDAVModule module from the application. ```xml <handlers> <!-- Remove WebDAV module so that we can make DELETE requests --> <remove name="WebDAV" /> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> ``` Handlers are IIS components that are configured to process requests to specific content, typically to generate a response for the requested resource. For example, an ASP.NET Web page is one type of handler. You can use handlers to process requests to any resource that needs to return information to users that is not a static file. The `<handlers>` element contains a collection of `<add>`, `<remove>`, and `<clear>` elements, each of which defines a handler mapping for the application. The `<add>` element adds a handler to the collection of handlers, the `<remove>` element removes references of the handler from the handler's collection, and the `<clear>` element removes all references of handlers from the handlers collection. Here in the above code "WebDAV" handler is removed and the handler for module `AspNetCoreModuleV2` is added. ```xml <aspNetCore requestTimeout="23:00:00" processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" forwardWindowsAuthToken="false" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600" hostingModel="InProcess"/> ``` ```xml <httpProtocol> <customHeaders> <remove name="X-Powered-By" /> <!-- Protects against XSS injections. ref.: https://www.veracode.com/blog/2014/03/guidelines-for-setting-security-headers/ --> <add name="X-XSS-Protection" value="1; mode=block" /> <!-- Protects against Clickjacking attacks. ref.: http://stackoverflow.com/a/22105445/1233379 --> <add name="X-Frame-Options" value="SAMEORIGIN" /> <!-- Protects against MIME-type confusion attack. ref.: https://www.veracode.com/blog/2014/03/guidelines-for-setting-security-headers/ --> <add name="X-Content-Type-Options" value="nosniff" /> <!-- Protects against Clickjacking attacks. ref.: https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet --> <add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains" /> <!-- CSP modern XSS directive-based defence, used since 2014. ref.: http://content-security-policy.com/ --> <add name="Content-Security-Policy" value="default-src 'self'; connect-src *; font-src * data:; frame-src *; img-src * data:; media-src *; object-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline';" /> <!-- Prevents from leaking referrer data over insecure connections. ref.: https://scotthelme.co.uk/a-new-security-header-referrer-policy/ --> <add name="Referrer-Policy" value="same-origin" /> <!-- Permissions-Policy is a new header that allows a site to control which features and APIs can be used in the browser. ref.: https://w3c.github.io/webappsec-permissions-policy/ --> <add name="Permissions-Policy" value="accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=*, usb=()" /> </customHeaders> </httpProtocol> ``` The `<customHeaders>` element of the `<httpProtocol>` element specifies custom HTTP headers that IIS will return in HTTP responses from the Web server. HTTP headers are name and value pairs that are returned in responses from a Web server. Custom response headers are sent to the client together with the default HTTP header. Unlike redirect response headers, which are returned in responses only when redirection occurs, custom response headers are returned in every response. ## Configure the redirect rules in IIS We can add other configurations additional to the above configurations. Here we will see how to configure redirect rules in IIS. A redirect rule enables more than one URL to point to a single Web page. There may be several reasons why you want to redirect a request from one server to another. For example, maybe your company name is changed and you may want to register a new domain for your company and move your website to a new domain, so in that case, you may want to redirect all requests from your old domain to a new domain. For our website to be able to use redirect rules, we need to install the "URL rewrite" module which is an extension to IIS. For demonstration purposes, let's say we have to redirect a request from our old site to our new site, for that we need to write the following rules in our `web.config` file. ```xml <rewrite> <rules> <rule name="[RULE NAME]" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAny" trackAllCaptures="false"> <add input="{HTTP_HOST}{REQUEST_URI}" pattern="[OLD URL]" /> </conditions> <action type="Redirect" url="http://[NEW URL]/{R:1}" redirectType="Permanent"/> </rule> </rules> </rewrite> ``` > [!NOTE] > > By using this rule we can redirect all pages of an old domain name to the same page on a new domain name. Here we need to replace [RULE NAME], [OLD URL], and [NEW URL] with the appropriate information. * [RULE NAME] can be anything that describes what this rule is doing * [OLD URL] is the old URL you want to redirect from. * [NEW URL] is the new URL you want to redirect to. ```xml <match url="(.*)" /> ``` The above element states that this rule will match all URL strings. ```xml <add input="{HTTP_HOST}{REQUEST_URI}" pattern="[OLD URL]" /> ``` The element above adds a condition to the rule that retrieves the host and requests Uri header value by reading the server variable HTTP_HOST and REQUEST_URI and matches it against the pattern with the value supplied for [OLD URL]. ```xml <action type="Redirect" url="http://[NEW URL]/{R:1}" redirectType="Permanent"/> ``` This element redirects the matching old URL to the new URL. --- <!-- page: Extending Permissions | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/permissions.html | source: en/developer/tutorials/permissions.md --> # Extending Permissions **Permissions** are an important element of application resource security. With their help, you can restrict access to a particular part of the application, or vice versa, providing the necessary rights to read/change a specific area. All available permissions to control the scope are in the *Access Control List (ACL)* section. Like any other changes in the application, it is recommended to be made through plugins. So let's look at adding permissions via an abstract plugin. This tutorial aims to show you how to manage permissions, for learning about creating the plugin itself check out [this page](xref:en/developer/plugins/index). ## Adding a custom permission in nopCommerce 4.80 and above First of all, let's create a class that describes the new permission - this will be the permission provider. It is necessary and sufficient that this class be inherited from the `IPermissionConfigManager` interface. ```csharp public partial class WebApiBackendPermissionConfigManager : IPermissionConfigManager { public const string ACCESS_WEB_API = "AccessWebApi"; /// <summary> /// Gets all permission configurations /// </summary> public IList<PermissionConfig> AllConfigs => new List<PermissionConfig> { new("Access Web API Backend", ACCESS_WEB_API , nameof(StandardPermission.System), NopCustomerDefaults.AdministratorsRoleName) }; } ``` The specified records will be installed into the database without any additional actions. In this example, the permission is set only for the *administrator role*, but this list can be expanded if necessary. Do not forget to also remove the permission in the `UninstallAsync()` method when removing the plugin: ```csharp //delete permission var permissionRecord = (await _permissionService.GetAllPermissionRecordsAsync()) .FirstOrDefault(x => x.SystemName == WebApiBackendPermissionConfigManager.ACCESS_WEB_API); await _permissionService.DeletePermissionRecordAsync(permissionRecord); ``` Now, in any place where we need to check the legitimacy of the user's access to a specific resource, we need to call the `AuthorizeAsync()` method of the `IPermissionService` service with the permission: ```csharp //check whether current customer has access to Web API if (await _permissionService.AuthorizeAsync(WebApiBackendPermissionConfigManager.ACCESS_WEB_API)) return; ``` Another way of using permissions as an attribute of a controller action filter is as follows: ```csharp [CheckPermission(WebApiBackendPermissionConfigManager.ACCESS_WEB_API)] public virtual async Task<IActionResult> Configure() { ... } ``` That's essentially all, after installing the plugin, you can see the permission you added in the **ACL** section. > [!NOTE] > > If you want to use the default permissions out of the box, they are all listed in the `StandardPermission` class (`Nop.Services.Security` namespace). > For example: > > ```csharp > [CheckPermission(StandardPermission.Configuration.MANAGE_SETTINGS)] > ``` ## Adding a custom permission in nopCommerce 4.70 and below First of all, let's create a class that describes the new permission - this will be the permission provider. It is necessary and sufficient that this class be inherited from the `IPermissionProvider` interface. ```csharp public partial class WebApiBackendPermissionProvider : IPermissionProvider { public static readonly PermissionRecord AccessWebApiBackend = new () { Name = "Access Web API Backend", SystemName = "AccessWebApi", Category= "Standard" }; /// <summary> /// Get permissions /// </summary> /// <returns>Permissions</returns> public virtual IEnumerable<PermissionRecord> GetPermissions() { return new[] { AccessWebApiBackend }; } /// <summary> /// Get default permissions /// </summary> /// <returns>Permissions</returns> public virtual HashSet<(string systemRoleName, PermissionRecord[]permissions)> GetDefaultPermissions() { return new () { (NopCustomerDefaults.AdministratorsRoleName, new [] { AccessWebApiBackend }) }; } } ``` In this example, the permission is set only for the *administrator role*, but this list can be expanded if necessary. Now we will add this permission when our plugin is installed. This must be done in the `InstallAsync()` method: ```csharp //add permission await _permissionService.InstallPermissionsAsync(new WebApiBackendPermissionProvider()); ``` Do not forget to also remove the permission in the `UninstallAsync()` method when removing the plugin: ```csharp //delete permission var permissionRecord = (await _permissionService.GetAllPermissionRecordsAsync()) .FirstOrDefault(x => x.SystemName == WebApiBackendPermissionProvider.AccessWebApiBackend.SystemName); var listMappingCustomerRolePermissionRecord = await _permissionService.GetMappingByPermissionRecordIdAsync(permissionRecord.Id); foreach (var mappingCustomerPermissionRecord in listMappingCustomerRolePermissionRecord) await _permissionService.DeletePermissionRecordCustomerRoleMappingAsync( mappingCustomerPermissionRecord.PermissionRecordId, mappingCustomerPermissionRecord.CustomerRoleId); await _permissionService.DeletePermissionRecordAsync(permissionRecord); ``` Now, in any place where we need to check the legitimacy of the user's access to a specific resource, we need to call the `AuthorizeAsync()` method of the `IPermissionService` service with the permission: ```csharp //check whether current customer has access to Web API if (await _permissionService.AuthorizeAsync(WebApiBackendPermissionProvider.AccessWebApiBackend)) return; ``` That's essentially all, after installing the plugin, you can see the permission you added in the **ACL** section. ## See also - [Access control list](xref:en/running-your-store/customer-management/access-control-list) --- <!-- page: Scheduled Tasks | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/scheduled-tasks.html | source: en/developer/tutorials/scheduled-tasks.md --> # Scheduled Tasks With Scheduled tasks, you can schedule a task to run at certain periods. For example, nopCommerce sends queued emails periodically. The basic steps to create a new task are: 1. Define a class that implements the **IScheduleTask** interface. It has only one method that takes no arguments; **ExecuteAsync**. As you guessed this method is invoked when the task should be run. ```csharp public partial class KeepAliveTask : IScheduleTask { private readonly StoreHttpClient _storeHttpClient; public KeepAliveTask(StoreHttpClient storeHttpClient) { _storeHttpClient = storeHttpClient; } public async System.Threading.Tasks.Task ExecuteAsync() { await _storeHttpClient.KeepAliveAsync(); } } ``` 1. To schedule a task the developer should insert a new **ScheduleTask** record into the appropriate database table. You can use **IScheduleTaskService** for inserting such a record. ```csharp await _scheduleTaskService.InsertTaskAsync(new ScheduleTask { Name = "Keep alive", Seconds = 300, Type = "Nop.Services.Common.KeepAliveTask, Nop.Services", Enabled = true, LastEnabledUtc = lastEnabledUtc, StopOnError = false }); ``` > [!IMPORTANT] > > When inserting the new record into the **ScheduleTask** database table for a new scheduled task, it is important to keep the **Type** column format as **Namespace.TaskClassName, AssemblyName**. ## Troubleshooting - Make sure your store has a valid URL. - Restart the application after adding a new scheduled task. --- <!-- page: ITypeFinder Interface | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/type-finder.html | source: en/developer/tutorials/type-finder.md --> # ITypeFinder Interface ## ITypeFinder This is a very simple interface. It contains only two methods (although one has two overloads). You can see the definition of the interface below: ```csharp /// <summary> /// Classes implementing this interface provide information about types /// to various services in the Nop engine. /// </summary> public interface ITypeFinder { /// <param name="onlyConcreteClasses">A value indicating whether to find only concrete classes</param> IEnumerable<Type> FindClassesOfType<T>(bool onlyConcreteClasses = true); /// <param name="assignTypeFrom">Assign type from</param> /// <param name="onlyConcreteClasses">A value indicating whether to find only concrete classes</param> IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true); /// <summary> /// Gets the assemblies related to the current implementation. /// </summary> IList<Assembly> GetAssemblies(); } ``` The main task of a class that implements this interface is to search in assemblies for the types of the specified class or interface. We'll look at where this can come in handy using the examples from the source code of nopCommerce. But first, let's take a look at the ``GetAssemblies`` method. The task of this method is simply to return a list of the assemblies in which the search is performed. How exactly this list is formed depends on the specific implementation of the interface. ## Default implementation of ITypeFinder The main default implementation of this interface is the ``WebAppTypeFinder`` class. In turn ``WebAppTypeFinder`` only slightly extends the ``AppDomainTypeFinder`` class, which essentially does all the work of searching for types. But we use the derived class since it extends the scope of the search for types to all assemblies from the **\Bin** directory, while the main class works with assemblies from the current application domain only. Without dwelling on the implementation details of the ``FindClassesOfType`` methods (since they both boil down to the very simple function which code is available at [this link](https://github.com/nopSolutions/nopCommerce/blob/develop/src/Libraries/Nop.Core/Infrastructure/AppDomainTypeFinder.cs#L184)) let's move on to the most important thing about this interface. ## So why do we need the ITypeFinder interface This interface is used in some very important aspects of how nopCommerce works: 1. Searching assemblies for configuring the migration mechanism ([How do migrations work?](xref:en/developer/tutorials/migrations)) 1. Searching classes of certain interfaces necessary for the correct launch of the site, such as: * ``IStartupTask`` - Initial initialization of the modules and plugins * ``INopStartup`` - Configuring services and middleware on application startup * ``IOrderedMapperProfile`` - Create **Mapster** configuration * ``IEntityBuilder``, ``INameCompatibility`` - Configure database entity builder for backward compatibility of table naming for **Linq2Db**([nopCommerce Data Access Layer](xref:en/developer/tutorials/source-code-organization#librariesnopdata)) * ``IRouteProvider`` - Register routes * ``IConsumer<T>`` - Register handlers for internal events such as changes in database entities * ``IExternalAuthenticationRegistrar`` - Register and configure external authentication methods 1. Searching for a suitable shipment tracker in real-time ## Conclusion As you can see, the interface is small but very valuable. It would be difficult to implement such a flexible modular structure as it's done in nopCommerce without using the approach implemented through the `ITypeFinder` interface methods. --- <!-- page: Deployment on Azure with Git and Automatic Builds | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/azure-deploy.html | source: en/developer/tutorials/azure-deploy.md --> # Deployment on Azure with Git and Automatic Builds ## Step by step guide for automatic deployment of nopCommerce with git on Azure 1. **Setup your git-repository** The default way to deploy nopCommerce is by using the “Publish” function in Visual Studio. But for publishing to Azure you need to have your own repository. You may use Bitbucket and keep that in sync with the official repository. Or you can [setup git on Azure](https://azure.microsoft.com/documentation/articles/web-sites-publish-source-control/). There's [a great video here](http://channel9.msdn.com/Shows/Azure-Friday/What-is-Kudu-Azure-Web-Sites-Deployment-with-David-Ebbo). 1. **Prepare for local deployment** When you ensure that the automatic build works, we are ready to customize our deployment scripts. This is needed because the default automatic build only builds `Nop.Web` project. The problem with this is that it does not build any of the plugins. You cannot add their reference to `Nop.Web' project either as they would create circular references. So, we need to get the custom build working, these are the tools we need to install: - Install NodeJs: [https://nodejs.org](https://nodejs.org) - Install Azure CLI: [https://azure.microsoft.com/documentation/articles/xplat-cli-install/](https://azure.microsoft.com/documentation/articles/xplat-cli-install/) 1. **Get NuGet to work at the command line level.** The default behavior of the KUDU script (which is a tool for generating deployment scripts for Azure App Service) is to check for NuGet packages. - To get access to the `Nuget.exe` file you could either [download it from here](https://docs.nuget.org/consume/command-line-reference). You can also "Enable automatic restore of NuGet packages" in your Visual Studio, and it will be added to your project automatically. - Ensure that NuGet is in the PATH. Copy the `nuget.exe` file to the preferred location (e.g. `c:/Program Files/Nuget/Nuget.exe`). Add it to the PATH environment variable. - Confirm that NuGet is in your PATH by starting `cmd.exe` and writing *nuget*. you should see the command options. 1. **Generate deployment scripts locally** - Open the "Microsoft Azure Command Prompt" - Navigate to the src folder of your project as you normally would in a shell window - Execute the kudu script generator (You may find wiki by [this link](https://github.com/projectkudu/kudu/wiki) or see [this video](https://azure.microsoft.com/resources/videos/custom-web-site-deployment-scripts-with-kudu/)). So you would write something like: `kuduscript site deploymentscript --aspNetCore Presentation\Nop.Web\Nop.Web.csproj -s NopCommerce.sln -y` - Verify that it has generated 2 files (in your local repository root): `.deployment` `deploy.cmd` 1. **Run generated script** - You must keep the .deployment and deploy.cmd file in the root of the git repository - Edit the `deploy.cmd` as the `%DEPLOYMENT_SOURCE%` variable containing the root of the git repository. So we would add `%DEPLOYMENT_SOURCE%\src\Presentation\Nop.Web\Nop.Web.csproj` instead of `%DEPLOYMENT_SOURCE%\Presentation\Nop.Web\Nop.Web.csproj`. All paths in the deployment section must be corrected. - Run `deploy.cmd` to see if the default deploy script works locally. It should create an `\artifact` folder just outside of your git repository. 1. **Customize the deployment script** Now we are at the final part. This is where all that work pays off. We want to alter the following piece: ```sh :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Deployment :: ---------- echo Handling ASP.NET Core Web Application deployment. :: 1. Restore nuget packages call :ExecuteCmd dotnet restore "%DEPLOYMENT_SOURCE%\NopCommerce.sln" IF !ERRORLEVEL! NEQ 0 goto error :: 2. Build and publish call :ExecuteCmd dotnet publish "%DEPLOYMENT_SOURCE%\Presentation\Nop.Web\Nop.Web.csproj" --output "%DEPLOYMENT_TEMP%" --configuration Release IF !ERRORLEVEL! NEQ 0 goto error :: 3. KuduSync call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_TEMP%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd" IF !ERRORLEVEL! NEQ 0 goto error :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ``` Between no ::1 and ::2 is where we are gonna place our commands for building plugins. An example for the first plugin would be: ```sh :: 1.01 Build plugin customer roles to temporary path call :ExecuteCmd dotnet build "%DEPLOYMENT_SOURCE%\src\Plugins\Nop.Plugin.DiscountRules.CustomerRoles\Nop.Plugin.DiscountRules.CustomerRoles.csproj" -c Release ``` Now the plugin is built when you run the deploy scripts. --- <!-- page: Using Docker | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/docker.html | source: en/developer/tutorials/docker.md --> # Using Docker This document is a step-by-step guide to building and running a Docker container. 1. **Install Docker** in Windows environment. First, we need to install Docker on our PC. We will use [Docker Desktop](https://www.docker.com/products/docker-desktop/) for Windows, it helps us to build and share containerized applications and microservices. The Docker Desktop is also available for Linux and Mac. After installing and running the application, you will have access to all the possibilities of containerization. Further, we will do all the work in PowerShell, since the command mode will be the same in any environment. 2. **Build the Docker container**. For the convenience of executing commands, go to the directory where `Dockerfile` is located (the root directory of the nopCommerce source files). The command that we need: ```csharp [docker build -t nopcommerce .] ``` This command builds the container according to the instructions described in the "Dockerfile" file. The first launch of the assembly will take a lot of time since it will require downloading two basic images for .Net Core applications. The first image containing the SDK is required for the intermediate container, which will assemble the application by repairing all the dependencies, and then execute the process of publishing the `Nop.Web` application to a separate directory, from which you will create the resulting container with the name *nopcommerce* later (you can create an image without the name, but the name is more convenient. To specify the name of the container during assembly, you must specify the flag [–t], as was done in our case). After installation, if everything went well, execute the next command: ```csharp [docker images] ``` We should see something similar to the following image: ![docker_2](_static/docker/docker_2.png) This is a list of all loaded containers, among which we can easily see our container, it is created and is ready to go. 3. **Run and test the container** First, let's start the container with the command: ```bash docker run -d -p 80:80 nopcommerce ``` This command will launch our container in the background (flag [-d]) and set port 80 from the container to port 80 of the host machine (flag [–p]). > [!TIP] > > You can view the list of running containers using the next command: > > ```bash > docker ps > ``` On the browser, we should see the installation page of nopCommerce. ![docker_3](_static/docker/docker_3.png) This will be our verification that the container is being created, launched, and successfully operating. 4. But to **fully test** the operation of the application in this way will only work if you have an SQL server that our container can access. But, as a rule, our and user environments are limited, so we have prepared a layout file that will allow you to deploy the nopCommerce container in conjunction with the container containing the SQL server. To deploy container composition, use the command: ```bash docker-compose up -d ``` This command uses the docker-compose.yml file for deployment, which describes the creation of two containers "nopcommerce_web" and "nopcommerce_database", which provide a bundle of applications and a database. And by opening the page on the browser we will be able to test everything we want. To connect to the database server, we use the following data (as described in the docker-compose.yml file): ```bash Server name: nopcommerce_mssql_server User: sa Password: nopCommerce_db_password ``` 5. After testing is complete, you can remove all containers so that they do not interfere next time. Two commands will help to accomplish this: ```bash docker stop $ (docker ps -a -q) ``` and ```bash docker system prune -a ``` ## Docker Hub Starting from nopCommerce version 4.20, we publish the completed image on the GitHub service, you can check the available versions by [this link](https://hub.docker.com/r/nopcommerceteam/nopcommerce), or download the latest version with the following command: ```bash docker pull nopcommerceteam/nopcommerce:latest ``` --- <!-- page: Deploy nopCommerce to an Azure VM | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/azure-publish.html | source: en/developer/tutorials/azure-publish.md --> # Deploy nopCommerce to an Azure VM ## Create a VM on Azure This instruction of the steps required to set up an Azure virtual machine to host nopCommerce web applications, and to allow them to be published using **WebDeploy**. ### Create a new VM 1. Log in to the [Azure portal](https://portal.azure.com/) 1. Click the **Add** button ![azure-publish_1](_static/azure-publish/azure-publish_1.png) 1. Select *Windows Server 2016 VM* in the *Get Started* category or any Windows Server 2016 in the Compute category, such as **Windows Server 2016 Datacenter** 1. Complete the required fields to configure the new VM. - Username/password. You will need it to access the VM. This is the admin account for connecting to the VM by RDP. - Resource group. This is the name of the "virtual folder" that contains all resources created for this VM. You can delete all the resources created during this process by deleting the resource group. ### Configure components and features on the VM 1. DNS-name: - From the [Azure portal](https://portal.azure.com/), navigate to the Overview page of your virtual machine. - Under the DNS name, click **Configure** - Provide a globally unique DNS name. (A green tick appears when the name is validated.) - Click **Save** to save the configuration. ### Configure Azure Firewall rules 1. Configure inbound firewall rules in the Azure portal. On the Networking section add an inbound port rule to create new firewall entries: - http - Port 80 (Priority 100) - WebDeploy - Port 8172 (Priority 1010) - RDP - Port 3389 (Priority 320) ![azure-publish_2](_static/azure-publish/azure-publish_2.png) 2. Configure outbound firewall rules in the Azure portal. On the *Networking* section add an outbound port rule to create new firewall entries: - RDP - Port 3389 (Priority 100) ### Connect to the VM (RDP) using login and password ![azure-publish_3](_static/azure-publish/azure-publish_3.png) ### Install IIS (Web Server) and ASP.NET 4.6 1. Open the **Server Manager Dashboard** (Server Manager - Dashboard opens on the first startup) 1. Choose **2 Add roles and features** ![azure-publish_4](_static/azure-publish/azure-publish_4.png) 1. Accept the defaults and press **Next** three times to progress to the Server Roles section. 1. Select **Web Server (IIS)** ![azure-publish_5](_static/azure-publish/azure-publish_5.png) 1. When prompted, confirm the additional installation of the *IIS Management Console*. 1. Press **Next** three times to progress to the *Web Server Role (IIS) --> Roles Services section* 1. Select **Management** Service, which is required to enable Web Deploy (through port 8172). When prompted, confirm the additional installation of ASP.NET 4.6. ![azure-publish_6](_static/azure-publish/azure-publish_6.png) 1. Select **Next** to confirm the configuration, then **Install** to complete the IIS setup. ![azure-publish_7](_static/azure-publish/azure-publish_7.png) Once installation is completed: - IIS is installed and running with an internal firewall rule created for port 80. - Web Management Service is installed with an internal firewall rule created for port 8172. ### Configure IE Enhanced Security (Off) On a new Azure VM, default security rules prevent executables from being downloaded via Internet Explorer. To download the WebDeploy executable, you must first disable IE enhanced security. 1. In the **Server Manager**, open the **Local Server** section on the left. 1. In the main panel, next to "**IE Enhanced Security Configuration:**", select On. 1. In the dialog that appears, select **Off for Administrators**, select **On for Users**, then select **OK**. ![azure-publish_8](_static/azure-publish/azure-publish_8.png) ### Install Web Deploy 1. Launch Internet Explorer. 1. Accept default security settings. 1. [Download](https://www.microsoft.com/download/details.aspx?id=43717) *WebDeploy_amd64_en-US.msi* 1. Follow the installation steps for Web Deploy 1. Choose the Complete option to install all components ### Install the latest version [NET Core SDK](https://www.microsoft.com/net/download/all) ### Install package [.NET Core Windows Server Hosting](https://www.microsoft.com/net/download/all) ![azure-publish_9](_static/azure-publish/azure-publish_9.png) IIS is used to host ASP.NET Core web applications, its role will be reduced to a proxy server. Hosting of ASP.NET Core applications on IIS occurs using the native *AspNetCoreModuleV2*, which is configured to redirect requests to the *Kestrel* web server. This module controls the start of the external process `dotnet.exe`, within which the application is hosted, and forwards all requests from IIS to this host process. After installing this package, run the **iisreset** command on the command line or manually restart IIS so that the server applies the changes. ### Configure IIS 1. You must grant permission to the folder `wwwroot`. With the site selected in the **IIS Manager**, choose **Edit Permissions**, and make sure that *IUSR*, *IIS_IUSRS*, or the user configured for the Application Pool is an authorized user with Read & Execute rights. If none of these users are present, add *IUSR* as a user with *Read & Execute* rights. ![azure-publish_10](_static/azure-publish/azure-publish_10.png) 1. Click **Restart** on the right panel to restart the IIS Now everything is ready to publish the project. ## Publish nopCommerce to an Azure VM from Microsoft Visual Studio Publishing the nopCommerce application is no different from publishing any other ASP.NET Core application. Therefore, the minimum requirements to run the publication will be described. More details can be found [here](https://docs.microsoft.com/aspnet/core/tutorials/publish-to-azure-webapp-using-vs?view=aspnetcore-2.1#deploy-the-app-to-azure). ## Publish project `Nop.Web` 1. Open your web app solution in Microsoft Visual Studio. Right-click the project in *Solution Explorer* and choose **Publish**. ![azure-publish_11](_static/azure-publish/azure-publish_11.png) 1. Use the arrow on the right of the page to scroll through the publishing options until you find **Microsoft Azure Virtual Machines**. Select the appropriate VM from the list of Existing Virtual Machines. 1. Click **Create Profile**. ![azure-publish_12](_static/azure-publish/azure-publish_12.png) 1. To view and modify the publish profile settings, select **Configure**. Use the **Validate Connection** button to confirm that you have entered the right information. ![azure-publish_13](_static/azure-publish/azure-publish_13.png) 1. If you want to ensure that the webserver has a clean copy of the web application after each upload (and that no other files are left hanging around from a previous deployment), you can check the **Remove additional files at destination** checkbox in the **Settings** tab. Warning: Publishing with this setting deletes all files that exist on the webserver (*wwwroot* directory). Be sure you know the state of the machine before publishing with this option enabled. ![azure-publish_14](_static/azure-publish/azure-publish_14.png) 1. Click **Save**. 1. Click **Publish** to begin publishing. You have now published your web app to an Azure virtual machine. ## Potential problems and solutions To [more](https://docs.microsoft.com/aspnet/core/host-and-deploy/aspnet-core-module) accurately investigate any problem, you need to enable logging - enabled stdoutLog in `web.config`: ```sh stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" ``` ### IIS not being able to locate the web.config A possible solution can be found at: [support.microsoft.com](http://support.microsoft.com/kb/942055) --- <!-- page: Content Security Policy (CSP) Headers | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/csp-headers.html | source: en/developer/tutorials/csp-headers.md --> # Content Security Policy (CSP) Headers Content-Security-Policy is the name of an HTTP response header that modern browsers use to enhance the security of a document (or web page). The HTTP Content Security Policy response header gives website admins a sense of control by giving them the authority to restrict the resources such as JavaScript and CSS a user is allowed to load within the site. In other words, you can whitelist your site's content sources. Although it is primarily used as an HTTP response header, you can also apply it via a meta tag. ```html <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' https://img.nopcommerce.com; object-src 'none'; script-src 'self'; style-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self';"> ``` To add this custom meta tag, you can go to `www.yourStore.com/Admin/Setting/GeneralCommon` and find **`Custom <head> tag`** and add this as shown in the image below. ![custom CSP head tag image](_static/csp-headers/custom-csp-head-tag.png) Content Security Policy protects against **Cross Site Scripting (XSS)** and other forms of attacks such as **ClickJacking**. Although it doesn't eliminate their possibility, it can surely minimize the damage. Compatibility isn't a problem as most of the major browsers support CSP. It is not supported in Internet Explorer. To test your browser if it supports CSP or not, you can follow this [link](https://content-security-policy.com/browser-test/). ## CSP Directive Reference The **Content-Security-Policy** header value is made up of one or more directives (defined below), and multiple directives are separated with a *semicolon (;)* ### default-src The *default-src* directive defines the default policy for fetching resources such as JavaScript, Images, CSS, Fonts, AJAX requests, Frames, and HTML5 Media. Not all directives fall back to *default-src*. ```html default-src 'self' cdn.nopcommerce.com; ``` ### script-src Defines valid sources of JavaScript. ```html script-src 'self' js.nopcommerce.com; ``` ### style-src Defines valid sources of stylesheets or CSS. ```html style-src 'self' css.nopcommerce.com; ``` ### img-src Defines valid sources of images. ```html img-src 'self' img.nopcommerce.com; ``` ### connect-src Applies to *XMLHttpRequest (AJAX), WebSocket, or EventSource*. If not allowed the browser emulates a **400** HTTP status code. ```html connect-src 'self'; ``` ### font-src Defines valid sources of font resources (loaded via *@font-face*). ```html font-src font.nopcommerce.com; ``` ### object-src Defines valid sources of plugins, eg `<object>`, `<embed>`, or `<applet>`. ```html object-src 'self'; ``` ### media-src Defines valid sources of audio and video, eg HTML5 `<audio>`, `<video>` elements. ```html media-src media.nopcommerce.com; ``` ### frame-src Defines valid sources for loading frames. ```html frame-src 'self'; ``` ### sandbox Enables a sandbox for the requested resource similar to the *iframe sandbox* attribute. The sandbox applies the same-origin policy and prevents popups, plugins, and script execution. You can keep the sandbox value empty to keep all restrictions in place, or add values: *allow-forms allow-same-origin allow-scripts allow-popups, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-presentation, allow-popups-to-escape-sandbox*, and *allow-top-navigation* ```html sandbox allow-forms allow-scripts; ``` ### child-src Defines valid sources for web workers and nested browsing contexts loaded using elements such as `<frame>` and `<iframe>` ```html child-src 'self' ``` ### form-action Defines valid sources that can be used as an HTML `<form>` action. ```html form-action 'self'; ``` ### frame-ancestors Defines valid sources for embedding the resource using `<frame> <iframe> <object> <embed> <applet>`. Setting this directive to **'none'** should be roughly equivalent to **X-Frame-Options: DENY** ```html frame-ancestors 'none'; ``` ### plugin-types Defines valid MIME types for plugins invoked via `<object>` and `<embed>`. To load an `<applet>` you must specify *application/x-java-applet*. ```html plugin-types application/pdf; ``` ### report-to Defines a reporting group name defined by a *Report-To* HTTP response header. See the [Reporting API](https://w3c.github.io/reporting/) for more info. ```html report-to groupName; ``` ### worker-src Restricts the URLs which may be loaded as a Worker, SharedWorker, or ServiceWorker. ```html worker-src 'none'; ``` ### manifest-src Restricts the URLs that application manifests can be loaded. ```html manifest-src 'none'; ``` ### navigate-to Restricts the URLs that the document may navigate to by any means. For example, when a link is clicked, a form is submitted, or *window.location* is invoked. If *form-action* is present then this directive is ignored for form submissions. [Implementation Status](https://www.chromestatus.com/features/6457580339593216) ```html navigate-to nopcommerce.com ``` ## Content-Security-Policy Examples ### Allow everything but only from the same origin ```html default-src 'self'; ``` ### Only Allow Scripts from the same origin ```html script-src 'self'; ``` ### Allow Google Analytics, Google AJAX CDN, and Same Origin ```html script-src 'self' www.google-analytics.com ajax.googleapis.com; ``` ### Starter Policy ```html default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self'; ``` This policy allows images, scripts, AJAX, and CSS from the same origin, and does not allow any other resources to load (eg object, frame, media, etc). It is a good starting point for many sites. ## Content-Security-Policy Error Messages Based on the browser, the CSP error messages may differ. In Chrome developer tools, we can see the following message. ```js Refused to load the script 'script-uri' because it violates the following Content Security Policy directive: "your CSP directive". ``` In Firefox developer tools are as follows. ```js Content Security Policy: A violation occurred for a report-only CSP policy ("An attempt to execute inline scripts has been blocked"). The behavior was allowed, and a CSP report was sent. ``` In addition to a console message, a **securitypolicyviolation** event is fired on the window. For more info, follow this [link](https://www.w3.org/TR/CSP2/#firing-securitypolicyviolationevent-events.). --- <!-- page: Unit Testing | url: http://nopdocs.service.hedr.dev/en/developer/tutorials/unit-tests.html | source: en/developer/tutorials/unit-tests.md --> # Unit Testing I think everyone knows about the concept of UNIT tests. We know what UNIT tests are used for and agree that this is an important part of the process of developing reliable software. In this article, we won't discuss these issues. You can easily find all the necessary information on the Internet, for example, by following these links: * [https://en.wikipedia.org/wiki/Unit_testing](https://en.wikipedia.org/wiki/Unit_testing) * [https://docs.microsoft.com/dotnet/core/testing/unit-testing-best-practices](https://docs.microsoft.com/dotnet/core/testing/unit-testing-best-practices) * [https://en.wikipedia.org/wiki/Test-driven_development](https://en.wikipedia.org/wiki/Test-driven_development) In this article, we will get acquainted with the features of testing in the nopCommerce project and learn how to add new tests and check their performance. We won't test an abstract task but will write a full-fledged test for the existing functionality from scratch. At the end of the article, you will be provided with a reference to the appropriate commit with all described code changes. ## Features overview ![tests-project](_static/unit-tests/tests-project.png) In the screenshot, you can see the structure of the `Nop.Tests` project. The folders such as `Nop.Core.Tests` contain tests for the corresponding projects of the solution. The other files are responsible for the auxiliary and base classes. Let's look at the `BaseNopTest` class. ### BaseNopTest This is the main static class that exposes the IoC container for tests and allows us to use all the advantages of DI. ![base-nop-test](_static/unit-tests/base-nop-test.png) This class contains two methods available for child classes: * ``PropertiesShouldEqual`` that compares all fields of the database entity with the fields of the model. * ``GetService`` that allows using the advantages of DI and relieves creating the classes necessary for testing. The initialization of the **IoC** container is carried out in the static constructor of the class; this constructor contains the bulk of the code. ## IScheduleTaskService As an example, we will create tests for a class that implements the `IScheduleTaskService` interface. ```csharp public partial interface IScheduleTaskService { System.Threading.Tasks.Task DeleteTaskAsync(ScheduleTask task); Task<ScheduleTask> GetTaskByIdAsync(int taskId); Task<ScheduleTask> GetTaskByTypeAsync(string type); Task<IList<ScheduleTask>> GetAllTasksAsync(bool showHidden = false); System.Threading.Tasks.Task InsertTaskAsync(ScheduleTask task); System.Threading.Tasks.Task UpdateTaskAsync(ScheduleTask task); } ``` As you can see this is a simple interface. But at the same time, it allows nopCommerce to perform very important tasks such as sending email messages to customers. So we need to be sure that it works properly. Next, we will write tests for each of the interface methods. > [!NOTE] > > We don't use **TDD** but we are not against this approach. The reliability of the functionality is important for us, not a specific approach to testing. ## ScheduleTaskServiceTests class Add a new `ScheduleTaskServiceTests` class to the project (Nop.Tests\Nop.Services.Tests\Tasks). Its code is shown below: ```csharp using NUnit.Framework; namespace Nop.Tests.Nop.Services.Tests.Tasks { [TestFixture] public class ScheduleTaskServiceTests : ServiceTest { } } ``` This is the class template for testing. From this code, we can see that nopCommerce uses the **NUnit framework** for tests. There are two points to pay attention to: 1. Our class has the **TestFixture** attribute which tells the engine that this class is a class with tests. 1. We do not directly inherit the `BaseNopTest` class but inherit another abstract class - `ServiceTest` which adds the main plugins to the configuration. The next step is to add a method for the initialization of our tests. As a rule, such a method is called **SetUp**. In this method, we get an instance of a class that implements the ``IScheduleTaskService`` interface, which we will test. ```csharp private IScheduleTaskService _scheduleTaskService; [OneTimeSetUp] public void SetUp() { _scheduleTaskService = GetService<IScheduleTaskService>(); } ``` As you can see, the **SetUp** method should be declared with the **OneTimeSetUp** attribute as well as you may use the **SetUp** attribute. The difference between these two attributes is only the number of calls to the method itself: in the first case, the **SetUp** method is called once for all tests, and in the second, for each test separately. Next, let's add tests for CRUD methods. In this service, these are methods such as: **InsertTaskAsync**, **GetTaskByIdAsync**, **UpdateTaskAsync**, and **DeleteTaskAsync**. But first, let's add one more field to the class. This will be an instance of the `ScheduleTask` class which will be used for testing: ```csharp private ScheduleTask _task; ``` Update the **SetUp** method the following way: ```csharp [OneTimeSetUp] public void SetUp() { _scheduleTaskService = GetService<IScheduleTaskService>(); _task = new ScheduleTask { Enabled = true, Name = "Test task", Seconds = 60, Type = "nop.test.task" }; } ``` All CRUD testing methods are given below and as you can see there is nothing complicated in them: ```csharp #region CRUD tests [Test] public async System.Threading.Tasks.Task CanInsertAndGetTask() { _task.Id = 0; await _scheduleTaskService.InsertTaskAsync(_task); var task = await _scheduleTaskService.GetTaskByIdAsync(_task.Id); await _scheduleTaskService.DeleteTaskAsync(_task); _task.Id.Should().NotBe(0); task.Id.Should().Be(_task.Id); task.Name.Should().Be(_task.Name); } [Test] public void InsertTaskShouldRaiseExceptionIfTaskIsNull() { Assert.Throws<AggregateException>(() => _scheduleTaskService.InsertTaskAsync(null).Wait()); } [Test] public async System.Threading.Tasks.Task GetTaskByIdShouldReturnNullIfTaskIdIsZero() { var task = await _scheduleTaskService.GetTaskByIdAsync(0); task.Should().BeNull(); } [Test] public async System.Threading.Tasks.Task GetTaskByIdShouldReturnNullIfTaskIdIsNotExists() { var task = await _scheduleTaskService.GetTaskByIdAsync(int.MaxValue); task.Should().BeNull(); } [Test] public async System.Threading.Tasks.Task CanUpdateTask() { _task.Id = 0; await _scheduleTaskService.InsertTaskAsync(_task); var task = await _scheduleTaskService.GetTaskByIdAsync(_task.Id); task.Name = "new test name"; await _scheduleTaskService.UpdateTaskAsync(task); var task2 = await _scheduleTaskService.GetTaskByIdAsync(_task.Id); await _scheduleTaskService.DeleteTaskAsync(_task); task.Id.Should().Be(task2.Id); task2.Name.Should().NotBe(_task.Name); } [Test] public void UpdateTaskShouldRaiseExceptionIfTaskIsNull() { Assert.Throws<AggregateException>(() => _scheduleTaskService.UpdateTaskAsync(null).Wait()); } public async System.Threading.Tasks.Task CanDeleteTask() { _task.Id = 0; await _scheduleTaskService.InsertTaskAsync(_task); await _scheduleTaskService.DeleteTaskAsync(_task); var task = await _scheduleTaskService.GetTaskByIdAsync(_task.Id); task.Should().BeNull(); } [Test] public void DeleteTaskShouldRaiseExceptionIfTaskIsNull() { Assert.Throws<AggregateException>(() => _scheduleTaskService.DeleteTaskAsync(null).Wait()); } #endregion ``` In addition, the list of connected namespaces has been changed. The updated list is provided below: ```csharp using System; using FluentAssertions; using Nop.Core.Domain.Tasks; using Nop.Services.Tasks; using NUnit.Framework; ``` > [!NOTE] > > We have to delete all changes made by a test from the database. In our case, we use the `DeleteTaskAsync` method for this purpose. Also, note that it should be done just before we call test methods such as `task.Should().BeNull();`, `task2.Name.Should().NotBe(_task.Name);` etc. because if the test fails, the database will contain data that can affect other testing processes. Then let's test the two remaining methods: ```csharp [Test] public async System.Threading.Tasks.Task CanGetTaskByType() { _task.Id = 0; var task = await _scheduleTaskService.GetTaskByTypeAsync(_task.Type); task.Should().BeNull(); await _scheduleTaskService.InsertTaskAsync(_task); task = await _scheduleTaskService.GetTaskByTypeAsync(_task.Type); await _scheduleTaskService.DeleteTaskAsync(_task); task.Should().NotBeNull(); } [Test] public async System.Threading.Tasks.Task GetTaskByTypeShouldReturnNullIfTypeIsNull() { var task = await _scheduleTaskService.GetTaskByTypeAsync(null); task.Should().BeNull(); } [Test] public async System.Threading.Tasks.Task GetTaskByTypeShouldReturnNullIfTypeIsEmpty() { var task = await _scheduleTaskService.GetTaskByTypeAsync(string.Empty); task.Should().BeNull(); } [Test] public async System.Threading.Tasks.Task CanGetAllTasks() { _task.Id = 0; var tasks = await _scheduleTaskService.GetAllTasksAsync(true); tasks.Count.Should().Be(0); tasks = await _scheduleTaskService.GetAllTasksAsync(false); tasks.Count.Should().Be(0); await _scheduleTaskService.InsertTaskAsync(_task); var tasksWithHidden = await _scheduleTaskService.GetAllTasksAsync(true); var tasksWitoutHidden = await _scheduleTaskService.GetAllTasksAsync(false); await _scheduleTaskService.DeleteTaskAsync(_task); tasksWithHidden.Count.Should().Be(1); tasksWitoutHidden.Count.Should().Be(1); _task.Enabled = false; await _scheduleTaskService.InsertTaskAsync(_task); tasksWithHidden = await _scheduleTaskService.GetAllTasksAsync(true); tasksWitoutHidden = await _scheduleTaskService.GetAllTasksAsync(false); await _scheduleTaskService.DeleteTaskAsync(_task); _task.Enabled = true; tasksWithHidden.Count.Should().Be(1); tasksWitoutHidden.Count.Should().Be(0); } ``` Finally, let's add one more standard method for many tests which is usually called **TearDown**. In this method, we will carry out the final cleaning of the database for possible changes made by us during the testing process. This method must have the **OneTimeTearDown** or **TearDown** attribute, similar to the attributes of the SetUp method. ```csharp [OneTimeTearDown] public async System.Threading.Tasks.Task TearDown() { var tasks = await _scheduleTaskService.GetAllTasksAsync(true); foreach (var task in tasks.Where(t=>t.Type.Equals(_task.Type, StringComparison.InvariantCultureIgnoreCase))) await _scheduleTaskService.DeleteTaskAsync(task); } ``` That's it, our test class is ready! As promised at the beginning, you can find all the materials via the links below: * **[Full Source Code: ScheduleTaskServiceTests](https://github.com/nopSolutions/nopCommerce/blob/develop/src/Tests/Nop.Tests/Nop.Services.Tests/ScheduleTasks/ScheduleTaskServiceTests.cs)** — the final version of the test class in the repository. * **[Git Commit](https://github.com/nopSolutions/nopCommerce/commit/81c31e1ee754f771ddfdc26e9b95a729e38b2d29)** — the exact commit showing all additions and changes. --- <!-- page: Creating a nopCommerce plugin | url: http://nopdocs.service.hedr.dev/en/developer/plugins/index.html | source: en/developer/plugins/index.md --> # Creating a nopCommerce plugin * [How to write a plugin for nopCommerce 5.00](xref:en/developer/plugins/how-to-write-plugin-5.00) * [How to write a plugin for nopCommerce 4.90](xref:en/developer/plugins/how-to-write-plugin-4.90) * [How to write a plugin for nopCommerce 4.80](xref:en/developer/plugins/how-to-write-plugin-4.80) * [How to write a plugin for nopCommerce 4.70](xref:en/developer/plugins/how-to-write-plugin-4.70) * [How to write a plugin for nopCommerce 4.60](xref:en/developer/plugins/how-to-write-plugin-4.60) * [How to write a plugin for nopCommerce 4.50](xref:en/developer/plugins/how-to-write-plugin-4.50) * [How to write a plugin for nopCommerce 4.40](xref:en/developer/plugins/how-to-write-plugin-4.40) * [How to write a plugin for nopCommerce 4.30](xref:en/developer/plugins/how-to-write-plugin-4.30) * [How to write a plugin for nopCommerce 4.20](xref:en/developer/plugins/how-to-write-plugin-4.20) * [How to write a plugin for nopCommerce 4.10](xref:en/developer/plugins/how-to-write-plugin-4.10) * [How to write a plugin for nopCommerce 4.00](xref:en/developer/plugins/how-to-write-plugin-4.00) * [How to write a plugin for nopCommerce 3.90 (and previous versions)](xref:en/developer/plugins/how-to-write-plugin-3.90) * [How to code my own payment method](xref:en/developer/plugins/payment-method) * [How to code my own shipping rate computation method](xref:en/developer/plugins/shipping-plugin) * [Cloudflare Images](xref:en/developer/plugins/cloudflare-images) * [Plugin with data access](xref:en/developer/plugins/plugin-with-data-access) * [Plugin with data access 4.20 and below](xref:en/developer/plugins/plugin-with-data-access-4.20) * [How to add a menu item into the administration area from a plugin](xref:en/developer/plugins/menu-item) * [Adding CSS and JS resource files into nopCommerce Plugin](xref:en/developer/plugins/resource-files) * [How to write a widget for nopCommerce](xref:en/developer/plugins/how-to-write-widget-for-nopCommerce) * [How to write a Tax Plugin for nopCommerce 4.20](xref:en/developer/plugins/how-to-write-tax-plugin-4.20) * [Description of the structure of the plugin.json file](xref:en/developer/plugins/plugin_json) --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-5.00.html | source: en/developer/plugins/how-to-write-plugin-5.00.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. The first thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalCommerce*). For example, the PayPal Commerce payment plugin has the following name: **`Nop.Plugin.Payments.PayPalCommerce`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-5.00/write_plugin_5.00_all_plugins.png) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>$(SolutionDir)\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(SolutionDir)\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(SolutionDir)\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target executes after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalCommerce`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But actually, it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPaymentAsync()`* or *`GetAdditionalHandlingFeeAsync()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > > This is a new interface, since version 4.40 we have provided the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > > After each project build, clean the solution before making changes. Some resources will be cached, which can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern here](https://docs.microsoft.com/aspnet/core/mvc/overview). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your needs. - **Create the view**. Add a **Views** folder in the new plugin, and then add a `*.cshtml` file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file in your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.ADMIN)] //specifies the area containing a controller or action public class PayPalCommerceController : BasePluginController { public async Task<IActionResult> Configure(bool showtour = false) { return View("~/Plugins/Payments.PayPalCommerce/Views/Admin/Configure.cshtml"); } } ``` > [!TIP] > > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalCommerce` payment plugin and look at its implementation of `PayPalCommerceController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp private readonly INopUrlHelper _nopUrlHelper; public PayPalCommercePaymentMethod(INopUrlHelper nopUrlHelper) { _nopUrlHelper = nopUrlHelper; } public override string GetConfigurationPageUrl() { return _nopUrlHelper.RouteUrl(PayPalCommerceDefaults.Route.Configuration); } ``` *INopUrlHelper* is now used for routing outside of controllers. The names of the standard routes are stored in plugin defaults as constants. ```csharp /// <summary> /// Represents the plugin constants /// </summary> public class PayPalCommerceDefaults { /// <summary> /// Represents the route names /// </summary> public class Route { /// <summary> /// Gets the configuration route name /// </summary> public static string Configuration => "Plugin.Payments.PayPalCommerce.Configure"; } } ``` Registering the route to the plugin configuration page will look like below. ```csharp endpointRouteBuilder.MapControllerRoute(name: PayPalCommerceDefaults.Route.Configuration, pattern: "Admin/PayPalCommerce/Configure", defaults: new { controller = "{CONTROLLER_NAME}", action = "{ACTION_NAME}", area = AreaNames.ADMIN }); ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalCommerce* plugin looks like the image below: ![p3](_static/how-to-write-plugin-5.00/write_plugin_5.00_proj_struct.png) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during the plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > > If you override one of these methods, do not hide its base implementation. For example, the overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more [routing information here](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PayPalCommerceWebhook/WebhookHandler` URL : ```csharp public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { ... endpointRouteBuilder.MapControllerRoute(name: PayPalCommerceDefaults.Route.Webhook, pattern: "Plugins/PayPalCommerce/Webhook", defaults: new { controller = "PayPalCommerceWebhook", action = "WebhookHandler" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugins will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all the initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (PluginNopStartup.cs, _ViewImports.cshtml, ObjectContex, plugin.json, configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.90.html | source: en/developer/plugins/how-to-write-plugin-4.90.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. The first thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalCommerce*). For example, the PayPal Commerce payment plugin has the following name: **`Nop.Plugin.Payments.PayPalCommerce`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-4.90/write_plugin_4.90_all_plugins.png) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net9.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>$(SolutionDir)\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(SolutionDir)\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(SolutionDir)\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target executes after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalCommerce`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But actually, it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPaymentAsync()`* or *`GetAdditionalHandlingFeeAsync()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > This is a new interface, since version 4.40 we have provided the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached, which can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern here](https://docs.microsoft.com/aspnet/core/mvc/overview). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your needs. - **Create the view**. Add a **Views** folder in the new plugin, and then add a `*.cshtml` file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file in your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.ADMIN)] //specifies the area containing a controller or action public class PayPalCommerceController : BasePluginController { public async Task<IActionResult> Configure(bool showtour = false) { return View("~/Plugins/Payments.PayPalCommerce/Views/Admin/Configure.cshtml"); } } ``` > [!TIP] > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalCommerce` payment plugin and look at its implementation of `PayPalCommerceController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp private readonly INopUrlHelper _nopUrlHelper; public PayPalCommercePaymentMethod(INopUrlHelper nopUrlHelper) { _nopUrlHelper = nopUrlHelper; } public override string GetConfigurationPageUrl() { return _nopUrlHelper.RouteUrl(PayPalCommerceDefaults.Route.Configuration); } ``` *INopUrlHelper* is now used for routing outside of controllers. The names of the standard routes are stored in plugin defaults as constants. ```csharp /// <summary> /// Represents the plugin constants /// </summary> public class PayPalCommerceDefaults { /// <summary> /// Represents the route names /// </summary> public class Route { /// <summary> /// Gets the configuration route name /// </summary> public static string Configuration => "Plugin.Payments.PayPalCommerce.Configure"; } } ``` Registering the route to the plugin configuration page will look like below. ```csharp endpointRouteBuilder.MapControllerRoute(name: PayPalCommerceDefaults.Route.Configuration, pattern: "Admin/PayPalCommerce/Configure", defaults: new { controller = "{CONTROLLER_NAME}", action = "{ACTION_NAME}", area = AreaNames.ADMIN }); ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalCommerce* plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.90/write_plugin_4.90_proj_struct.png) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during the plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, the overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more [routing information here](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PayPalCommerceWebhook/WebhookHandler` URL : ```csharp public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { ... endpointRouteBuilder.MapControllerRoute(name: PayPalCommerceDefaults.Route.Webhook, pattern: "Plugins/PayPalCommerce/Webhook", defaults: new { controller = "PayPalCommerceWebhook", action = "WebhookHandler" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugins will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all the initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (PluginNopStartup.cs, _ViewImports.cshtml, ObjectContex, plugin.json, configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.80.html | source: en/developer/plugins/how-to-write-plugin-4.80.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. The first thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalCommerce*). For example, the PayPal Commerce payment plugin has the following name: **`Nop.Plugin.Payments.PayPalCommerce`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-4.80/write_plugin_4.80_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net9.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>$(SolutionDir)\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(SolutionDir)\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(SolutionDir)\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target executes after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalStandard`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But actually, it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPaymentAsync()`* or *`GetAdditionalHandlingFeeAsync()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > This is a new interface, since version 4.40 we have provided the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached, which can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](https://docs.microsoft.com/aspnet/core/mvc/overview). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your needs. - **Create the view**. Add a **Views** folder in the new plugin, and then add a `*.cshtml` file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file in your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.ADMIN)] //specifies the area containing a controller or action public class PayPalCommerceController : BasePluginController { public async Task<IActionResult> Configure(bool showtour = false) { return View("~/Plugins/Payments.PayPalCommerce/Views/Configure.cshtml"); } } ``` > [!TIP] > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalStandard` payment plugin and look at its implementation of `PaymentPayPalStandardController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp protected readonly IWebHelper _webHelper; public PaymentPayPalStandardProvider(IWebHelper webHelper) { _webHelper = webHelper; } public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalCommerce* plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.80/write_plugin_4.80_3.jpg) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during the plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, the overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more [routing information](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PayPalCommerceWebhook/WebhookHandler` URL : ```csharp public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { endpointRouteBuilder.MapControllerRoute(PayPalCommerceDefaults.ConfigurationRouteName, "Admin/PayPalCommerce/Configure", new { controller = "PayPalCommerce", action = "Configure" }); endpointRouteBuilder.MapControllerRoute(PayPalCommerceDefaults.WebhookRouteName, "Plugins/PayPalCommerce/Webhook", new { controller = "PayPalCommerceWebhook", action = "WebhookHandler" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugins will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all the initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (PluginNopStartup.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.70.html | source: en/developer/plugins/how-to-write-plugin-4.70.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. The first thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalCommerce*). For example, the PayPal Commerce payment plugin has the following name: **`Nop.Plugin.Payments.PayPalCommerce`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-4.70/write_plugin_4.70_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target executes after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalStandard`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But actually, it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPaymentAsync()`* or *`GetAdditionalHandlingFeeAsync()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > This is a new interface, since version 4.40 we have provided the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached, which can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](https://docs.microsoft.com/aspnet/core/mvc/overview). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your needs. - **Create the view**. Add a **Views** folder in the new plugin, and then add a `*.cshtml` file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file in your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.ADMIN)] //specifies the area containing a controller or action public class PayPalCommerceController : BasePluginController { public async Task<IActionResult> Configure(bool showtour = false) { return View("~/Plugins/Payments.PayPalCommerce/Views/Configure.cshtml"); } } ``` > [!TIP] > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalStandard` payment plugin and look at its implementation of `PaymentPayPalStandardController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp protected readonly IWebHelper _webHelper; public PaymentPayPalStandardProvider(IWebHelper webHelper) { _webHelper = webHelper; } public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalCommerce* plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.70/write_plugin_4.70_3.jpg) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during the plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, the overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more [routing information](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PayPalCommerceWebhook/WebhookHandler` URL : ```csharp public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { endpointRouteBuilder.MapControllerRoute(PayPalCommerceDefaults.ConfigurationRouteName, "Admin/PayPalCommerce/Configure", new { controller = "PayPalCommerce", action = "Configure" }); endpointRouteBuilder.MapControllerRoute(PayPalCommerceDefaults.WebhookRouteName, "Plugins/PayPalCommerce/Webhook", new { controller = "PayPalCommerceWebhook", action = "WebhookHandler" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugins will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all the initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (PluginNopStartup.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.60.html | source: en/developer/plugins/how-to-write-plugin-4.60.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalCommerce*). For example, the PayPal Commerce payment plugin has the following name: **`Nop.Plugin.Payments.PayPalCommerce`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-4.60/write_plugin_4.60_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net7.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalStandard`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But actually, it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPaymentAsync()`* or *`GetAdditionalHandlingFeeAsync()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > This is a new interface, since version 4.40 we provide the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](https://docs.microsoft.com/aspnet/core/mvc/overview?view=aspnetcore-6.0). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a **Views** folder in the new plugin, and then add a `*.cshtml` file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that configuration page should use `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file into your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` > [!TIP] > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalStandard` payment plugin and look at its implementation of `PaymentPayPalStandardController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalCommerce* plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.60/write_plugin_4.60_3.jpg) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PayPalCommerceWebhook/WebhookHandler` URL : ```csharp public class RouteProvider : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { endpointRouteBuilder.MapControllerRoute(PayPalCommerceDefaults.WebhookRouteName, "Plugins/PayPalCommerce/Webhook", new { controller = "PayPalCommerceWebhook", action = "WebhookHandler" }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (PluginNopStartup.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.50.html | source: en/developer/plugins/how-to-write-plugin-4.50.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalStandard*). For example, the PayPal Standard payment plugin has the following name: **`Nop.Plugin.Payments.PayPalStandard`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-4.50/write_plugin_4.50_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalStandard`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But actually, it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPaymentAsync()`* or *`GetAdditionalHandlingFeeAsync()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > This is a new interface, since version 4.40 we provide the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](https://docs.microsoft.com/aspnet/core/mvc/overview?view=aspnetcore-6.0). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a **Views** folder in the new plugin, and then add a `*.cshtml` file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that configuration page should use `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file into your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` > [!TIP] > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalStandard` payment plugin and look at its implementation of `PaymentPayPalStandardController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalStandard* plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.50/write_plugin_4.50_3.jpg) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by *PayPal* plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { //PDT endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }); } public int Priority => -1; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (DependencyRegistrar.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.40.html | source: en/developer/plugins/how-to-write-plugin-4.40.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new *`Class Library`* project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with `\Plugins` subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the `Plugins` solution folder. A recommended name for a plugin project is **`Nop.Plugin.{Group}.{Name}`**. **`{Group}`** is your plugin group (for example, *Payment* or *Shipping*). **`{Name}`** is your plugin name (for example, *PayPalStandard*). For example, the PayPal Standard payment plugin has the following name: **`Nop.Plugin.Payments.PayPalStandard`**. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyGreatPlugin`. ![p1](_static/how-to-write-plugin-4.40/write_plugin_4.40_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where **PLUGIN_OUTPUT_DIRECTORY** should be replaced with the plugin name, for example, `Payments.PayPalStandard`. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements **`IPlugin`** interface (`Nop.Services.Plugins` namespace). nopCommerce has **`BasePlugin`** class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the `IPaymentMethod` interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *`ProcessPayment()`* or *`GetAdditionalHandlingFee()`*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IMultiFactorAuthenticationMethod**. Used for creating multi-factor authentication methods such as *GoogleAuthenticator*, etc. >[!NOTE] > This is a new interface, since version 4.40 we provide the corresponding infrastructure for MFA integrations out of the box. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under `Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY`, you need to rebuild your solution. nopCommerce will not list your plugin in the *Local Plugins* page if your DLLs do not exist in the correct folder in `Nop.Web`. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET Core MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET Core MVC` application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](https://docs.microsoft.com/aspnet/core/mvc/overview?view=aspnetcore-5.0). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a **Views** folder in the new plugin, and then add a cshtml file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use the `_ConfigurePlugin` layout. - Also make sure that you have the `_ViewImports.cshtml` file into your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *`Configure`*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` > [!TIP] > You can also add these attributes directly to the controller. In this case, there is no need to tag each method with them. For example, open `PayPalStandard` payment plugin and look at its implementation of `PaymentPayPalStandardController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where **{CONTROLLER_NAME}** is the name of your controller and **{ACTION_NAME}** is the name of the action (usually it's `Configure`). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the *PayPalStandard* plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.40/write_plugin_4.40_3.jpg) ## Handling "InstallAsync", "UninstallAsync" and "UpdateAsync" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your `IPlugin` implementation (in most cases it'll be derived from the `BasePlugin` class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. 1. **UpdateAsync**. This method will be invoked during plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, overridden `InstallAsync` method should include the following method call: *`base.Install()`*. The `InstallAsync` method of the *PayPalStandard* plugin looks like the code below ```csharp public override async Task InstallAsync() { await _settingService.SaveSettingAsync(new PayPalStandardPaymentSettings { UseSandbox = true }); await _localizationService.AddLocaleResourceAsync(new Dictionary<string, string> { ... }); await base.InstallAsync(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following `RouteProvider` class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by *PayPal* plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { //PDT endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }); } public int Priority => -1; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (DependencyRegistrar.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.30.html | source: en/developer/plugins/how-to-write-plugin-4.30.md --> # How to write a plugin for nopCommerce Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new "Class Library" project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with \Plugins subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the "Plugins" solution folder. A recommended name for a plugin project is "Nop.Plugin.{Group}.{Name}". {Group} is your plugin group (for example, "Payment" or "Shipping"). {Name} is your plugin name (for example, "PayPalStandard"). For example, the PayPal Standard payment plugin has the following name: Nop.Plugin.Payments.PayPalStandard. But please note that it's not a requirement. And you can choose any name for a plugin. For example, "MyGreatPlugin". ![p1](_static/how-to-write-plugin-4.30/write_plugin_4.30_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where PLUGIN_OUTPUT_DIRECTORY should be replaced with the plugin name, for example, Payments.PayPalStandard. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements the **IPlugin** interface (Nop.Services.Plugins namespace). nopCommerce has **BasePlugin** class which already implements some IPlugin methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from IPlugin. For example, we have the "IPaymentMethod" interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *ProcessPayment()* or *GetAdditionalHandlingFee()*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > Important note: After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY, you need to rebuild your solution. nopCommerce will not list your plugin in the Local Plugins page if your DLLs do not exist in the correct folder in Nop.Web. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](https://docs.microsoft.com/aspnet/core/mvc/overview?view=aspnetcore-3.1). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a **Views** folder in the new plugin, and then add a cshtml file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use the "_ConfigurePlugin" layout. - Also make sure that you have the `_ViewImports.cshtml` file into your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *"Configure"*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` For example, open PayPalStandard payment plugin and look at its implementation of PaymentPayPalStandardController. Then for each plugin that has a configuration page, you should specify a configuration URL. A base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where *{CONTROLLER_NAME}* is the name of your controller and *{ACTION_NAME}* is the name of the action (usually it's "Configure"). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the PayPalStandard plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.30/write_plugin_4.30_3.jpg) ## Handling "Install", "Uninstall" and "Update" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your IPlugin implementation (in most cases it'll be derived from BasePlugin class) and override the following methods: 1. **Install**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **Uninstall**. This method will be invoked during plugin uninstallation. 1. **Update**. This method will be invoked during plugin update (when its version is changed in the `plugin.json` file). > [!IMPORTANT] > Important note: If you override one of these methods, do not hide its base implementation. For example, overridden "Install" method should include the following method call: *base.Install()*. The "Install" method of the PayPalStandard plugin looks like the code below ```csharp public override void Install() { var settings = new PayPalStandardPaymentSettings() { UseSandbox = true }; _settingService.SaveSetting(settings); ... base.Install(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following RouteProvider class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by PayPal plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { //PDT endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }); } public int Priority => -1; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers because now they don't have to do manually all initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (DependencyRegistrar.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.20.html | source: en/developer/plugins/how-to-write-plugin-4.20.md --> # How to write a plugin for nopCommerce 4.20 Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new "Class Library" project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with \Plugins subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the "Plugins" solution folder (you can find more information about [solution folders](http://msdn.microsoft.com/library/sx2027y2.aspx)). A recommended name for a plugin project is "Nop.Plugin.{Group}.{Name}". {Group} is your plugin group (for example, "Payment" or "Shipping"). {Name} is your plugin name (for example, "PayPalStandard"). For example, the PayPal Standard payment plugin has the following name: Nop.Plugin.Payments.PayPalStandard. But please note that it's not a requirement. And you can choose any name for a plugin. For example, "MyGreatPlugin". ![p1](_static/how-to-write-plugin-4.20/write_plugin_4.20_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!TIP] > Where PLUGIN_OUTPUT_DIRECTORY should be replaced with the plugin name, for example, Payments.PayPalStandard. > > We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json) 1. The last required step is to create a class that implements the **IPlugin** interface (Nop.Services.Plugins namespace). nopCommerce has **BasePlugin** class which already implements some IPlugin methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from IPlugin. For example, we have the "IPaymentMethod" interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as *ProcessPayment()* or *GetAdditionalHandlingFee()*. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. > > You may need to rebuild your solution after adding your plugin. If you do not see DLLs for your plugin under Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY, you need to rebuild your solution. nopCommerce will not list your plugin in the Local Plugins page if your DLLs do not exist in the correct folder in Nop.Web. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Local Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. 1. MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. Each browser request is mapped to a particular controller. 1. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application. 1. An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](http://www.asp.net/mvc/tutorials/older-versions/overview/understanding-models-views-and-controllers-cs). So let's start: - **Create the model**. Add a **Models** folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a **Views** folder in the new plugin, and then add a cshtml file named `Configure.cshtml`. Set **"Build Action"** property of the view file is set to **"Content"**, and the **"Copy to Output Directory"** property is set to **"Copy always"**. Note that the configuration page should use the "_ConfigurePlugin" layout. - Also make sure that you have the `_ViewImports.cshtml` file into your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a **Controllers** folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it *"Configure"*. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` For example, open PayPalStandard payment plugin and look at its implementation of PaymentPayPalStandardController. Then for each plugin that has a configuration page, you should specify a configuration URL. A base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where *{CONTROLLER_NAME}* is the name of your controller and *{ACTION_NAME}* is the name of the action (usually it's "Configure"). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under **Admin → Configuration → Local Plugins**. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the PayPalStandard plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.20/write_plugin_4.20_3.jpg) ## Handling "Install" and "Uninstall" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your IPlugin implementation (in most cases it'll be derived from BasePlugin class) and override the following methods: 1. **Install**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). 1. **Uninstall**. This method will be invoked during plugin uninstallation. > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, overridden "Install" method should include the following method call: *base.Install()*. The "Install" method of the PayPalStandard plugin looks like the code below ```csharp public override void Install() { var settings = new PayPalStandardPaymentSettings() { UseSandbox = true }; _settingService.SaveSetting(settings); ... base.Install(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\Plugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: 1. If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following RouteProvider class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by PayPal plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(IRouteBuilder routeBuilder) { routeBuilder.MapRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }); } public int Priority => -1; } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. ## Plugin template You can use [our Visual Studio template](https://github.com/nopSolutions/nopCommerce-plugin-template-VS/) for new nopCommerce plugins. It can save a lot of time for developers. Because now they don't have to do manually all initial steps. Such as folders creation (Controllers, Views, Models etc.), other required files (DependencyRegistrar.cs, _ViewImports.cshtml, ObjectContex, plugin.json etc), configuration, project references, etc). --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.10.html | source: en/developer/plugins/how-to-write-plugin-4.10.md --> # How to write a plugin for nopCommerce 4.10 > In computing, a plug-in (or plugin) is a set of software components that add specific abilities to a larger software application (Wikipedia). Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new "Class Library" project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with \Plugins subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the "Plugins" solution folder (you can find more information about [solution folders](http://msdn.microsoft.com/library/sx2027y2.aspx)). A recommended name for a plugin project is "Nop.Plugin.{Group}.{Name}". {Group} is your plugin group (for example, "Payment" or "Shipping"). {Name} is your plugin name (for example, "PayPalStandard"). For example, the PayPal Standard payment plugin has the following name: Nop.Plugin.Payments.PayPalStandard. But please note that it's not a requirement. And you can choose any name for a plugin. For example, "MyGreatPlugin". ![p1](_static/how-to-write-plugin-4.10/write_plugin_4.10_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> </PropertyGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` Where PLUGIN_OUTPUT_DIRECTORY should be replaced with the plugin name, for example, Payments.PayPalStandard. We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json). 1. The last required step is to create a class that implements the `IPlugin` interface (Nop.Core.Plugins namespace). nopCommerce has the `BasePlugin` class which already implements some IPlugin methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the "IPaymentMethod" interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as ProcessPayment() or GetAdditionalHandlingFee(). Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. - MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. Each browser request is mapped to a particular controller. - A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application. - An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](http://www.asp.net/mvc/tutorials/older-versions/overview/understanding-models-views-and-controllers-cs). So let's start: - **Create the model**. Add a Models folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a Views folder in the new plugin, and then add a cshtml file named `Configure.cshtml`. Set "Build Action" property of the view file is set to "Content", and the "Copy to Output Directory" property is set to "Copy if newer". Note that the configuration page should use the `_ConfigurePlugin` layout. Also, make sure that you have the `_ViewImports` file in your \Views directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a Controllers folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it "Configure". Prepare a model class and pass it to the following view using a physical view path: - `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` For example, open PayPalStandard payment plugin and look at its implementation of PaymentPayPalStandardController. Then for each plugin that has a configuration page, you should specify a configuration URL. A base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp return $"{_webHelper.GetStoreLocation()}Admin/ControllerName/ActionName"; ``` Where ControllerName is the name of your controller and ActionName is a name of the action (usually it's "Configure"). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under Admin → Configuration → Plugins. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the PayPalStandard plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.10/write_plugin_4.10_3.jpg) ## Handling "Install" and "Uninstall" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your IPlugin implementation (in most cases it'll be derived from BasePlugin class) and override the following methods: - Install. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). - Uninstall. This method will be invoked during plugin uninstallation. > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, overridden "Install" method should include the following method call: base.Install(). The "Install" method of the PayPalStandard plugin looks like the code below ```csharp public override void Install() { var settings = new PayPalStandardPaymentSettings() { UseSandbox = true }; _settingService.SaveSetting(settings); base.Install(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\installedPlugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: - If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following RouteProvider class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by PayPal plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(IRouteBuilder routeBuilder) { routeBuilder.MapRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/ PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }); } public int Priority { get { return -1; } } } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully this will get you started with nopCommerce and prepare you to build more elaborate plugins. --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-4.00.html | source: en/developer/plugins/how-to-write-plugin-4.00.md --> # How to write a plugin for nopCommerce 4.00 > In computing, a plug-in (or plugin) is a set of software components that add specific abilities to a larger software application (Wikipedia). Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new "Class Library" project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with \Plugins subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the "Plugins" solution folder (you can find more information about [solution folders](http://msdn.microsoft.com/library/sx2027y2.aspx)). A recommended name for a plugin project is "Nop.Plugin.{Group}.{Name}". {Group} is your plugin group (for example, "Payment" or "Shipping"). {Name} is your plugin name (for example, "PayPalStandard"). For example, the PayPal Standard payment plugin has the following name: Nop.Plugin.Payments.PayPalStandard. But please note that it's not a requirement. And you can choose any name for a plugin. For example, "MyGreatPlugin". ![p1](_static/how-to-write-plugin-4.00/write_plugin_4.00_1.jpg) 1. Once the plugin project is created you have to open its `.csproj` file in any text editor and replace its content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net461</TargetFramework> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> </PropertyGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.proj" Properties="PluginPath=$(MSBuildProjectDirectory)\$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` Where PLUGIN_OUTPUT_DIRECTORY should be replaced with the plugin name, for example, Payments.PayPalStandard. We do it this way to be able to use a new approach to add third-party references which were introduced in .NET Core. But it's not required. Moreover, references from already referenced libraries will be loaded automatically. So it is very convenient. 1. The next step is creating a `plugin.json` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json). 1. The last required step is to create a class that implements the `IPlugin` interface (Nop.Core.Plugins namespace). nopCommerce has the `BasePlugin` class which already implements some `IPlugin` methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from `IPlugin`. For example, we have the "IPaymentMethod" interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as `ProcessPayment()` or `GetAdditionalHandlingFee()`. Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. - MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. Each browser request is mapped to a particular controller. - A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application. - An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more information about the [MVC pattern](http://www.asp.net/mvc/tutorials/older-versions/overview/understanding-models-views-and-controllers-cs). So let's start: - **Create the model**. Add a Models folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a Views folder in the new plugin, and then add a cshtml file named `Configure.cshtml`. Set "Build Action" property of the view file is set to "Content", and the "Copy to Output Directory" property is set to "Copy if newer". Note that the configuration page should use the `_ConfigurePlugin` layout. Also, make sure that you have the `_ViewImports` file in your `\Views` directory. You can just copy it from any other existing plugin. - **Create the controller**. Add a Controllers folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentPayPalStandardController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it "Configure". Prepare a model class and pass it to the following view using a physical view path: - `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. - Use the following attributes for your action method: ```csharp [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action ``` For example, open PayPalStandard payment plugin and look at its implementation of PaymentPayPalStandardController. Then for each plugin that has a configuration page, you should specify a configuration URL. A base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```csharp return $"{_webHelper.GetStoreLocation()}Admin/ControllerName/ActionName"; ``` Where ControllerName is the name of your controller and ActionName is the name of the action (usually it's "Configure"). Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under Admin → Configuration → Plugins. > [!TIP] > The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. For example, the project structure of the PayPalStandard plugin looks like the image below: ![p3](_static/how-to-write-plugin-4.00/write_plugin_4.00_3.jpg) ## Handling "Install" and "Uninstall" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your IPlugin implementation (in most cases it'll be derived from BasePlugin class) and override the following methods: - Install. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). - Uninstall. This method will be invoked during plugin uninstallation. > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, overridden "Install" method should include the following method call: base.Install(). The "Install" method of the PayPalStandard plugin looks like the code below ```csharp public override void Install() { var settings = new PayPalStandardPaymentSettings() { UseSandbox = true }; _settingService.SaveSetting(settings); base.Install(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\installedPlugins.json`. The list is created during installation. ## Routes Here we will have a look at how to register plugin routes. ASP.NET Core routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more information about [routing](https://docs.microsoft.com/aspnet/core/fundamentals/routing). So follow the next steps: - If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following RouteProvider class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by PayPal plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(IRouteBuilder routeBuilder) { routeBuilder.MapRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/ PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }); } public int Priority { get { return -1; } } } ``` ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. --- <!-- page: How to write a plugin for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-plugin-3.90.html | source: en/developer/plugins/how-to-write-plugin-3.90.md --> # How to write a plugin for nopCommerce 3.90 (and previous versions) > In computing, a plug-in (or plugin) is a set of software components that add specific abilities to a larger software application (Wikipedia). Plugins are used to extend the functionality of nopCommerce. nopCommerce has several types of plugins. For example, payment methods (such as PayPal), tax providers, shipping method computation methods (such as UPS, USP, FedEx), widgets (such as 'live chat' block), and many others. nopCommerce is already distributed with many different plugins. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If not, this article will guide you through the process of creating your plugin. ## The plugin structure, required files, and locations 1. First thing you need to do is to create a new "Class Library" project in the solution. It's a good practice to place all plugins into the `\Plugins` directory in the root of your solution (do not mix up with \Plugins subdirectory located in `\Nop.Web` directory which is used for already deployed plugins). It's a good practice to place all plugins into the "Plugins" solution folder (you can find more [information about solution folders](http://msdn.microsoft.com/library/sx2027y2.aspx)). A recommended name for a plugin project is "Nop.Plugin.{Group}.{Name}". {Group} is your plugin group (for example, "Payment" or "Shipping"). {Name} is your plugin name (for example, "PayPalStandard"). For example, the PayPal Standard payment plugin has the following name: Nop.Plugin.Payments.PayPalStandard. But please note that it's not a requirement. And you can choose any name for a plugin. For example, "MyGreatPlugin". ![p1](_static/how-to-write-plugin-3.90/write_plugin_3.90_4.jpg) 1. Once the plugin project is created update the project build output path. Set it to `..\..\Presentation\Nop.Web\Plugins\{Group}.{Name}`. For example, Authorize.NET payment plugin has the following output path: `..\..\Presentation\Nop.Web\Plugins\Payments.AuthorizeNet`. After it's done, appropriate plugin DLLs will be automatically copied to the `\Presentation\Nop.Web\Plugins` directory which is searched by the nopCommerce core for valid plugins. But please note that it's also not a requirement. And you can choose any output directory name for a plugin. ![p1](_static/how-to-write-plugin-3.90/write_plugin_3.90_1.jpg) - On the Project menu, click Properties. - Click the Build tab. - Click the Browse button next to the Output path box and select a new build output directory. You should do the steps described above to all existing configurations ("Debug" and "Release"). 1. The next step is creating a `Description.txt` file required for each plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin and modify it for your needs. For example, the PayPal Standard payment plugin has the following `Description.txt` file: ```txt Group: Payment methods FriendlyName: PayPal Standard SystemName: Payments.PayPalStandard Version: 1.28 SupportedVersions: 3.90 Author: nopCommerce team DisplayOrder: 1 FileName: Nop.Plugin.Payments.PayPalStandard.dll Description: This plugin allows paying with PayPal Standard ``` All fields are self-descriptive, but here are some notes. **SystemName** field should be unique. **Version** field is a version number of your plugin; you can set it to any value you like. **SupportedVersions** field can contain a list of supported nopCommerce versions separated by commas (ensure that the current version of nopCommerce is included in this list, otherwise, it will not be loaded). **FileName** field has the following format *Nop.Plugin.{Group}.{Name}.dll* (it is your plugin assembly filename). Ensure that the "Copy to Output Directory" property of this file is set to "Copy if newer". ![p2](_static/how-to-write-plugin-3.90/write_plugin_3.90_2.jpg) 1. You should also created a web.config file and ensure that it's copied to the output. Just copy it from any existing plugin. > [!IMPORTANT] > Going forward make sure "Copy local" properties of all third-party assembly references (including core libraries such as Nop.Services.dll or Nop.Web.Framework.dll) are set to "False" (do not copy) 1. The last required step is to create a class that implements the IPlugin interface (Nop.Core.Plugins namespace). nopCommerce has BasePlugin class which already implements some IPlugin methods and allows you to avoid source code duplication. nopCommerce also provides you with some specific interfaces derived from IPlugin. For example, we have the "IPaymentMethod" interface which is used for creating new payment method plugins. It contains some methods which are specific only for payment methods such as ProcessPayment() or GetAdditionalHandlingFee(). Currently, nopCommerce has the following specific plugin interfaces: - **IPaymentMethod**. These plugins are used for payment processing. - **IShippingRateComputationMethod**. These plugins are used for retrieving accepted delivery methods and appropriate shipping rates. For example, UPS, UPS, FedEx, etc. - **IPickupPointProvider**. These plugins are used for providing pickup points. - **ITaxProvider**. Tax providers are used for getting tax rates. - **IExchangeRateProvider**. Used for getting currency exchange rate. - **IDiscountRequirementRule**. Allows you to create new discount rules such as "Billing country of a customer should be…" - **IExternalAuthenticationMethod**. Used for creating external authentication methods such as Facebook, X (Twitter), OpenID, etc. - **IWidgetPlugin**. It allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a "Live chat" block on your site's left column. - **IMiscPlugin**. If your plugin doesn't fit any of the interfaces above. > [!IMPORTANT] > After each project build, clean the solution before making changes. Some resources will be cached and can lead to developer insanity. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area → Configuration → Plugins**. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, and a view. - MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. Each browser request is mapped to a particular controller. - A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application. - An MVC model contains all of your application logic that is not contained in a view or a controller. You can find more [information about the MVC pattern](http://www.asp.net/mvc/tutorials/older-versions/overview/understanding-models-views-and-controllers-cs). So let's start: - **Create the model**. Add a Models folder in the new plugin, and then add a new model class that fits your need. - **Create the view**. Add a Views folder in the new plugin, then add a {Name} folder (where {Name} is your plugin name), and finally add a cshtml file named `Configure.cshtml`. Important note: for versions 2.00-3.30 the view should be marked as an embedded resource. And starting version 3.40 views, ensure that the "Build Action" property of the view file is set to "Content", and the "Copy to Output Directory" property is set to "Copy if newer". - **Create the controller**. Add a Controllers folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers `{Group}{Name}Controller.cs`. For example, PaymentAuthorizeNetController. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it "Configure". Prepare a model class and pass it to the following view. For nopCommerce versions 2.00-3.30 you should pass embedded view path - "Nop.Plugin.{Group}.{Name}.Views. {Group}{Name}.Configure". And starting nopCommerce version 3.40 you should pass physical view path - `~/Plugins/{PluginOutputDirectory}/Views/{ControllerName}/Configure.cshtml`. For example, open the Authorize.NET payment plugin and look at its implementation of PaymentAuthorizeNetController. > [!TIP] > > - The easiest way to complete the steps described above is by opening any other plugin and copying these files into your plugin project. Then just rename appropriate classes and directories. > > - If you want to limit access to a certain action method of the controller to administrators (store owners), then just mark it with the [AdminAuthorize] attribute. For example, the project structure of the Authorize.NET plugin looks like the image below ![p3](_static/how-to-write-plugin-3.90/write_plugin_3.90_3.jpg) ## Routes Now we need to register appropriate plugin routes. ASP.NET routing is responsible for mapping incoming browser requests to particular MVC controller actions. You can find more [information about routing](http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs). So follow the next steps: - Some of the specific plugin interfaces (described above) and the "IMiscPlugin" interface have the following method: "GetConfigurationRoute". It should return a route to a controller action that is used for plugin configuration. Implement the "GetConfigurationRoute" method of your plugin interface. This method informs nopCommerce about what route is used for plugin configuration. If your plugin doesn't have a configuration page, then "GetConfigurationRoute" should return null. For example, see the code below: ```csharp public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "PaymentAuthorizeNet"; routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.AuthorizeNet.Controllers" }, { "area", null } }; } ``` - (optional) If you need to add some custom route, then create the `RouteProvider.cs` file. It informs the nopCommerce system about plugin routes. For example, the following RouteProvider class adds a new route which can be accessed by opening your web browser and navigating to `http://www.yourStore.com/Plugins/PaymentPayPalStandard/PDTHandler` URL (used by PayPal plugin): ```csharp public partial class RouteProvider : IRouteProvider { public void RegisterRoutes(RouteCollection routes) { routes.MapRoute("Plugin.Payments.PayPalStandard.PDTHandler", "Plugins/PaymentPayPalStandard/PDTHandler", new { controller = "PaymentPayPalStandard", action = "PDTHandler" }, new[] { "Nop.Plugin.Payments.PayPalStandard.Controllers" } ); } public int Priority { get { return 0; } } } ``` Once you have installed your plugin and added the configuration method you will find a link to configure your plugin under Admin → Configuration → Plugins. ## Handling "Install" and "Uninstall" methods This step is optional. Some plugins can require additional logic during plugin installation. For example, a plugin can insert new locale resources. So open your IPlugin implementation (in most cases it'll be derived from BasePlugin class) and override the following methods: - Install. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). - Uninstall. This method will be invoked during plugin uninstallation. > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation. For example, the project structure of the Authorize.NET plugin looks like the image below ```csharp public override void Install() { var settings = new AuthorizeNetPaymentSettings() { UseSandbox = true, TransactMode = TransactMode.Authorize, TransactionKey = "123", LoginId = "456" }; _settingService.SaveSetting(settings); base.Install(); } ``` > [!TIP] > The list of installed plugins is located in `\App_Data\InstalledPlugins.txt`. The list is created during installation. ## Upgrading nopCommerce may break plugins Some plugins may become outdated and no longer work with the newer version of nopCommerce. If you have issues after upgrading to the newer version, delete the plugin and visit the official nopCommerce website to see if a newer version is available. Many plugin authors will upgrade their plugins to accommodate the newer version, however, some will not and their plugin will become obsolete with the improvements in nopCommerce. But in most cases, you can simply open an appropriate `plugin.json` file and update the **SupportedVersions** field. ## Conclusion Hopefully, this will get you started with nopCommerce and prepare you to build more elaborate plugins. --- <!-- page: How to code my own payment method | url: http://nopdocs.service.hedr.dev/en/developer/plugins/payment-method.html | source: en/developer/plugins/payment-method.md --> # How to code my payment method Payment methods are implemented as plugins in nopCommerce. We recommend you read [How to write a plugin for nopCommerce 5.00](xref:en/developer/plugins/how-to-write-plugin-5.00) before you start coding a new payment method. It will explain to you what the required steps are for creating a plugin. So actually a payment method is an ordinary plugin that implements an **`IPaymentMethod`** interface (*Nop.Services.Payments namespace*). As you already guessed *IPaymentMethod* interface is used for creating payment method plugins. It contains some methods which are specific only for payment methods such as `ProcessPaymentAsync()` or `GetAdditionalHandlingFeeAsync()`. So, add a new payment plugin project (*class library*) to the solution, and let's get started. ## Controllers, views, models The first thing you need to do is create a controller. This controller is responsible for responding to requests made against an ASP.NET MVC website. 1. When implementing a new payment method, this controller should be derived from a special **BasePaymentController** abstract class. 1. Then implement **Configure** action methods used for plugin configuration (by a store owner in the admin area). This method and an appropriate view will define how a store owner sees configuration options in the admin panel (*System → Configuration → Payment methods*). ## Public view component.GetPublicViewComponent Then you have to create a view component for displaying the plugin in the public store. This view component and an appropriate view will define how your customers will see the payment information page during checkout. First, let's create a view component class. It should be placed in the *`/Components`* folder. Look how it's done for *PayPalCommerce* plugin: ```csharp public class PaymentInfoViewComponent : NopViewComponent { public IViewComponentResult Invoke(string widgetZone, object additionalData) { return View("~/Plugins/Payments.PayPalCommerce/Views/Public/PaymentInfo.cshtml"); } } ``` **Invoke** method returns an appropriate `PaymentInfo` view from the */Views* folder of your plugin. Note that we use our custom NopViewComponent class as a base class instead of the existing built-in ViewComponent. Then let's create the `PaymentInfo` view which shows payment information. There we just render text saying that a customer will be redirected to the payment page. But it's possible to create a more complex view component if needed. For example, if you want to collect customer's information on the payment information page look how it's already done in the `PayPalDirect` payment plugin. ## Payment processing Now you need to create a class that implements the **IPaymentMethod** interface. This is the class that will be doing all the actual work of communicating with your payment gateway. When someone creates an order either the `ProcessPayment` or `PostProcessPayment` methods of your class will be called. Here is how **CheckMoneyOrderPaymentProcessor** class is defined (`CheckMoneyOrder` payment method): ```csharp public class CheckMoneyOrderPaymentProcessor : BasePlugin, IPaymentMethod ``` **IPaymentMethod** interface has several methods and properties which are required to implement. - **ValidatePaymentFormAsync** is used in the public store to validate customer input. It returns a list of warnings (for example, a customer did not enter his credit card name). If your payment method does not ask the customer to enter additional information, then the `ValidatePaymentFormAsync` should return an empty list: ```csharp public Task<IList<string>> ValidatePaymentFormAsync(IFormCollection form) { return Task.FromResult<IList<string>>(new List<string>()); } ``` - **GetPaymentInfoAsync** method is used in the public store to parse customer input, such as credit card information. This method returns a ProcessPaymentRequest object with parsed customer input (for example, credit card information). If your payment method does not ask the customer to enter additional information, then `GetPaymentInfoAsync` will return an empty ProcessPaymentRequest object: ```csharp public Task<ProcessPaymentRequest> GetPaymentInfoAsync(IFormCollection form) { return Task.FromResult(new ProcessPaymentRequest()); } ``` - **ProcessPaymentAsync**. This method is always invoked right before a customer places an order. Use it when you need to process payment before an order is stored in a database. For example, capture or authorize credit card. Usually, this method is used when a customer is not redirected to a third-party site for completing payment and all payments are handled on your site (for example, *PayPalCommerce*). ```csharp public Task<ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest) { return Task.FromResult(new ProcessPaymentResult()); } ``` - **PostProcessPaymentAsync**. This method is invoked right after a customer places an order. Usually, this method is used when you need to redirect a customer to a third-party site for completing a payment (for example, PayPal Standard). - **HidePaymentMethodAsync**. You can put any logic here. For example, hide this payment method if all products in the cart are downloadable. Or hide this payment method if the current customer is from a certain country. - **GetAdditionalHandlingFeeAsync**. You can return any additional handling fees which will be added to an order total. - **CaptureAsync**. Some payment gateways allow you to authorize payments before they're captured. It allows store owners to review order details before the payment is done. In this case, you just authorize a payment in **ProcessPaymentAsync** or **PostProcessPaymentAsync** method (described above), and then just capture it. In this case, a *Capture* button will be visible on the order details page in the admin area. Note that an order should be already authorized and **SupportCapture** property should return **`true`**. - **RefundAsync**. This method allows you to make a refund. In this case, a *Refund* button will be visible on the order details page in the admin area. Note that an order should be paid, and **SupportRefund** or **SupportPartiallyRefund** property should return **`true`**. - **VoidAsync**. This method allows you to void an authorized but not captured payment. In this case, a *Void* button will be visible on the order details page in the admin area. Note that an order should be authorized and **SupportVoid** property should return **`true`**. - **ProcessRecurringPaymentAsync**. Use this method to process recurring payments. - **CancelRecurringPaymentAsync**. Use this method to cancel recurring payments. - **CanRePostProcessPaymentAsync**. Usually, this method is used when it redirects a customer to a third-party site for completing a payment. If the third-party payment fails this option will allow customers to attempt the order again later without placing a new order. **CanRePostProcessPaymentAsync** should return **`true`** to enable this feature. - **GetConfigurationPageUrl**. As you remember we created a controller in the previous step. This method should return a URL of its `Configure` method. For example: ```csharp public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/PaymentCheckMoneyOrder/Configure"; } ``` - **GetPaymentMethodDescriptionAsync**. This method gets a payment method description that will be displayed on checkout pages in the public store. ```csharp public async Task<string> GetPaymentMethodDescriptionAsync() { return await _localizationService.GetResourceAsync("Plugins.Payment.CheckMoneyOrderPaymentMethodDescription"); } ``` - **SupportCapture, SupportPartiallyRefund, SupportRefund, SupportVoid**. These properties indicate whether appropriate methods of payment method are supported. - **RecurringPaymentType**. This property indicates whether recurring payments are supported. - **PaymentMethodType**. This property indicates the payment method type. Currently, there are three types. **`Standard`** is used by payment methods when a customer is not redirected to a third-party site. **`Redirection`** is used when a customer is redirected to a third-party site. And **`Button`** is similar to **`Redirection`** payment methods. The only difference is used that it's displayed as a button on the shopping cart page (for example, *Google Checkout*). - **SkipPaymentInfo**. Indicates whether we should display a payment information page for this plugin. ## Conclusion Hopefully, this will get you started with adding a new payment method. --- <!-- page: How to code my own shipping rate computation method | url: http://nopdocs.service.hedr.dev/en/developer/plugins/shipping-plugin.html | source: en/developer/plugins/shipping-plugin.md --> # How to code my shipping rate computation method If customers have some shippable products, they can choose a shipping option during checkout. These shipping options are returned from shipping rate computation methods (such as *UPS*, *USPS*, *FedEx*, etc). Shipping rate computation methods are implemented as plugins in nopCommerce. We recommend you read [How to write a plugin for nopCommerce 5.00](xref:en/developer/plugins/how-to-write-plugin-5.00) before you start coding a new shipping rate computation method. The article will explain to you the required steps for creating a plugin. So actually a shipping rate computation method is an ordinary plugin that implements an **IShippingRateComputationMethod** interface (`Nop.Services.Shipping` namespace). So add a new shipping plugin project (*class library*) to the solution and let's get started. ## Controllers, views, models Add a controller and an appropriate **Configure** action method and a view. These will define how a store owner sees configuration options in the admin panel *System → Configuration → Shipping → Shipping providers*. This article does not explain how to configure plugins, but you can find [more info about it here](xref:en/getting-started/configure-shipping/shipping-providers/index). ![shipping-plugin_1](_static/shipping-plugin/shipping-plugin_1.png) Once this step is complete, you can start adding the required business logic for getting shipping options. ## Getting shipping options Now you need to create a class that implements the **IShippingRateComputationMethod** interface. This is the class that will be doing all the actual work. When nopCommerce calculates shipping totals or needs to get a list of available shipping options, the **GetShippingOptionsAsync** or **GetFixedRateAsync** methods of your class will be called. Here is how UPSComputationMethod class is defined ("UPS" method): ```csharp public class UPSComputationMethod : BasePlugin, IShippingRateComputationMethod ``` **IShippingRateComputationMethod** interface has several methods and properties which are required to implement. - **GetShippingOptionsAsync**. This method is always invoked when a customer chooses a shipping option during checkout. This method returns **`GetShippingOptionResponse`** which contains a list of **ShippingOption** objects. Each **ShippingOption** object contains information about certain shipping options such as option name (for example, "By ground"), its rate (for example, 10 USD), and other information. Put all your logic here (get the rates from your database or request them from a third-party site such as *UPS*). - **GetFixedRateAsync**. As you already know **GetShippingOptionsAsync** is used to get shipping options during checkout (on the "Select shipping method" page). But sometimes we need to know a shipping rate before a shipping option is chosen (for example, on the shopping cart page). In this case, you can return a fixed rate. For example, your shipping rate computation method provides only one shipping option, and there's no need to wait until the customer chooses it on the "Select shipping method" page. Return will be **`null`** if your fixed rates are not supported. In this case, customers will see the following message besides "Shipping total" on the shopping cart: "*Calculated during checkout*". - **GetShipmentTrackerAsync**. This method is used to get the associated shipping tracker. As a result, an **IShipmentTracker** is passed which contains the URL of the page to display the tracking information (third party tracking page) as well as all information about the shipment events. ## Conclusion Hopefully, this will get you started with adding a new shipping rate computation method. --- <!-- page: Cloudflare Images | url: http://nopdocs.service.hedr.dev/en/developer/plugins/cloudflare-Images.html | source: en/developer/plugins/cloudflare-Images.md --> # Cloudflare Images Integration ## Overview Starting with version 4.90, thumbnail management has been refactored for greater flexibility. A new interface, `IThumbService`, has been introduced to handle all thumbnail-related operations previously managed by 'IPictureService`. The following methods have been moved to `IThumbService`: - `GetThumbLocalPathAsync` - `GeneratedThumbExistsAsync` - `SaveThumbAsync` - `GetThumbLocalPathByFileNameAsync` - `GetThumbUrlAsync` - `DeletePictureThumbsAsync` As part of this change, thumbnail storage logic has been decoupled from the core application into standalone plugins. The existing **Azure Blob Storage** functionality is now a separate plugin. A new plugin has been developed to integrate **Cloudflare Images** as a thumbnail storage solution. > [!NOTE] > > By default, both the Azure Blob and Cloudflare Images plugins (`Misc.AzureBlob` and `Misc.CloudflareImages`) are listed in the `InstallationConfig.DisabledPlugins` property. This ensures that neither plugin is installed during a fresh setup, allowing store owners to choose and install the storage solution that best fits their needs. ## Configuration Azure Blob Storage We can use *Azure Blob Storage* to store blob data. nopCommerce already has a feature integrated for that, we just need to set the following information correctly to use this feature. Values for these settings can be obtained for *Azure* while you create the storage account. ![Image](_static/cloudflare-images/azure-blob.png) - **ConnectionString** This setting expects a string value. Here you need to add your `AzureBlobStorage` connection string. - **ContainerName** Value for this setting is also of type string. In this setting, we set the container name for *Azure BLOB storage*. - **EndPoint** This setting also expects a string value. Here we need to set the endpoint for *Azure BLOB storage*. - **AppendContainerName** This setting expects a boolean value. Set the value to **`true`** or **`false`** based on whether the Container Name is appended to the `EndPoint` when constructing the URL. ## Configuration Cloudflare Images The plugin settings are straightforward, consisting of four fields in addition to the master enable/disable switch. ![Image](_static/cloudflare-images/cloudflare-images.png) A critical field is the **Delivery URL**. It must be configured in the following specific format: ```bash https://imagedelivery.net/[account_hash]/<image_id>/<variant_name> ``` This URL acts as a template. The plugin will dynamically insert the required `image_id` and `variant_name` to generate the final URLs for the thumbnails displayed on the website. ## Usage Once configured and enabled, the plugin operates automatically in the background, similar to the Azure Blob storage integration. It seamlessly handles: - Uploading new thumbnails to the Cloudflare Images service. - Replacing local thumbnail URLs with the corresponding Cloudflare Images URLs on all public-facing pages. --- <!-- page: Plugin with data access | url: http://nopdocs.service.hedr.dev/en/developer/plugins/plugin-with-data-access.html | source: en/developer/plugins/plugin-with-data-access.md --> # Plugin with data access In this tutorial, I'll be using the nopCommerce plugin architecture to implement a product view tracker. Before we begin with the development you must read, understood, and completed the tutorials listed below. I'll be skipping over some explanations covered in the previous articles, but you can recap using the links provided. - [Developer tutorials](xref:en/developer/tutorials/index) - [Updating an existing entity. How to add a new property.](xref:en/developer/tutorials/update-existing-entity) - [How to write a plugin for nopCommerce 5.00](xref:en/developer/plugins/how-to-write-plugin-5.00) We will start coding with the data access layer, move on to the service layer, and finally end on dependency injection. ## Getting started Create a new class library project "Nop.Plugin.Misc.ProductViewTracker". Add the `plugin.json` file. > [!TIP] > > For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json). Then add references to the **Nop.Web.Framework** projects. This will be enough for us, as other dependencies, such as **Nop.Core** and **Nop.Data**will be connected automatically ## The Data Access Layer (A.K.A. Creating new entities in nopCommerce) Inside of the "*domain*" namespace we're going to create a public class named **`ProductViewTrackerRecord`**. This class extends **`BaseEntity`**, but it is otherwise a very simple file. Something to remember is that we do not have navigation properties (relational properties), because the *Linq2DB* framework, which we use to work with databases does not support the navigation properties. ```csharp namespace Nop.Plugin.Misc.ProductViewTracker.Domain public class ProductViewTrackerRecord : BaseEntity { public int ProductId { get; set; } public string ProductName { get; set; } public int CustomerId { get; set; } public string IpAddress { get; set; } public bool IsRegistered { get; set; } } ``` The next class to create is the *FluentMigrator* entity builder class. Inside the mapping class, we map the columns, table relationships, and the database table. ```csharp using FluentMigrator.Builders.Create.Table; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Customers; using Nop.Data.Mapping.Builders; using Nop.Plugin.Other.ProductViewTracker.Domains; using Nop.Data.Extensions; using System.Data; namespace Nop.Plugin.Other.ProductViewTracker.Mapping.Builders public class ProductViewTrackerRecordBuilder : NopEntityBuilder<ProductViewTrackerRecord> { /// <summary> /// Apply entity configuration /// </summary> /// <param name="table">Create table expression builder</param> public override void MapEntity(CreateTableExpressionBuilder table) { //map the primary key (not necessary if it is Id field) table.WithColumn(nameof(ProductViewTrackerRecord.Id)).AsInt32().PrimaryKey() //map the additional properties as foreign keys .WithColumn(nameof(ProductViewTrackerRecord.ProductId)).AsInt32().ForeignKey<Product>(onDelete: Rule.Cascade) .WithColumn(nameof(ProductViewTrackerRecord.CustomerId)).AsInt32().ForeignKey<Customer>(onDelete: Rule.Cascade) //avoiding truncation/failure //so we set the same max length used in the product name .WithColumn(nameof(ProductViewTrackerRecord.ProductName)).AsString(400) //not necessary if we don't specify any rules .WithColumn(nameof(ProductViewTrackerRecord.IpAddress)).AsString() .WithColumn(nameof(ProductViewTrackerRecord.IsRegistered)).AsInt32(); } } ``` The next important class for us will be the migration class, which creates our table directly in the database. You can create as many migrations as you like in your plugin, the only thing you need to keep track of is the version of your migration. We specially created our **NopMigration** attribute to make it easier for you. By indicating here the most complete and accurate file creation date, you practically guarantee the uniqueness of your migration number. ```csharp using FluentMigrator; using Nop.Data.Extensions; using Nop.Data.Migrations; using Nop.Plugin.Other.ProductViewTracker.Domains; namespace Nop.Plugin.Other.ProductViewTracker.Migrations [NopSchemaMigration("2020-05-27 08:40:55:1687541", "Other.ProductViewTracker base schema", MigrationProcessType.Installation)] public class SchemaMigration : ForwardOnlyMigration { public override void Up() { Create.TableFor<ProductViewTrackerRecord>(); } } ``` ## Service layer The service layer connects the data access layer and the presentation layer. Since it is bad form to share any type of responsibility in code each layer needs to be isolated. The service layer wraps the data layer with business logic and the presentation layer depends on the service layer. Because our task is very small our service layer does nothing but communicate with the repository (the repository in nopCommerce acts as a facade to the object context). ```csharp using Nop.Data; using Nop.Plugin.Other.ProductViewTracker.Domains; using System; namespace Nop.Plugin.Other.ProductViewTracker.Services public interface IProductViewTrackerService { /// <summary> /// Logs the specified record. /// </summary> /// <param name="record">The record.</param> void Log(ProductViewTrackerRecord record); } namespace Nop.Plugin.Misc.ProductViewTracker.Services public class ProductViewTrackerService : IProductViewTrackerService { private readonly IRepository<ProductViewTrackerRecord> _productViewTrackerRecordRepository; public ProductViewTrackerService(IRepository<ProductViewTrackerRecord> productViewTrackerRecordRepository) { _productViewTrackerRecordRepository = productViewTrackerRecordRepository; } /// <summary> /// Logs the specified record. /// </summary> /// <param name="record">The record.</param> public virtual void Log(ProductViewTrackerRecord record) { if (record == null) throw new ArgumentNullException(nameof(record)); _productViewTrackerRecordRepository.Insert(record); } } ``` ## Dependency Injection Martin Fowler has written a great description of dependency injection or Inversion of Control. I'm not going to duplicate his work, and you can find [his article here](https://martinfowler.com/articles/injection.html). Dependency injection manages the life cycle of objects and provides instances for dependent objects to use. First, we need to configure the dependency container so it understands which objects it will control and what rules might apply to the creation of those objects. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Nop.Core.Infrastructure; using Nop.Plugin.Other.ProductViewTracker.Services; namespace Nop.Plugin.Other.ProductViewTracker.Infrastructure /// <summary> /// Represents object for the configuring services on application startup /// </summary> public class NopStartup : INopStartup { /// <summary> /// Add and configure any of the middleware /// </summary> /// <param name="services">Collection of service descriptors</param> /// <param name="configuration">Configuration of the application</param> public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.AddScoped<IProductViewTrackerService, ProductViewTrackerService>(); } /// <summary> /// Configure the using of added middleware /// </summary> /// <param name="application">Builder for configuring an application's request pipeline</param> public void Configure(IApplicationBuilder application) { } /// <summary> /// Gets order of this startup configuration implementation /// </summary> public int Order => 3000; } ``` In the code above we register different types of objects so they can later be injected into controllers, services, and repositories. Now that we've covered the new topics I'll bring back some of the older ones so we can finish the plugin. ## The view component Let's create a view component: ```csharp using Microsoft.AspNetCore.Mvc; using Nop.Core; using Nop.Plugin.Other.ProductViewTracker.Domains; using Nop.Plugin.Other.ProductViewTracker.Services; using Nop.Services.Catalog; using Nop.Services.Customers; using Nop.Web.Framework.Components; using Nop.Web.Models.Catalog; namespace Nop.Plugin.Other.ProductViewTracker.Components public class ProductViewTrackerViewComponent : NopViewComponent { private readonly ICustomerService _customerService; private readonly IProductService _productService; private readonly IProductViewTrackerService _productViewTrackerService; private readonly IWorkContext _workContext; public ProductViewTrackerViewComponent(ICustomerService customerService, IProductService productService, IProductViewTrackerService productViewTrackerService, IWorkContext workContext) { _customerService = customerService; _productService = productService; _productViewTrackerService = productViewTrackerService; _workContext = workContext; } public async Task<IViewComponentResult> InvokeAsync(string widgetZone, object additionalData) { if (!(additionalData is ProductDetailsModel model)) return Content(""); //Read from the product service var productById = await _productService.GetProductByIdAsync(model.Id); //If the product exists we will log it if (productById != null) { var currentCustomer = await _workContext.CurrentCustomerAsync(); //Setup the product to save var record = new ProductViewTrackerRecord { ProductId = model.Id, ProductName = productById.Name, CustomerId = currentCustomer.Id, IpAddress = currentCustomer.LastIpAddress, IsRegistered = await _customerService.Async(currentCustomer) }; //Map the values we're interested in to our new entity _productViewTrackerService.Log(record); } return Content(""); } } ``` ## The main plugin class > [!IMPORTANT] > > We implement our plugin as a widget. In this case, we won't need to edit a `cshtml` file. ```csharp using Nop.Services.Cms; using Nop.Services.Plugins; using Nop.Web.Framework.Infrastructure; using System.Collections.Generic; namespace Nop.Plugin.Other.ProductViewTracker public class ProductViewTrackerPlugin : BasePlugin, IWidgetPlugin { /// <summary> /// Gets a value indicating whether to hide this plugin on the widget list page in the admin area /// </summary> public bool HideInWidgetList => true; /// <summary> /// Gets a type of a view component for displaying widget /// </summary> /// <param name="widgetZone">Name of the widget zone</param> /// <returns>View component type</returns> public Type GetWidgetViewComponent(string widgetZone) { return typeof(ProductViewTrackerViewComponent); } /// <summary> /// Gets widget zones where this widget should be rendered /// </summary> /// <returns>Widget zones</returns> public Task<IList<string>> GetWidgetZonesAsync() { return Task.FromResult<IList<string>>(new List<string> { PublicWidgetZones.ProductDetailsTop }); } } ``` --- <!-- page: Plugin with data access | url: http://nopdocs.service.hedr.dev/en/developer/plugins/plugin-with-data-access-4.20.html | source: en/developer/plugins/plugin-with-data-access-4.20.md --> # Plugin with data access" (4.20 and below) In this tutorial I'll be using the nopCommerce plugin architecture to implement a product view tracker. Before we begin with the development it is very important that you have read, understood, and successfully completed the tutorials listed below. I'll be skipping over some explanations covered in the previous articles, but you can recap using the links provided. - [Developer tutorials](xref:en/developer/tutorials/index) - [Updating an existing entity. How to add a new property.](xref:en/developer/tutorials/update-existing-entity) - [How to write a plugin for nopCommerce 4.20](xref:en/developer/plugins/how-to-write-plugin-4.20) We will start coding with the data access layer, move on to the service layer, and finally end on dependency injection. > [!NOTE] > > The practical application of this plugin is questionable, but I couldn't think of a feature that didn't come with nopCommerce and would fit in a reasonable size post. If you use this plugin in a production environment I offer no warranties. I am always interested in success stories and I would be happy to hear that the post provided more than just an educational value. ## Getting started Create a new class library project "Nop.Plugin.Other.ProductViewTracker". ![plugin-with-data-access_1](_static/plugin-with-data-access/plugin-with-data-access_1.jpg) Add the following folders and `plugin.json` file. ![plugin-with-data-access_2](_static/plugin-with-data-access/plugin-with-data-access_2.jpg) For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json). Then add references to the following projects: Nop.Core, Nop.Data, Nop.Web.Framework ## The Data Access Layer (A.K.A. Creating new entities in nopCommerce) Inside of the "domain" namespace we're going to create a public class named ProductViewTrackerRecord. This class extends BaseEntity, but it is otherwise a very boring file. Something to remember is that all properties are marked as virtual and it isn't just for fun. Virtual properties are required on database entities because of how Entity Framework instantiates and tracks classes. One other thing to note is that we do not have navigation properties (relational properties), and I'll cover those in more detail later. ```csharp namespace Nop.Plugin.Other.ProductViewTracker.Domain { public class ProductViewTrackerRecord : BaseEntity { public virtual int ProductId { get; set; } public virtual string ProductName { get; set; } public virtual int CustomerId { get; set; } public virtual string IpAddress { get; set; } public virtual bool IsRegistered { get; set; } } } ``` **File Locations**: To figure out where certain files should exist analyze the namespace and create the file accordingly. The next class to create is the Entity Framework mapping class. Inside of the mapping class we map the columns, table relationships, and the database table. ```csharp namespace Nop.Plugin.Other.ProductViewTracker.Data { public class ProductViewTrackerRecordMap : NopEntityTypeConfiguration<ProductViewTrackerRecord> { /// <summary> /// Configures the entity /// </summary> /// <param name="builder">The builder to be used to configure the entity</param> public override void Configure(EntityTypeBuilder<ProductViewTrackerRecord> builder) { builder.ToTable(nameof(ProductViewTrackerRecord)); //Map the primary key builder.HasKey(record => record.Id); //Map the additional properties builder.Property(record => record.ProductId); //Avoiding truncation/failure //so we set the same max length used in the product tame builder.Property(record => record.ProductName).HasMaxLength(400); builder.Property(record => record.IpAddress); builder.Property(record => record.CustomerId); builder.Property(record => record.IsRegistered); } } } ``` The next class is the most complicated and the most important class in the data access layer. The Entity Framework Object Context is a pass-through class that gives us database access and helps track entity state (e.g. add, update, delete). The context is also used to generate the database schema or update an existing schema. In custom context classes we cannot reference previously existing entities because those types are already associated to another object context. That is also why we do not have complex navigation properties in our tracking record. ```csharp namespace Nop.Plugin.Other.ProductViewTracker.Data { public class ProductViewTrackerRecordObjectContext : DbContext, IDbContext { public ProductViewTrackerRecordObjectContext(DbContextOptions<ProductViewTrackerRecordObjectContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new ProductViewTrackerRecordMap()); base.OnModelCreating(modelBuilder); } public new virtual DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity { return base.Set<TEntity>(); } public virtual string GenerateCreateScript() { return Database.GenerateCreateScript(); } public virtual IQueryable<TQuery> QueryFromSql<TQuery>(string sql) where TQuery : class { throw new NotImplementedException(); } public virtual IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity { throw new NotImplementedException(); } public virtual int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters) { using (var transaction = Database.BeginTransaction()) { var result = Database.ExecuteSqlCommand(sql, parameters); transaction.Commit(); return result; } } public void Install() { //create the table this.ExecuteSqlScript(GenerateCreateScript()); } public void Uninstall() { //drop the table this.DropPluginTable(nameof(ProductViewTrackerRecord)); } public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new() { throw new NotImplementedException(); } public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters) { throw new NotImplementedException(); } public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters) { throw new NotImplementedException(); } public virtual void Detach<TEntity>(TEntity entity) where TEntity : BaseEntity { throw new NotImplementedException(); } public IQueryable<TQuery> QueryFromSql<TQuery>(string sql, params object[] parameters) where TQuery : class { throw new NotImplementedException(); } public virtual bool ProxyCreationEnabled { get => ProxyCreationEnabled; set => ProxyCreationEnabled = value; } public virtual bool AutoDetectChangesEnabled { get => AutoDetectChangesEnabled; set => AutoDetectChangesEnabled = value; } } } ``` ## Application Startup This part registers the record object context we created in the previous step. ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Nop.Core.Infrastructure; using Nop.Plugin.Other.ProductViewTracker.Data; using Nop.Web.Framework.Infrastructure.Extensions; namespace Nop.Plugin.Misc.RepCred.Infrastructure { /// <summary> /// Represents object for the configuring plugin DB context on application startup /// </summary> public class PluginDbStartup : INopStartup { /// <summary> /// Add and configure any of the middleware /// </summary> /// <param name="services">Collection of service descriptors</param> /// <param name="configuration">Configuration of the application</param> public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { //add object context services.AddDbContext<ProductViewTrackerRecordObjectContext>(optionsBuilder => { optionsBuilder.UseSqlServerWithLazyLoading(services); }); } /// <summary> /// Configure the using of added middleware /// </summary> /// <param name="application">Builder for configuring an application's request pipeline</param> public void Configure(IApplicationBuilder application) { } /// <summary> /// Gets order of this startup configuration implementation /// </summary> public int Order => 11; } } ``` ## Service layer The service layer connects the data access layer and the presentation layer. Since it is bad form to share any type of responsibility in code each layer needs to be isolated. The service layer wraps the data layer with business logic and the presentation layer depends on the service layer. Because our task is very small our service layer does nothing but communicate with the repository (the repository in nopCommerce acts as a facade to the object context). ```csharp namespace Nop.Plugin.Other.ProductViewTracker.Services { public interface IProductViewTrackerService { /// <summary> /// Logs the specified record. /// </summary> /// <param name="record">The record.</param> void Log(ProductViewTrackerRecord record); } } namespace Nop.Plugin.Other.ProductViewTracker.Services { public class ProductViewTrackerService : IProductViewTrackerService { private readonly IRepository<ProductViewTrackerRecord> _productViewTrackerRecordRepository; public ViewTrackingService(IRepository<ProductViewTrackingRecord> productViewTrackerRecordRepository) { _productViewTrackerRecordRepository = productViewTrackerRecordRepository; } /// <summary> /// Logs the specified record. /// </summary> /// <param name="record">The record.</param> public virtual void Log(ProductViewTrackerRecord record) { if (record == null) throw new ArgumentNullException(nameof(record)); _productViewTrackerRecordRepository.Insert(record); } } } ``` ## Dependency Injection Martin Fowler has written a great description of dependency injection or Inversion of Control. I'm not going to duplicate his work, and you can find his article here. Dependency injection manages the life cycle of objects and provides instances for dependent objects to use. First we need to configure the dependency container so it understands which objects it will control and what rules might apply to the creation of those objects. ```csharp namespace Nop.Plugin.Other.ProductViewTracker.Infrastructure { public class DependencyRegistrar : IDependencyRegistrar { private const string CONTEXT_NAME = "nop_object_context_product_view_tracker"; public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) { builder.RegisterType<ProductViewTrackerService>().As<IProductViewTrackerService>().InstancePerLifetimeScope(); //data context builder.RegisterPluginDataContext<ProductViewTrackerRecordObjectContext>(CONTEXT_NAME); //override required repository with our custom context builder.RegisterType<EfRepository<ProductViewTrackerRecord>>() .As<IRepository<ProductViewTrackerRecord>>() .WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME)) .InstancePerLifetimeScope(); } public int Order => 1; } } ``` In the code above we register different types of objects so they can later be injected into controllers, services, and repositories. Now that we've covered the new topics I'll bring back some of the older ones so we can finish the plugin. ## The view component Let's create a view component: ```csharp namespace Nop.Plugin.Other.ProductViewTracker.Components { [ViewComponent(Name = "ProductViewTracker")] public class ProductViewTrackerViewComponent : NopViewComponent { private readonly IProductService _productService; private readonly IProductViewTrackerService _productViewTrackerService; private readonly IWorkContext _workContext; public ProductViewTrackerViewComponent(IWorkContext workContext, IProductViewTrackerService productViewTrackerService, IProductService productService) { _workContext = workContext; _productViewTrackerService = productViewTrackerService; _productService = productService; } public IViewComponentResult Invoke(int productId) { //Read from the product service Product productById = _productService.GetProductById(productId); //If the product exists we will log it if (productById != null) { //Setup the product to save var record = new ProductViewTrackerRecord(); record.ProductId = productId; record.ProductName = productById.Name; record.CustomerId = _workContext.CurrentCustomer.Id; record.IpAddress = _workContext.CurrentCustomer.LastIpAddress; record.IsRegistered = _workContext.CurrentCustomer.IsRegistered(); //Map the values we're interested in to our new entity _productViewTrackerService.Log(record); } return Content(""); } } } ``` ## Plugin installer ```csharp namespace Nop.Plugin.Other.ProductViewTracker { public class ProductViewTrackerPlugin : BasePlugin { private readonly ProductViewTrackerRecordObjectContext _context; public ProductViewTrackerPlugin(ProductViewTrackerRecordObjectContext context) { _context = context; } public override void Install() { _context.Install(); base.Install(); } public override void Uninstall() { _context.Uninstall(); base.Uninstall(); } } } ``` ## The usage The tracking code should be added to `ProductTemplate.Simple.cshtml` and `ProductTemplate.Grouped.cshtml` files. These ones are product templates. ```csharp @await Component.InvokeAsync("ProductViewTrackerIndex", new { productId = Model.Id }) ``` P.S. You can also implement it as a widget. In this case you won't need to edit a cshtml file. --- <!-- page: How to add a menu item into the administration area from a plugin | url: http://nopdocs.service.hedr.dev/en/developer/plugins/menu-item.html | source: en/developer/plugins/menu-item.md --> # How to add a menu item into the administration area from a plugin (for version 4.80 and above) To add menu items you should use **AdminMenuCreatedEvent** event. You can use the following code example which you should add to your plugins `*.cs` file. Then, You can also put any security (ACL) logic to this method. For example, validate whether the current customer has "Manage plugins" permission. ```csharp public class EventConsumer: IConsumer<AdminMenuCreatedEvent> { private readonly IPermissionService _permissionService; public EventConsumer(IPermissionService permissionService) { _permissionService = permissionService; } public Task HandleEventAsync(AdminMenuCreatedEvent eventMessage) { if (!await _permissionService.AuthorizeAsync(StandardPermission.Configuration.MANAGE_PLUGINS)) return; eventMessage.RootMenuItem.InsertBefore("Local plugins", new AdminMenuItem { SystemName = "YourCustomSystemName", Title = "Plugin Title", Url = eventMessage.GetMenuItemUrl("CONTROLLER_NAME", "ACTION_NAME"), IconClass = "far fa-dot-circle", Visible = true, }); return Task.CompletedTask; } } ``` > [!NOTE] > > In nopCommerce version 4.70 and below, the administration menu is built from the *sitemap.config* file which is located in *~/Areas/Admin folder*. > > To do the same, you can use the following sample code which you need to add in your plugins' `*.cs` file. First, implement the *IAdminMenuPlugin* interface in your plugin main class. > >```csharp > public class CustomPlugin : BasePlugin, IAdminMenuPlugin > { > > public Task ManageSiteMapAsync(SiteMapNode rootNode) > { > var menuItem = new SiteMapNode() > { > SystemName = "YourCustomSystemName", > Title = "Plugin Title", > ControllerName = "ControllerName", > ActionName = "List", > IconClass = "far fa-dot-circle", > Visible = true, > RouteValues = new RouteValueDictionary() { { "area", AreaNames.Admin } }, > }; > var pluginNode = rootNode.ChildNodes.FirstOrDefault(x => x.SystemName == "Third party plugins"); > if(pluginNode != null) > pluginNode.ChildNodes.Add(menuItem); > else > rootNode.ChildNodes.Add(menuItem); > > return Task.CompletedTask; > } >} > > ``` --- <!-- page: Adding CSS and JS resource files into nopCommerce Plugin | url: http://nopdocs.service.hedr.dev/en/developer/plugins/resource-files.html | source: en/developer/plugins/resource-files.md --> # Adding CSS and JS resource files into nopCommerce Plugin To load resource files correctly you need to add its references into your plugin's view files. You can use `AddScriptParts()` or `AddCssFileParts()` helper methods by `INopHtmlHelper`. - `@NopHtml.AddCssFileParts()` - `@NopHtml.AddScriptParts()` You can check into more details about this methods by going to its definition in your nopCommerce projects. ```js //Loading CSS file @NopHtml.AddCssFileParts("~/Plugins/{PluginName}/Content/{CSSFileName.Css}", excludeFromBundle: false); //Loading js file //Third parameter value indicating whether to exclude this script from bundling @NopHtml.AddScriptParts(ResourceLocation.Footer, "~/Plugins/{PluginName}/Scripts/{JSFileName.js}", excludeFromBundle: true); ``` If you want to add a resource link in the header then you can use **ResourceLocation.Head** and for footer you can use **ResourceLocation.Footer**. But what if you want to add external scripts to your page? In this case, you must disable the Tag Helper at the element level with the Tag Helper opt-out character ("!"): ```js <!script async src="https://www.googletagmanager.com/gtag/js"></!script> ``` > [!NOTE] > > If for some reason you want your script to be generated at the place where you added it, then in this case you must also use the `!` in the `script` attribute so that it is not processed by the built-in helper tag. If you want to place the specified resources in the `head` tag of the page, then you need to add the following code: ```js @NopHtml.GenerateScripts(ResourceLocation.Head) ``` Similarly, if you need to move resources to `Footer`: ```js @NopHtml.GenerateScripts(ResourceLocation.Footer) ``` If you just need to add your `js` code to the page, then here is an example of how to do it. Note that the location where it will be generated is specified in the `GenerateScripts` tag helper method. ```js <script> $(document).ready(function () { //enable "back top" arrow $('#backTop').backTop(); //enable tooltips $('[data-toggle="tooltip"]').tooltip({ placement: 'bottom' }); }); </script> @NopHtml.GenerateScripts(ResourceLocation.Footer) ``` --- <!-- page: Description of the structure of the plugin.json file | url: http://nopdocs.service.hedr.dev/en/developer/plugins/plugin.json.html | source: en/developer/plugins/plugin.json.md --> # Description of the structure of the `plugin.json` file This file contains the Meta information description for a plugin that is used by nopCommerce to determine which group this plugin belongs to if the plugin is compatible with the current version of nopCommerce or not, what is the version of the plugin and several other information. Each nopCommerce plugin must have this file. ## File Structure ```json { "Group": "Payment methods", "FriendlyName": "PayPal Commerce", "SystemName": "Payments.PayPalCommerce", "Version": "4.70.1", "SupportedVersions": [ "4.70" ], "Author": "nopCommerce team", "DisplayOrder": -1, "FileName": "Nop.Plugin.Payments.PayPalCommerce.dll", "Description": "" } ``` - **Group**. It is used by nopCommerce to identify or search or filter plugins by their group name in the plugin list under the `Admin/Configuration/LocalPlugin` menu. This may be your company name. - **FriendlyName**. It is the display name for the plugin. It is used to identify our plugin from the plugin list. - **SystemName**. It is used by nopCommerce to identify the plugin uniquely, so it needs to be unique from all other plugins. We cannot register more than one plugin with the same `SystemName`. - **Version**. This is the version number of the plugin, you can set this to any value you like. This number is used to identify which version of the plugin is currently installed in the nopCommerce application. However, we recommend sticking to the following format - `"{nopCommerce_version_number}.{build_number}"`. - **SupportedVersions**. It is an array of strings. It contains one or more than one version of nopCommerce that this plugin is supported on or we can say this plugin is a target for. During development ensure that the current version of nopCommerce in which you are developing this plugin is included in this list, otherwise, it will not be loaded in the plugin list. - **Author**. This is the information about the creator of the plugin. It may be a personal name or a company name or a team who created this plugin. - **DisplayOrder**. It is used to set the order in which this plugin should be displayed in the plugin list. Its value is of type number. - **FileName**. It has the following format **Nop.Plugin.{Group}.{Name}.dll** (it is your plugin assembly filename). - **Description**. It contains a short description of your plugin like what this plugin is all about, what this plugin does. This is shown in the Plugin list under the plugin name. - **LimitedToStores** - The list of store identifiers in which this plugin is available. If empty, then this plugin is available in all stores. - **LimitedToCustomerRoles** - The list of customer role identifiers for which this plugin is available. If empty, then this plugin is available for all ones. - **DependsOnSystemNames** - The list of plugins' system names that this plugin depends on. > [!TIP] > > After you edit your **plugin.json** file's content you need to set its `Copy to Output Directory` property value to `Copy if newer`. > ![image3](_static/plugin.json/plugin_json_0.jpg) > It is required because we need this file to be copied to the compiled directory from where nopCommerce can access this file to display our plugin in the plugin list in the admin panel. ## Examples - The **FixedOrByCountryStateZip** plugin has the following `plugin.json` file: ```json { "Group": "Tax providers", "FriendlyName": "Manual (Fixed or By Country/State/Zip)", "SystemName": "Tax.FixedOrByCountryStateZip", "Version": "4.70.1", "SupportedVersions": [ "4.70" ], "Author": "nopCommerce team", "DisplayOrder": 1, "FileName": "Nop.Plugin.Tax.FixedOrByCountryStateZip.dll", "Description": "This plugin allow to configure fix tax rates or tax rates by countries, states and zip codes" } ``` - The **Google Analytics** widget has the following *plugin.json* file: ```json { "Group": "Widgets", "FriendlyName": "Google Analytics", "SystemName": "Widgets.GoogleAnalytics", "Version": "4.70.1", "SupportedVersions": [ "4.70" ], "Author": "nopCommerce team, Nicolas Muniere", "DisplayOrder": 1, "FileName": "Nop.Plugin.Widgets.GoogleAnalytics.dll", "Description": "This plugin integrates with Google Analytics. It keeps track of statistics about the visitors and ecommerce conversion on your website" } ``` --- <!-- page: Designer's Guide | url: http://nopdocs.service.hedr.dev/en/developer/design/index.html | source: en/developer/design/index.md --> # Designer's Guide * [Overview (Designer's Guide)](xref:en/developer/design/overview) * [Installing / Applying theme in nopCommerce](xref:en/developer/design/installing-theme) * [Creating / Writing your own theme (using current / default theme)](xref:en/developer/design/new-theme) * [Understanding Layout / Design](xref:en/developer/design/understanding-layout) * [Customizing nopCommerce Themes](xref:en/developer/design/customizing-theme) * [Right To Left Theme](xref:en/developer/design/right-to-left-theme) * [Widgets (Designer's Guide)](xref:en/developer/design/widgets) * [Responsive Design](xref:en/developer/design/responsive) * [Tips and Tricks](xref:en/developer/design/tips-and-tricks) * [Contributing a Theme](xref:en/developer/design/contributing-theme) * [Entity events system](xref:en/developer/design/entity-events-system) --- <!-- page: Overview (Designer's Guide) | url: http://nopdocs.service.hedr.dev/en/developer/design/overview.html | source: en/developer/design/overview.md --> # Overview (Designer's Guide) ## What is a theme A theme is a collection of property settings that allow you to define the look of pages and controls and then apply the look consistently across pages in a Web application, across an entire Web application, or all Web applications on a server. Themes are made up of a set of elements: skins, cascading style sheets (CSS), images, and other resources. At a minimum, a theme will contain skins. Themes are defined in special directories on your Web site or your Web server. A theme can also include a cascading style sheet (`.CSS` file). When you put a `.CSS` file in the theme folder, the style sheet is applied automatically as part of the theme. You define a style sheet using the file name extension `.CSS` in the theme folder. (Source: [msdn.microsoft.com](https://msdn.microsoft.com)) ## Definition of a nopCommerce theme A nopCommerce theme is used for having a consistent layout and appearance across all pages or an entire website. nopCommerce theme consists of several supporting files, including style sheets for page appearance and supporting images. ![location-of-themes](_static/overview/location-of-themes.png) **Location of theme(s) in nopCommerce**: All themes are located under `[nopCommerce root folder]/Themes/`. --- <!-- page: Installing / Applying theme in nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/design/installing-theme.html | source: en/developer/design/installing-theme.md --> # Installing / Applying theme in nopCommerce Let's assume you just downloaded a new theme which is in a zip file. 1. Extract the contents of your zip file and copy it under the "Themes" folder as shown in the figure below: ![extracting-theme](_static/installing-theme/extracting-theme.jpg) 1. Go to the admin section (`http://www.yourdomain.com/admin`) 1. Go to Configuration → Settings → General And Miscellaneous settings 1. Select a new theme from the **Default Store Theme** and click **Save**. Now, go to the public store. You should be able to see the new theme on your website. --- <!-- page: Creating / Writing your own theme (using current / default theme) | url: http://nopdocs.service.hedr.dev/en/developer/design/new-theme.html | source: en/developer/design/new-theme.md --> # Creating / Writing your theme (using current/default theme) Open your nopCommerce solution or website (web version) in Microsoft Visual Studio - Go to this location: * If using source code: `\Nop.Web\Themes\` * If using web version: `\[Project Root]\Themes\` 1. Select any default / current theme ![step-1](_static/new-theme/new-theme-step-1.jpg) 1. Now, Right-click on the theme → select **COPY** ![step-2](_static/new-theme/new-theme-step-2.jpg) 1. Now select the "Theme" folder → right-click → **PASTE** ![step-3](_static/new-theme/new-theme-step-3.jpg) 1. You will get something like "Copy of default/current theme" ![step-4](_static/new-theme/new-theme-step-4.jpg) 1. Rename it - whatever you like to be the name of your new theme – For instance, let's say: MyFirstTheme ![step-5](_static/new-theme/new-theme-step-5.jpg) 1. Now inside your New theme folder "MyFirstTheme" → open `theme.json` ![step-6](_static/new-theme/new-theme-step-6.jpg) 1. Change the current/existing theme name with your new theme name "MyFirstTheme" ![step-7](_static/new-theme/new-theme-step-7.jpg) 1. Now, inside your new theme folder **"MyFirstTheme" → Content → Images** add your new images in the "images" directory and start updating/customizing your `style.css` according to your requirements. If you would like to test the changes → Go to the Admin section → Apply your new theme → Save the change and preview your public store. ![step-8](_static/new-theme/new-theme-step-8.jpg) --- <!-- page: Understanding Layout / Design | url: http://nopdocs.service.hedr.dev/en/developer/design/understanding-layout.html | source: en/developer/design/understanding-layout.md --> # Understanding Layout / Design What are layouts? Every web developer/designer wants to maintain a consistent look and feel across all of the pages within the website. Back in the day, the concept of "Master Pages" was introduced in ASP.NET 2.0 which helps in maintaining a consistent look of the website by mapping it with .aspx pages. Razor also supports this similar concept with a feature called "Layouts". It allows you to define a common site template and then inherit its look and feel across all the views/pages on your website. In nopCommerce, there are 2 different kinds of layouts: * `_ColumnsOne.cshtml` * `_ColumnsTwo.cshtml` All these 2 layouts are inherited from one main layout called: `_Root.cshtml`. The `_Root.cshtml` itself is inherited from `_Root.Head.cshtml`. `_Root.Head.cshtml` is the file you need to look into if you are linked CSS stylesheet and jquery files (you can add/link more `.css` and `.js` files here). The location of all these layouts in nopCommerce is as follows: `[nopCommerce root directory]/Views/Shared/...`. If you are using the source code version then: `\Presentation\Nop.Web\Views\Shared\...` * **Layout of _Root.cshtml** ![root-layout](_static/understanding-layout/root-layout.jpg) * **Layout of `_Root.cshtml` (in respect of css class)** ![root-layout-css](_static/understanding-layout/root-layout-css.jpg) Now the following 2 layouts override the body of `_Root.cshtml`: * `_ColumnsOne.cshtml` In this case, there is no change in the layout of the body, so the structure remains pretty much the same as `_Root.cshtml`: ![columns-one](_static/understanding-layout/column-one.jpg) * `_ColumnsTwo.cshtml` In this case, there are 2 columns in the body structure: ![column-two](_static/understanding-layout/column-two.jpg) --- <!-- page: Customizing nopCommerce Themes | url: http://nopdocs.service.hedr.dev/en/developer/design/customizing-theme.html | source: en/developer/design/customizing-theme.md --> # Customizing nopCommerce Themes ## Uploading your store logo To upload your store logo to a nopCommerce website, there are 2 methods: ### First Method Upload your logo through the admin area. See how to do this in the [Uploading your logo](xref:en/getting-started/design-your-store/uploading-your-logo) article. ### Second method 1. Go to nopCommerce root folder `/Themes/YOUR THEME/Content/images/` 1. Look for logo.png image file 1. Replace the `logo.png` with your store logo and name it as `logo.png` (with same width:250px and height:50px) If you wish to make changes in the stylesheet regarding the logo, look for the following code in your `styles.css`: ```css .header-logo { margin: 0 0 20px; text-align: center; } .header-logo a { display: inline-block; max-width: 100%; line-height: 0; /*firefox line-height bug fix*/ } .header-logo a img { max-width: 100%; opacity: 1; } ``` > [!IMPORTANT] > > You might have to clear the browser cache (or refresh the page using Ctrl+F5 keys) to see the changes (new store logo). ## How to change a layout 1. If you would like to customize/make changes in the base layout (i.e. `_Root.cshtml`) of your nopCommerce website look for this CSS code in your `styles.css` file ```css .master-wrapper-content { position: relative; z-index: 0; width: 90%; margin: 0 auto; } .master-column-wrapper { position: relative; z-index: 0; } .master-column-wrapper:after { content: ""; display: block; clear: both; } ``` 1. If you would like to customize/make changes in the layout of `_ColumnOne.cshtml`. Please look for this CSS code in your `style.css` ```css .center-1 { margin: 0 0 100px; } ``` 1. If you would like to customize/make changes in the layout of `_ColumnTwo.cshtml`. Please look for this CSS code in your `style.css` ```css .center-2, .side-2 { margin: 0 0 50px; } .side-2:after { content: ""; display: block; clear: both; } ``` ## How to make changes in the header menu (top menu) 1. If you would like to customize/make changes in the header menu (top menu) of your nopCommerce website, please go to the following location: Go to nopCommerce root folder `/Views/Shared/Components/TopMenu/Default.cshtml` 1. Open file `Default.cshtml` - You can add or remove menu items in `<li>` according to your requirements. ## How to make changes in the footer (or footer links) 1. If you would like to customize/make changes in a footer (or footer links) of your nopCommerce website, please go to the following location: Go to nopCommerce root folder `/Views/Shared/Components/Footer/Default.cshtml` 1. Open file `Default.cshtml` - You can add or remove links in `<li>` or complete `<ul>` according to your requirements. --- <!-- page: Right To Left Theme | url: http://nopdocs.service.hedr.dev/en/developer/design/right-to-left-theme.html | source: en/developer/design/right-to-left-theme.md --> # Right To Left Theme nopCommerce also supports the RTL version of the public store theme. nopCommerce default public store theme **DefaultClean** comes with the feature of a right to a left version style sheet. To enable the "Right to Left" version of the theme, please go to `Administration → Configuration → Languages`, click on **Edit** a language, and ensure that the **Right-to-Left** option is enabled. ![rtm-settings](_static/right-to-left-theme/rtm-settings.png) Now, if you see the public store, it will look like this: ![rtm-public](_static/right-to-left-theme/rtm-public.jpg) Styles used for RTL support are located in the `styles.rtl.css` file. ![rtm-css](_static/right-to-left-theme/rtm-css.jpg) --- <!-- page: Widgets (Designer's Guide) | url: http://nopdocs.service.hedr.dev/en/developer/design/widgets.html | source: en/developer/design/widgets.md --> # Widgets (Designer's Guide) > A widget is a stand-alone application that can be embedded into third-party sites by any user on a page. It's a small application that can be installed and executed within a web page by an end-user. (Wikipedia). In nopCommerce, a widget plugin allows you to embed 3rd party code/application in a public store in certain areas (for example, head tag, after the body tag, left column block, and right column block). Currently, default nopCommerce installation allows the store admin to embed few widget plugins: 1. Google Analytics 1. Swiper 1. Facebook Pixel ## Google Analytics Widget Google Analytics is a free website stats tool from Google. It keeps track of statistics about the visitors and eCommerce conversion on your website. This widget block can be rendered at: * HTML Header tag * After `<body>` end HTML tag. To configure Google Analytics Widget, go to `Administration → Configuration → Widgets`, click on **Configure** against **Google Analytics** and add your Google Analytics code. ## Swiper Swiper is a nice and clean jquery image slider for your website/homepage to display several images scrolling with unique transition effects. By default, nopCommerce comes with Swiper integration as a widget (Enabled by default) which allows you to display several images scrolling automatically on your homepage. ## Facebook Pixel *Facebook Pixel* is an analytics tool that tracks how users behave on the site: what pages they visit, what buttons and links they click on, what forms they fill out, and other actions. It allows you to create audiences for Facebook ad campaigns. --- <!-- page: Responsive Design | url: http://nopdocs.service.hedr.dev/en/developer/design/responsive.html | source: en/developer/design/responsive.md --> # Responsive Design **Understanding Responsive Design.** Responsive Web Design is simply a design of a website that changes its layout according to different screen sizes to fit the content properly when it comes to a desktop, smartphones, tablets, and other mobile devices. In this definition, there is a keyword here "properly" – In this context, "properly", means consistent. While working on a responsive design, the web developers have to make sure that the user experience of a website remains consistent throughout all the devices, irrespective of their screen size. (Source: [nopCommerce Blog](https://www.nopcommerce.com/why-a-responsive-design-should-be-a-priority-for-your-business-website)) * The number of mobile devices is increasing at a very fast pace and due to different screen sizes/screen resolution, a responsive design approach is used by web developers to keep the user experience the same or similar across the website. * Yes, nopCommerce default layout/theme does support a responsive design that is optimized for all screen sizes, and this approach is handled via media-queries in the CSS. This allows your online eCommerce store layout to display the content of your website by automatically adjusting the viewing area depending on the size of the screen. **Viewing the responsive design.** Just re-size your browser windows and keep decreasing its size. As the size of the browser windows will decrease, you will see the nopCommerce site will adjust the content accordingly. ![responsive](_static/responsive/Responsive.jpg) --- <!-- page: Tips and Tricks | url: http://nopdocs.service.hedr.dev/en/developer/design/tips-and-tricks.html | source: en/developer/design/tips-and-tricks.md --> # Tips and Tricks 1. One of the major issues in web development/designing is that different browsers use different default values for various CSS properties. While customizing or creating your theme – Always make sure that your styling is compatible with all the browsers. Test your website in major browsers like Edge, Firefox, Opera, Safari, and Chrome. 1. While working with CSS style sheets, if you don't see any change on your website – Do not panic. Try deleting the history and cookies of your browser and then try again by refreshing your page. 1. Make sure you understand the difference between id and classes. You can apply classes to multiple elements, while ids refer to only one element. 1. CSS style sheets do not allow you to start the name of your ids and classes with a number or other non-alphabetical character. 1. Do not limit yourself to span and div tags only. There are a lot of other / better features offered by CSS to style a page. > [!TIP] > > Make use of **Firefox Developer Tools** plug-in offered by Mozilla. It is a very useful tool that allows you to edit, debug, and monitor CSS, HTML, and JavaScript live on any web page. You can learn more about it here: [Firefox Developer Tools.](https://developer.mozilla.org/en-US/docs/Tools) > > Or you can use the **Chrome DevTools tool**, which is part of the Chrome browser. You can learn more about it here: [Chrome DevTools.](https://developers.google.com/web/tools/chrome-devtools) --- <!-- page: Contributing a Theme | url: http://nopdocs.service.hedr.dev/en/developer/design/contributing-theme.html | source: en/developer/design/contributing-theme.md --> # Contributing a Theme nopCommerce is supported by a very active community. So, any kind of contribution is highly appreciated. You can now share your theme with other users by [Marketplace](https://www.nopcommerce.com/marketplace) section of the nopCommerce website. Just go to [My account](https://www.nopcommerce.com/customer/info) page, then **Your contributions and extensions** tab. Click the **Upload a new extension** button to upload a new theme. --- <!-- page: Entity events system | url: http://nopdocs.service.hedr.dev/en/developer/design/entity-events-system.html | source: en/developer/design/entity-events-system.md --> # Entity events system ## OverView nopCommerce implements event-driven architecture which allows developers to subscribe or consume events broadcast by event publishers or event sources when some action/event is performed and also enables us to perform certain business logic when some specific event is triggered. In nopCommerce, we can subscribe or listen to various events published by the nopCommerce system event, or even we can write a logic that emits/publish an event which then can be listened to or subscribed to. For example, let's suppose we want to sync customer details to some other external system, so in that case, we can fire an event when new customer registers to our store or a customer change their profile. We can listen to that event and perform business logic which then can extract that newly created customer and send it to the external service for sync. And the best part is that we can do all these without changing the nopCommerce source code. Developers can either publish an event or consume an event: - To publish an event a developer will need to obtain an instance of **IEventPublisher** and call the **Publish** method with the appropriate event data. - To listen for an event the developer will want to create a new implementation of the generic **IConsumer** interface. Once a new consumer implementation has been created nopCommerce uses reflection to find and register the implementation for event handling. There are three event publisher extension methods that are used for data modification events named `EntityInsertedAsync`, `EntityUpdatedAsync` and `EntityDeletedAsync` with **BaseEntity** inherit of **IEventPublisher** interface which is responsible to broadcast the insert, updating, and deleting entity events respectively. ## EntityInsertedAsync This extension method takes the model entity of type `BaseEntity` as a parameter. This extension method is used to publish/broadcast the entity inserted event of type `BaseEntity` when new data is inserted. This extension method then invokes the parameterized constructor of the EntityInsertedEvent generic class and exposes the inserted entity by its Entity property. Which then can be subscribed/handled by the developer by implementing IConsumer interface of type EntityInsertedEvent of type Entity we recently inserted eg: `IConsumer<EntyInsertedEvent<BaseEntity>>`. Here `BaseEntity` can be any model class that inherits from the `BaseEntity` class. ### Publisher Implementation for EntityInserted Event ```cs public class MyFirstPublisherClass { IEventPublisher _eventPublisher; public MyFirstPublisherClass(IEventPublisher eventPublisher) { this._eventPublisher = eventPublisher; } public async Task MyFirstProductInsertMethod(Product product) { //Logic to insert goes here await _eventPublisher.EntityInsertedAsync(product); } } ``` In the above example, we are injecting the `IEventPublisher` Interface to get the instance of EventPublisher class using the constructor dependency injection mechanism. Here in `MyFirstProductInsertMethod` after completing the logic to insert product we are invoking the `EntityInserted` method with a generic type of `Product` (which needs to inherit from BaseEntity class) with newly created product object as a parameter. Now upon invoking this extension method, it will broadcast entity inserted event for product type and now whoever is subscribing/listening for this event will receive this product object as an event parameter. Now let's see how to consume this event. ### Consumer Implementation for EntityInserted Event ```cs public class MyFirstConsumerClass : IConsumer<EntityInsertedEvent<Product>> { public async Task HandleEventAsync(EntityInsertedEvent<Product> insertEvent) { //you can access entity using insertEvent.Entity var insertedEntity = insertEvent.Entity; //Here goes the business logic you want to perform... } } ``` Here we are creating a class that is inherent from `IConsumer<EntityInsertedEvent<Product>>`. `IConsumer` interface has only one method that needs to be implemented i.e. `HandleEvent` method. Now, whenever the EntityInserted event of type Product is fired this `HandleEvent` method will be invoked with `EntityInsertedEvent` of type product entity object. And here inside this class, we can perform our business logic for further processing of that data. ## EntityUpdatedAsync This extension method of the `IEventPublisher` interface is also implemented in the same way as EntityInserted. This extension method also takes the model entity of type `BaseEntity` as an argument/parameter. This extension method is used to publish/broadcast the entity updated event of type `BaseEntity` when an existing entity is updated. This extension method invokes the parameterized constructor of the `EntityUpdatedEvent` generic class and exposes the updated entity by its Entity property. Which then can be subscribed/handled by the developer by implementing IConsumer interface of type `EntityUpdatedEvent` of type `Entity` we recently inserted eg: `IConsumer<EntityUpdatedEvent<BaseEntity>>`. ### Publisher Implementation for EntityUpdated Event ```cs public class MyFirstPublisherClass { IEventPublisher _eventPublisher; public MyFirstPublisherClass(IEventPublisher eventPublisher) { this._eventPublisher = eventPublisher; } public async Task MyFirstProductUpdateMethod(Product product) { //Logic to insert goes here await _eventPublisher.EntityUpdatedAsync(product); } } ``` The implementation of this class is moreover the same as the example in the `EntityInserted`. Here in `MyFirstProductInsertMethod` after completing the logic to update the product we are invoking the `EntityUpdatedAsync` method with a generic type of with recently updated product object as a parameter. Now upon invoking this extension method, it will broadcast entity updated event for product type and now whoever is subscribing/listening for this event will receive this product object as an event parameter. Now let's see how to consume this event. ### Consumer Implementation for EntityUpdated Event ```cs public class MyFirstConsumerClass : IConsumer<EntityUpdatedEvent<Product>> { public async Task HandleEventAsync(EntityUpdatedEvent<Product> updateEvent) { //you can access entity using updateEvent.Entity var updatedEntity = updateEvent.Entity; //Here goes the business logic you want to perform... } } ``` Again this is also the same as the consumer class for entity inserted event. Here we are creating a class that inherits from `IConsumer<EntityUpdatedEvent<Product>>`. Now, whenever the `EntityUpdated` event of type `Product` is fired the `HandleEvent` method of this class will be invoked with the parameter of type `EntityUpdatedEvent` product entity object. And here inside this class, we can perform our business logic for further processing of that data. ## EntityDeletedAsync The logic to implement this extension method is also the same as the `EntityInsertedAsync` and `EntityUpdatedAsync` extension method of `IEventPublisher`. This extension method also takes the model entity of type `BaseEntity` as an argument. This extension method is used to publish/broadcast the entity deleted event of `BaseEntity` when an existing entity is deleted. This extension method invokes the constructor of the `EntityDeletedEvent` generic class and exposes the deleted entity by its Entity property. Which then can be subscribed/handled by the developer by implementing `IConsumer<EntityDeletedEvent<BaseEntity>>`. ### Publisher Implementation for EntityDeleted Event ```cs public class MyFirstPublisherClass { IEventPublisher _eventPublisher; public ExamplePublisherClass(IEventPublisher eventPublisher) { this._eventPublisher = eventPublisher; } public async Task MyFirstProductDeleteMethod(Product product) { //Logic to insert goes here await _eventPublisher.EntityDeletedAsync(product); } } ``` The implementation of this class is also the same as in the above example. Here in `MyFirstProductDeleteMethod` after completing the logic to delete the product we are invoking the `EntityDeleted` method with the product object we recently deleted as of a parameter. Now upon invoking this extension method, it will broadcast entity deleted event for product type and now whoever is subscribing/listening for this event will receive this product object as an event parameter. Now let's see how to consume this event. ### Consumer Implementation for EntityDeleted Event ```cs public class MyFirstConsumerClass : IConsumer<EntityDeletedEvent<Product>> { public async Task HandleEventAsync(EntityDeletedEvent<Product> deleteEvent) { //you can access entity using deleteEvent.Entity var updatedEntity = deleteEvent.Entity; //Here goes the business logic you want to perform... } } ``` Again this is also the same as the consumer class for entity inserted event or entity updated event. Here we are creating a class that inherits from `IConsumer<EntityDeletedEvent<Product>>`. Now, whenever the `EntityDeleted` event of type `Product` is fired the `HandleEvent` method of this class will be invoked with the parameter of type `EntityDeletedEvent` product entity object. And here inside this class, we can perform our business logic for further processing of that data. --- <!-- page: Web API documentation | url: http://nopdocs.service.hedr.dev/en/developer/web-api/index.html | source: en/developer/web-api/index.md --> # Web API documentation ## Introduction [Web API](https://www.nopcommerce.com/web-api) for nopCommerce provides access to all platform functions as well as full control over database entities. It is a RESTful API built according to the [OpenAPI 3.0 specification (OAS)](https://swagger.io/). Using a tool like Swagger UI or within the [SwaggerHub platform](https://swagger.io/tools/swaggerhub/) you can convert your OAS contract into an interactive API console that developers can use to interact with the API and quickly learn how the API is supposed to behave. nopCommerce offers a suite of APIs that allow developers to use and extend the platform’s built-in features. These APIs allow developers to read and write merchant data, interoperate with other systems and platforms, and add new functionality to nopCommerce. ## Available APIs (method coverage) The Web API framework provides integrators and developers the means to use web services that communicate with the nopCommerce system. ### Frontend methods The Web API Frontend offers you a way to implement the nopCommerce buying capabilities in any application, whenever it is a website or mobile app. Using the API is essential when sellers want to reach a wider audience and their requirements go beyond the standard nopCommerce functionality. The Web API Frontend provides methods that allow using the built-in public store functionality outside of the nopCommerce store. Even if you have customizations in your nopCommerce store you will be able to use this plugin since it is provided with the source code. After installing the plugin you will be able to see a list of the existing API methods using the following Swagger UI endpoint: **`{store location}/api/index.html`** > [!TIP] > > You can't use multi-factor authentication (MFA) through the Frontend API. ### Backend methods The Web API Backend provides access to all nopCommerce admin area functionality. Meaning, using the Web API Backend methods you can get full control over such functionality as customer management, creating and updating products, sales monitoring, and actually whatever you want to control in the admin area of the nopCommerce store. Use this API to build such applications as CRM and ERP systems, social network integrations, and other apps that require accessing the store business processes. After installing the plugin you will be able to see a list of the existing API methods using the following Swagger UI endpoint: **`{store location}/api/index.html`** > [!IMPORTANT] > > After installing the backend and frontend APIs, switching between them is implemented directly through the Swagger UI page in the dropdown list of available definitions. > ![image](./_static/index/SwaggerUI_1.png) #### Scopes and permissions To use the API, the client application should have appropriate permissions (ACL) in a nopCommerce store where the API plugin is installed. For example, to access backend (admin panel) methods through the API, a special "Access Web API Backend" permission is required. By default, this permission is provided for the administrator role only. You can change these settings through the standard ACL used in nopCommerce. ## Authentication To keep transactions on the nopCommerce platform safe and secure, all apps connecting with our APIs must authenticate when making API calls. To make a web API call from a client such as a mobile application, an API client has to prove its identity. To do this, the API provides an access token with each request in the Authorization header using the Bearer HTTP authorization scheme. This token acts like an electronic key that lets you access the API. After you install the Web API plugin, you need to generate a secret key on the plugin configuration page. This key will be used to sign and verify each JWT token. ### Request a token 1. Endpoint For each API, there is an unsecured endpoint that serves to obtain an access token: * **`/api-backend/Authenticate/GetToken`** * **`/api-frontend/Authenticate/GetToken`** 1. Content type The content type of the request body. Set this value to either `Content-Type:application/json-patch+json` 1. Credentials The username and password for a nopCommerce account. To specify these credentials in a JSON request body, include code similar to the following in the call: ```json { "username":"<user name>", "email":"<Email>", "password":"<password>" } ``` #### Examples The following example uses the curl command to request a token for a customer account: ```rest curl -X 'POST' \ 'http://localhost:15536/api-backend/Authenticate/GetToken' \ -H 'accept: application/json' \ -H 'Content-Type: application/json-patch+json' \ -d '{ "username": "admin@yourstore.com", "email": "admin@yourstore.com", "password": "123456" }' ``` ### Authentication token response A successful request returns a response body with the token, as follows: ```json { "username": "admin@yourStore.com", "customer_id": 1, "token": <authentication token> } ``` ### Using the token in a Web API request Any web API call accessing a resource that requires a permission level higher than anonymous should contain an authentication token in the header. To do this, the HTTP header is sent in the following format: ```rest curl -X 'GET' \ 'http://localhost:15536/api-backend/BlogPost/GetById/1' \ -H 'accept: application/json' \ -H 'Authorization: <authentication token>' ``` ## Testing The *Developer mode* is provided especially for the convenience of testing API endpoints. By activating this mode on the plugin configuration page, the token verification is essentially disabled. You can test the APIs using the following tools: 1. [Swagger UI](https://swagger.io/swagger-ui/). It offers a web-based UI that provides information about the service, using the generated OpenAPI specification. 1. [Postman](https://www.getpostman.com/). It is a tool for testing APIs. Below are instructions on how to use Postman to authenticate a user to get a JWT token from the API, and then make an authenticated request with the JWT token to retrieve a list of topics from the API. ### How to authenticate a user with Postman To authenticate a user and get a JWT token, follow these steps: 1. Open a *new request* tab by clicking the plus(+) button at the end of the tabs. 1. Change the HTTP request method to "POST" using the dropdown selector on the left of the URL input field. 1. In the URL field, enter the authentication URL of your API: **`{storeURL}/api-backend/Authenticate/GetToken`**. 1. Select the "Body" tab below the URL field, change the body type radio button to "raw", and change the format using the dropdown selector to "JSON (application/json)". 1. Enter a JSON object containing the test username and password into the "Body" textarea. 1. Click the "Send" button. You should receive a "200 OK" response with the user details including a JWT token in the response body. Copy the token value because we'll be using it in the next step to make an authenticated request. Here's a screenshot of Postman after the request is sent and the user has been authenticated: ![image](./_static/index/Postman_1.png) ### How to make an authenticated request to retrieve a topic by ID To make an authenticated request using the JWT token from the previous step, follow these steps: 1. Open a new request tab by clicking the plus (+) button at the end of the tabs. 1. Change the HTTP request method to "GET" using the dropdown selector on the left of the URL input field. 1. In the URL field, enter the “Get topic” URL of your API: `{storeURL}/api-backend/Topic/GetById/:id`. 1. Select the "Authorization" tab below the URL field, change the type to "Bearer Token" in the type dropdown selector, and paste the JWT token from the previous authentication step into the "Token" field. ![image](./_static/index/Postman_2.png) 1. Click the "Send" button. You should receive a "200 OK" response containing a JSON array with all the user records in the system (just the one test user in the example). Here's a screenshot of Postman after making an authenticated request to get a topic by id: ![image](./_static/index/Postman_3.png) ## License The Web API plugin is licensed under the [following terms](https://www.nopcommerce.com/web-api-license-terms). --- <!-- page: Mobile app documentation | url: http://nopdocs.service.hedr.dev/en/developer/mobile-app/index.html | source: en/developer/mobile-app/index.md --> # Mobile app documentation ## Introduction nopCommerce team provides a [mobile application for iOS and Android](https://www.nopcommerce.com/ecommerce-mobile-app). It will bring enormous value to your business. The mobile app is completely ready-to-go, so you can start selling your products and services straight away. Like the nopCommerce platform, the mobile app comes with the source code and offers unlimited customization options. What’s more, it can seamlessly adapt to your online store design and functionality. No coding or designing skills are required to integrate the app with your nopCommerce store, configure its content and features, publish it on the Google Play Store and App Store, and manage its workflow. Here are some other significant features that will ensure efficient mobile eCommerce launching, customization, and maintenance: - Build with latest version of Flutter and Dart - Compatible with Android and iOS - Used Riverpod (state management) features - Easy to use UI and beautiful Material design 3 - Token-Based Authentication - Internationalization support - Dark and Light theme support - Free icons ## Setup With the "nopCommerce mobile app" plugin, in addition to the "Web API Frontend" plugin, it is possible to manage some application settings. ![image](./_static/index/app_plugin.png) The following functions are available: 1. It is possible to transfer certain settings to the mobile application. This is done on purpose so as not to give access to absolutely all application settings. If you need additional settings, you must ensure that they are supported in the mobile application. 1. Slider control on the main screen. You can also specify which products users will go to if they click on each slider image. ## Visual Studio Code The recommended development environment for Flutter is [Android Studio](https://developer.android.com/studio). A convenient alternative is the VS Studio Code editor, below are the basic settings that help you comfortably work with the code, as well as a set of extensions necessary for development and debugging. ### Editor settings ```json { "[dart]": { "editor.codeActionsOnSave": { "source.fixAll": true }, "editor.selectionHighlight": false, "editor.suggest.snippetsPreventQuickSuggestions": false, "editor.suggestSelection": "first", "editor.tabCompletion": "onlySnippets", "editor.wordBasedSuggestions": false, }, "dart.warnWhenEditingFilesOutsideWorkspace": false, "dart.renameFilesWithClasses": "prompt", "editor.bracketPairColorization.enabled": true, "editor.inlineSuggest.enabled": true, "editor.formatOnSave": true, "explorer.compactFolders": false, "dart.debugExternalPackageLibraries": false, "dart.debugSdkLibraries": false, "editor.minimap.enabled": false } ``` ### Extensions For development, you will need to install the following extensions: Name: **Flutter**\ Id: Dart-Code.flutter\ Description: Flutter support and debugger for Visual Studio Code.\ Publisher: Dart Code\ VS Marketplace Link: <https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter> Name: **Dart**\ Id: Dart-Code.dart-code\ Description: Dart language support and debugger for Visual Studio Code.\ Publisher: Dart Code\ VS Marketplace Link: <https://marketplace.visualstudio.com/items?itemName=Dart-Code.dart-code> ## Start development and customization Open the source code from the archive that you will receive after purchasing the application in the Visual Studio Code editor. Immediately after opening the project in the code editor, you will be prompted to download the included libraries. You can also do it yourself by running the following command in the terminal: ```bash flutter pub get ``` Now you need to specify an endpoint to connect to the server to access the API. This setting is in the `lib\constants\app_constants.dart` file: ```dart class AppConstants { static const String storeUrl = 'https://yourstore.com'; } ``` Now everything is ready to run the application: ```bash flutter run ``` > [!IMPORTANT] > > Make sure the `paymentSettings.BypassPaymentMethodSelectionIfOnlyOne` setting is disabled. > > Another general recommendation for checkout flow settings: do not enable settings that disable or skip steps (for example, `ordersettings.disablebillingaddresscheckoutstep`). Such settings will have no effect in the mobile app. ## Project structure A mobile application developed on Flutter carries the functions of interacting with a public store using the Web API (Frontend). All the main processes of user interaction with the application are presented in the diagram below: ![image](./_static/index/app_flow.png) The approach that focuses on the fact that the functions of the application are root folders will be applied. And inside this folder, we describe the architectural layers inherent in this particular function in the form of subfolders. Thus, everything related to the functionality of interest to us is located in one folder, which greatly simplifies the understanding of the code. ![image](./_static/index/app_structure.png) ## Technology stack Frameworks & Libraries used: - Flutter SDK 3.35.1 - Dart SDK 3.9.0 - flutter_riverpod: 2.6.1 - go_router: 16.1.0 - flutter_secure_storage: 9.2.4 - dio: 5.9.0 > [!IMPORTANT] > > For correct operation of the application, it is recommended to use the package versions specified in the configuration. ## App architecture The application architecture is built according to generally accepted standards, described in the [Android documentation](https://developer.android.com/topic/architecture). Since the project uses the Riverpod state management system, the architecture has been extended and looks like this: ![image](./_static/index/app_arch.png) ## Navigation - go_router For navigation in the application, the [go_router](https://pub.dev/packages/go_router) library is used. It is a declarative routing system built on top of the [Flutter Router API](https://api.flutter.dev/flutter/widgets/Router-class.html). The navigation map in the app looks like this: ```bash ├─/splash (SplashScreen) └─ (ShellRoute) ├─/home ├─/catalog │ ├─/catalog/category/:id (CategoryDetailsScreen) │ ├─/catalog/manufacturer/:id (ManufacturerDetailsScreen) │ ├─/catalog/vendor/:id (VendorDetailsScreen) │ ├─/catalog/productsByTag/:id (ProductsByTagScreen) │ ├─/catalog/productSearch/:q (ProductsSearchScreen) │ └─/catalog/product/:id (ProductDetailsScreen) │ ├─/catalog/product/:id/review (ProductReviewScreen) │ └─/catalog/product/:id/addReview ├─/cart │ └─/cart/checkout └─/account ├─/account/logincheckout ├─/account/login │ └─/account/login/forgotPassword (ForgotPasswordScreen) ├─/account/register ├─/account/settings ├─/account/contactUs ├─/account/wishlist (WishlistScreen) ├─/account/accountInfo (AccountInfoScreen) ├─/account/accountAddresses (AccountAddressesScreen) │ └─/account/accountAddresses/createUpdateAddress/:id teAddressScreen) ├─/account/accountOrders (AccountOrdersScreen) │ └─/account/accountOrders/orderDetails/:id (OrderDetailsScreen) ├─/account/accountDownloadableProducts nloadableProductsScreen) ├─/account/accountBackInStock (AccountBackInStockScreen) ├─/account/accountRewardPoints (AccountRewardPointsScreen) ├─/account/accountChangePassword (AccountChangePassword) ├─/account/accountProductReviews (AccountProductReviewsScreen) ├─/account/accountGdprTools (AccountGdprToolsScreen) ├─/account/accountReturnRequests (AccountReturnRequestsScreen) └─/account/returnRequest/:id (ReturnRequestScreen) ``` ## Web API client generation Istall the [OpenAPI Generator](https://openapi-generator.tech/) (Requires [Node.js](https://nodejs.org/en/download/)) To update the version of OpenAPI Generator, use the following command and select the latest stable version from the list provided. ```bash openapi-generator-cli version-manager list ``` Create a file *openapitools.json*. Use the [dart-dio](https://openapi-generator.tech/docs/generators/dart-dio) generator. ```json { "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", "spaces": 2, "generator-cli": { "version": "7.14.0", "generators": { "frontend": { "input-spec": "swagger.json", "generator-name": "dart-dio", "output": "frontend_api", "additionalProperties": { "pubName": "frontend_api" } } } } } ``` > [!NOTE] > > To update the generator version, run the following command: > > ```bash > openapi-generator-cli version-manager list >``` It is necessary that the OpenAPI schema *swagger.json* be in the directory with the generator installed. 1. Call the following command to generate the client: ```bash openapi-generator-cli generate ``` 1. The standard openapi-generator will only generate base code that uses libraries that rely on Dart's own code generation. Therefore, after the completion of the base generation, it is necessary to start the Dart generator: ```bash cd frontend_api flutter pub get dart run build_runner build -d ``` As a result, we get a ready-made package, which will be located where you specified in the configuration file or console command. It remains to include it in *pubspec.yaml*: ```yaml frontend_api: # <- nopCommerce generated api library path: lib/frontend_api ``` ## Localization To localize the interface of the application itself, you need to place a file with locales in the `\lib\localization` folder. It is important that the file name is in the following format: `intl_`**{your_language_code_from_server}**`.arb` As a basis, you can take the *intl_en.arb* file already in the kit and translate its resources into the target language. Run the following command in a terminal to generate the required resource files for localization. ```bash flutter gen-l10n ``` You can make sure that all the necessary resources are generated correctly in the `lib\localization\generated\i18n` path. ![image](./_static/index/localization.png) > [!WARNING] > > Do not make any changes to this file as this part of the code is auto-generated. All localization changes should be made strictly in the `intl_`**{your_language_code_from_server}**`.arb` file located along the path `\lib\localization`. Now, when switching the language in the application settings, the application interface will also be localized. > [!IMPORTANT] > > The language code that will be embedded in the name of the localization file must match the one added on your server. Otherwise, the interface will be localized by the default locales (i.e. `en`). ## Designing the user interface To maintain a unified and consistent look across devices, we harnessed the potential of design tokens provided by Material 3. These tokens allow for storing styles, fonts, and animation values, enabling us to use the same style values in both design files and code. Using tokens provides several advantages: - Consistency: Tokens ensure consistent design across screens and components. - Theming: Easily switch between light/dark/dynamic themes by swapping the ColorScheme or ThemeData. - Maintainability: Change the look of the entire app from one place (no need to search and replace color codes). - Design/Dev collaboration: Tokens serve as a bridge between Figma and Flutter. ### Integrating Tokens from Design Tools **Material Theme Builder** (MTB) is a designer/developer tool for creating Material Design 3 (M3) color & type tokens and exporting them as code (Flutter, Compose, Android XML, design tokens, etc.). It helps you produce coordinated light/dark `ColorScheme`s from a seed/brand color, preview components, and export ready-to-use artifacts for implementation. #### Generate a color scheme 1. Open the **[Material Theme Builder](https://m3.material.io/theme-builder)**. 1. Pick a seed / primary color - Enter a hex value, use the color picker, or use an eyedropper. The seed (primary) color is the single starting point from which tonal palettes are generated. ![image](./_static/index/color-picker.png) - You can also enable *dynamic color* input (wallpaper/image) or import an image to extract colors — MTB will derive tonal palettes from that source. ![image](./_static/index/source-image.png) 1. Choose or tweak secondary / tertiary / error / neutral colors MTB shows slots for common roles (secondary, tertiary, error, neutral, etc.). You can accept automatically-generated values or override specific role colors (enter hex values manually). The builder keeps role relationships consistent with M3 rules. ![image](./_static/index/core-colors.png) Here you need to select the base colors for the entire scheme. You can enter them manually, for example, if your brand colors are already defined. On the **Dynamic** panel, you can upload an image and extract colors from it. It is recommended to use the service [https://coolors.co/](https://coolors.co/) to generate harmonious colors. Сlick **Start the generator**: ![image](./_static/index/make_colors.png) You can delete the extra blocks until only 3 remain, and then press the spacebar to generate variations. 1. Switch between Light and Dark previews Toggle Light/Dark to immediately see both schemes; ![image](./_static/index/light-scheme.png) MTB generates paired light/dark `ColorScheme`s so contrast & visual hierarchy are preserved across brightness modes. ![image](./_static/index/dark-scheme.png) 1. Preview components and surfaces The builder has live previews (app bars, buttons, chips, cards, list items, navigation bars, dialogs). Use them to validate how your palette behaves on surfaces, text, icons, and interactive controls. ![image](./_static/index/preview-components.gif) 1. Use color-matching / harmonization If you have brand colors that clash with generated tonal palettes, MTB offers color-matching or harmonization modes that nudge palettes to harmonize with brand hues while still following M3 tonal rules. This is useful when starting from multiple brand colors. ![image](./_static/index/extended-colors.png) 1. Typography Select base font family. MTB can produce tokens for typography (weights, sizes, line heights) to accompany your color tokens. ![image](./_static/index/choose-fonts.png) 1. Export Choose the export format - **Flutter (Dart)**, then export/download a ZIP with code artifacts and token files. For Flutter, the builder typically generates `theme.dart` that you can drop into your project. ![image](./_static/index/export.png) #### Overview of the theme.dart file Once you've created your color palette in *Material Theme Builder* and exported it, you'll get a `theme.dart` file. This file is the starting point for styling your app. Typically, its main content is two `ColorScheme` objects: - `lightScheme`: Defines a set of colors for your app's light theme (e.g. background, text, and accent colors in light mode). - `darkScheme`: Defines the same colors for your dark theme. These schemes are generated based on the seed color you choose and ensure a harmonious and consistent color combination throughout your app, following the principles of Material Design 3. #### Integration `theme.dart` into the project To keep your project structure organized, it is recommended to store theme-related files in a separate directory. Peplace the generated `ColorScheme` objects from `theme.dart` into - `lib/themes/material_theme.dart`. As your design system grows, you may need to introduce custom tokens (e.g., specific brand colors, semantic states). Use extensions. This code demonstrates which extension tokens are used in the mobile application. ```dart ThemeData theme(ColorScheme colorScheme) => ThemeData( useMaterial3: true, brightness: colorScheme.brightness, colorScheme: colorScheme, textTheme: textTheme.apply( bodyColor: colorScheme.onSurface, displayColor: colorScheme.onSurface, ), scaffoldBackgroundColor: colorScheme.surface, canvasColor: colorScheme.surface, // defailt extensions - BEGIN extensions: [ CustomColors( subTextColor: colorScheme.onSurfaceVariant, ratingStarColor: colorScheme.secondary, pictureIndicatorColor: colorScheme.surfaceContainerHighest, pictureIndicatorCurrentColor: colorScheme.primary, inStockColor: colorScheme.tertiary, outOfStockColor: colorScheme.error, ), ], // defailt extensions - END ); ``` >[!NOTE] > > You can use the entire contents of the `theme.dart` file, but don't forget to include the default extensions that are available in the `custom_color_scheme.dart` file. That’s it — restart the application and enjoy your new color scheme. ## Publishing to the Google Play Store The process for releasing your Flutter app on the Google Play Store involves preparing, building, and then uploading your application to the Google Play Console. Key Steps: 1. Sign Up for a Google Play Developer Account: You'll need to register for a developer account. 1. Prepare the App for Release: This includes configuring the app's name, icon, and version number in the `pubspec.yaml` file and setting up necessary permissions. 1. Sign the Application: You must generate an upload keystore and sign your app with it to verify your identity. 1. Build the Release Version: Use the `flutter build appbundle` command to create an Android App Bundle (*.aab*) of your application. 1. Publish on the Google Play Console: Create a new app listing in your Play Console, fill out all the required store listing details (title, description, screenshots, privacy policy), and upload your *.aab* file for review. Official Documentation: [Build and release an Android app](https://docs.flutter.dev/deployment/android) ## Publishing to the Apple App Store Deploying to the Apple App Store requires enrolling in the Apple Developer Program and using Xcode to manage the final steps of the process. Key Steps: 1. Enroll in the Apple Developer Program: This is a paid annual subscription that grants you access to publish on the App Store. 1. Configure the Project in Xcode: Open the `ios` folder of your project in Xcode to set up the Bundle ID, version number, and code signing settings. 1. Create an App Store Connect Listing: Log in to App Store Connect to create a new app record. Here, you will enter all the metadata for your app, such as its name, description, screenshots, keywords, and privacy information. 1. Build and Archive the App: Use Xcode to create a build archive (*.ipa*) of your application. 1. Upload to App Store Connect: Upload the archived build using Xcode or the Transporter tool. 1. Submit for Review: Once the build is processed and all metadata is complete, you can submit the app to Apple for review. Official Documentation: [Build and release an iOS app](https://docs.flutter.dev/deployment/ios) --- <!-- page: Microsoft Dynamics 365 | url: http://nopdocs.service.hedr.dev/en/developer/ms-dynamics-365/index.html | source: en/developer/ms-dynamics-365/index.md --> # Microsoft Dynamics 365 [Dynamics 365](https://www.microsoft.com/en-us/dynamics-365) is a portfolio of intelligent business applications that delivers superior operational efficiency and breakthrough customer experiences enabling businesses to become more agile and reduce complexity without increasing costs. This section describes how to integrate the Dynamics 365 plugin into your store. Please get the [official integration with Dynamics 365](https://www.nopcommerce.com/microsoft-dynamics-365). ## What the Dynamics 365 plugin does The Dynamics 365 plugin for nopCommerce allows the store owner to unidirectionally synchronise the following data between your nopCommerce store and Dynamics 365: - Customers. - Products. - Orders. ## Connecting to Microsoft Dataverse To synchronize your store’s data to Dynamics 365, you need to connect to a Dataverse environment which requires the URL to the environment and credential information for a user account with access to that environment. To connect to Microsoft Dataverse, you can either use credentials for an ordinary user or create an app user through Microsoft Entra ID. Using credentials for an ordinary user, isn’t the recommended approach as it would need a paid license. To overcome this limitation, you can create a special application user that is bound to a Microsoft Entra ID registered application and use a key secret configured for the app. Another benefit of this approach is that it doesn't require a paid license. When you create client applications that use Dataverse web services you need to authenticate to gain access to data. OAuth is the preferred means to authenticate because it provides access to all web services. > [!NOTE] > > Client applications must support using of OAuth to access data using the Web API. > OAuth requires an identity provider for authentication. For Dataverse, the identity provider is Microsoft Entra ID. ### Requirements to connect as an app To connect as an app you will need: - A registered app - A Dataverse user bound to the registered app - Connect using either the application secret ## App Registration When you connect using OAuth, you must first register an application in your Microsoft Entra ID tenant. For an app to authenticate with Dataverse and gain access to business data, you must first register the app in Microsoft Entra ID. That app registration is then used during the authentication process. Creating a client application facilitates authentication and authorization and you can grant access permissions accordingly. ### Steps to Create an app Registering your application establishes a trust relationship between your app and the Microsoft identity platform. The trust is unidirectional: your app trusts the Microsoft identity platform, and not the other way around. Once created, the application object cannot be moved between different tenants. 1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) 1. Browse to **Identity > Applications > App registrations and select New registration**. 1. Enter a display **Name** for your application. 1. Specify who can use the application - Accounts in any organizational directory 1. Don't enter anything for **Redirect URI (optional)**. You'll configure a redirect URI in the next section. 1. Select **Register** to complete the initial app registration. ![image](./_static/register_app.png) When registration finishes, the Microsoft Entra admin center displays the app registration's **Overview** pane. You see the **Application (client) ID**. Also called the *client ID*, this value uniquely identifies your application in the Microsoft identity platform. ![image](./_static/app_overview.png) ### Configure application 1. On the **Overview** page under **Essentials**, select the **Add a Redirect URI link**. Set the redirect URI by first selecting **Add a platform**, entering a URI value, and then selecting **Configure**. Use a URI value of `http://localhost`. 1. On the **Overview** page of your newly created app, hover the cursor over the **Application (client) ID** value, and select the copy to clipboard icon to copy the ID value. Record the value somewhere. You need to specify this value later. 1. Add credentials. Credentials allow your application to authenticate as itself, requiring no interaction from a user at runtime. ![image](./_static/app_client_secrets.png) - In the Microsoft Entra admin center, in **App registrations**, select your application. - Select **Certificates & secrets > Client secrets > New client secret**. - Add a description for your client secret. - Select an expiration for the secret or specify a custom lifetime. - Client secret lifetime is limited to two years (24 months) or less. You can't specify a custom lifetime longer than 24 months. - Microsoft recommends that you set an expiration value of less than 12 months. - Select **Add**. > [!NOTE] > > Record the secret's value for use in your client application code. > This secret value is never displayed again after you leave this page. 1. Then switch to **Manage > Manifest** where we can see many properties. Our concern here is **allowPublicClient**. Set *allowPublicClient* to *true* and **save**. ![image](./_static/manifest.png) 1. Lastly in **Manage > API permissions > Add permission** then search for **Dynamics CRM** and select **user_impersonation** and add it. ![image](./_static/api_permission.png) 1. Also, grant admin consent for your organization since without admin consent the connection might raise errors. ![image](./_static/request_api_permission.png) ### Create a new app user Follow these steps to create an app user and bind it to your app registration. 1. Log into the [Power Platform admin center](https://admin.powerplatform.microsoft.com/) using an account in the same tenant as your app registration. 1. Select **Environments** in the left navigation pane, and then select the target environment in the list to display the environment information. 1. Select the **S2S** link on the right side of the page. ![image](./_static/power_platform_admin_center_environments.png) 1. Select **New app user**. 1. On the Create a new app user slide-out, select **+ Add app**. 1. Start typing the name of your app registration in the search field, and then select (check) it within the results list. Next, select **Add**. ![image](./_static/environment_app_user.png) 1. Back on the **Create a new app user** slide-out, select the target **Business unit** from the drop-down and add a security role for the app user (also known as a service principle). 1. Select **Save** and then **Create**. You should see your new application user in the displayed list of application users. ![image](./_static/environment_business_unit.png) 1. In the end, a notification pops up confirming that Power Apps is linked with our client application successfully. ![image](./_static/environment_app_user_successfull.png) ## Dynamics 365 Sales and Business Central integration setup The Microsoft Dynamics 365 plugin by nopCommerce supports synchronization with two main Dynamics 365 applications - Business Central and Sales. Dynamics 365 Business Central is a complete ERP solution for managing finances, operations, and inventory. Dynamics 365 Sales is a CRM solution that offers sales process automation, customer behavior insights, and sales performance tracking. ![image](./_static/sales_hub.png) ### Connect Microsoft Dataverse with Dynamics365 Business Central Integration with Business Central is through Dataverse, and there are many default settings and tables provided by the integration. Choose **Settings -> Advanced settings** in Business Central. ![image](./_static/advanced_settings.png) > [!NOTE] > > Choose **Settings -> Assisted setup** in Business Central. > You can also find the "Connect with other systems" settings group to learn more about integration options. > ![image](./_static/assisted_setup.png) The integration with Business Central is through Dataverse, and there are many default settings and tables provided by the integration. Therefore, you must first configure the connection to Dataverse. > [!WARNING] > > Do not try to connect to *Dynamics 365 Sales* first. ![image](./_static/dataverse_connection_setup.png) Choose **Next**. ![image](./_static/dataverse_connection_setup_1.png) Click "Install Bussiness Central Virtual Table". ![image](./_static/dataverse_connection_setup_2.png) Select your Dynamics 365 environment URL, then choose **OK**. Log in with an administrator user account and give permission to the application that will be used to connect to Dataverse. Choose **Sign in with administrator user**. ![image](./_static/dataverse_connection_setup_3.png) You can check this link in the [Power Platform Admin Center](https://admin.powerplatform.microsoft.com/environments). After *Sign in with administrator user* turns green and bold, choose **Next**. ![image](./_static/dataverse_connection_setup_3_1.png) Choose an ownership model. **Team** is recommended. ![image](./_static/dataverse_connection_setup_4.png) Choose **Finish** to complete the Setup. ![image](./_static/dataverse_connection_setup_5.png) You can try to test the connection to Dataverse. Go to the **Dataverse Connection Setup** page to check your setup. ![image](./_static/dataverse_connection_setup_6.png) Now you can open Dataverse pages in Business Central. ![image](./_static/dataverse_connection_setup_7.png) ### Connection to Dynamics 365 Sales Once the Dataverse integration setup is complete, you can begin the integration with Dynamics 365 Sales. Choose **Set up a connection to Dynamics 365 Sales** on the **Assisted Setup** page. ![image](./_static/sales_connection_setup_1.png) All integration setup steps are similar to the integration with Dataverse. You need to specify the same environment as last time. As a result, if everything went without errors you will see that both your connections are configured and working correctly. ![image](./_static/sales_connection_setup_2.png) ![image](./_static/sales_connection_setup_3.png) Now you can open Dynamics 365 Sales pages in Business Central. ![image](./_static/sales_connection_setup_4.png) For example, **Products – Microsoft Dynamics 365 Sales**: ![image](./_static/sales_connection_setup_5.png) For example, **Sales Order – Microsoft Dynamics 365 Sales**: ![image](./_static/sales_connection_setup_6.png) > [!NOTE] > > To ensure that the integration process works correctly, make sure that the following lines are present in the settings on the "All Solutions" page: > ![image](./_static/sales_connection_setup_7.png) > > The Job Queue Entries will be created automatically: > ![image](./_static/sales_connection_setup_8.png) ### Currency Ensure that Business Central and Dataverse currencies match to avoid synchronization errors. Make sure of this by going to the following settings. ![image](./_static/currencies.png) The organization’s base currency in Dynamics 365 Sales can only be set when the organization is created. ![image](./_static/currencies_1.png) ## Plugin installation This section describes how to integrate the Dynamics 365 service into your store. 1. [Purchase the integration](https://www.nopcommerce.com/microsoft-dynamics-365). 1. Download the plugin archive. 1. Go to **Admin area > Configuration > Local plugins**. 1. Upload the plugin archive using the "Upload plugin or theme" button. 1. Scroll down the list of plugins to find the newly uploaded plugin. 1. Click on the **Install** button to install the plugin. ![Find the plugin](_static/plugin_list.png) ## How to configure the plugin Click the **Configure** button. You will see the *Configure - Dynamics 365* window: ![Find the plugin](_static/plugin_disconnected.png) To use Dynamics 365 with nopCommerce, you will first need to register and set up your account in MS Dynamics 365 as described earlier and enter all the necessary settings in the fields on the plugin configuration form: - **Application (client) ID**. The registered client ID on Azure portal. - **Directory (tenant) ID**. The registered tenat ID on Azure portal. - **Client secret**. Client secret for Application ID. A secret string that the application uses to prove its identity when requesting a token. - **Environment URL**. Direct URL of Dataverse instance to connect too. - **Currency code**. Displays the primary currency code of the your store. > [!NOTE] > > If you change the primary currency of the store, the plugin settings will be updated only after you save them. - **Image sync enabled**. Determine whether to synchronize images of the selected products by default. - **Check Dynamics product exists enabled**. When this setting is enabled, when synchronizing orders, the presence of records in Dataverse about the products included in the order will be checked. ATTENTION: this will significantly increase traffic and negatively affect performance. - **Enable auto synchronization**. Determine whether to enable auto synchronization. If disabled, synchronization must be started manually on this page. - **Auto synchronization period**. Set the period (in minutes) for auto synchronization. Click the **Save** button. ![Find the plugin](_static/plugin_connected.png) Go to the **Synchronization** panel to synchronize your nopCommerce customers, products, and orders with your Dynamics 365 environment. ![Find the plugin](_static/plugin_connected_sync.png) ## Contacts sync The plugin implements the initial import of all existing contacts (customers). It is performed when the user has just installed the plugin and wants to import all existing store contacts into Dynamics 365. Then, adding and editing customers is performed automatically according to the corresponding event. ![image](_static/sales_hub_contacts.png) ## Products sync The plugin implements the import of products. Synchronization of two types of products is supported: - Simple products - Group product ![image](_static/sales_hub_products.png) In the plugin track a number of events to notify the Dynamics 365 service: - Create product. - Changing a product (increasing the quantity, adding images, etc.). ## Orders sync In the plugin track a number of events to notify the Dynamics 365 service: - Placing an order. - Payment of an order. - Canceling an order. - Finalizing the order processing. - Changing the order status. ![image](_static/sales_hub_orders.png) ### Scenarios for changing order statuses to transfer them to Dynamics 365 The diagram below shows the relationship between order status changes in the nopCoomerce system and Dynamcs 365. ![Find the plugin](_static/Dynamics_365_Order_status.png) > [!NOTE] > > There is a limitation on deleting orders with a Paid status; such paid orders cannot be deleted from the Dynamics 365 system. --- <!-- page: Contribute | url: http://nopdocs.service.hedr.dev/en/developer/contribute/index.html | source: en/developer/contribute/index.md --> # Contribute You are more than welcome to contribute to the success of nopCommerce by helping out in the realization of the project, by participating in the forums, or just by spreading the word! If you have a site, write about us or place a hyperlink! We are committed to nurturing the growth of the nopCommerce community! nopCommerce has a young but growing community of contributors. It is a very active community that is passionate about developing a very robust .NET Core open source eCommerce application. nopCommerce has had over 30,000 downloads in the last month, so it's pretty popular. So join the community and see what you can learn and what you can share! * [Possible ways to contribute](xref:en/developer/contribute/possible-ways) * [Sharing your plugins, themes, and language packs](xref:en/developer/contribute/sharing) * [Working with source code and contributions](xref:en/developer/contribute/source-code) --- <!-- page: Possible ways to contribute | url: http://nopdocs.service.hedr.dev/en/developer/contribute/possible-ways.html | source: en/developer/contribute/possible-ways.md --> # Possible ways to contribute ## Here are a few ways you can contribute to the nopCommerce project * If you have a site, write about us or place a hyperlink * Answer a question on our [forums](http://www.nopcommerce.com/boards/). * Help us verify submitted fixes for bugs. * Share an idea for a new feature or a better way to do something on the [forums](http://www.nopcommerce.com/boards/). * Create a new language pack. * Create a new graphical theme to share with the community. * Implement a new plugin (payment gateway module, etc). * Tell your friends about nopCommerce. * Our logos. PNG: [250x250](http://www.nopcommerce.com/images/nopLogos/nopcommerce_logo_250x250-trans.png) and [340x140](http://www.nopcommerce.com/images/nopLogos/nopcommerce_logo-340x140-trans.png). PSD: [250x250](http://www.nopcommerce.com/images/nopLogos/250x250.psd) and [340x140](http://www.nopcommerce.com/images/nopLogos/340x140.psd) and [1600x1200](http://www.nopcommerce.com/images/nopLogos/1600x1200.psd) --- <!-- page: Sharing your plugins and themes | url: http://nopdocs.service.hedr.dev/en/developer/contribute/sharing.html | source: en/developer/contribute/sharing.md --> # Sharing your plugins and themes You can easily upload your plugin to our [Marketplace](http://www.nopcommerce.com/marketplace) directory to share it with other users. Just go to [My account](http://www.nopcommerce.com/customer/info) page, then "Your extensions" tab. Click the "Upload a new extension" button to upload a new extension. And here are some of the benefits of hosting your plugin at the [Marketplace](http://www.nopcommerce.com/marketplace) directory: * Track basic statistics regarding how many people are downloading * Give your plugin greater exposure to the community * Get your plugin rated against the many other hosted plugins * Provide a centralized location for users to leave comments and feedback nopCommerce team examines each extension for quality and makes sure that it meets all our requirements (including the documentation and images). If your submission does not pass our reviews, we will tell you why, and how to fix it. Otherwise, your successful submissions will be listed on our marketplace. Please find a complete list of our requirements and information about the review process [here](https://www.nopcommerce.com/submitting-plugins-to-nopcommerce-marketplace). --- <!-- page: Working with source code and contributions | url: http://nopdocs.service.hedr.dev/en/developer/contribute/source-code.html | source: en/developer/contribute/source-code.md --> # Working with source code and contributions ## Checking out source code nopCommerce manages a repository at GitHub ([https://github.com/nopSolutions/nopCommerce](https://github.com/nopSolutions/nopCommerce)). So you can always check out the latest source code! Git SCM (Source Code Management) access is public and allows you to fetch in real-time the latest version of nopCommerce! It allows you to follow daily nopCommerce developments and improvements. Get the latest patches, fixes without waiting for the next release. If you're not familiar with Git, there's good and free documentation [here](https://git-scm.com/docs). Also, find more info about GitHub support [here](https://opensource.guide/how-to-contribute/). Please note that these versions should not be used in a production environment. We do not guarantee that any of the functionality or code found in our SCM (Source Code Management) will be made available in our official releases. The best way to get the source code is to clone the repository. Git comes with built-in GUI tools for committing (git-gui) and browsing (gitk), but there are several third-party tools for users looking for a platform-specific experience. Please find them at [https://git-scm.com/downloads/guis](https://git-scm.com/downloads/guis) (we use [SourceTree](https://www.sourcetreeapp.com/)). ## Branch Descriptions and Naming Recently we started using Vincent Driessen's branching model (seen here: [http://nvie.com/posts/a-successful-git-branching-model/](https://nvie.com/posts/a-successful-git-branching-model/)) including the use of feature branches, a development branch (for integration), and a master branch (for publishing/production). Previously we had a "master" branch only (till January 2016) * Production branch: master * Development branch: develop * Branches for work items (issues): Should start with "issue". It should be followed by issue ID (according to our Github issue list) and some friendly names (example, "multistore"). Finally, it should look like "issue-35-paypal-redirection-bug" * Release branches: Should start with "release". It should be followed by version number (example, "3.00"). Finally, it should look like "release-3.00" ## Forking and submitting pull requests If you want to contribute some source code to nopCommerce core (issue fix or some new feature), then you should follow the next approach. Here is a shortlist of steps to contribute: * First of all, you have to create a fork. Please find more about repository forking on GitHub at [https://help.github.com/articles/fork-a-repo/](https://help.github.com/articles/fork-a-repo/). * Clone it locally. * Create a new branch from "develop". Please always create a new branch for each contribution. You should create it from our "develop" branch only. Do not use "master". * Write the code and push back to your GitHub fork. * Create pull request. Please read more about it at [https://help.github.com/articles/using-pull-requests/](https://help.github.com/articles/using-pull-requests/). And please always sync with our repository before doing it. --- <!-- page: How to write a Tax Plugin for nopCommerce 4.20 | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-tax-plugin-4.20.html | source: en/developer/plugins/how-to-write-tax-plugin-4.20.md --> # How to write a Tax Plugin for nopCommerce To extend nopCommerce functionality, plugins are used. There are various types of plugins like "PickupInStore" and "PayPal Standard" which are already contained in the nopCommerce distro. You can also search various plugins on the [nopCommerce official site](https://www.nopcommerce.com/marketplace) to see if someone has already created a plugin that suits your needs. If you haven't found one, then you are at the right place because this article will guide you through the process of creating a plugin, especially a tax plugin, according to your need. ## The plugin structure, required files, and locations 1. Start by creating a new "Class Library" project in the solution. It is recommended to place your plugin in the **Plugins** directory, located in the root folder of the source, where other plugins and widgets already reside. ![image1](_static/how-to-write-a-tax-plugin-4.20/image1.png) > [!NOTE] > Do not get confused this directory with the one which exists in the `Presentation\Nop.Web` directory. The Plugins directory in the Nop.Web directory contains the plugin's compiled files. A recommended name for a plugin project is `Nop.Plugin.{Group}.{Name}`. `{Group}` is your plugin group (for example, `Payment` or `Shipping`). `{Name}` is your plugin name (for example, `FixedOrByCountryStateZip`). For example, `FixedOrByCountryStateZip` tax plugin has the following name: `Nop.Plugin.Tax.FixedOrByCountryStateZip`. But please note that it's not a requirement. And you can choose any name for a plugin. For example, `MyFirstTaxPlugin`. The Plugins directory structure of a solution looks like the following. ![image2](_static/how-to-write-a-tax-plugin-4.20/image2.png) 1. Once the plugin project is created, the **.csproj** file content should be updated using any available text editor application. Replace the content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>..\..\Presentation\Nop.Web\Plugins\PLUGIN_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(MSBuildProjectDirectory)\..\..\Build\ClearPluginAssemblies.sproj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(MSBuildProjectDirectory)\ $ (OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!NOTE] > The **PLUGIN_OUTPUT_DIRECTORY** should be replace by the plugin name, for example, `Tax.FixedOrByCountryStateZip`. 1. After updating the **.csproj** file, the `plugin.json` file should be added which is required for the plugin. This file contains meta-information describing your plugin. Just copy this file from any other existing plugin/widget and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json). 1. The last required step is to create a class that implements `BasePlugin` (`Nop.Core.Plugins` namespace) and `ITaxProvider` interface (`Nop.Services.Tax` namespace). **ITaxProvider** implements the `GetTaxRate` method which returns type **CalculateTaxResult** (contains tax rate, errors if any, and `Boolean` success status) based on the custom logic, usually based on the customer address. ## Handling requests. Controllers, models, and views Now you can see the plugin by going to **Admin area** → **Configuration** → **Local Plugins**. ![image4](_static/how-to-write-a-tax-plugin-4.20/image4.png) When a plugin/widget is installed, you will see the **Uninstall** button. It is a good practice that you uninstall plugins/widgets which are not necessary for performance improvement. ![image5](_static/how-to-write-a-tax-plugin-4.20/image5.png) There will be the **Install** and **Delete** buttons when a plugin/widget is not installed or uninstalled. > [!NOTE] > Deleting will remove physical files from the server. But as you guessed our plugin does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the plugin. What we need to do now is create a controller, a model, a view, and a view component. * MVC controllers are responsible for responding to requests made against an `ASP.NET MVC` website. Each browser request is mapped to a particular controller. * A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an `ASP.NET MVC` application. * A view component that implements **NopViewComponent** which contains logic and codes to render a view. * An MVC model contains all of your application logic that is not contained in a view or a controller. So let's start: * **Create the model**. Add a `Models` folder in the new plugin, and then add a new model class that fits your need. * **Create the view**. Add a `Views` folder in the new plugin, and then add a `.cshtml` file named `Configure.cshtml`. Set **Build Action** property of the view file is set to **Content**, and the **Copy to Output Directory** property is set to **Copy always**. Note that the configuration page should use the *_ConfigurePlugin* layout. ```html @model Nop.Plugin.Tax.FixedOrByCountryStateZip.Models.ConfigurationModel @{ Layout = "_ConfigurePlugin"; } <div class="form-group"> <div class="col-md-12"> <div class="onoffswitch"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="advanced-settings-mode" checked="@Model.CountryStateZipEnabled"> <label class="onoffswitch-label" for="advanced-settings-mode"> <span class="onoffswitch-inner" data-locale-basic="@T("Plugins.Tax.FixedOrByCountryStateZip.Fixed")" data-locale-advanced="@T("Plugins.Tax.FixedOrByCountryStateZip.TaxByCountryStateZip")"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> </div> <script> function checkAdvancedSettingsMode(advanced) { if (advanced) { $("body").addClass("advanced-settings-mode"); $("body").removeClass("basic-settings-mode"); } else { $("body").removeClass("advanced-settings-mode"); $("body").addClass("basic-settings-mode"); } } checkAdvancedSettingsMode($("#advanced-settings-mode").is(':checked')); $(document).ready(function() { $("#advanced-settings-mode").click(function() { checkAdvancedSettingsMode($(this).is(':checked')); $.ajax({ cache: false, url: "@Url.Action("SaveMode", "FixedOrByCountryStateZip")", type: "POST", data: { value: $(this).is(':checked') }, dataType: "json", error: function (jqXHR, textStatus, errorThrown) { $("#saveModeAlert").click(); } }); ensureDataTablesRendered(); }); }); </script> <nop-alert asp-alert-id="saveModeAlert" asp-alert-message="@T("Admin.Common.Alert.Save.Error")" /> @await Html.PartialAsync("~/Plugins/Tax.FixedOrByCountryStateZip/Views/_FixedRate.cshtml") @await Html.PartialAsync("~/Plugins/Tax.FixedOrByCountryStateZip/Views/_CountryStateZip.cshtml", Model) ``` * Also make sure that you have **_ViewImports.cshtml** file into your `Views` directory. You can just copy it from any other existing plugin or widget. ![image6](_static/how-to-write-a-tax-plugin-4.20/image6.png) * **Create the controller**. Add a `Controllers` folder in the new plugin, and then add a new controller class. A good practice is to name plugin controllers **{Group}{Name}Controller.cs**. For example, `FixedOrByCountryStateZipController`. Of course, it's not a requirement to name controllers this way (but just a recommendation). Then create an appropriate action method for the configuration page (in the admin area). Let's name it `Configure`. Prepare a model class and pass it to the following view using a physical view path: **~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml**. ```cs public IActionResult Configure() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings)) return AccessDeniedView(); var taxCategories = _taxCategoryService.GetAllTaxCategories(); if (!taxCategories.Any()) return Content("No tax categories can be loaded"); var model = new ConfigurationModel { CountryStateZipEnabled = _countryStateZipSettings.CountryStateZipEnabled }; //stores model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "0" }); var stores = _storeService.GetAllStores(); foreach (var s in stores) model.AvailableStores.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); //tax categories foreach (var tc in taxCategories) model.AvailableTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id.ToString() }); //countries var countries = _countryService.GetAllCountries(showHidden: true); foreach (var c in countries) model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() }); //states model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "0" }); var defaultCountry = countries.FirstOrDefault(); if (defaultCountry != null) { var states = _stateProvinceService.GetStateProvincesByCountryId(defaultCountry.Id); foreach (var s in states) model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); } return View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", model); } ``` * Use the following attributes for your action method: ```cs [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action [AdminAntiForgery] //Helps prevent malicious scripts from submitting forged page requests. ``` For example, open `FixedOrByCountryStateZip` plugin and look at its implementation of `FixedOrByCountryStateZipController`. Then for each plugin that has a configuration page, you should specify a configuration URL. Base class named `BasePlugin` has `GetConfigurationPageUrl` method which returns a configuration URL: ```cs public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where *{CONTROLLER_NAME}* is the name of your controller and *{ACTION_NAME}* is the name of the action (usually it's `Configure`). For assigning different tax rates according to the customer address, a new table is required which records all data related to tax. For this purpose, the `Domain` folder is added where we add a class that extends the **BaseEntity** class. In this case `TaxRate.cs` ![image7](_static/how-to-write-a-tax-plugin-4.20/image7.png) Another folder `Data` is also added which consists of Map class(es) and Object Context class(es). Mapping class implements **`NopEntityTypeConfiguration<T>`** (`Nop.Data.Mapping` namespace). Here, the configure method is overridden. ```cs public override void Configure(EntityTypeBuilder<TaxRate> builder) { builder.ToTable(nameof(TaxRate)); builder.HasKey(rate => rate.Id); builder.Property(rate => rate.Percentage).HasColumnType("decimal(18, 4)"); } ``` Object Context class implements **DbContext** class (`Microsoft.EntityFrameworkCore` namespace) and **IDbContext** interface (`Nop.Data` namespace). This `IDbContext` interface consists of methods related to table creation, deletion, and other custom actions like executing a raw SQL query according to the model which was previously added in the `Domain` folder. ```cs public class CountryStateZipObjectContext : DbContext, IDbContext { #region Ctor public CountryStateZipObjectContext(DbContextOptions<CountryStateZipObjectContext> options) : base(options) { } #endregion #region Utilities /// <summary> /// Further configuration the model /// </summary> /// <param name="modelBuilder">Model muilder</param> protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new TaxRateMap()); base.OnModelCreating(modelBuilder); } #endregion #region Methods /// <summary> /// Creates a DbSet that can be used to query and save instances of entity /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <returns>A set for the given entity type</returns> public new virtual DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity { return base.Set<TEntity>(); } /// <summary> /// Generate a script to create all tables for the current model /// </summary> /// <returns>A SQL script</returns> public virtual string GenerateCreateScript() { return Database.GenerateCreateScript(); } /// <summary> /// Creates a LINQ query for the query type based on a raw SQL query /// </summary> /// <typeparam name="TQuery">Query type</typeparam> /// <param name="sql">The raw SQL query</param> /// <param name="parameters">The values to be assigned to parameters</param> /// <returns>An IQueryable representing the raw SQL query</returns> public virtual IQueryable<TQuery> QueryFromSql<TQuery>(string sql, params object[] parameters) where TQuery : class { throw new NotImplementedException(); } /// <summary> /// Creates a LINQ query for the entity based on a raw SQL query /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="sql">The raw SQL query</param> /// <param name="parameters">The values to be assigned to parameters</param> /// <returns>An IQueryable representing the raw SQL query</returns> public virtual IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity { throw new NotImplementedException(); } /// <summary> /// Executes the given SQL against the database /// </summary> /// <param name="sql">The SQL to execute</param> /// <param name="doNotEnsureTransaction">true - the transaction creation is not ensured; false - the transaction creation is ensured.</param> /// <param name="timeout">The timeout to use for command. Note that the command timeout is distinct from the connection timeout, which is commonly set on the database connection string</param> /// <param name="parameters">Parameters to use with the SQL</param> /// <returns>The number of rows affected</returns> public virtual int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters) { using (var transaction = Database.BeginTransaction()) { var result = Database.ExecuteSqlCommand(sql, parameters); transaction.Commit(); return result; } } /// <summary> /// Detach an entity from the context /// </summary> /// <typeparam name="TEntity">Entity type</typeparam> /// <param name="entity">Entity</param> public virtual void Detach<TEntity>(TEntity entity) where TEntity : BaseEntity { throw new NotImplementedException(); } /// <summary> /// Install object context /// </summary> public void Install() { //create tables this.ExecuteSqlScript(GenerateCreateScript()); } /// <summary> /// Uninstall object context /// </summary> public void Uninstall() { //drop the table this.DropPluginTable(nameof(TaxRate)); } #endregion } ``` For tax rates **CRUD** operation, services are created. In this case, interface **ICountryStateZipService** and class **CountryStateZipService** is created. It contains method like `InsertTaxRate`, `UpdateTaxRate`, `DeleteTaxRate`, `GetAllTaxRates` and `GetTaxRateById`. These method names are self-explanatory and will be consumed by controllers. Other methods can be introduced/added based according to the requirements. ### ICountryStateZipService.cs ```cs public partial interface ICountryStateZipService { /// <summary> /// Deletes a tax rate /// </summary> /// <param name="taxRate">Tax rate</param> void DeleteTaxRate(TaxRate taxRate); /// <summary> /// Gets all tax rates /// </summary> /// <returns>Tax rates</returns> IPagedList<TaxRate> GetAllTaxRates(int pageIndex = 0, int pageSize = int.MaxValue); /// <summary> /// Gets a tax rate /// </summary> /// <param name="taxRateId">Tax rate identifier</param> /// <returns>Tax rate</returns> TaxRate GetTaxRateById(int taxRateId); /// <summary> /// Inserts a tax rate /// </summary> /// <param name="taxRate">Tax rate</param> void InsertTaxRate(TaxRate taxRate); /// <summary> /// Updates the tax rate /// </summary> /// <param name="taxRate">Tax rate</param> void UpdateTaxRate(TaxRate taxRate); } ``` #### CountryStateZipService.cs ```cs public partial class CountryStateZipService : ICountryStateZipService { #region Fields private readonly IEventPublisher _eventPublisher; private readonly IRepository<TaxRate> _taxRateRepository; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="eventPublisher">Event publisher</param> /// <param name="cacheManager">Cache manager</param> /// <param name="taxRateRepository">Tax rate repository</param> public CountryStateZipService(IEventPublisher eventPublisher, ICacheManager cacheManager, IRepository<TaxRate> taxRateRepository) { _eventPublisher = eventPublisher; _cacheManager = cacheManager; _taxRateRepository = taxRateRepository; } #endregion #region Methods /// <summary> /// Deletes a tax rate /// </summary> /// <param name="taxRate">Tax rate</param> public virtual void DeleteTaxRate(TaxRate taxRate) { if (taxRate == null) throw new ArgumentNullException(nameof(taxRate)); _taxRateRepository.Delete(taxRate); //event notification _eventPublisher.EntityDeleted(taxRate); } /// <summary> /// Gets all tax rates /// </summary> /// <returns>Tax rates</returns> public virtual IPagedList<TaxRate> GetAllTaxRates(int pageIndex = 0, int pageSize = int.MaxValue) { var key = string.Format(ModelCacheEventConsumer.TAXRATE_ALL_KEY, pageIndex, pageSize); return _cacheManager.Get(key, () => { var query = from tr in _taxRateRepository.Table orderby tr.StoreId, tr.CountryId, tr.StateProvinceId, tr.Zip, tr.TaxCategoryId select tr; var records = new PagedList<TaxRate>(query, pageIndex, pageSize); return records; }); } /// <summary> /// Gets a tax rate /// </summary> /// <param name="taxRateId">Tax rate identifier</param> /// <returns>Tax rate</returns> public virtual TaxRate GetTaxRateById(int taxRateId) { if (taxRateId == 0) return null; return _taxRateRepository.GetById(taxRateId); } /// <summary> /// Inserts a tax rate /// </summary> /// <param name="taxRate">Tax rate</param> public virtual void InsertTaxRate(TaxRate taxRate) { if (taxRate == null) throw new ArgumentNullException(nameof(taxRate)); _taxRateRepository.Insert(taxRate); //event notification _eventPublisher.EntityInserted(taxRate); } /// <summary> /// Updates the tax rate /// </summary> /// <param name="taxRate">Tax rate</param> public virtual void UpdateTaxRate(TaxRate taxRate) { if (taxRate == null) throw new ArgumentNullException(nameof(taxRate)); _taxRateRepository.Update(taxRate); //event notification _eventPublisher.EntityUpdated(taxRate); } #endregion } ``` The last thing, we need is to register the services and configure plugin DB context on application startup. For this, the **Infrastructure** folder is added which contains classes – `DependencyRegister` and `PluginDbStartup`. **DependencyRegister** class implements `IDependencyRegister` interface (`Nop.Core.Infrastructure.DependencyManagement` namespace) which has `Register` method. ```cs public class DependencyRegistrar : IDependencyRegistrar { /// <summary> /// Register services and interfaces /// </summary> /// <param name="builder">Container builder</param> /// <param name="typeFinder">Type finder</param> /// <param name="config">Config</param> public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) { builder.RegisterType<FixedOrByCountryStateZipTaxProvider>().As<ITaxProvider>().InstancePerLifetimeScope(); builder.RegisterType<CountryStateZipService>().As<ICountryStateZipService>().InstancePerLifetimeScope(); //data context builder.RegisterPluginDataContext<CountryStateZipObjectContext>("nop_object_context_tax_country_state_zip"); //override required repository with our custom context builder.RegisterType<EfRepository<TaxRate>>().As<IRepository<TaxRate>>() .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_tax_country_state_zip")) .InstancePerLifetimeScope(); } /// <summary> /// Order of this dependency registrar implementation /// </summary> public int Order => 1; } ``` Similarly, **PluginDbStartup** class implements `INopStartup` interface (`Nop.Core.Infrastructure` namespace) which has `ConfigureServices` and `Configure` methods. For this example, object context is added in `ConfigureServices` method. ```cs public class PluginDbStartup : INopStartup { /// <summary> /// Add and configure any of the middleware /// </summary> /// <param name="services">Collection of service descriptors</param> /// <param name="configuration">Configuration of the application</param> public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { //add object context services.AddDbContext<CountryStateZipObjectContext>(optionsBuilder => { optionsBuilder.UseSqlServerWithLazyLoading(services); }); } /// <summary> /// Configure the using of added middleware /// </summary> /// <param name="application">Builder for configuring an application's request pipeline</param> public void Configure(IApplicationBuilder application) { } /// <summary> /// Gets order of this startup configuration implementation /// </summary> public int Order => 11; } ``` ## Project structure of Tax Plugin ![image8](_static/how-to-write-a-tax-plugin-4.20/image8.png) ## Handling "Install" and "Uninstall" methods This step is optional. Some plugins can require additional logic during their installation. For example, a plugin can insert new locale resources or add necessary tables or settings values. So open your `BasePlugin` implementation and override the following methods: * `Install`. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). ```cs public override void Install() { //database objects _objectContext.Install(); //settings _settingService.SaveSetting(new FixedOrByCountryStateZipTaxSettings()); //locales _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fixed", "Fixed rate"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.TaxByCountryStateZip", "By Country"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.TaxCategoryName", "Tax category"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Rate", "Rate"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Store", "Store"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Store.Hint", "If an asterisk is selected, then this shipping rate will apply to all stores."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Country", "Country"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Country.Hint", "The country."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.StateProvince", "State / province"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.StateProvince.Hint", "If an asterisk is selected, then this tax rate will apply to all customers from the given country, regardless of the state."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Zip", "Zip"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Zip.Hint", "Zip / postal code. If zip is empty, then this tax rate will apply to all customers from the given country or state, regardless of the zip code."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.TaxCategory", "Tax category"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.TaxCategory.Hint", "The tax category."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Percentage", "Percentage"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Percentage.Hint", "The tax rate."); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.AddRecord", "Add tax rate"); _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.AddRecordTitle", "New tax rate"); base.Install(); } ``` * `Uninstall`. This method will be invoked during plugin uninstallation. You can remove previously initialized settings, locale resources, or database tables by plugin during installation. ```cs public override void Uninstall() { //settings _settingService.DeleteSetting<FixedOrByCountryStateZipTaxSettings>(); //fixed rates var fixedRates = _taxCategoryService.GetAllTaxCategories() .Select(taxCategory => _settingService.GetSetting(string.Format(FixedOrByCountryStateZipDefaults.FixedRateSettingsKey, taxCategory.Id))) .Where(setting => setting != null).ToList(); _settingService.DeleteSettings(fixedRates); //database objects _objectContext.Uninstall(); //locales _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fixed"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.TaxByCountryStateZip"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.TaxCategoryName"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Rate"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Store"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Store.Hint"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Country"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Country.Hint"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.StateProvince"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.StateProvince.Hint"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Zip"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Zip.Hint"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.TaxCategory"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.TaxCategory.Hint"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Percentage"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.Fields.Percentage.Hint"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.AddRecord"); _localizationService.DeletePluginLocaleResource("Plugins.Tax.FixedOrByCountryStateZip.AddRecordTitle"); base.Uninstall(); } ``` > [!IMPORTANT] > If you override one of these methods, do not hide its base implementation -base.Install() and base.Uninstall(). --- <!-- page: How to write a widget for nopCommerce | url: http://nopdocs.service.hedr.dev/en/developer/plugins/how-to-write-widget-for-nopCommerce.html | source: en/developer/plugins/how-to-write-widget-for-nopCommerce.md --> # How to write a widget for nopCommerce To extend nopCommerce functionality, widgets are used. There are various types of widgets like [Swiper](https://github.com/nopSolutions/nopCommerce/tree/master/src/Plugins/Nop.Plugin.Widgets.Swiper) and [Google Analytics](https://github.com/nopSolutions/nopCommerce/tree/master/src/Plugins/Nop.Plugin.Widgets.GoogleAnalytics) which are already contained in the nopCommerce's repo. nopCommerce marketplace already contains various widgets (both free and paid) which may meet your requirement(s). If you have not found one, then you are at the right place because this article will guide you through the process of creating a widget according to your need. ## The widget structure, required files, and locations 1. Start by creating a new **Class Library** project in the solution. It is recommended to place your widget in the **Plugins** directory, located in the root folder of the source, where other widgets and plugins already reside. ![image1](_static/how-to-write-a-widget-for-nopCommerce/image1.png) > [!NOTE] > > Do not get confused this directory with the one which exists in *Presentation\Nop.Web* directory. The *Plugins* directory in the *Nop.Web* directory contains the plugin's compiled files. A recommended name for a widget project is `Nop.Plugin.Widgets.{Name}`. `{Name}` is your widget name (for example, "**GoogleAnalytics**"). For example, *Google Analytics widget* has the following name: `Nop.Plugin.Widgets.GoogleAnalytics`. But please note that it's not a requirement. And you can choose any name for a widget. For example, "*MyFirstNopWidget*". The *Plugins* directory structure of a solution looks like the following. ![image2](_static/how-to-write-a-widget-for-nopCommerce/image2.png) 1. Once the widget project is created, the **.csproj** file content should be updated using any available text editor application. Replace the content with the following one: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net9.0</TargetFramework> <Copyright>SOME_COPYRIGHT</Copyright> <Company>YOUR_COMPANY</Company> <Authors>SOME_AUTHORS</Authors> <PackageLicenseUrl>PACKAGE_LICENSE_URL</PackageLicenseUrl> <PackageProjectUrl>PACKAGE_PROJECT_URL</PackageProjectUrl> <RepositoryUrl>REPOSITORY_URL</RepositoryUrl> <RepositoryType>Git</RepositoryType> <OutputPath>$(SolutionDir)\Presentation\Nop.Web\Plugins\WIDGET_OUTPUT_DIRECTORY</OutputPath> <OutDir>$(OutputPath)</OutDir> <!--Set this parameter to true to get the dlls copied from the NuGet cache to the output of your project. You need to set this parameter to true if your plugin has a nuget package to ensure that the dlls copied from the NuGet cache to the output of your project--> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(SolutionDir)\Presentation\Nop.Web.Framework\Nop.Web.Framework.csproj" /> <ClearPluginAssemblies Include="$(SolutionDir)\Build\ClearPluginAssemblies.csproj" /> </ItemGroup> <!-- This target execute after "Build" target --> <Target Name="NopTarget" AfterTargets="Build"> <!-- Delete unnecessary libraries from plugins path --> <MSBuild Projects="@(ClearPluginAssemblies)" Properties="PluginPath=$(OutDir)" Targets="NopClear" /> </Target> </Project> ``` > [!NOTE] > > The **WIDGET_OUTPUT_DIRECTORY** should be replace by the plugin name, for example *Widgets.GoogleAnalytics*. 1. After updating the *.csproj* file, the **plugin.json** file should be added which is required for a widget. This file contains meta-information describing your widget. Just copy this file from any other existing plugin/widget and modify it for your needs. For information about the `plugin.json` file, please see [plugin.json file](xref:en/developer/plugins/plugin_json). The last required step is to create a class which implements **BasePlugin** (*Nop.Core.Plugins* namespace) and **IWidgetPlugin** interface (*Nop.Services.Cms* namespace). IWidgetPlugin allows you to create widgets. Widgets are rendered on some parts of your site. For example, it can be a live chat block on the bottom right of your site. ## Handling requests. Controllers, models, and views Now you can see the widget by going to **Admin area** → **Configuration** → **Local Plugins**. ![image4](_static/how-to-write-a-widget-for-nopCommerce/image4.png) When a plugin/widget is installed, you will see the **Uninstall** button. *For performance improvement, it is a good practice that you uninstall plugins/widgets which are not necessary*. ![image5](_static/how-to-write-a-widget-for-nopCommerce/image5.png) There will be the **Install** and **Delete** buttons when a plugin/widget is not installed or uninstalled. *Deleting will remove physical files from the server*. But as you guessed our widget does nothing. It does not even have a user interface for its configuration. Let's create a page to configure the widget. What we need to do now is create a controller, a model, a view, and a view component. - **MVC controllers** are responsible for responding to requests made against an *ASP.NET MVC* website. Each browser request is mapped to a particular controller. - A view contains the **HTML** markup and content that is sent to the browser. A view is the equivalent of a page when working with an *ASP.NET MVC* application. - A view component that implements **NopViewComponent** which contains logic and codes to render a view. - The **MVC model** contains all of your application logic that is not contained in a view or a controller. So let's start: 1. Create the model. Add a `Models` folder in the new widget, and then add a new model class that fits your need. 1. Create the view. Add a `Views` folder in the new widget, and then add a `cshtml` file named `Configure.cshtml`. Set "**Build Action**" property of the view file is set to "**Content**", and the "**Copy to Output Directory**" property is set to "**Copy always**". Note that the configuration page should use the "**_ConfigurePlugin**" layout. ```cs @{ Layout = "_ConfigurePlugin"; } ``` 1. Also make sure that you have **_ViewImports.cshtml** file into your `Views` directory. You can just copy it from any other existing plugin or widget. ![image7](_static/how-to-write-a-widget-for-nopCommerce/image7.png) 1. Create the controller. Add a `Controllers` folder in the new widget, and then add a new controller class. A good practice is to name plugin controllers `Widgets{Name}Controller.cs`. For example, **WidgetsGoogleAnalyticsController**. Of course, it's not a requirement to name controllers this way, but just a recommendation. Then create an appropriate action method for the configuration page (in the admin area). Let's name it `Configure`. Prepare a model class and pass it to the following view using a physical view path: `~/Plugins/{PluginOutputDirectory}/Views/Configure.cshtml`. ```cs public async Task<IActionResult> Configure() { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageWidgets)) return AccessDeniedView(); //load settings for a chosen store scope var storeScope = await _storeContext.GetActiveStoreScopeConfigurationAsync(); var myWidgetSettings = await _settingService.LoadSettingAsync<MyWidgetSettings>(storeScope); var model = new ConfigurationModel { // configuration model settings here }; if (storeScope > 0) { // override settings here based on store scope } return View("~/Plugins/Widgets.MyFirstNopWidget/Views/Configure.cshtml", model); } ``` 1. Use the following attributes for your action method: ```cs [AutoValidateAntiforgeryToken] [AuthorizeAdmin] //confirms access to the admin panel [Area(AreaNames.Admin)] //specifies the area containing a controller or action [AdminAntiForgery] //Helps prevent malicious scripts from submitting forged page requests. ``` For example, open the `GoogleAnalytics` widget and look at its implementation of `WidgetsGoogleAnalyticsController`. Then for each widget that has a configuration page, you should specify a configuration URL. Base class named **BasePlugin** has `GetConfigurationPageUrl` method which returns a configuration URL: ```cs public override string GetConfigurationPageUrl() { return $"{_webHelper.GetStoreLocation()}Admin/{CONTROLLER_NAME}/{ACTION_NAME}"; } ``` Where `{CONTROLLER_NAME}` is the name of your controller and `{ACTION_NAME}` is the name of the action (usually it's "Configure"). Each widget should specify a list of widget zones. A base class named **IWidgetPlugin** has the `GetWidgetZones` method which returns a list of widget zones where it will be rendered. ```cs public Task<IList<string>> GetWidgetZonesAsync() { return Task.FromResult<IList<string>>(new List<string> {PublicWidgetZones.HeadHtmlTag }); } ``` You can find [a list of public widget zones from this link](https://github.com/nopSolutions/nopCommerce/blob/master/src/Presentation/Nop.Web.Framework/Infrastructure/PublicWidgetZones.cs) and [admin widget zones following this link](https://github.com/nopSolutions/nopCommerce/blob/master/src/Presentation/Nop.Web.Framework/Infrastructure/AdminWidgetZones.cs). In addition to `GetWidgetZonesAsync`, **IWidgetPlugin** has `GetWidgetViewComponentName` method which returns ViewComponent name. It accepts "*widgetZone*" name as parameter and can be used to render different view based on the selected widget zone. ```cs public string GetWidgetViewComponentName(string widgetZone) { return "MyFirstWidget"; } ``` ## Project structure of Google Analytics widget ![image11](_static/how-to-write-a-widget-for-nopCommerce/image11.png) ## Handling "InstallAsync" and "UninstallAsync" methods This step is optional. Some widgets can require additional logic during their installation. For example, a widget can insert new locale resources or settings values. So open your **IWidgetPlugin** implementation (in most cases it'll be derived from **BasePlugin** class) and override the following methods: 1. **InstallAsync**. This method will be invoked during plugin installation. You can initialize any settings here, insert new locale resources, or create some new database tables (if required). ```cs public override async Task InstallAsync() { // custom logic like adding settings, locale resources, and database table(s) here await base.InstallAsync(); } ``` 1. **UninstallAsync**. This method will be invoked during plugin uninstallation. You can remove previously initialized settings, locale resources, or database tables by widget during installation. ```cs public override async Task UninstallAsync() { // custom logic like removing settings, locale resources, and database table(s) which was created during widget installation await base.UninstallAsync(); } ``` > [!IMPORTANT] > > If you override one of these methods, do not hide its base implementation - **base.InstallAsync()** and **base.UninstallAsync()** which has been marked in the above images. --- <!-- page: Automated Content Translation | url: http://nopdocs.service.hedr.dev/en/getting-started/advanced-configuration/translation.html | source: en/getting-started/advanced-configuration/translation.md --> # Automated Content Translation ## Overview This feature integrates automated translation capabilities into the core application, allowing store administrators to translate website content into multiple languages using two of the most popular machine translation platforms: **DeepL** and **Google Translate**. Currently, automated translation is supported for the following entities: - Category - Manufacturer - Product - Product Attribute - Specification Attribute ## Configuration All settings for this feature are located on the **General settings** page within the **Translation** section. ![Translation](_static/translation/settings.png) Key configuration options include: - **Allow to pre-translate**: A master switch to turn the entire translation functionality on or off. - **Translate from the language**: In the "standard" tab, you can specify the default language from which all translations will be generated. - **Languages to ignore**: A list of languages that should be excluded from the automated translation process. - **Translation service**: A dropdown menu to select the translation service to use (DeepL or Google Translate). - **DeepL**: Requires an **Auth key**. - **Google Translate**: Requires an **API key**. > [!NOTE] > > The system will not automatically translate a field that already contains a manually saved value. ## How to Use Once the feature is enabled, using it is very straightforward. A new button will appear in the main button container on the edit pages for all supported entities. For example, on the product edit page, it looks like this: ![Translation](_static/translation/pretranslate.png) 1. Click the **"Pre-translate"** button. 1. If the translation is successful, a confirmation message will appear. The localized fields for other languages will be populated with the translated text. ![Translation](_static/translation/translate.png) 1. If an error occurs during the translation process, a warning message will be displayed. ![Translation](_static/translation/error.png) > [!WARNING] > > It is important to note that this function acts as a **pre-translation** tool. The translated content is populated in the fields but is **not saved automatically**. This gives the user full control to review, edit, or discard the translations before manually saving the changes. --- <!-- page: PayPal Commerce | url: http://nopdocs.service.hedr.dev/en/getting-started/configure-payments/payment-methods/paypal-commerce-old-version.html | source: en/getting-started/configure-payments/payment-methods/paypal-commerce-old-version.md --> > [!NOTE] > > This documentation page describes old versions of the plugin (before 4.70.10). You can find the current documentation on [this page](xref:en/getting-started/configure-payments/payment-methods/paypal-commerce). # PayPal Commerce `PayPal Commerce` gives your buyers a simplified and secure checkout experience. PayPal intelligently presents the most relevant payment types to your shoppers automatically, making it easier for them to complete their purchases using such methods as Pay with Venmo, PayPal Credit, credit card payments, iDEAL, Bancontact, Sofort, and other payment types. ## Configure the payment method To configure the `PayPal Commerce` plugin, go to **Configuration → Payment methods**. Then find the **PayPal Commerce** payment method in the payment method list: ![List](_static/paypal-commerce-old-version/list.jpg) Follow these steps to configure `PayPal Commerce`: ### 1. Activate the payment method To do this, click the **Edit** button in the plugin row on the payment method list page. Activate the plugin by selecting the **Is active** checkbox. Click the **Update** button. Your changes will be saved. ### 2. Create a PayPal account If you already have a PayPal account, just proceed to the [next section](#3-set-up-the-paypal-developer-dashboard). If you don't then register a Business account. You have two options to do this: you can register an account on the PayPal website or you can do this from the plugin configuration page. Let's briefly consider both options: #### Register an account on the PayPal website 1. Register a Business account on [PayPal](https://www.paypal.com/us/webapps/mpp/referral/paypal-business-account2?partner_id=9JJPJNNPQ7PZ8). Just click the **Sign up** button there: ![Sign up page](_static/paypal-commerce-old-version/sign-up-page.png) 1. Then fill in the information about yourself and your business: ![Sign up form](_static/paypal-commerce-old-version/sign-up-form.png) > [!NOTE] > > If you already have an account, you will be redirected to the authorization. #### Register an account from the plugin configuration page 1. Open the PayPal Commerce configuration page in the admin area. You will see the following form: ![PayPal Commerce configuration page](_static/paypal-commerce-old-version/auto-configure.jpg) 1. Enter your email address and let PayPal check everything out by clicking the **Save** button. 1. If everything is OK, you will see the following green notification and a newly added **Sign up for PayPal** button: ![When email is already entered](_static/paypal-commerce-old-version/configure-entered-email.png) 1. Click this button and you will see the following pop-up window allowing you to fill in some data and register an account: ![PayPal Commerce configuration page](_static/paypal-commerce-old-version/popup-form-first-page.png) You should pass through a few steps to fill in all the required data. The last one will ask you to confirm your email to activate your account. ### 3. Set up the Paypal Developer Dashboard 1. Log into the [Developer Dashboard](https://developer.paypal.com/developer/applications?partner_id=9JJPJNNPQ7PZ8) with your PayPal account credentials. 1. In **My Apps & Credentials**, use the toggle to switch between live and sandbox testing apps. ![My Apps & Credentials](_static/paypal-commerce-old-version/my-apps.jpg) 1. Navigate to the *REST API apps* section and click **Create App**. ![Create App](_static/paypal-commerce-old-version/rest.jpg) 1. Type a name for your app and click **Create App**. The app details page will open and display your credentials. 1. Copy and save the **Client ID** and **Secret** for your app. 1. Review your app details and save your app if you made any changes. ### 4. Configure the payment method in nopCommerce 1. Find the **PayPal Commerce** payment method on the **Configuration → Payment methods** page and click **Configure**. The *Configure - PayPal Commerce* page will be displayed as follows: ![Configure](_static/paypal-commerce-old-version/configure.jpg) 1. Define the following settings on the *Configure - PayPal Commerce* page: * **Specify API credentials manually** - determine if you need to manually set credentials. Select this option if you already have an application created or if you want to use sandbox mode. Otherwise, the plugin will be set up automatically and you will be able to start accepting PayPal payments in your store after completing your PayPal registration. ![Auto configure](_static/paypal-commerce-old-version/auto-configure.jpg) * **Use sandbox** if you want to test the payment method first. * Enter the **Client ID** you saved in the previous steps. * Enter the **Secret** you saved in the previous steps. * Choose the **Payment type** to either capture payment immediately or authorize payment for an order after order creation. 1. Then proceed to the *PayPal Prominently* panel: ![Create App](_static/paypal-commerce-old-version/display.jpg) On this panel, define the display settings: * Select the **Display buttons on shopping cart** checkbox to display PayPal buttons on the shopping cart page instead of the default checkout button. * Select the **Display buttons on product details** to display PayPal buttons on product details pages; clicking them matches the behavior of the default 'Add to cart' button. * Select the **Display Pay Later messages** box to take advantage of the pay later messaging feature on your website. The message is displayed on the product and checkout pages, showing how much the customer is paying in four installments. ![Pay Later messages](_static/paypal-commerce-old-version/pay_later.jpg) * Tick the **Display logo in header links** checkbox to display a PayPal logo in the header links. These logos and banners are a great way to let your buyers know that you choose PayPal to securely process their payments. * If the previous checkbox is selected, the **Logo source code** field is displayed. In this field, enter the source code of the logo. Find more logos and banners on PayPal Logo Center. You can also modify the code to fit correctly into your theme and site style. * Tick the **Display logo in footer** checkbox to display a PayPal logo in the footer. These logos and banners are a great way to let your buyers know that you choose PayPal to securely process their payments. * If the previous checkbox is selected, the **Logo source code** field is displayed. In this field, enter the source code of the logo. Find more logos and banners on PayPal Logo Center. You can also modify the code to fit correctly into your theme and site style. Click **Save** to save the plugin settings. ## Limit to stores and customer roles You can limit any payment method to store and customer role. This means that the method will be available to certain stores or customer roles only. You can do this from the *plugin list* page. 1. Go to **Configuration → Local plugins**. Find the plugin you want to limit. In our case, it's **PayPal Commerce**. To find it faster, use the *Search* panel in the top of the page and search by **Plugin name** or **Group** using the *Payment methods* option. ![Plugins](_static/paypal-commerce-old-version/plugins.jpg) 1. Click the **Edit** button, and the *Edit plugin details* window will be displayed as follows: ![Edit](_static/paypal-commerce-old-version/edit.jpg) 1. You can set up the following limits: * In the **Limited to customer roles** field, choose one or several customer roles, that is, administrators, vendors, guests, who will be able to use this plugin. If you don't need this option just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore ACL rules (sitewide)**. Read more about the [access control list](xref:en/running-your-store/customer-management/access-control-list). * Use the **Limited to stores** option to limit this plugin to a certain store. If you have multiple stores, choose one or several from the list. If you don't use this option, just leave this field empty. > [!Important] > > In order to use this functionality, you have to disable the following setting: **Catalog settings → Ignore "limit per store" rules (sitewide)**. Read more about [multi-store functionality](xref:en/getting-started/advanced-configuration/multi-store). Click **Save**.