共用方式為


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

此套件包含適用於 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";
const 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/記錄器套件檔。

後續步驟

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

貢獻

如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。

印象