Partager via


Azure Messages client library for Java - version 1.1.0

This package contains a Java SDK for Azure Communication Messages Services.

Documentation

Various documentation is available to help you get started

Getting started

Prerequisites

Adding the package to your product

Please include the azure-sdk-bom to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. To learn more about the BOM, see the AZURE SDK BOM README.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

and then include the direct dependency in the dependencies section without the version tag.

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-messages</artifactId>
  </dependency>
</dependencies>

Include direct dependency

If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-messages</artifactId>
    <version>1.0.0</version>
</dependency>

Key concepts

Then SDK provides two clients and each client can be async client or normal client:

  • NotificationMessageClient or NotificationMessageAsyncClient provide operation to send message (text, media or template) and download media file from Whatsapp for given mediaId which we receive in incoming message event (User to Business Flow).
  • MessageTemplateClient or MessageTemplateAsyncClient provide operation to fetch template list for given channel.

Authentication

You can get a key and/or connection string from your Communication Services resource in Azure Portal. Once you have a key, you may authenticate with any of the following methods:

Using a connection string

NotificationMessagesClient notificationClient = new NotificationMessagesClientBuilder()
    .connectionString("<CONNECTION_STRING>")
    .buildClient();
MessageTemplateClient messageTemplateClient = new MessageTemplateClientBuilder()
    .connectionString("<CONNECTION_STRING>")
    .buildClient();

Using AzureKeyCredential

String endpoint = "https://<resource-name>.communication.azure.com";
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
NotificationMessagesClient notificationClient = new NotificationMessagesClientBuilder()
    .endpoint(endpoint)
    .credential(azureKeyCredential)
    .buildClient();
String endpoint = "https://<resource-name>.communication.azure.com";
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
MessageTemplateClient messageTemplateClient = new MessageTemplateClientBuilder()
    .endpoint(endpoint)
    .credential(azureKeyCredential)
    .buildClient();

Using Azure Active Directory managed identity

Client API key authentication is used in most of the examples, but you can also authenticate with Azure Active Directory using the Azure Identity library. To use the DefaultAzureCredential provider shown below,

The AZURE_CLIENT_SECRET, AZURE_CLIENT_ID, and AZURE_TENANT_ID environment variables are needed to create a DefaultAzureCredential object.

String endpoint = "https://<resource-name>.communication.azure.com";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
NotificationMessagesClient notificationClient =  new NotificationMessagesClientBuilder()
    .endpoint(endpoint)
    .credential(credential)
    .buildClient();
String endpoint = "https://<resource-name>.communication.azure.com";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
MessageTemplateClient messageTemplateClient = new MessageTemplateClientBuilder()
    .endpoint(endpoint)
    .credential(credential)
    .buildClient();

Examples

/*
* This sample shows how to send template message with below details
* Name: sample_shipping_confirmation, Language: en_US
*  [
      {
        "type": "BODY",
        "text": "Your package has been shipped. It will be delivered in {{1}} business days."
      },
      {
        "type": "FOOTER",
        "text": "This message is from an unverified business."
      }
    ]
* */
private void sendTemplateMessage() {

    //Update Template Name and language according your template associate to your channel.
    MessageTemplate template = new MessageTemplate("sample_shipping_confirmation", "en_US");

    //Update template parameter type and value
    List<MessageTemplateValue> messageTemplateValues = new ArrayList<>();
    messageTemplateValues.add(new MessageTemplateText("Days", "5"));
    template.setValues(messageTemplateValues);

    //Update template parameter binding
    List<WhatsAppMessageTemplateBindingsComponent> components = new ArrayList<>();
    components.add(new WhatsAppMessageTemplateBindingsComponent("Days"));
    MessageTemplateBindings bindings = new WhatsAppMessageTemplateBindings()
        .setBody(components);
    template.setBindings(bindings);

    NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        .connectionString("<CONNECTION_STRING>")
        .buildClient();
    List<String> recipients = new ArrayList<>();
    recipients.add("<RECIPIENT_IDENTIFIER e.g. PhoneNumber>");
    SendMessageResult result = client.send(
        new TemplateNotificationContent("CHANNEL_ID", recipients, template));

    result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
}
/*
 * This sample shows how to send simple text message with below details
 * Note: Business cannot initiate conversation with text message.
 * */
