你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的 Azure CommunicationMessages REST 客户端库 - 版本 1.0.1

此包包含适用于 Azure 通信消息服务的 JavaScript SDK。

关键链接:

入门

目前支持的环境

先决条件

安装 @azure-rest/communication-messages

使用 npm安装适用于 JavaScript 的 Azure CommunicationMessages REST 客户端客户端库:

npm install @azure-rest/communication-messages

身份验证

可以从 Azure 门户中的通信服务资源获取密钥和/或连接字符串。 获得密钥后,可以使用以下任一方法进行身份验证:

使用连接字符串

import MessageClient, { MessagesServiceClient } from "@azure-rest/communication-messages";

const connectionString = `endpoint=https://<resource-name>.communication.azure.com/;accessKey=<Base64-Encoded-Key>`;
const client:MessagesServiceClient = MessageClient(connectionString);

使用 AzureKeyCredential

import { AzureKeyCredential } from "@azure/core-auth";
import MessageClient, { MessagesServiceClient } from "@azure-rest/communication-messages";

const endpoint = "https://<resource-name>.communication.azure.com";
const credential = new AzureKeyCredential("<Base64-Encoded-Key>");
const client:MessagesServiceClient = MessageClient(endpoint, credential);

使用 Azure Active Directory 托管标识

大多数示例都使用客户端 API 密钥身份验证,但也可以使用 Azure 标识库通过 Azure Active Directory 进行身份验证。 若要使用如下所示的 DefaultAzureCredential 提供程序或 Azure SDK 随附的其他凭据提供程序,请安装 @azure/identity 包:

npm install @azure/identity

@azure/identity 包提供应用程序可用于执行此操作的各种凭据类型。 @azure/identity 的自述文件提供了更多详细信息和示例来帮助你入门。 AZURE_CLIENT_SECRET,需要AZURE_CLIENT_ID和AZURE_TENANT_ID环境变量来创建 DefaultAzureCredential 对象。

import { DefaultAzureCredential } from "@azure/identity";
import MessageClient, { MessagesServiceClient } from "@azure-rest/communication-messages";

const endpoint = "https://<resource-name>.communication.azure.com";
let credential = new DefaultAzureCredential();
const client:MessagesServiceClient = MessageClient(endpoint, credential);

使用 WhatsApp 频道发送模板消息

Note: Business always starts the conversation with a template message.

若要发送模板消息,需要将模板添加到 WhatsApp Bussiness 帐户。 有关 WhatsApp 模板的更多详细信息,请参阅 创建和管理模板。 在下面的示例中,我们将使用

 Template Name: sample_issue_resolution
 Template Language: en_US

 Template Body: "Hi {{1}}, were we able to solve the issue that you were facing?"
 
 With Quick Action Button (Yes, No)

const nameValue:MessageTemplateValue = {
        kind: "text",
        name: "name",
        text: "Arif"
    };

    const yesAction: MessageTemplateValue = {
        kind: "quickAction",
        name: "Yes",
        payload: "Yes"
    };

    const noAction: MessageTemplateValue = {
        kind: "quickAction",
        name: "No",
        payload: "No"
    };

    const templateBindings:MessageTemplateBindings = {
        kind: "whatsApp",
        body: [
            {
                refValue: "name"
            }
        ],
        buttons: [
            {
                subType: "quickReply",
                refValue: "Yes"
            },
            {
                subType: "quickReply",
                refValue: "No"
            }
        ]
    };

    const template:MessageTemplate = {
        name: "sample_issue_resolution",
        language: "en_US",
        bindings: templateBindings,
        values: [nameValue, yesAction, noAction]
    };

    const  result = await client.path("/messages/notifications:send").post({
        contentType: "application/json",
        body: {
            channelRegistrationId: "<Channel_Registration_Id>",
            to: ["<to-phone-number-1>"],
            kind: "template",
            template: template
        }
    });
    if (result.status === "202") {
        const response:Send202Response = result as Send202Response;
        response.body.receipts.forEach((receipt) => {
            console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
        });
    } else {
        throw new Error("Failed to send message");
    }

使用 WhatsApp 频道发送短信

Note: Business can't start a conversation with a text message. It needs to be user initiated.

const  result = await client.path("/messages/notifications:send").post({
        contentType: "application/json",
        body: {
            channelRegistrationId: "<Channel_Registration_Id>",
            to: ["<to-phone-number-1>"],
            kind: "text",
            content: "Hello World!!"
        }
    });

 if (result.status === "202") {
        const response:Send202Response = result as Send202Response;
        response.body.receipts.forEach((receipt) => {
            console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
        });
    } else {
        throw new Error("Failed to send message");
    }

使用 WhatsApp 频道发送媒体消息

Note: Business can't start a conversation with a media message. It needs to be user initiated.

const  result = await client.path("/messages/notifications:send").post({
        contentType: "application/json",
        body: {
            channelRegistrationId: "<Channel_Registration_Id>",
            to: ["<to-phone-number-1>"],
            kind: "image",
            mediaUri: "https://<your-media-image-file>"
        }
    });

 if (result.status === "202") {
        const response:Send202Response = result as Send202Response;
        response.body.receipts.forEach((receipt) => {
            console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId);
        });
    } else {
        throw new Error("Failed to send message");
    }

疑难解答

日志记录

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以在运行时通过调用 @azure/logger 中的 setLogLevel 来启用日志记录:

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

有关如何启用日志的更详细说明,请查看 @azure/logger 包文档

后续步骤

请查看 示例 目录,获取有关如何使用此库的详细示例。

贡献

若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。

曝光数