共用方式為


適用於 JavaScript 的 Azure CommunicationMessages REST 用戶端連結庫 - 1.0.1 版

此套件包含適用於 Azure 通訊訊息服務的 JavaScript SDK。

重要連結:

開始使用

目前支援的環境

必要條件

安裝 @azure-rest/communication-messages 套件

使用 npm安裝適用於 JavaScript 的 Azure CommunicationMessages REST 用戶端 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 套件文件

下一步

如需如何使用此連結庫的詳細 範例 ,請參閱範例目錄。

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。

曝光數