1. Integrations

Using webhooks

The OrderCloud API supports user-defined HTTP callbacks, known as webhooks. These webhooks can be configured at either the marketplace level or for specific applications. You can specify which OrderCloud API endpoints trigger your webhook, define the roles to be passed to the configured Base URL, and include additional configuration data for authenticating with third-party systems.

Webhooks respond only to database operations (POST, PUT, PATCH, DELETE). When a webhook is triggered, it receives the original request body sent to the OrderCloud endpoint.

Webhook types

There are two types of webhooks available in OrderCloud:

  • Post-Hook: Used for replicating state changes to another database (such as analytics) or triggering external events like sending user notifications
  • Pre-Hook: Used for validating incoming requests before they are processed, such as verifying address data or validating other input

Implementation

While webhooks can be implemented in any language that can receive HTTPS requests, we recommend using OrderCloud Catalyst for C# implementations. OrderCloud Catalyst provides strongly typed webhook support and includes practical examples to help you get started.

For detailed setup instructions, see: Creating middleware

Request format

To better understand the data OrderCloud sends in webhooks, here's an example of an update to a buyer (v1/buyers/buyer_10). This example demonstrates the structure and content of a webhook payload:

json
{
  "Route": "v1/buyers/{buyerID}",
  "RouteParams": {
    "buyerID": "buyer_10"
  },
  "QueryParams": {},
  "Verb": "PUT",
  "Date": "2021-04-04T19:41:39.6504645+00:00",
  "LogID": "71ce120a-17d5-4833-89f6-4f9a33ddd42f",
  "UserToken": "...",
  "Request": {
    "Body": {
      "Active": true,
      "Name": "New Name Updated",
      "xp": {
        "segment": "Foo"
      }
    },
    "Headers": null
  },
  "Response": {
    "Body": {},
    "Headers": null
  },
  "ConfigData": {
    "config_key": "config_value"
  }
}

The webhook payload includes these key properties:

  • Route: The original route requested against OrderCloud
  • RouteParams: The path identifiers used in requests like PUT which update objects
  • QueryParams: Any query parameters included in the URL route
  • Verb: The type of request (POST, PUT, PATCH, DELETE)
  • Date: The timestamp when the request was made
  • LogID: A unique identifier for correlating requests with OrderCloud support
  • UserToken: The JWT token of the user who made the original request
  • Request.Body: The data passed in the original request (note that PATCH requests may contain partial data)
  • Request.Headers: Any headers from the original request
  • Response: For Post-Webhooks, contains the response from OrderCloud
  • ConfigData: Optional configuration data defined when setting up the webhook

Request verification

OrderCloud can optionally include an x-oc-hash header with each webhook request. This header contains a fingerprint of the request, generated using a secret that you define when registering your webhook. By verifying this fingerprint, you can ensure that incoming webhook requests are legitimate and originate from OrderCloud.

This verification process is handled automatically when using OrderCloud Catalyst. However, you can also implement the verification manually using SHA256 hashing with your registered secret.

Manual verification:

csharp
public bool VerifyWebhookHashAsync(string requestHash, string requestBody, OrderCloudWebhookAuthOptions options)
{
  Require.That(!string.IsNullOrEmpty(options.HashKey),
    new InvalidOperationException("OrderCloudWebhookAuthOptions.HashKey was not configured."));
  Require.That(!string.IsNullOrEmpty(requestBody), new WebhookUnauthorizedException());
  Require.That(!string.IsNullOrEmpty(requestHash), new WebhookUnauthorizedException());
  var bodyBytes = Encoding.UTF8.GetBytes(requestBody);
  var keyBytes = Encoding.UTF8.GetBytes(options.HashKey);
  var hash = new HMACSHA256(keyBytes).ComputeHash(bodyBytes);
  var computed = Convert.ToBase64String(hash);
  Require.That(requestHash == computed, new WebhookUnauthorizedException());
  return true;
}

Pre-hook responses

