Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

Amazon SNS: Subscribe an SMS Phone Number to a Standard Topic

See more Amazon SNS Examples

Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.

Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.

Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.

Subscribes an endpoint to a standard topic. The sample explicitly requests ReturnSubscriptionArn=false and distinguishes the literal pending confirmation from a returned ARN. Email recipients must follow the confirmation workflow; an accepted Subscribe request does not prove confirmation or delivery. Do not bypass endpoint-owner confirmation. Email/SMS are not FIFO-topic subscription protocols.

Use an authorized E.164 phone number. This creates a topic subscription; a direct SMS Publish does not need it. Sandbox verification, origination/registration requirements, opt-outs and spending restrictions still apply. A subscription ARN alone is not a handset-delivery guarantee. See SMS sandbox requirements.

Required IAM action: sns:Subscribe. Grant only the intended resource access; direct SMS does not have a topic ARN resource. Topic policies and KMS key access can also affect requests.

AWS Subscribe reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkXmlW.h>
#include <CkSocketW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Private credentials; do not put this file in public web content or source control.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/sns.json");
    if (success != true) {
        wprintf(L"Could not load private SNS credentials.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"access_key"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid access_key.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"secret_key"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid secret_key.\n");
        return;
    }

    const wchar_t *region = L"us-west-2";
    CkStringBuilderW endpoint;
    endpoint.Append(L"sns.");
    endpoint.Append(region);
    endpoint.Append(L".amazonaws.com");
    CkAuthAwsW aws;
    aws.put_AccessKey(credentials.stringOf(L"access_key"));
    aws.put_SecretKey(credentials.stringOf(L"secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName(L"sns");
    aws.put_SignatureVersion(4);
    CkRestW rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        wprintf(L"Could not configure AWS signing.\n");
        return;
    }

    if (credentials.HasMember(L"session_token") == true) {
        stringCompare.SetString(credentials.stringOf(L"session_token"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
            wprintf(L"session_token must be a nonempty string when supplied.\n");
            return;
        }

    }

    CkXmlW xml;
    xml.put_Strict(true);
    const wchar_t *value = 0;
    const wchar_t *topicArn = L"arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
    CkStringBuilderW topic;
    topic.Append(topicArn);
    CkStringBuilderW arnPrefix;
    arnPrefix.Append(L"arn:aws:sns:");
    arnPrefix.Append(region);
    arnPrefix.Append(L":");
    if (topic.StartsWith(arnPrefix.getAsString(),true) != true) {
        wprintf(L"Select an SNS topic ARN in the configured region and commercial AWS partition.\n");
        return;
    }

    if (topic.EndsWith(L".fifo",true) == true) {
        wprintf(L"This example uses a standard topic. FIFO publishing needs group/deduplication handling.\n");
        return;
    }

    //  Use an authorized recipient in E.164 format; this number is a placeholder.
    const wchar_t *phoneNumber = L"+15551234567";
    CkStringBuilderW phone;
    phone.Append(phoneNumber);
    stringCompare.SetString(phone.getRange(1,1,false));
    bool stringMatch4 = stringCompare.ContentsEqual(L"0",true);
    if ((phone.StartsWith(L"+",true) != true) || (phone.get_Length() < 2) || (phone.get_Length() > 16) || (stringMatch4 == true)) {
        wprintf(L"Use E.164: + followed by at most 15 digits, starting with a nonzero digit.\n");
        return;
    }

    CkStringBuilderW digits;
    digits.Append(L"0123456789");
    int position = 1;
    while ((position < phone.get_Length())) {
        if (digits.Contains(phone.getRange(position,1,false),true) != true) {
            wprintf(L"Phone number must contain only + and digits.\n");
            return;
        }

        position = position + 1;
    }

    //  Explicit certificate verification; keep this Socket alive while Rest uses it.
    CkSocketW connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        wprintf(L"Could not attach TLS connection.\n");
        return;
    }

    success = rest.ClearAllQueryParams();
    if (success != true) {
        wprintf(L"Could not clear parameters from the previous request.\n");
        return;
    }

    //  Build a fresh form for each request; do not retain previous parameters.
    //  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
    success = rest.AddQueryParam(L"Action",L"Subscribe");
    if (success != true) {
        wprintf(L"Could not set Action.\n");
        return;
    }

    success = rest.AddQueryParam(L"Version",L"2010-03-31");
    if (success != true) {
        wprintf(L"Could not set Version.\n");
        return;
    }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember(L"session_token") == true) {
        success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
        if (success != true) {
            wprintf(L"Could not set X-Amz-Security-Token.\n");
            return;
        }

    }

    success = rest.AddQueryParam(L"TopicArn",topicArn);
    if (success != true) {
        wprintf(L"Could not set TopicArn.\n");
        return;
    }

    success = rest.AddQueryParam(L"Protocol",L"sms");
    if (success != true) {
        wprintf(L"Could not set Protocol.\n");
        return;
    }

    success = rest.AddQueryParam(L"Endpoint",phoneNumber);
    if (success != true) {
        wprintf(L"Could not set Endpoint.\n");
        return;
    }

    success = rest.AddQueryParam(L"ReturnSubscriptionArn",L"false");
    if (success != true) {
        wprintf(L"Could not set ReturnSubscriptionArn.\n");
        return;
    }

    const wchar_t *responseXml = rest.fullRequestFormUrlEncoded(L"POST",L"/");
    if (rest.get_LastMethodSuccess() != true) {
        wprintf(L"Request did not complete. Its outcome may be uncertain; reconcile before retrying.\n");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (rest.get_ResponseStatusCode() != 200) {
        wprintf(L"SNS HTTP status: %d\n",rest.get_ResponseStatusCode());
        if (success == true) {
            value = xml.getChildContent(L"Error|Code");
            if (xml.get_LastMethodSuccess() == true) {
                wprintf(L"AWS error code: %s\n",value);
            }

            value = xml.getChildContent(L"RequestId");
            if (xml.get_LastMethodSuccess() == true) {
                wprintf(L"AWS request ID: %s\n",value);
            }

        }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
    }

    if (success != true) {
        wprintf(L"Expected a well-formed XML response.\n");
        return;
    }

    stringCompare.SetString(xml.tag());
    bool stringMatch5 = stringCompare.ContentsEqual(L"SubscribeResponse",true);
    if (stringMatch5 != true) {
        wprintf(L"Unexpected SNS response element.\n");
        return;
    }

    value = xml.getChildContent(L"ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
    if ((xml.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
        wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
        return;
    }

    wprintf(L"AWS request ID: %s\n",value);
    value = xml.getChildContent(L"SubscribeResult|SubscriptionArn");
    stringCompare.SetString(value);
    bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
    if ((xml.get_LastMethodSuccess() != true) || (stringMatch7 == true)) {
        wprintf(L"Missing or empty SubscribeResult|SubscriptionArn.\n");
        return;
    }

    stringCompare.SetString(value);
    bool stringMatch8 = stringCompare.ContentsEqual(L"pending confirmation",true);
    if (stringMatch8 == true) {
        wprintf(L"Subscription is pending confirmation; delivery is not active yet.\n");
    }
    else {
        wprintf(L"Subscription ARN: %s\n",value);
        wprintf(L"Subscription request succeeded.\n");
    }
    }