You have no items in your shopping cart.

Blog posts of '2020' 'October'

Code Snippets for Licensing Plugin

To assist with our Licensing Plugin for Developers, here are some code snippets to auto-generate license keys upon purchase, as well as other conveniences for emailing keys to customers and verifying licenses during plugin use.

All code is valid for nopCommerce v4.40, but it should not be difficult to adapt to previous versions nor for your own business needs. As always, don't hesitate to contact us with questions or suggestions!

 

Auto-generate License Keys during purchase in an OrderPaidEventConsumer.cs:

using Nop.Core;
using Nop.Core.Domain.Orders;
using Nop.Plugin.Widgets.Licenses.Domain;
using Nop.Plugin.Widgets.Licenses.Services;
using Nop.Services.Catalog;
using Nop.Services.Events;
using Nop.Services.Orders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nop.Plugin.Widgets.Licenses.Events
{
    /// <summary>
    /// Adds licenses to appropriate products in Order Paid Event
    /// These have to be unique for each Product so that someone doesn't purchase a license for one Product and then use it for others
    /// </summary>
    public class OrderPaidConsumer : IConsumer<OrderPaidEvent>
    {
        private readonly ILicenseService _licenseService;
        private readonly IOrderService _orderService;
        private readonly IProductService _productService;
        private readonly IWorkContext _workContext;

        public OrderPaidConsumer(
            ILicenseService licenseService, 
            IOrderService orderService,
            IProductService productService,
            IWorkContext workContext)
        {
            _licenseService = licenseService;
            _orderService = orderService;
            _productService = productService;
            _workContext = workContext;
        }

        public async Task HandleEventAsync(OrderPaidEvent eventMessage)
        {
            IList<LicenseKey> licenses = new List<LicenseKey>();
            var orderItems = await _orderService.GetOrderItemsAsync(eventMessage.Order.Id, isShipEnabled: false);

            var cartProductIds = orderItems.Select(oi => oi.ProductId).ToArray();
            var downloadableProductsRequireLicensing = await _productService.HasAnyDownloadableProductAsync(cartProductIds);

            if (downloadableProductsRequireLicensing)
            {
                foreach (var item in orderItems)
                {
                    var product = await _productService.GetProductByIdAsync(item.ProductId);
                    if (product.IsDownload)
                    {
                        var license = await _licenseService.CreateLicenseAsync(item);
                        if (!string.IsNullOrEmpty(license.License))
                        {
                            licenses.Add(license);
                        }
                    }
                }
            }

            if (licenses.Count > 0)
            {
                //create info table
                var sb = new StringBuilder();
                sb.Append("<table cellspacing=\"5\"><tr><th>Type</th><th>Product</th><th>Url</th><th>License</th></tr>");
                foreach (var license in licenses)
                {
                    sb.Append(string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>", license.LicenseType, license.ProductName, license.Url, license.License));
                }
                sb.Append("</table>");
                var licenseTable = sb.ToString();

                sb = new StringBuilder();
                sb.Append("License Keys: " + Environment.NewLine);
                foreach (var license in licenses)
                {
                    sb.Append(string.Format("{0} - {1}: {2}{3}", license.ProductName, license.Url, license.License, Environment.NewLine));
                }
                var licensePlainText = sb.ToString();

                //add to order notes 
                await _orderService.InsertOrderNoteAsync(new OrderNote
                {
                    CreatedOnUtc = DateTime.UtcNow,
                    DisplayToCustomer = true,
                    Note = licensePlainText,
                    OrderId = eventMessage.Order.Id,
                });

                //await _orderService.UpdateOrderAsync(eventMessage.Order);

                //send email
                var emailId = await _licenseService.SendCustomerNoticeAsync(eventMessage.Order, licenseTable, (await _workContext.GetWorkingLanguageAsync()).Id);
                await _orderService.InsertOrderNoteAsync(new OrderNote()
                {
                    CreatedOnUtc = DateTime.UtcNow,
                    DisplayToCustomer = false,
                    Note = $"\"License Key\" email (to customer) has been queued. Queued email identifier: {emailId}.",
                    OrderId = eventMessage.Order.Id
                });
                //await _orderService.UpdateOrderAsync(eventMessage.Order);
            }
        }
    }
}