private void sendTextMessage() {
    NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        .connectionString("<CONNECTION_STRING>")
        .buildClient();
    List<String> recipients = new ArrayList<>();
    recipients.add("<RECIPIENT_IDENTIFIER e.g. PhoneNumber>");
    SendMessageResult result = client.send(
        new TextNotificationContent("<CHANNEL_ID>", recipients, "Hello from ACS messaging"));

    result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
}
/*
 * This sample shows how to send image message with below details.
 * Supported image - image/jpeg (.jpeg), image/png (.png)
 * Note: Business cannot initiate conversation with media message.
 * */
public void sendImageMessage() {
    //Update the Media URL
    String mediaUrl = "https://wallpapercave.com/wp/wp2163723.jpg";
    List<String> recipients = new ArrayList<>();
    recipients.add("<RECIPIENT_IDENTIFIER e.g. PhoneNumber>");
    NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        .connectionString("<CONNECTION_STRING>")
        .buildClient();
    SendMessageResult result = client.send(
        new ImageNotificationContent("<CHANNEL_ID>", recipients, mediaUrl));

    result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
}
/*
 * This sample shows how to send video message with below details
 * Supported video - video/3gp (.3gp), video/mp4 (.mp4)
 * Note: Business cannot initiate conversation with media message.
 * */
public void sendVideoMessage() {
    //Update the Media URL
    String mediaUrl = "https://sample-videos.com/video321/mp4/480/big_buck_bunny_480p_1mb.mp4";
    List<String> recipients = new ArrayList<>();
    recipients.add("<RECIPIENT_IDENTIFIER e.g. PhoneNumber>");
    NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        .connectionString("<CONNECTION_STRING>")
        .buildClient();
    SendMessageResult result = client.send(
        new VideoNotificationContent("<CHANNEL_ID>", recipients, mediaUrl));

    result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
}
/*
 * This sample shows how to send audio message with below details
 * Supported audio - audio/aac (.aac), audio/amr (.amr), audio/mpeg (.mp3), audio/a4a (.mp4), audio/ogg (.ogg )
 * Note: Business cannot initiate conversation with media message.
 * */
public void sendAudioMessage() {
    //Update the Media URL
    String mediaUrl = "https://sample-videos.com/audio/mp3/wave.mp3";
    List<String> recipients = new ArrayList<>();
    recipients.add("<RECIPIENT_IDENTIFIER e.g. PhoneNumber>");
    NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        .connectionString("<CONNECTION_STRING>")
        .buildClient();
    SendMessageResult result = client.send(
        new AudioNotificationContent("<CHANNEL_ID>", recipients, mediaUrl));

    result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
}
/*
 * This sample shows how to send document message with below details
 * Supported Document type - Plain Text (.txt), PDF (.pdf), Microsoft Excel, Word, PowerPoint
 * Note: Business cannot initiate conversation with media message.
 * */
public void sendDocumentMessage() {
    //Update the Media URL
    String mediaUrl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
    List<String> recipients = new ArrayList<>();
    recipients.add("<RECIPIENT_IDENTIFIER e.g. PhoneNumber>");
    NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        .connectionString("<CONNECTION_STRING>")
        .buildClient();
    SendMessageResult result = client.send(
        new DocumentNotificationContent("<CHANNEL_ID>", recipients, mediaUrl));

    result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
}

Get Template List for given channel example:

MessageTemplateClient templateClient =
    new MessageTemplateClientBuilder()
        .connectionString("<Connection_String>")
        .buildClient();

PagedIterable<MessageTemplateItem> response = templateClient.listTemplates("<CHANNEL_ID>");

response.stream().forEach(t -> {
    WhatsAppMessageTemplateItem template = (WhatsAppMessageTemplateItem) t;
    System.out.println("===============================");
    System.out.println("Template Name :: " + template.getName());
    System.out.println("Template Language :: " + template.getLanguage());
    System.out.println("Template Status :: " + template.getStatus());
    System.out.println("Template Content :: " + template.getContent());
    System.out.println("===============================");
});

Troubleshooting

More details coming soon,

Next steps

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Impressions