使用 API 傳送 OptOut API 要求 (HMAC)

Warning

Azure 通訊服務 正在推出突破性變更,部分服務也將被淘汰。 想了解更多,請參閱退休 與變更指南。

這很重要

此 Azure 通訊服務功能目前處於預覽狀態。 預覽中的功能可供公開使用,而且可供所有新的和現有的Microsoft客戶使用。

提供的預覽 API 和 SDK 並無服務等級協定。 建議您不要將其用於生產工作負載。 某些功能可能不受支援,或功能可能會受到限制。

如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款。

本文會說明如何使用雜湊訊息驗證碼 (HMAC) 型驗證,為您的 Azure 通訊服務資源啟用退出管理。

快速入門:使用 API 傳送 OptOut API 要求 (HMAC)

傳送退出 API 要求類似於 Azure 通訊服務 Postman 教學課程中所描述的 SMS,不同之處在於退出動作 (新增、移除或檢查) 的端點和本文。 所有動作的要求本文都具有相同的結構,而回應內容則略有不同。

端點

動作 端點
加 {{endpoint}}/sms/optouts:add?api-version=2024-12-10-preview
移除 {{endpoint}}/sms/optouts:remove?api-version=2024-12-10-preview
勾選 {{endpoint}}/sms/optouts:check?api-version=2024-12-10-preview

以下是不同語言的部分範例。

範例要求

要求標頭

頁首 值
Content-Type application/json
x-ms-date 2023 年 8 月 10 日星期四 12:39:55 GMT
x-ms-content-sha256 JKUqoPANwVA55u/NOCsS0Awa4cYrKKNtBwUqoaqrob0=
授權 HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature=IMbd3tE3nOgEkeUQGng6oQew5aEcrZJQqHkyq8qsbLg=

請求主體

{
    "from": "+15551234567",
    "recipients": [
        {
            "to": "+15550112233"
        },
        {
            "to": "+15550112234"
        }
    ]
}

範例回應

一般而言,所有動作的回應內容都相同,且包含每個收件者的成功或失敗 HttpStatusCode。 唯一的差異在於,Check 動作也會傳回 isOptedOut 旗標。

回應狀態

  • 200 確定

新增 OptOut 動作回應本文

{
    "value": [
        {
            "to": "+15550112233",
            "httpStatusCode": 200
        },
        {
            "to": "+15550112234",
            "httpStatusCode": 200
        }
    ]
}

移除 OptOut 動作回應本文

{
    "value": [
        {
            "to": "+15550112233",
            "httpStatusCode": 200
        },
        {
            "to": "+15550112234",
            "httpStatusCode": 200
        }
    ]
}

檢查 OptOut 動作回應本文

{
    "value": [
        {
            "to": "+15550112233",
            "httpStatusCode": 200,
            "isOptedOut": true
        },
        {
            "to": "+15550112234",
            "httpStatusCode": 200,
            "isOptedOut": false
        }
    ]
}

範例程式碼

藉由套用下列 C# 範例程式碼,開始使用 Azure 通訊服務 SMS 退出 API。

先決條件

使用退出 API 的範例程式碼

此範例會示範如何使用 C# 中的退出管理 API,以程式設計方式新增、移除或檢查退出項目。

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

藉由使用下列 JavaScript 範例程式碼,開始使用 Azure 通訊服務 SMS 退出 API。

先決條件

  • 具有有效訂用帳戶的 Azure 帳戶。 免費建立帳戶。
  • 瀏覽器或 Node.js 使用中 LTS 和維護 LTS 版本(建議使用 8.11.1 和 10.14.1)。
  • 作用中的 Azure 通訊服務資源和連接字串。 請參閱建立通訊服務資源。
  • 已啟用 SMS 的電話號碼。 請參閱取得電話號碼。
  • CryptoJS 是標準和安全密碼編譯演算法的 JavaScript 實作。

使用退出 API 的範例程式碼

此範例會示範如何使用 JavaScript 中的退出管理 API,以程式設計方式新增、移除或檢查退出項目。

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

藉由套用下列 JAVA 範例程式碼,開始使用 Azure 通訊服務 SMS 退出 API。

先決條件

使用退出 API 的範例程式碼

此範例會示範如何使用 JAVA 中的退出管理 API,以程式設計方式新增、移除或檢查退出項目。

// 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;
}

後續步驟

在本快速入門中,您已了解如何傳送退出要求。