Skip to content

Commit 3b4bd35

Browse files
committed
adding template javascript example
1 parent 02adcf1 commit 3b4bd35

File tree

1 file changed

+204
-1
lines changed

1 file changed

+204
-1
lines changed

articles/communication-services/quickstarts/advanced-messaging/whatsapp/includes/templates/messages-quickstart-template-messages-javascript.md

Lines changed: 204 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,208 @@ To set up an environment for sending messages, complete the steps in the followi
1919

2020
## Code examples
2121

22-
- TODO
22+
Follow these steps to add required code snippets to the main function of your `App.java` file.
23+
- [List WhatsApp templates in the Azure portal](#list-whatsapp-templates-in-the-azure-portal).
24+
- [Send template message with text parameters in the body](#send-template-message-with-text-parameters-in-the-body).
25+
26+
### List WhatsApp templates in the Azure portal
27+
28+
To view your templates in the Azure portal, go to your Azure Communication Services resource > **Advanced Messaging** > **Templates**.
29+
30+
:::image type="content" source="../../media/template-messages/list-templates-azure-portal.png" lightbox="../../media/template-messages/list-templates-azure-portal.png" alt-text="Screenshot that shows an Azure Communication Services resource in the Azure portal, viewing the advanced messaging templates tab.":::
31+
32+
Selecting a template to view the template details.
33+
34+
The **Content** field of the template details can include parameter bindings. The parameter bindings can be denoted as:
35+
- A `"format"` field with a value such as `IMAGE`.
36+
- Double brackets surrounding a number, such as `{{1}}`. The number, index started at 1, indicates the order in which the binding values must be supplied to create the message template.
37+
38+
:::image type="content" source="../../media/template-messages/sample-movie-ticket-confirmation-azure-portal.png" lightbox="../../media/template-messages/sample-movie-ticket-confirmation-azure-portal.png" alt-text="Screenshot that shows template details.":::
39+
40+
Alternatively, you can view and edit all of your WhatsApp Business Account templates in the [WhatsApp Manager](https://business.facebook.com/wa/manage/home/) > Account tools > [Message templates](https://business.facebook.com/wa/manage/message-templates/).
41+
42+
To list out your templates programmatically, you can fetch all templates for your channel ID using the following code:
43+
44+
```javascript
45+
// Copyright (c) Microsoft Corporation.
46+
// Licensed under the MIT License.
47+
48+
/**
49+
* @summary Get Template list for a channel
50+
*/
51+
52+
const MessageTemplateClient = require("@azure-rest/communication-messages").default,
53+
{ isUnexpected } = require("@azure-rest/communication-messages");
54+
55+
// Load the .env file if it exists
56+
require("dotenv").config();
57+
58+
async function main() {
59+
const connectionString = process.env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING || "";
60+
const client = MessageTemplateClient(connectionString);
61+
console.log("Fetch Templates...");
62+
const response = await client
63+
.path("/messages/channels/{channelId}/templates", process.env.CHANNEl_ID || "")
64+
.get({
65+
queryParameters: { maxPageSize: 2 },
66+
});
67+
68+
if (isUnexpected(response)) {
69+
throw new Error("Failed to get template for the channel.");
70+
}
71+
72+
// The paginate helper creates a paged async iterator using metadata from the first page.
73+
const items = paginate(client, response);
74+
75+
// We get an PageableAsyncIterator so we need to do `for await`.
76+
for await (const item of items) {
77+
console.log(JSON.stringify(item, null, 2));
78+
}
79+
}
80+
81+
main().catch((error) => {
82+
console.error("Encountered an error while sending message: ", error);
83+
throw error;
84+
});
85+
```
86+
87+
### Send template message with text parameters in the body
88+
89+
To define parameters in the body denoted with double brackets surrounding a number, such as `{{1}}`. The number, index started at 1, indicates the order in which the binding values must be supplied to create the message template. Including parameters not in the template is invalid.
90+
91+
Template definition with two parameters:
92+
```json
93+
{
94+
"type": "BODY",
95+
"text": "Message with two parameters: {{1}} and {{2}}"
96+
}
97+
```
98+
99+
#### Examples
100+
101+
`sample_shipping_confirmation` template:
102+
103+
:::image type="content" source="../../media/template-messages/sample-shipping-confirmation-details-azure-portal.png" lightbox="../../media/template-messages/sample-shipping-confirmation-details-azure-portal.png" alt-text="Screenshot that shows template details for template named sample_shipping_confirmation.":::
104+
105+
In this sample, the body of the template has one parameter:
106+
107+
```json
108+
{
109+
"type": "BODY",
110+
"text": "Your package has been shipped. It will be delivered in {{1}} business days."
111+
},
112+
```
113+
114+
Parameters are defined with the `values` values and `bindings` bindings. Use the values and bindings to assemble the `template` object.
115+
116+
```javascript
117+
/*
118+
* This sample shows how to send template message with below details
119+
* Name: sample_shipping_confirmation, Language: en_US
120+
* [
121+
{
122+
"type": "BODY",
123+
"text": "Your package has been shipped. It will be delivered in {{1}} business days."
124+
},
125+
{
126+
"type": "FOOTER",
127+
"text": "This message is from an unverified business."
128+
}
129+
]
130+
* */
131+
// Copyright (c) Microsoft Corporation.
132+
// Licensed under the MIT License.
133+
134+
/**
135+
* @summary Use AAD token credentials when sending a whatsapp template message.
136+
*/
137+
138+
const { isNode } = require("@azure/core-util");
139+
const { ClientSecretCredential, DefaultAzureCredential } = require("@azure/identity");
140+
const NotificationClient = require("@azure-rest/communication-messages").default,
141+
{ isUnexpected } = require("@azure-rest/communication-messages");
142+
143+
// Load the .env file if it exists
144+
require("dotenv").config();
145+
146+
async function main() {
147+
// You will need to set this environment variable or edit the following values
148+
const endpoint = process.env.ACS_URL || "";
149+
150+
// Azure AD Credential information is required to run this sample:
151+
if (
152+
!process.env.AZURE_TENANT_ID ||
153+
!process.env.AZURE_CLIENT_ID ||
154+
!process.env.AZURE_CLIENT_SECRET
155+
) {
156+
console.error(
157+
"Azure AD authentication information not provided, but it is required to run this sample. Exiting.",
158+
);
159+
return;
160+
}
161+
162+
// get credentials
163+
const credential = isNode
164+
? new DefaultAzureCredential()
165+
: new ClientSecretCredential(
166+
process.env.AZURE_TENANT_ID,
167+
process.env.AZURE_CLIENT_ID,
168+
process.env.AZURE_CLIENT_SECRET,
169+
);
170+
171+
const client = NotificationClient(endpoint, credential);
172+
173+
const DaysTemplateValue = {
174+
kind: "text",
175+
name: "Days",
176+
text: "5",
177+
};
178+
179+
const templateBindings = {
180+
kind: "whatsApp",
181+
body: [
182+
{
183+
refValue: "Days",
184+
},
185+
],
186+
};
187+
188+
const template = {
189+
name: "sample_shipping_confirmation",
190+
language: "en_US",
191+
bindings: templateBindings,
192+
values: [DaysTemplateValue],
193+
};
194+
195+
const result = await client.path("/messages/notifications:send").post({
196+
contentType: "application/json",
197+
body: {
198+
channelRegistrationId: process.env.CHANNEL_ID || "",
199+
to: [process.env.RECIPIENT_PHONE_NUMBER || ""],
200+
kind: "template",
201+
template: template,
202+
},
203+
});
204+
205+
console.log("Response: " + JSON.stringify(result, null, 2));
206+
207+
if (isUnexpected(result)) {
208+
throw new Error("Failed to send message");
209+
}
210+
211+
const response = result;
212+
response.body.receipts.forEach((receipt) => {
213+
console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId);
214+
});
215+
}
216+
217+
main().catch((error) => {
218+
console.error("Encountered an error while sending message: ", error);
219+
throw error;
220+
});
221+
222+
module.exports = { main };
223+
```
23224

24225
## Run the code
25226
Use the node command to run the code you added to the send-messages.js file.
@@ -29,3 +230,5 @@ node ./send-messages.js
29230
```
30231

31232
## Full sample code
233+
234+
Find the finalized code for this quickstart on [GitHub](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/).

0 commit comments

Comments
 (0)