Quickstart: Subscribe to Azure Communication Services events

In this quickstart, you learn how to subscribe to events from Azure Communication Services through the portal, Azure CLI, PowerShell and .NET SDK.

You can set up event subscriptions for Communication Services resources through the Azure portal or Azure CLI, PowerShell or with the Azure Event Grid Management SDK.

For this Quickstart, we walk through the process of setting up webhook as a subscriber for SMS events from Azure Communication Services. For a full list of events, see this page.

Prerequisites

Register the Event Grid resource provider

This article describes how to register the Event Grid resource provider. If you used Event Grid before in the same subscription, skip to the next section.

In the Azure portal, do the following steps:

  1. On the left menu, select Subscriptions.

  2. Select the Subscription you want to use for Event Grid from the subscription list.

  3. On the Subscription page, select Resource providers under Settings on the left menu.

  4. Search for Microsoft.EventGrid, and confirm that the Status is Not Registered.

  5. Select Microsoft.EventGrid in the provider list.

  6. Select Register on the command bar.

    Image showing the registration of Microsoft.EventGrid provider with the Azure subscription.

  7. Refresh to make sure the status of Microsoft.EventGrid is changed to Registered.

    Image showing the successful registration of Microsoft.EventGrid provider with the Azure subscription.

Create event subscription

To create an Event subscription for Azure Communication Services, use the following steps. This article shows how to create an Event subscription for Azure Communication Services to receive events via Webhook.

To create an Event subscription for Azure Communication Services resource, first sign in to the Azure portal. In the upper-left corner of the page, select the Communication Services resource.

  • Select on the Events tab on the left menu.
  • Select on + Event Subscription.

Screenshot highlighting the create event subscription button in the Azure portal.

  • On the Create Event Subscription page, follow these steps:
  1. Enter a name for the event subscription.

  2. Enter a name for the System topic name.

  3. Select the event types that you want to receive on the event subscription.

    Screenshot that shows the selection of event types.

    For more information on Communication Services events, see Communication Services Events

  4. Select the Endpoint Type as Web Hook.

    Screenshot that shows the selection of endpoint type.

  5. Select Configure an Endpoint

    Screenshot highlighting the create event page in the Azure portal.

  6. Enter the link to the webhook and Select Confirm Selection.

    Screenshot highlighting the select webhook endpoint page in the Azure portal.

  7. In the Filters tab, add the names of the event types you want to filter in the subscription and add context attribute filters you want to use in the subscription. Then, select Next: Additional features at the bottom of the page.

    Screenshot highlighting Event Grid create filters page in the Azure portal.

  8. To enable dead lettering and customize retry policies, select Additional Features.

    Screenshot that shows the Additional features tab of the Create Event Subscription page.

  9. When done, select Create.

Update event subscription

To update an Event subscription for Azure Communication Services, use the following steps. This section shows how to update an Event subscription for Azure Communication Services to update the events you want to receive via Webhook.

To update an Event subscription for Azure Communication Services resource, first sign in to the Azure portal. In the upper-left corner of the page, select the Communication Services resource.

  1. Select the Events tab on the left menu.

  2. Select the Event Subscriptions and select on the Event subscription you want to update.

    Screenshot highlighting the event subscription button in the Azure portal.

  3. On the Event Subscription page, select on Filters tab. Select the event types that you want to receive on the event subscription.

    Screenshot that shows the selection of event types to update.

  4. To enable dead lettering and customize retry policies, select Additional Features.

    Screenshot that shows the Additional features tab of the Update Event Subscription page.

  5. To update the webhook to receive events, select on Change next to the webhook link and enter the new webhook endpoint. Screenshot that shows the Change the webhook endpoint link in the Event Subscription page.

  6. When done, select Save, Screenshot that shows the save button in the Azure portal.

Delete event subscription

To delete an Event subscription for Azure Communication Services, use the following steps.

