Skip to content

Commit 9a58dde

Browse files
authored
Update opt-out-api-quickstart.md
1 parent ebac1bd commit 9a58dde

File tree

1 file changed

+12
-235
lines changed

1 file changed

+12
-235
lines changed

articles/communication-services/quickstarts/sms/opt-out-api-quickstart.md

Lines changed: 12 additions & 235 deletions
Original file line numberDiff line numberDiff line change
@@ -111,245 +111,22 @@ In general, response contents are the same for all actions and contain the succe
111111
]
112112
}
113113
```
114-
## Sample code to use Opt-Out API
114+
## Next steps
115115

116-
### C#
116+
In this quickstart, you learned how to send OPt-out requests.
117117

118-
#### Prerequisites
118+
> [!div class="nextstepaction"]
119+
> [Send an SMS message](./send.md)
119120
120-
- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
121-
- The .NET Core SDK version must be higher than v6 for your operating system.
122-
- An active Communication Services resource and connection string. See [Create a Communication Services resource](https://learn.microsoft.com/azure/communication-services/quickstarts/create-communication-resource).
123-
- An SMS-enabled telephone number. See [Get a phone number](https://learn.microsoft.com/azure/communication-services/quickstarts/telephony/get-phone-number) and `allowlisted` as described in the beginning of the article.
121+
> [!div class="nextstepaction"]
122+
> [Receive and reply to SMS](./receive-sms.md)
124123
125-
```cs
126-
using System.Globalization;
127-
using System.Security.Cryptography;
128-
using System.Text;
124+
> [!div class="nextstepaction"]
125+
> [Enable SMS analytics](../../concepts/analytics/insights/sms-insights.md)
129126
130-
// Sample for Add action. Replace with Check or Remove as necessary.
131-
async Task SendOptOutAdd(string acsResourceConnectionString, string payload)
132-
{
133-
const string ApiPrivatePreviewVersion = "2024-12-10-preview";
134-
135-
const string dateHeader = "x-ms-date";
136-
137-
string accesskey = GetConnectionStringPart(acsResourceConnectionString, "accesskey");
138-
var endpointUri = new Uri(GetConnectionStringPart(acsResourceConnectionString, "endpoint"));
139-
140-
using var httpClient = new HttpClient();
141-
httpClient.BaseAddress = endpointUri;
142-
143-
string method = "POST";
144-
string baseAddress = httpClient.BaseAddress.ToString().TrimEnd('/');
145-
var requestUri = new Uri($"{baseAddress}/sms/optouts:add?api-version={ApiPrivatePreviewVersion }", UriKind.RelativeOrAbsolute);
146-
string hashedBody = ComputeSha256Hash(payload);
147-
string utcNowString = DateTimeOffset.UtcNow.ToString("r", CultureInfo.InvariantCulture);
148-
string stringToSign = $"{method}\n{requestUri.PathAndQuery}\n{utcNowString};{requestUri.Host};{hashedBody}";
149-
string signature = ComputeHmacSha256Hash(accesskey, stringToSign);
150-
string authHeader = $"HMAC-SHA256 SignedHeaders={dateHeader};host;x-ms-content-sha256&Signature={signature}";
151-
152-
using HttpRequestMessage request = new();
153-
request.Headers.TryAddWithoutValidation(dateHeader, utcNowString);
154-
request.Headers.TryAddWithoutValidation("x-ms-content-sha256", hashedBody);
155-
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
156-
request.RequestUri = requestUri;
157-
request.Method = new HttpMethod(method);
158-
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
159-
160-
HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
161-
162-
Console.WriteLine(response.StatusCode);
163-
Console.WriteLine(await response.Content.ReadAsStringAsync());
164-
Console.WriteLine(response.Headers.ToString());
165-
}
166-
167-
string ComputeSha256Hash(string rawData)
168-
{
169-
using SHA256 sha256Hash = SHA256.Create();
170-
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
171-
return Convert.ToBase64String(bytes);
172-
}
173-
174-
string ComputeHmacSha256Hash(string key, string rawData)
175-
{
176-
using HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(key));
177-
byte[] bytes = hmacSha256.ComputeHash(Encoding.ASCII.GetBytes(rawData));
178-
return Convert.ToBase64String(bytes);
179-
}
180-
181-
string GetConnectionStringPart(string acsResourceConnectionString, string key)
182-
{
183-
return acsResourceConnectionString.Split($"{key}=").Last().Split(';').First();
184-
}
185-
186-
// Usage
187-
188-
const string ConnectionString = "endpoint=https://[CONTOSO].communication.azure.com/;accesskey=******";
189-
var payload = System.Text.Json.JsonSerializer.Serialize(new
190-
{
191-
from = "+15551234567", //replace with your allowed sender number
192-
recipients = new[] {
193-
new { to = "+15550112233" } //replace with your recipient
194-
},
195-
});
196-
197-
await SendOptOutAdd(ConnectionString, payload);
198-
199-
```
200-
### JavaScript
201-
202-
#### Prerequisites
203-
204-
- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
205-
- Browser or Node.js Active LTS and Maintenance LTS versions (8.11.1 and 10.14.1 are recommended).
206-
- An active Communication Services resource and connection string. See [Create a Communication Services resource](https://learn.microsoft.com/azure/communication-services/quickstarts/create-communication-resource).
207-
- An SMS-enabled telephone number. See [Get a phone number](https://learn.microsoft.com/azure/communication-services/quickstarts/telephony/get-phone-number).
208-
- [CryptoJS](https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/crypto-js/CryptoJS%20v3.1.2.zip) is JavaScript implementations of standard and secure cryptographic algorithms.
209-
210-
211-
```html
212-
<script src="Scripts/CryptoJS/sha256-min.js" type="text/javascript"></script>
213-
<script src="Scripts/CryptoJS/hmac-sha256.js" type="text/javascript"></script>
214-
<script src="Scripts/CryptoJS/enc-base64-min.js" type="text/javascript"></script>
215-
216-
```
127+
> [!div class="nextstepaction"]
128+
> [Phone number types](../../concepts/telephony/plan-solution.md)
217129
218-
```js
219-
const ConnectionString = "endpoint=https://[CONTOSO].communication.azure.com/;accesskey=******";
130+
> [!div class="nextstepaction"]
131+
> [Look up operator information for a phone number](../telephony/number-lookup.md)
220132
221-
// Sample for Add action. Replace with Check or Remove as necessary.
222-
function sendOptOutAdd(acsResourceConnectionString, payload, apiVersion = "2024-12-10-preview")
223-
{
224-
try
225-
{
226-
var acsRCS = acsResourceConnectionString
227-
.split(";")
228-
.map(i =>
229-
{
230-
var p = i.indexOf("=");
231-
return [i.substr(0, p), i.substr(p + 1)];
232-
})
233-
.reduce((a, i) => ({ ...a, [i[0]]: i[1] }), {});
234-
var uri = `${trimEnd(acsRCS.endpoint, "/")}/sms/optouts:add?api-version=${apiVersion}`;
235-
var url = new URL(uri);
236-
var method = "POST";
237-
var utcNow = new Date().toUTCString();
238-
var bodyJson = JSON.stringify(payload);
239-
var hashedBody = CryptoJS.SHA256(bodyJson).toString(CryptoJS.enc.Base64);
240-
var stringToSign = `${method}\n${url.pathname}${url.search}\n${utcNow};${url.host};${hashedBody}`;
241-
var signature = CryptoJS.HmacSHA256(stringToSign, CryptoJS.enc.Base64.parse(acsRCS.accesskey)).toString(CryptoJS.enc.Base64);
242-
243-
fetch(uri, {
244-
method: method,
245-
headers: {
246-
"content-type": "application/json",
247-
"x-ms-date": utcNow,
248-
"x-ms-content-sha256": hashedBody,
249-
Authorization: `HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature=${signature}`
250-
},
251-
body: bodyJson
252-
})
253-
.then(response => response.json())
254-
.then(console.warn)
255-
.catch(console.error);
256-
}
257-
catch (ex)
258-
{
259-
console.error(ex);
260-
}
261-
}
262-
263-
function trimEnd(s, c)
264-
{
265-
while (s.slice(-1) == c)
266-
s = s.slice(0, -1);
267-
return s;
268-
}
269-
270-
// Usage
271-
272-
var payload = {
273-
from: "+15551234567",
274-
recipients: [
275-
{ to: "+15550112233" }
276-
],
277-
};
278-
279-
sendOptOutAdd(ConnectionString, payload);
280-
281-
```
282-
### Java
283-
284-
#### Prerequisites
285-
286-
- An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
287-
- Java Development Kit (JDK) version 8 or above.
288-
- An active Communication Services resource and connection string. See [Create a Communication Services resource](https://learn.microsoft.com/azure/communication-services/quickstarts/create-communication-resource).
289-
- An SMS-enabled telephone number. See [Get a phone number](https://learn.microsoft.com/azure/communication-services/quickstarts/telephony/get-phone-number).
290-
291-
292-
```java
293-
// Sample for Add action. Replace with Check or Remove as necessary.
294-
public class App
295-
{
296-
public static void main(String[] args) throws Exception
297-
{
298-
String connectionString = "endpoint=https://[CONTOSO].communication.azure.com/;accesskey=******";
299-
300-
OptOutRequest payload = new OptOutRequest();
301-
payload.from = "+15551234567";
302-
payload.recipients = new ArrayList<Recipient>();
303-
payload.recipients.add(new Recipient("+15550112233"));
304-
305-
SendOptOut(connectionString, payload);
306-
}
307-
308-
public static void SendOptOutAdd(String connectionString, OptOutRequest payload) throws Exception
309-
{
310-
String apiVersion = "2024-12-10-preview";
311-
312-
String[] arrOfStr = connectionString.split(";");
313-
String endpoint = arrOfStr[0].split("=")[1];
314-
String accessKey = arrOfStr[1].split("=")[1];
315-
String body = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(payload);
316-
String dateHeaderName = "x-ms-date";
317-
DateTimeFormatter headerDateFormat = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).withZone(ZoneId.of("GMT"));
318-
String dateHeader = headerDateFormat.format(Instant.now());
319-
String verb = "POST";
320-
URI uri = URI.create(endpoint + "sms/optouts:add?api-version==" + apiVersion);
321-
String hostName = uri.getHost();
322-
String pathAndQuery = uri.getPath() + "?" + uri.getQuery();
323-
String encodedHash = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8)));
324-
String stringToSign = verb + '\n' + pathAndQuery + '\n' + dateHeader + ';' + hostName + ';' + encodedHash;
325-
Mac mac = Mac.getInstance("HmacSHA256");
326-
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(accessKey.getBytes()), "HmacSHA256");
327-
mac.init(secretKeySpec);
328-
String signature = Base64.getEncoder().encodeToString(mac.doFinal(stringToSign.getBytes()));
329-
String authHeader = "HMAC-SHA256 SignedHeaders=" + dateHeaderName + ";host;x-ms-content-sha256&Signature=" + signature;
330-
331-
HttpClient client = HttpClients.custom().build();
332-
HttpUriRequest request = RequestBuilder
333-
.post(uri)
334-
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
335-
.setHeader(dateHeaderName, dateHeader)
336-
.setHeader("x-ms-content-sha256", encodedHash)
337-
.setHeader("Authorization", authHeader)
338-
.setEntity(new StringEntity(body, "UTF-8"))
339-
.build();
340-
HttpResponse r = client.execute(request);
341-
HttpEntity entity = r.getEntity();
342-
}
343-
}
344-
345-
public class OptOutRequest
346-
{
347-
public String from;
348-
public ArrayList<Recipient> recipients;
349-
}
350-
351-
public class Recipient
352-
{
353-
public String to;
354-
}
355-
```

0 commit comments

Comments
 (0)