Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Belangrijk
Deze functie van Azure Communication Services is momenteel beschikbaar als preview-versie. Functies in preview zijn openbaar beschikbaar en kunnen worden gebruikt door alle nieuwe en bestaande Microsoft-klanten.
Preview-API's en SDK's worden geleverd zonder een serviceniveau-overeenkomst. U wordt aangeraden deze niet te gebruiken voor productieworkloads. Bepaalde functies worden mogelijk niet ondersteund of mogelijkheden zijn mogelijk beperkt.
Voor meer informatie, zie Aanvullende Gebruiksvoorwaarden voor Microsoft Azure Previews.
In dit artikel wordt beschreven hoe u opt-outbeheer inschakelt voor uw Azure Communication Services-resource met behulp van HMAC-verificatie (Hash Message Authentication Code).
Quickstart: OptOut-API-aanvragen verzenden met API (HMAC)
Het verzenden van een opt-out-API-aanvraag is vergelijkbaar met sms, zoals beschreven in de Zelfstudie over Azure Communication Services Postman met het verschil tussen eindpunten voor OptOut-acties (toevoegen, verwijderen of controleren) en hoofdtekst. De hoofdtekst van de aanvraag heeft dezelfde structuur voor alle acties, terwijl de antwoordinhoud enigszins verschilt.
Eindpunten
| Actie | Eindpunt |
|---|---|
| Toevoegen | {{endpoint}}/sms/optouts:add?api-version=2024-12-10-preview |
| Verwijderen | {{endpoint}}/sms/optouts:remove?api-version=2024-12-10-preview |
| Selecteren | {{endpoint}}/sms/optouts:check?api-version=2024-12-10-preview |
Hier volgen enkele voorbeelden in verschillende talen.
Voorbeeldaanvraag
Aanvraagheaders
| Kop | Weergegeven als |
|---|---|
| Inhoudstype | application/json |
| x-ms-datum | Do, 10 aug 2023 12:39:55 GMT |
| x-ms-inhoud-sha256 | JKUqoPANwVA55u/NOCsS0Awa4cYrKKNtBwUqoaqrob0= |
| Autorisatie | HMAC-SHA256 SignedHeaders=x-ms-date; gastheer; x-ms-content-sha256&Signature=IMbd3tE3nOgEkeUQGng6oQew5aEcrZJQQHkyq8qsbLg= |
Aanvraagtekst
{
"from": "+15551234567",
"recipients": [
{
"to": "+15550112233"
},
{
"to": "+15550112234"
}
]
}
Voorbeeldrespons
In het algemeen is de inhoud van het antwoord hetzelfde voor alle acties en bevat deze de geslaagde of mislukte inhoud per geadresseerde HttpStatusCode . Het enige verschil is dat de Check actie, die ook de isOptedOut vlag retourneert, wordt geretourneerd.
Antwoordstatus
- 200 OK
Antwoordtekst opt-outactie toevoegen
{
"value": [
{
"to": "+15550112233",
"httpStatusCode": 200
},
{
"to": "+15550112234",
"httpStatusCode": 200
}
]
}
Antwoordtekst opt-outactie verwijderen
{
"value": [
{
"to": "+15550112233",
"httpStatusCode": 200
},
{
"to": "+15550112234",
"httpStatusCode": 200
}
]
}
Antwoordtekst opt-outactie controleren
{
"value": [
{
"to": "+15550112233",
"httpStatusCode": 200,
"isOptedOut": true
},
{
"to": "+15550112234",
"httpStatusCode": 200,
"isOptedOut": false
}
]
}
Voorbeeldcode
Ga aan de slag met de OPT-out-API van Azure Communication Services door de volgende C#-voorbeeldcode toe te passen.
Vereisten
- Een Azure-account met een actief abonnement. Gratis een account maken
- De .NET Core SDK-versie moet hoger zijn dan v6 voor uw besturingssysteem.
- Een actieve Communication Services-resource en verbindingsreeks. Zie Een Communication Services-resource maken.
- Een telefoonnummer met sms-functionaliteit. Zie Een telefoonnummer ophalen.
Voorbeeldcode voor het gebruik van opt-out-API
In dit voorbeeld ziet u hoe u de OPT-Out Management-API in C# gebruikt om opt-outvermeldingen programmatisch toe te voegen, te verwijderen of te uitchecken.
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
// Sample for Add action. Replace with Check or Remove as necessary.
async Task SendOptOutAdd(string acsResourceConnectionString, string payload)
{
const string ApiPrivatePreviewVersion = "2024-12-10-preview";
const string dateHeader = "x-ms-date";
string accesskey = GetConnectionStringPart(acsResourceConnectionString, "accesskey");
var endpointUri = new Uri(GetConnectionStringPart(acsResourceConnectionString, "endpoint"));
using var httpClient = new HttpClient();
httpClient.BaseAddress = endpointUri;
string method = "POST";
string baseAddress = httpClient.BaseAddress.ToString().TrimEnd('/');
var requestUri = new Uri($"{baseAddress}/sms/optouts:add?api-version={ApiPrivatePreviewVersion }", UriKind.RelativeOrAbsolute);
string hashedBody = ComputeSha256Hash(payload);
string utcNowString = DateTimeOffset.UtcNow.ToString("r", CultureInfo.InvariantCulture);
string stringToSign = $"{method}\n{requestUri.PathAndQuery}\n{utcNowString};{requestUri.Host};{hashedBody}";
string signature = ComputeHmacSha256Hash(accesskey, stringToSign);
string authHeader = $"HMAC-SHA256 SignedHeaders={dateHeader};host;x-ms-content-sha256&Signature={signature}";
using HttpRequestMessage request = new();
request.Headers.TryAddWithoutValidation(dateHeader, utcNowString);
request.Headers.TryAddWithoutValidation("x-ms-content-sha256", hashedBody);
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
request.RequestUri = requestUri;
request.Method = new HttpMethod(method);
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
Console.WriteLine(response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine(response.Headers.ToString());
}
string ComputeSha256Hash(string rawData)
{
using SHA256 sha256Hash = SHA256.Create();
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
return Convert.ToBase64String(bytes);
}
string ComputeHmacSha256Hash(string key, string rawData)
{
using HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(key));
byte[] bytes = hmacSha256.ComputeHash(Encoding.ASCII.GetBytes(rawData));
return Convert.ToBase64String(bytes);
}
string GetConnectionStringPart(string acsResourceConnectionString, string key)
{
return acsResourceConnectionString.Split($"{key}=").Last().Split(';').First();
}
// Usage
const string ConnectionString = "endpoint=https://[CONTOSO].communication.azure.com/;accesskey=******";
var payload = System.Text.Json.JsonSerializer.Serialize(new
{
from = "+15551234567", //replace with your allowed sender number
recipients = new[] {
new { to = "+15550112233" } //replace with your recipient
},
});
await SendOptOutAdd(ConnectionString, payload);
Ga aan de slag met de SMS Opt-out-API van Azure Communication Services met behulp van de volgende JavaScript-voorbeeldcode.
Vereisten
- Een Azure-account met een actief abonnement. Gratis een account maken
- Browser- of Node.js Active LTS- en Maintenance LTS-versies (8.11.1 en 10.14.1 worden aanbevolen).
- Een actieve Communication Services-resource en verbindingsreeks. Zie Een Communication Services-resource maken.
- Een telefoonnummer met sms-functionaliteit. Zie Een telefoonnummer ophalen.
- CryptoJS is JavaScript-implementaties van standaard en veilige cryptografische algoritmen.
Voorbeeldcode voor het gebruik van opt-out-API
In dit voorbeeld ziet u hoe u de Opt-Out Management-API in JavaScript gebruikt om opt-outvermeldingen programmatisch toe te voegen, te verwijderen of te uitchecken.
<script src="Scripts/CryptoJS/sha256-min.js" type="text/javascript"></script>
<script src="Scripts/CryptoJS/hmac-sha256.js" type="text/javascript"></script>
<script src="Scripts/CryptoJS/enc-base64-min.js" type="text/javascript"></script>
const ConnectionString = "endpoint=https://[CONTOSO].communication.azure.com/;accesskey=******";
// Sample for Add action. Replace with Check or Remove as necessary.
function sendOptOutAdd(acsResourceConnectionString, payload, apiVersion = "2024-12-10-preview")
{
try
{
var acsRCS = acsResourceConnectionString
.split(";")
.map(i =>
{
var p = i.indexOf("=");
return [i.substr(0, p), i.substr(p + 1)];
})
.reduce((a, i) => ({ ...a, [i[0]]: i[1] }), {});
var uri = `${trimEnd(acsRCS.endpoint, "/")}/sms/optouts:add?api-version=${apiVersion}`;
var url = new URL(uri);
var method = "POST";
var utcNow = new Date().toUTCString();
var bodyJson = JSON.stringify(payload);
var hashedBody = CryptoJS.SHA256(bodyJson).toString(CryptoJS.enc.Base64);
var stringToSign = `${method}\n${url.pathname}${url.search}\n${utcNow};${url.host};${hashedBody}`;
var signature = CryptoJS.HmacSHA256(stringToSign, CryptoJS.enc.Base64.parse(acsRCS.accesskey)).toString(CryptoJS.enc.Base64);
fetch(uri, {
method: method,
headers: {
"content-type": "application/json",
"x-ms-date": utcNow,
"x-ms-content-sha256": hashedBody,
Authorization: `HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature=${signature}`
},
body: bodyJson
})
.then(response => response.json())
.then(console.warn)
.catch(console.error);
}
catch (ex)
{
console.error(ex);
}
}
function trimEnd(s, c)
{
while (s.slice(-1) == c)
s = s.slice(0, -1);
return s;
}
// Usage
var payload = {
from: "+15551234567",
recipients: [
{ to: "+15550112233" }
],
};
sendOptOutAdd(ConnectionString, payload);
Ga aan de slag met de SMS Opt-out-API van Azure Communication Services door de volgende Java-voorbeeldcode toe te passen.
Vereisten
- Een Azure-account met een actief abonnement. Gratis een account maken
- Java Development Kit (JDK) versie 8 of hoger.
- Een actieve Communication Services-resource en verbindingsreeks. Zie Een Communication Services-resource maken.
- Een telefoonnummer met sms-functionaliteit. Zie Een telefoonnummer ophalen.
Voorbeeldcode voor het gebruik van opt-out-API
In dit voorbeeld ziet u hoe u de OPT-Out Management-API in Java gebruikt om opt-outvermeldingen programmatisch toe te voegen, te verwijderen of te uitchecken.
// Sample for Add action. Replace with Check or Remove as necessary.
public class App
{
public static void main(String[] args) throws Exception
{
String connectionString = "endpoint=https://[CONTOSO].communication.azure.com/;accesskey=******";
OptOutRequest payload = new OptOutRequest();
payload.from = "+15551234567";
payload.recipients = new ArrayList<Recipient>();
payload.recipients.add(new Recipient("+15550112233"));
SendOptOut(connectionString, payload);
}
public static void SendOptOutAdd(String connectionString, OptOutRequest payload) throws Exception
{
String apiVersion = "2024-12-10-preview";
String[] arrOfStr = connectionString.split(";");
String endpoint = arrOfStr[0].split("=")[1];
String accessKey = arrOfStr[1].split("=")[1];
String body = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(payload);
String dateHeaderName = "x-ms-date";
DateTimeFormatter headerDateFormat = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).withZone(ZoneId.of("GMT"));
String dateHeader = headerDateFormat.format(Instant.now());
String verb = "POST";
URI uri = URI.create(endpoint + "sms/optouts:add?api-version==" + apiVersion);
String hostName = uri.getHost();
String pathAndQuery = uri.getPath() + "?" + uri.getQuery();
String encodedHash = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8)));
String stringToSign = verb + '\n' + pathAndQuery + '\n' + dateHeader + ';' + hostName + ';' + encodedHash;
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(accessKey.getBytes()), "HmacSHA256");
mac.init(secretKeySpec);
String signature = Base64.getEncoder().encodeToString(mac.doFinal(stringToSign.getBytes()));
String authHeader = "HMAC-SHA256 SignedHeaders=" + dateHeaderName + ";host;x-ms-content-sha256&Signature=" + signature;
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder
.post(uri)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.setHeader(dateHeaderName, dateHeader)
.setHeader("x-ms-content-sha256", encodedHash)
.setHeader("Authorization", authHeader)
.setEntity(new StringEntity(body, "UTF-8"))
.build();
HttpResponse r = client.execute(request);
HttpEntity entity = r.getEntity();
}
}
public class OptOutRequest
{
public String from;
public ArrayList<Recipient> recipients;
}
public class Recipient
{
public String to;
}
Volgende stappen
In deze quickstart hebt u geleerd hoe u opt-outaanvragen verzendt.