To delete an Event subscription for Azure Communication Services resource, first sign in to the Azure portal. In the upper-left corner of the page, select the Communication Services resource.

  1. Select on the Events tab on the left menu.

  2. Select on Event Subscriptions and Select on the Event subscription you want to delete.

    Screenshot highlighting the event subscriptions button to access event subscription to be deleted in the Azure portal.

  3. On the Event Subscription page, Select on Delete button at the top.

    Screenshot highlighting the delete button in the Azure portal.

Next steps

Prerequisites

Register the Event Grid resource provider

This article describes how to register the Event Grid resource provider. If you used Event Grid before in the same subscription, skip to the next section.

  1. Run the following command to register the provider:

    az provider register --namespace Microsoft.EventGrid
    
  2. It might take a moment for the registration to finish. To check the status, run the following command:

    az provider show --namespace Microsoft.EventGrid --query "registrationState"
    

    When registrationState is Registered, you're ready to continue.

Create event subscription

To create event subscriptions for Azure Communication Services resource, sign in to Azure CLI. You can sign in running the az login command from the terminal and providing your credentials. Run the following command to create the event subscription for the resource:

To create an event subscription by using the Azure CLI, use the az eventgrid event-subscription create command.

az eventgrid event-subscription create 
    --name EventsWebhookSubscription
    --source-resource-id /subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>
    --included-event-types Microsoft.Communication.SMSReceived Microsoft.Communication.SMSDeliveryReportReceived
    --endpoint-type webhook 
    --endpoint https://azureeventgridviewer.azurewebsites.net/api/updates  

For a list of Communication Services events, see Communication Services Events.

List event subscriptions

To list all the existing event subscriptions set up for an Azure Communication Services resource, by using the Azure CLI, use the az eventgrid event-subscription list command.

az eventgrid event-subscription list 
    --source-resource-id /subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>    

Update event subscription

To update an existing event subscription by using the Azure CLI, use the az eventgrid event-subscription update command.

az eventgrid event-subscription update 
    --name EventsWebhookSubscription
    --source-resource-id /subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>
    --included-event-types Microsoft.Communication.SMSReceived Microsoft.Communication.SMSDeliveryReportReceived Microsoft.Communication.ChatMessageReceived
    --endpoint-type webhook 
    --endpoint https://azureeventgridviewer.azurewebsites.net/api/updates

Delete event subscription

To delete an existing event subscription by using the Azure CLI, use the az eventgrid event-subscription delete command.

az eventgrid event-subscription delete 
    --name EventsWebhookSubscription 
    --source-resource-id /subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>

Next steps

Prerequisites

Register the Event Grid resource provider

This article describes how to register the Event Grid resource provider. If you used Event Grid before in the same subscription, skip to the next section.

In the Azure portal, do the following steps:

  1. On the left menu, select Subscriptions.

  2. Select the Subscription you want to use for Event Grid from the subscription list.

  3. On the Subscription page, select Resource providers under Settings on the left menu.

  4. Search for Microsoft.EventGrid, and confirm that the Status is Not Registered.

  5. Select Microsoft.EventGrid in the provider list.

  6. Select Register on the command bar.

    Image showing the registration of Microsoft.EventGrid provider with the Azure subscription.

  7. Refresh to make sure the status of Microsoft.EventGrid is changed to Registered.

    Image showing the successful registration of Microsoft.EventGrid provider with the Azure subscription.

Installing the SDK

First, install the Microsoft Azure Event Grid Management library for .NET with NuGet:

dotnet add package Azure.ResourceManager.EventGrid;

Include the Event Grid Management SDK in your C# project:

using Microsoft.Azure.Management.EventGrid;
using Microsoft.Azure.Management.EventGrid.Models;

Authenticating with Azure Identity library

