Calling all developers! We invite you to provide your input on Feature Experimentation by completing this brief survey.

 

K Khan
Oct 24, 2017
  4641
(4 votes)

EPiServer integration with azure logic apps(part 1)

Microsoft Logic Apps provide a way to simplify and implement scalable integrations and workflows in the cloud. There are three major components that we will need to understand to before start working.

  1. Designer - It is relevantly independent module built in ReactJS to design workflows in Visual Studio, or in the Azure portal. Prepares workflow data model in JSON for us.
  2. Logic App Runtime - Responsible to run all the tasks retrieved from workflow definition in a distributed model.
  3. Connectors - Wrapped third-party APIs that allows us to use them.

How to connect EPiServer CMS or Commerce website with Azure Logic Apps. 

Azure logic app designer consists of connectors, triggers, actions and control flows, Its designer looks into open API/swagger of third party APIs and connectors and design cards to use in designing a workflow. Writing a managed connectors can be one way to integrate your EPiServer application, But we can use EPiServer.ServiceApi.Commerce.WebHooks or any webhook to Trigger the workflow and can use EPiServer.ServiceApi.Commerce or any custom API as Action

We presented a working demo at Episerver Close-up 2017 Sweden, Credits: Wessel Terpstra, where on submission of an order was used as a trigger and a custom promotion API was used to prepare a coupon code and post it mail this to the customer.

Image 2017-10-24_1710.png

Prepare your project

Install following packages

  • EPiServer.ServiceApi.Commerce.WebHooks
  • EPiServer.ServiceApi.Commerce
  • EPiServer.ServiceApi(For CMs Projects)
  • Swashbuckle

Create A Trigger

We need to post, purchase order(JSON) to Logic APP 

//NOT FOR PRODUCTION
[ServiceConfiguration(typeof(IWebHookManager), Lifecycle = ServiceInstanceScope.Singleton)]
    public class QuicksilverWebHookManager : IWebHookManager
    {
        public Task VerifyWebHookAsync(WebHook webHook)
        {
            return new Task(() => { });
        }

        public Task<int> NotifyAsync(string user, IEnumerable<NotificationDictionary> notifications, Func<WebHook, string, bool> predicate)
        {
            return Task.FromResult(default(int));
        }

        public async Task<int> NotifyAllAsync(IEnumerable<NotificationDictionary> notifications, Func<WebHook, string, bool> predicate)
        {
            int i = 0;
            var url = "Replace It with your settings"; //Webhook end point retrive from logic app designer when adding a wenhook triger
            foreach (var notification in notifications)
            {
                if (notification.Action != "OrderGroupUpdated" && (Type) notification["OrderGroupType"] != typeof(PurchaseOrder)) continue;
                
                using (var httpClient = new HttpClient())
                {
                    var json = JsonConvert.SerializeObject(notification);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var result = await httpClient.PostAsync(url, content);
                    if (result.IsSuccessStatusCode) i++;
                }
            }

            return i;
        }
    }

Create a custom API (to use as Action):

Commerce service API offers a lot but few times those are not just enough and we require some custom API

[AuthorizePermission("EPiServerServiceApi", "WriteAccess"), RequireHttps, RoutePrefix("episerverapi/commerce/promotion")]
    public class PromotionApiController : ApiController
    {
        private static readonly ApiCallLogger Logger = new ApiCallLogger(typeof(PromotionApiController));
        private readonly IContentRepository _contentRepository;
        private readonly IPromotionEngine _promotionEngine;

        public PromotionApiController(IContentRepository contentRepository,  IPromotionEngine promotionEngine)
        {
            _contentRepository = contentRepository;
            _promotionEngine = promotionEngine;
        }

        /// <summary>
        /// Add a new coupon code and return back
        /// </summary>
        /// <param name="username">User name</param>
        /// <returns>returns coupon code</returns>
        [AuthorizePermission("EPiServerServiceApi", "WriteAccess"), HttpGet, Route("{username}")]
        [ResponseType(typeof(string))]
        public virtual IHttpActionResult GetCouponCode(string username)
        {
            Logger.LogGet("GetCouponCode", Request, new []{ username});
            
            try
            {
                var promotionId = ""; // Generate a coupon code
                return ContentReference.IsNullOrEmpty(promotionId) ? Ok("") : Ok(promoCode);
            }
            catch (Exception exception)
            {
                Logger.Error(exception.Message, exception);
                return InternalServerError(exception);
            }
        }
}

EPiServer integration with azure logic apps(part 2) by Wessel Terpstra


References: What are azure logic apps
Glossary: 

  • Workflow - Logic Apps provides a graphical way to model your business processes as a series of steps or a workflow.
  • Managed Connectors - Your logic apps need access to data and services. Managed connectors are created specifically to aid you when you are connecting to and working with your data. See the list of connectors available now in managed connectors.
  • Triggers - Some Managed Connectors can also act as a trigger. A trigger starts a new instance of a workflow based on a specific event, like the arrival of an e-mail or a change in your Azure Storage account.
  • Actions - Each step after the trigger in a workflow is called an action. Each action typically maps to an operation on your managed connector or custom API apps.
  • Enterprise Integration Pack - For more advanced integration scenarios, Logic Apps includes capabilities from BizTalk. BizTalk is Microsoft's industry-leading integration platform. The Enterprise Integration Pack connectors allow you to easily include validation, transformation, and more into your Logic App workflows.
Oct 24, 2017

Comments

Please login to comment.
Latest blogs
Optimizely CMS easy RSS feed integration library

As I've mentioned in my  previous blog post , while I was developing the Optimizely version of my blog, I tried to look for a library that could...

David Drouin-Prince | Jan 25, 2025 | Syndicated blog

Decimal numbers in Optimizely Graph

Storing prices as decimal numbers on a commerce website and planning to expose them through Optimizely Graph? It might not be as straightforward as...

Damian Smutek | Jan 23, 2025 | Syndicated blog

Find and delete non used media and blocks

On my new quest to play around with Blazor and MudBlazor I'm going back memory lane and porting some previously plugins. So this time up is my plug...

Per Nergård (MVP) | Jan 21, 2025

Optimizely Content Graph on mobile application

CG everywhere! I pull schema from our default index https://cg.optimizely.com/app/graphiql?auth=eBrGunULiC5TziTCtiOLEmov2LijBf30obh0KmhcBlyTktGZ in...

Cuong Nguyen Dinh | Jan 20, 2025

Image Analyzer with AI Assistant for Optimizely

The Smart Image Analyzer is a new feature in the Epicweb AI Assistant for Optimizely CMS that automates the management of image metadata, such as...

Luc Gosso (MVP) | Jan 16, 2025 | Syndicated blog

How to: create Decimal metafield with custom precision

If you are using catalog system, the way of creating metafields are easy – in fact, you can forget about “metafields”, all you should be using is t...

Quan Mai | Jan 16, 2025 | Syndicated blog