Delen via


Azure CommunicationMessages REST-clientbibliotheek voor JavaScript - versie 1.0.1

Dit pakket bevat een JavaScript-SDK voor Azure Communication Messages Services.

Belangrijke koppelingen:

Aan de slag

Momenteel ondersteunde omgevingen

Vereisten

Installeer het pakket @azure-rest/communication-messages

Installeer de REST-clientbibliotheek van de Rest-client van Azure CommunicationMessages voor JavaScript met npm:

npm install @azure-rest/communication-messages

Verificatie

U kunt een sleutel en/of verbindingsreeks ophalen uit uw Communication Services-resource in Azure Portal. Zodra u een sleutel hebt, kunt u zich verifiëren met een van de volgende methoden:

Een verbindingsreeks gebruiken

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 gebruiken

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);

Beheerde identiteit van Azure Active Directory gebruiken

Verificatie van client-API-sleutels wordt in de meeste voorbeelden gebruikt, maar u kunt zich ook verifiëren met Azure Active Directory met behulp van de Azure Identity-bibliotheek. Als u de hieronder weergegeven DefaultAzureCredential-provider of andere referentieproviders wilt gebruiken die bij de Azure SDK worden geleverd, installeert u het @azure/identity pakket:

npm install @azure/identity

Het @azure/identity pakket biedt verschillende referentietypen die uw toepassing kan gebruiken om dit te doen. Leesmij voor @azure/identity biedt meer details en voorbeelden om u op weg te helpen. AZURE_CLIENT_SECRET, AZURE_CLIENT_ID en AZURE_TENANT_ID omgevingsvariabelen zijn nodig om een DefaultAzureCredential-object te maken.

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);

Een sjabloonbericht verzenden met WhatsApp-kanaal

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

Als u een sjabloonbericht wilt verzenden, moet u een sjabloon toevoegen aan uw WhatsApp Bussiness-account. Zie Sjablonen maken en beheren voor meer informatie over WhatsApp-sjablonen. In het onderstaande voorbeeld gebruiken we

 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");
    }

Een sms-bericht verzenden met WhatsApp-kanaal

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");
    }

Een mediabericht verzenden met WhatsApp-kanaal

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");
    }

Problemen oplossen

Logboekregistratie

Het inschakelen van logboekregistratie kan helpen bij het ontdekken van nuttige informatie over fouten. Als u een logboek met HTTP-aanvragen en -antwoorden wilt zien, stelt u de AZURE_LOG_LEVEL omgevingsvariabele in op info. U kunt logboekregistratie ook tijdens runtime inschakelen door aan te roepen setLogLevel in de @azure/logger:

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

setLogLevel("info");

Voor meer gedetailleerde instructies over het inschakelen van logboeken kunt u de @azure-/loggerpakketdocumenten bekijken.

Volgende stappen

Bekijk de map met voorbeelden voor gedetailleerde voorbeelden van het gebruik van deze bibliotheek.

Bijdragen

Als u een bijdrage wilt leveren aan deze bibliotheek, leest u de handleiding voor bijdragen voor meer informatie over het bouwen en testen van de code.

Weergaven