For pre-webhooks, you need to return a response indicating whether OrderCloud should proceed with the original request. The response includes a proceed flag and an optional body that can contain any JSON object or value. Here's the expected format:

json
{
  "proceed": false,
  "body": {
    "customMessage": "Not a Valid Address",
    "suggestions": [
      "..."
    ]
  }
}

When you set proceed to false, OrderCloud returns an error message to the original caller that includes the data you provided in the body. This allows you to provide custom validation messages or additional information about why the request was rejected.

Webhook configuration

Basic settings

When configuring a webhook in the OrderCloud Console, you'll need to provide these basic settings:

  • Name: An internal name or label to identify the webhook
  • Description: Optional information about the webhook's purpose
  • Secret: A key used for generating the x-oc-hash verification fingerprint
  • Payload URL: The publicly accessible endpoint where your webhook will receive requests
  • Pre-hook: Enable this flag if you want the webhook to fire before OrderCloud processes the request
  • DeliveryConfigID: Optionally specify a delivery configuration to use alternative delivery mechanisms

Note: When using DeliveryConfigID, the Pre-hook option is disabled, and the Secret and Payload URL fields are ignored since delivery is handled through the configured mechanism.

API client settings

Webhooks only fire for the API clients you explicitly assign. This feature is particularly useful when you have multiple API clients representing different storefronts or applications with distinct behaviors. If you want a webhook to fire for all your API clients, you can select all of them in the portal UI.

Configuration data

You can define optional key-value pairs that OrderCloud will include with each webhook request. This feature is particularly useful when integrating with third-party services, as you can pass registration information, account details, or other configuration data needed by the service.

Event triggers

This section is where you specify which OrderCloud operations should trigger your webhook. You can register one or more of these operations:

  • POST: Create new resources
  • PUT: Replace existing resources
  • PATCH: Update specific fields
  • DELETE: Remove resources

For example, if you want to monitor all changes to Buyers, you would register POST, PUT, PATCH, and DELETE operations for the relevant buyer endpoints.

Elevated roles

Elevated roles allow your webhook to receive an access token with higher permissions than the client that triggered the webhook. For example, if an authenticated user only has the UserAdmin role, but your webhook needs to list Categories and perform additional actions, you can add CategoryReader to the elevated roles. This ensures your webhook has all the necessary permissions to complete its tasks.

Registration example

The following example demonstrates how to register a webhook that monitors all Buyer endpoints. This configuration includes basic settings, elevated roles, configuration data, and the specific routes to monitor:

json
{
  "ID": "...",
  "Name": "sample-webhook",
  "Description": "Sample Description",
  "Url": "https://.../mywebhook",
  "HashKey": "...",
  "ElevatedRoles": [
    "BuyerAdmin"
  ],
  "ConfigData": {
    "config_key": "config_value"
  },
  "BeforeProcessRequest": true,
  "ApiClientIDs": [
    "...."
  ],
  "WebhookRoutes": [
    {
      "Route": "v1/buyers",
      "Verb": "POST"
    },
    {
      "Route": "v1/buyers/{buyerID}",
      "Verb": "DELETE"
    },
    {
      "Route": "v1/buyers/{buyerID}",
      "Verb": "PATCH"
    },
    {
      "Route": "v1/buyers/{buyerID}",
      "Verb": "PUT"
    }
  ]
}

Plugin development

Third parties developing reusable plugins for OrderCloud can create solutions that work for multiple customers by following these guidelines:

Authentication and configuration

  • Use a shared secret to validate incoming requests via the x-oc-hash header
  • Use configuration data to pass customer-specific information, such as service IDs or account details

Deployment options

  1. GitHub repository:

    • Provide integration code that customers can deploy
    • Allow customization of extended properties (XP) and field mappings
    • Enable customers to modify the code for their specific needs
  2. Global service:

    • Host a central endpoint that multiple customers can use
    • Use configuration data to identify and handle different customer accounts
    • Provide documentation for integration setup

For optimal maintenance and cost efficiency, consider implementing these services as serverless functions.

If you have suggestions for improving this article, let us know!