Prerequisites:

  1. Create a Microsoft Entra application and Service Principal and set up a client secret or trusted certificate issued by certificate authority by following the instructions here.
  2. Store the secret or the certificate in the Azure Keyvault.
  3. Give contributor or owner access to the subscription to that application following the instructions here.
  4. Read more about authorizing access to Event Grid resources here.

The Azure Identity library provides Microsoft Entra ID (Formerly Azure Active Directory) token authentication support across the Azure SDK. It provides a set of TokenCredential implementations, which can be used to construct Azure SDK clients that support Microsoft Entra token authentication. You can read more about it here.

  1. Include the Azure Identity client library for .NET with NuGet:
dotnet add package Azure.Identity;
dotnet add package Azure.Security.KeyVault.Secrets
  1. Include the Azure Identity library in your C# project
using Microsoft.Azure.Identity;
using Azure.Security.KeyVault.Secrets
  1. You can either pass the secret credentials or certificate credentials to get access token, based on how your Service Principal is configured.

    • Get access token using secret credential

      To get the secret credentials, you need to read it from the Keyvault you created in Prerequisite #2 using SecretClient.

      // Authenticate the Keyvault client with DefaultAzureCredential and get the secret.
      SecretClient secretClient = new SecretClient(new Uri("https://myvault.vault.azure.net/"), new DefaultAzureCredential());
      string clientSecret = await secretClient.GetSecretAsync(secretName).Value;
      
      // Get access token using secret credentials
      string[] scopes = { "https://management.azure.com/.default" };
      var application = ConfidentialClientApplicationBuilder
                          .Create('your-servicePrincipal-appId')
                          .WithAuthority(authorityUri: new Uri(authority), validateAuthority: true)
                          .WithTenantId('your-tenant_id')
                          .WithClientSecret(clientSecret)
                          .Build();
      
      var token = await application
                      .AcquireTokenForClient(scopes)
                      .ExecuteAsync();
      
    • Get access token using certificate credential

      To get the certificate credentials, you need to read it from the Keyvault you created in Prerequisite #2 using CertificateClient.

      Read more about the Microsoft Entra application configuration authority here

      // Authenticate the certificate client with DefaultAzureCredential and get the certificate.
      CertificateClient certificateClient = new SecretClient(new Uri("https://myvault.vault.azure.net/"), new DefaultAzureCredential());
      X509Certificat2 cert = await certificateClient.DownloadCertificateAsync(certificateName);
      
      // Get access token using certificate credentials
      string[] scopes = { "https://management.azure.com/.default" };
      string authority = "https://login.microsoftonline.com/<tenant>/";
      var application = ConfidentialClientApplicationBuilder
                          .Create('<servicePrincipal-appId>')
                          .WithAuthority(authorityUri: new Uri(authority), validateAuthority: true)
                          .WithTenantId("<tenantId>")
                          .WithCertificate(cert)
                          .Build();
      
      var token = await application
                      .AcquireTokenForClient(scopes)
                      .WithSendX5C(true)
                      .ExecuteAsync();
      
  2. Authenticate EventGridManagementClient with access token using secret or certificate credentials

// Authenticate EventGridManagementClient with Microsoft Entra ID access token credential
eventGridClient = new EventGridManagementClient(new Uri("https://management.azure.com/"),
    new TokenCredentials(token.AccessToken));

eventGridClient.SubscriptionId = 'your_subscripiton_id';

Create Event Subscription

This code sample shows how to create the event subscription for the webhook subscriber endpoint.

string webhookUri = $"<webhookUri>";
string resourceId="/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>";
string[] includedEventTypes = new string[]{ "Microsoft.Communication.SMSReceived", 
                                            "Microsoft.Communication.SMSDeliveryReportReceived"
                                            };

EventSubscription eventSubscription = new EventSubscription(
    name: "<eventSubscriptionName>",
    eventDeliverySchema: "EventGridSchema",
    filter: new EventSubscriptionFilter(
    includedEventTypes: includedEventTypes),
    destination: new WebHookEventSubscriptionDestination(webhookUri));

