# Clarity Event Webhook
source: https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/event-webhook/index.md

## Overview {#overview}

The Consumer Clarity Event Webhook API enables near real-time webhook notifications for subscription-related actions originating from the Mastercard Consumer Clarity ecosystem. When a cardholder performs an action, like canceling, pausing, resuming, or changing a subscription, Consumer Clarity delivers an HTTPS `POST` event to your registered endpoint so your systems can respond immediately.

This guide is intended for issuers and issuer partners integrating a webhook. It outlines the minimum required steps to register a webhook endpoint, select an authentication method, validate incoming requests, and process events in both sandbox and production environments.
Note: The Clarity Event Webhook service is expanding. If you would like access, contact the [Ethoca Customer Delivery Team](mailto:customerdelivery@ethoca.com) for details.

### What you need {#what-you-need}

Before you start integrating with the Clarity Event Webhook API, make sure both your business account and technical environment meet the following prerequisites.

#### Account requirements {#account-requirements}

To use Clarity Event Webhooks, your organization must meet these onboarding and integration conditions:

* Be onboarded to **Smart Subscriptions**.
* Be actively working on a Consumer Clarity integration.

For full onboarding details, see our [Quick Start Guide](https://developer.mastercard.com/consumer-clarity/documentation/quick-start-guide/index.md).

#### Technical requirements {#technical-requirements}

Your systems must be capable of securely receiving and processing webhook events. During onboarding, you are required to provide the following:

* A publicly accessible **HTTPS** endpoint that supports `POST` requests.
* Support for **TLS 1.2 or higher**.
* The ability to respond within **5 seconds** (strongly recommended).

Authentication-dependent requirements:

* **HMAC SHA‑512**: A shared secret key provided securely during onboarding.
* **OAuth 2.0 (client_credentials)** : A `clientId`, `clientSecret`, and token endpoint URL.

## Webhook Lifecycle {#webhook-lifecycle}

The webhook lifecycle describes the end-to-end flow of an event, from the moment a cardholder takes an action to the point where your system acknowledges receipt.

A typical webhook workflow follows these steps:

1. A cardholder performs an action within a Clarity product (for example, subscription cancellation).
2. Consumer Clarity generates an event.
3. The event payload is signed using HMAC SHA‑512 or an OAuth 2.0 bearer token.
4. Consumer Clarity sends an HTTPS `POST` request to your endpoint.
5. Your service validates request authenticity and timestamps.
6. Your application processes the event.
7. Your endpoint acknowledges receipt with an HTTP `200` response.

If delivery fails, Consumer Clarity retries up to **three times** at **five-minute intervals**.

### Supported Event Types {#supported-event-types}

The Clarity Event Webhook currently supports the `SUBSCRIPTION_ACTION_UPDATE` event type. This event is triggered when a subscription action is created or updated, such as when a cardholder cancels, pauses, or resumes a subscription, or initiates a change plan. Additional event types might be introduced in the future. Your implementation should safely ignore any unknown event types.

## Integrate a Clarity Event Webhook {#integrate-a-clarity-event-webhook}

The following steps walk you through the complete lifecycle of integrating a Clarity Event Webhook, from registering and securing your endpoint, to validating requests, processing events, and testing your implementation before production use.

### Step 1: Register your webhook endpoint {#step-1-register-your-webhook-endpoint}

Webhook registration is handled during onboarding. You will work with your Mastercard representative to:

* Provide **sandbox** and **production** webhook URLs.
* Select an authentication method (HMAC or OAuth 2.0).

**Example endpoints**

* Sandbox: `https://webhooks.yourbank.com/sandbox/mastercard/clarity/events`
* Production: `https://webhooks.yourbank.com/prod/mastercard/clarity/events`

### Step 2: Implement your webhook endpoint {#step-2-implement-your-webhook-endpoint}

Once registered, your endpoint must meet basic request-handling and response requirements to successfully receive events:

* Accept `POST` requests.
* Consume `application/json` payloads.
* Respond with HTTP 200 upon successful receipt.

#### Required request headers {#required-request-headers}

Each incoming webhook request includes headers used for authentication and replay protection:

* `X-Signature`: HMAC SHA‑512 signature of request components (HMAC only).
* `X-Event-Date`: ISO 8601 timestamp indicating when the event was created.
* `X-Timestamp`: UTC epoch seconds.
* `Content-Type: application/json`.

#### Successful response {#successful-response}

```json
{ "requestReceived": true }
```

### Step 3: Validate request authenticity {#step-3-validate-request-authenticity}

To ensure webhook requests are legitimate and unaltered, you must validate their authentication tokens before processing the payload.

#### HMAC signature validation {#hmac-signature-validation}

When using HMAC authentication, validate each request using the following steps:

1. Extract the `X-Signature` header.
2. Recompute the HMAC SHA‑512 signature using newline‑delimited values in the following order:
   * HTTP verb
   * `Content-Type`
   * `X-Timestamp`
   * Raw request body (no formatting changes)
3. Compare the computed value with the received signature.
4. Reject mismatches with HTTP 401.

Here is an example snippet for HMAC signature validation:

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class WebhookHmacVerifier {

  public static boolean verifyBase64(
      String secret,
      String httpVerb,
      String contentType,
      String xTimestamp,
      String rawBody,
      String receivedSignatureBase64
  ) throws Exception {

    String stringToSign = httpVerb.toUpperCase() + "\n"
           + contentType + "\n"
           + xTimestamp + "\n"
           + rawBody + "\n";

    Mac mac = Mac.getInstance("HmacSHA512");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"));
    byte[] digestBytes = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));

    String computedBase64 = Base64.getEncoder().encodeToString(digestBytes);

    // constant-time compare
    return MessageDigest.isEqual(
        computedBase64.getBytes(StandardCharsets.UTF_8),
        receivedSignatureBase64.getBytes(StandardCharsets.UTF_8)
    );
  }
}
```

### Step 4: Validate timestamp {#step-4-validate-timestamp}

Timestamp validation helps protect your endpoint from replay attacks by ensuring events are recent.

To validate the timestamp:

* Parse the `X-Event-Date (ISO 8601)` header.
* Compare the event time to the current server time.
* Reject events older than **five minutes** (recommended).

### Step 5: Process the event payload {#step-5-process-the-event-payload}

After you validate the timestamp:

* Parse the JSON payload.
* Identify the `eventCategoryType`.
* Extract identifiers such as `paymentId`, `actionId`, `serviceId`, and `subscriptionId`.
* Use the `referenceId` for idempotent processing.
* Update internal systems as required.

Here is an event payload example:

```json
{
  "metadata": {
    "product": "SUBSCRIPTION_CONTROLS",
    "referenceId": "7e07e52b-d423-4e30-941b-bf8fd615bd8c"
  },
  "data": [
    {
      "eventCategoryType": "SUBSCRIPTION_ACTION_UPDATE",
      "paymentId": "52318413-bd05-4960-a745-f79e5c3d6de9",
      "actionId": "e9d67d1a-f5ec-4eb1-9579-208fd7b37dd7",
      "serviceId": "6f4ba885-48f6-4fa4-ba58-cd16832674d4",
      "serviceName": "Streaming Service",
      "merchantName": "Streaming Merchant",
      "subscriptionId": "0194b23d-a61d-73be-9915-0491b0a23a2e",
      "action": "CANCEL",
      "method": "AUTOMATED",
      "status": "SUCCESSFUL",
      "statusReasonCode": "PROCESSED",
      "estimatedProcessingDays": "3-5",
      "flowState": "ACTION_APPLIED",
      "createdDate": "2024-02-28T13:45:00.121778707Z",
      "updatedDate": "2024-02-28T13:45:00.121778707Z",
      "effectiveDate": "2024-02-28T13:45:00.121778707Z"
    }
  ]
}
```

### Step 6: Acknowledge the event {#step-6-acknowledge-the-event}

Always return HTTP 200 as soon as the request is received, even if additional processing continues asynchronously. Keep synchronous processing lightweight and delegate complex logic to background jobs.

### Step 7: Test in sandbox {#step-7-test-in-sandbox}

Before enabling webhooks in production, thoroughly validate your implementation using the Consumer Clarity sandbox.

* Use the Consumer Clarity sandbox environment.
* Trigger test events with Mastercard support.
* Validate error scenarios, such as invalid signatures and stale timestamps.
* Review logs and monitoring.

**Sandbox base URL**

    https://sandbox.api.mastercard.com/consumer-clarity

## Authentication Options {#authentication-options}

Consumer Clarity webhooks support multiple authentication mechanisms to accommodate different security models.

### HMAC SHA‑512 (recommended) {#hmac-sha512-recommended}

This option uses symmetric key signing to verify request authenticity.

* Uses a shared secret exchanged securely during onboarding.
* Ensures request authenticity and payload integrity.

### OAuth 2.0 (client_credentials) {#oauth-20-client_credentials}

This option relies on bearer tokens issued by your authorization server.

* Mastercard retrieves an access token from your token endpoint.
* The bearer token is included in the `Authorization` header.
* Token and timestamp must be validated when received.

Note: We currently support only HMAC and OAuth 2.0 authentication. Other methods, including mTLS, aren't supported.   

This diagram shows the Clarity Event Webhook OAuth 2.0 Authentication Flow:

![Clarity Event Webhook OAuth 2.0 Authentication Flow](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/oauth20-webhook-authentication-flow.png)

### TLS and security requirements {#tls-and-security-requirements}

To ensure secure communication, all endpoints must comply with the following TLS and security requirements.

* HTTPS is mandatory.
* TLS 1.2 or higher is required.
* Valid CA‑signed certificates only.
* Separate credentials for sandbox and production are recommended.

## Webhook Use Case Example {#webhook-use-case-example}

In this scenario, a cardholder cancels a subscription using the issuer's banking app. Because the subscription qualifies for a retention offer (indicated by `flowState = OFFER_EXTENDED`), a `SUBSCRIPTION_ACTION_UPDATE` event is sent to the issuer. This allows the issuer to present contextual UI messaging and guide the cardholder on next steps.

```json
{
  "metadata": {
    "product": "SUBSCRIPTION_CONTROLS",
    "referenceId": "7e07e52b-d423-4e30-941b-bf8fd615bd8c"
  },
  "data": [
    {
      "eventCategoryType": "SUBSCRIPTION_ACTION_UPDATE",
      "paymentId": "52318413-bd05-4960-a745-f79e5c3d6de9",
      "actionId": "e9d67d1a-f5ec-4eb1-9579-208fd7b37dd7",
      "serviceId": "6f4ba885-48f6-4fa4-ba58-cd16832674d4",
      "serviceName": "Streaming Service",
      "merchantName": "Streaming Merchant",
      "subscriptionId": "0194b23d-a61d-73be-9915-0491b0a23a2e",
      "action": "CANCEL",
      "method": "AUTOMATED",
      "status": "SUCCESSFUL",
      "statusReasonCode": "PROCESSED",
      "statusReasonCodeDescription": "Additional context for expired offer action",
      "estimatedProcessingDays": "3-5",
      "flowState": "ACTION_APPLIED"  ,
      "createdDate": "2024-02-28T13:45:00.121778707Z",
      "updatedDate": "2024-02-28T13:45:00.121778707Z",
      "effectiveDate": "2024-02-28T13:45:00.121778707Z"
    }
  ]
}
```

## Good to Know {#good-to-know}

After your webhook integration is complete, use the following resources and processes to expand and refine your Consumer Clarity implementation.

* Review the [Clarity Event Webhook API specification](https://developer.mastercard.com/consumer-clarity/documentation/api-reference/index.md#apis) for complete schema details.
* Monitor webhook retries and delivery metrics after go‑live.
* Coordinate production enablement with your [Ethoca Customer Success team](mailto:customerservice@ethoca.com).

### Reference Application {#reference-application}

Download this reference application to see a working example of webhook event handling, including payload validation and best‑practice processing patterns:
[clarity-webhook-reference-1.0-SNAPSHOT-dist.zip](https://static.developer.mastercard.com/content/consumer-clarity/uploads/clarity-webhook-reference-1.0-SNAPSHOT-dist.zip) (27KB)

## Next Steps {#next-steps}

Now that you have an understanding of what the Clarity Event Webhook service does, you can proceed to the [Quick Start Guide](https://developer.mastercard.com/consumer-clarity/documentation/quick-start-guide/index.md) and [Reference Application Tutorial](https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/reference-app-tutorial/index.md) for further assistance.
