How to create a custom Webhook for Sitecore OrderCloud

Sitecore OrderCloud Webhooks are user-defined HTTP callbacks. It’s one of the possible types of extensibility for OrderCloud. You can choose which OrderCloud API endpoints will trigger your hook, the roles to be passed onto the configured Base URL, and any additional configuration data OrderCloud may need to authenticate into 3rd party systems.

Sitecore OrderCloud Webhooks can only be triggered for OrderCloud API endpoints that write to the database (POST, PUT, PATCH, DELETE).

There are two types of Webhooks:

1. Pre-Hook (Webhook will be triggered before executing OrderCloud API endpoint, mostly used for any custom validation)
2. Post-Hook (Webhook will be triggered after executing OrderCloud API endpoint, for example, send order details to 3rd party system)

I will show you how you can extend the existing OrderCloud Headstart Middleware with the custom Webhook. I will create the webhook for Create LineItem (Add to cart).

Let’s create WebhookController under Headstart.API project:

WebhookController inherits OrderCloud.Catalyst.BaseController. Make sure to add OrderCloud.Catalyst NuGet package if it is missing. We have to provide route for HTTP POST request and the OrderCloudWebhookAuth attribute for the webhook endpoint. OrderCloudWebhookAuthAttribute is a security feature that blocks requests that do not come from OrderCloud webhooks

 

OrderCloudWebhookAuthAttribute has to use WebhookHashKey from the Azure App Configuration. We will configure this string in OrderCloud to give webhook access to your protected route.

Once everything is ready from the middleware perspective, we can deploy and run it.
As a result in Swagger we will be able to see our endpoint:

Now we have to create/register our webhook in OrderCloud. We have to navigate to the OrderCloud portal and create the webhook:

We have to provide the webhook name, secret, payload URL, and enable the Pre-Hook switcher. The value for the Secret field you can get from your Azure App Configuration for OrderCloudSettings:WebhookHashKey key.

You can check all API Clients, provide any Configuration Data if it is needed and choose Trigger Events. In my case, I will select LineItems |  Post (Create a line item). Save it and test.

If we will try to add any product with a quantity greater than 5 we will see the following:

As far as we can see, OrderCloud Webhooks is very flexible and extension mechanism which can be used for different business needs.

Happy coding!