await eventGridClient.EventSubscriptions.CreateOrUpdateAsync(
    scope: resourceId,
    eventSubscriptionName: "<eventSubscriptionName>",
    eventSubscriptionInfo: eventSubscription);

Update event subscription

This code sample shows how to update the event subscription to add more events, you want to receive on the webhook subscriber endpoint.

string webhookUri = $"<webhookUri>";
string resourceId="/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>";
string[] additionalEventTypes = new string[]{ 
                                            "Microsoft.Communication.ChatMessageReceived"
                                        };

await eventGridClient.EventSubscriptions.UpdateAsync(
    scope: resourceId,
    eventSubscriptionName: "<eventSubscriptionName>",
    eventSubscriptionUpdateParameters: new EventSubscriptionUpdateParameters(
            filter: new EventSubscriptionFilter(includedEventTypes: additionalEventTypes)));

Delete event Subscription

This code sample shows how to delete the event subscription for the webhook subscriber endpoint.

string webhookUri = $"<webhookUri>";
string resourceId="/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>";

await eventGridClient.EventSubscriptions.DeleteAsync(
    scope: resourceId,
    eventSubscriptionName: "<eventSubscriptionName>");

Prerequisites

Register the Event Grid resource provider

This article describes how to register the Event Grid Resource Provider. If you used Event Grid before in the same subscription, skip to the next section.

  1. Run the following command:
Register-AzResourceProvider -ProviderNamespace Microsoft.EventGrid
  1. It may take a moment for the registration to finish. To check the status, run:
Get-AzResourceProvider -ProviderNamespace Microsoft.EventGrid

When RegistrationStatus is Registered, you're ready to continue.

Create event subscription

First, make sure to install the Azure Communication Services module Az.EventGrid using the following command.

PS C:\> Install-Module Az.EventGrid
  • Sign in to your Azure subscription with the Connect-AzAccount command and follow the on-screen directions:

    Connect-AzAccount
    
  • If your identity is associated with more than one subscription, then set your active subscription to subscription of the Web PubSub resource that you want to move.

    $context = Get-AzSubscription -SubscriptionId <subscription-id>
    Set-AzContext $context
    

To create an event subscription by using the Azure PowerShell, use the New-AzEventGridSubscription command.

$includedEventTypes = "Microsoft.Communication.SMSReceived", "Microsoft.Communication.SMSDeliveryReportReceived"
New-AzEventGridSubscription 
    -EndpointType webhook
    -Endpoint https://azureeventgridviewer.azurewebsites.net/api/updates
    -EventSubscriptionName EventsWebhookSubscription 
    -IncludedEventType $includedEventTypes
    -ResourceId "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>"

For a list of Communication Services events, see Communication Services Events.

List event subscriptions

To list all the existing event subscriptions set up for an Azure Communication Services resource, by using the Azure PowerShell, use the Get-AzEventGridSubscription command.

Get-AzEventGridSubscription 
    -ResourceId "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>"

Update event subscription

To update an existing event subscription by using the Azure PowerShell, use the Update-AzEventGridSubscription command.

$includedEventTypes = "Microsoft.Communication.SMSReceived", "Microsoft.Communication.SMSDeliveryReportReceived", "Microsoft.Communication.ChatMessageReceived"
Update-AzEventGridSubscription 
    -EventSubscriptionName ES2 
    -IncludedEventType $includedEventTypes
    -ResourceId "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>" 
    -Endpoint https://azureeventgridviewer2.azurewebsites.net/api/updates
    -SubjectEndsWith "phoneNumber"
 

Delete event subscription

To delete an existing event subscription by using the Azure PowerShell, use the Remove-AzEventGridSubscription command.

Get-AzResource 
    -ResourceId "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Communication/CommunicationServices/<acsResourceName>" | Remove-AzEventGridSubscription -EventSubscriptionName ES2

Next steps