JavaScript 用 Azure CommunicationMessages REST クライアント ライブラリ - バージョン 1.0.1

このパッケージには、Azure Communication Messages Services 用の JavaScript SDK が含まれています。

主要リンク:

はじめに

現在サポートされている環境

前提条件

@azure-rest/communication-messages パッケージのインストール

を使用して、JavaScript 用の Azure CommunicationMessages REST クライアント REST クライアント ライブラリを npmインストールします。

npm install @azure-rest/communication-messages

認証

Azure Portal で Communication Services リソースからキーや接続文字列を取得できます。 キーを取得したら、次のいずれかの方法で認証できます。

接続文字列の使用

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 マネージド ID の使用

クライアント API キー認証はほとんどの例で使用されますが、Azure Id ライブラリを使用して Azure Active Directory で認証することもできます。 下に示した DefaultAzureCredential プロバイダーか、Azure SDK で提供されている他の資格情報プロバイダーを使用するには、@azure/identity パッケージをインストールしてください。

npm install @azure/identity

@azure/identity パッケージには、アプリケーションでこれを行うために使用できるさまざまな資格情報の種類が用意されています。 @azure/identity の README には、作業を開始するための詳細とサンプルが記載されています。 DefaultAzureCredential オブジェクトを作成するには、AZURE_CLIENT_SECRET、AZURE_CLIENT_ID、およびAZURE_TENANT_ID環境変数が必要です。

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_LEVELinfo に設定します。 または、@azure/loggersetLogLevel を呼び出して、実行時にログ記録を有効にすることもできます。

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

setLogLevel("info");

ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。

次の手順

このライブラリの使用方法の詳細な例については、 samples ディレクトリを参照してください。

共同作成

このライブラリに投稿する場合、コードをビルドしてテストする方法の詳細については、投稿ガイドを参照してください。

インプレッション数