> For the complete documentation index, see [llms.txt](https://api-docs.adcreative.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://api-docs.adcreative.ai/docs/getting-started/notifications/how-to-receive-notifications.md).

# How to Receive Notifications

### Overview

To receive notifications, you need to configure a WebHook Notification Channel for your application. Notifications such as **ImageGenerationProgress** and **ImageGenerationTaskCompleted** will be sent to the configured endpoint.

### Setting Up a WebHook Listener

Below is an example implementation of a WebHook listener to receive and parse notifications.

#### Example Listener (C#)

```csharp
/// <summary>
/// Listens to the AdCreative API webhook notifications.
/// </summary>
[HttpPost, AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> WebhookListener()
{
    using var reader = new StreamReader(Request.Body);
    var jsonBody = await reader.ReadToEndAsync();

    if (string.IsNullOrEmpty(jsonBody))
    {
        _logger.LogError("Invalid WebHook request body.");
        return BadRequest("Invalid WebHook request body.");
    }

    var message = UnionConverter<INotificationMessage>.Deserialize(jsonBody);

    switch (message)
    {
        case ImageGenerationProgress progress:
            _logger.LogInformation("Image Generation Progress received for User: {0}", progress.UserId);
            // Process Progress
            break;

        case ImageGenerationTaskCompleted taskCompleted:
            _logger.LogInformation("Image Generation Task Completed for User: {0}", taskCompleted.UserId);
            // Process Task Completion
            break;
            
        case ImageUpscalingProgress progress:
            _logger.LogInformation("Image Upscaling Progress received for User: {0}", progress.UserId);
            // Process Progress
            break;

        case ImageUpscalingTaskCompleted taskCompleted:
            _logger.LogInformation("Image Upscaling Task Completed for User: {0}", taskCompleted.UserId);
            // Process Task Completion
            break;
            
        case ImageFaceEnhancingProgress progress:
            _logger.LogInformation("Image Face Enhancing Progress received for User: {0}", progress.UserId);
            // Process Progress
            break;

        case ImageFaceEnhancingTaskCompleted taskCompleted:
            _logger.LogInformation("Image Face Enhancing Task Completed for User: {0}", taskCompleted.UserId);
            // Process Task Completion
            break;
            
        case ImageBackgroundRemovingProgress progress:
            _logger.LogInformation("Image Background Removing Progress received for User: {0}", progress.UserId);
            // Process Progress
            break;

        case ImageBackgroundRemovingTaskCompleted taskCompleted:
            _logger.LogInformation("Image Background Removing Task Completed for User: {0}", taskCompleted.UserId);
            // Process Task Completion
            break;
            
        case ImageStockGenerationProgress progress:
            _logger.LogInformation("Image Stock Generation Progress received for User: {0}", progress.UserId);
            // Process Progress
            break;

        case ImageStockGenerationTaskCompleted taskCompleted:
            _logger.LogInformation("Image Stock Generation Task Completed for User: {0}", taskCompleted.UserId);
            // Process Task Completion
            break;

        default:
            _logger.LogWarning("Unknown notification type received.");
            return BadRequest("Unknown notification type.");
    }

    return Ok();
}
```

### Notification Message Types

#### 1. ImageGenerationTaskCompleted

Represents a notification sent when an image generation task is completed.

**Sample JSON Structure**

```json
{
    "MessageType": "ImageGenerationTaskCompleted",
    "ApplicationId": "d5eabbb8-c0f6-4640-94fd-3566edad499f",
    "UserId": "2581c740-8e9d-4d63-96bc-5665bb9a646b",
    "ImageRenderProcessId": "cbda4889-ac1d-4073-9b84-b3ab29417606",
    "TaskId": "9baa8e55-ddc8-4940-907f-eb5fc81e53f6",
    "ImageContentBytes": "BASE64_ENCODED_IMAGE_DATA",
    "IsSuccessful": true,
    "ErrorMessage": ""
}
```

#### 2. ImageGenerationProgress

Represents the progress of an image generation process.

**Sample JSON Structure**

```json
{
    "MessageType": "ImageGenerationProgress",
    "RequestRenderState": 1,
    "ApplicationId": "d5eabbb8-c0f6-4640-94fd-3566edad499f",
    "UserId": "2581c740-8e9d-4d63-96bc-5665bb9a646b",
    "ImageRenderProcessId": "cbda4889-ac1d-4073-9b84-b3ab29417606",
    "TotalTaskCount": 10,
    "CompletedTaskCount": 5,
    "Progress": 50.0,
    "Tasks": {
        "9baa8e55-ddc8-4940-907f-eb5fc81e53f6": 5
    },
    "RenderKind": 1,
    "RenderType": 2,
    "IsSuccessful": true,
    "ErrorMessage": ""
}
```

### Key Considerations

1. **Endpoint Security:**
   * ***Currently, no authentication mechanisms are supported for WebHook endpoints. Ensure your endpoint is secure.***
   * ***Future updates will include authentication support.***
2. **Message Parsing:**
   * Use a JSON parser compatible with your programming language to handle incoming messages.
   * Validate the message structure before processing.
3. **Error Handling:**
   * Return appropriate HTTP status codes (`400`, `500`) for malformed requests or server-side issues.

***

### Language-Agnostic Workflow

1. **Setup WebHook Endpoint:**
   * Create a POST endpoint to listen for incoming notifications.
2. **Read Request Body:**
   * Parse the incoming JSON payload to extract the notification message.
3. **Identify Message Type:**
   * Use the `MessageType` field to determine the notification type.
4. **Process Message:**
   * Handle each message type appropriately.

***
