Skip to content
Skip to chapter

Chapter 48

Advanced integrations and data

18 min read

Send and inspect a Twilio SMS

Prepare one fictional Twilio SMS, approve its live cost and recipient, and inspect the same Message SID without sending again.

By the end

Tell permission to create a message apart from consent to contact a person, keep the record of a send whose outcome is uncertain, and tell API creation apart from carrier delivery and a person reading the message.

Chapter navigation

Send one fictional SMS through Twilio's REST API from Apps Script, then follow its status by reading the same Message SID. A successful HTTP request means that Twilio created a Message resource. A delivery receipt means that a carrier reported delivery. Nothing in the API tells you that the recipient read the message.

The message describes fictional workshop request REQ-001. It names the real sender, says that the content is fictional, includes a unique marker for this send, and explains how to opt out. The recipient is your own handset, with your documented consent. You first change and restore the wording locally. Then you approve one live send. The exercise has no loop over recipients, second message, voice call, automatic reply, or callback receiver.

warning

A live SMS incurs carrier and Twilio charges and reaches a real phone number. Use a paid practice account, an existing verified sender number, and your own handset with your consent. If you do not have those, run only the local preview functions.

Establish the sender, recipient, and cost

This example uses US1 credentials, an existing SMS-capable US toll-free Twilio number, and one approved US mobile recipient. Confirm that the sender number belongs to the exact account or subaccount whose AC... SID appears in the request, and that toll-free verification is approved for this use. Pending verification is not enough. A voice-capable number is not necessarily SMS-capable (sender requirements, toll-free verification).

Send to your own handset, and document that you opted in to this sender and this fictional workshop message. Record the consent outside the script: who agreed, the recipient and sender numbers, the message subject, the timestamp, and the opt-out mechanism. Check that the consent is still current before you send. Stop if the recipient opts out through any channel.

Twilio treats traffic sent through its platform as application-to-person messaging. Its Messaging Policy requires consent and sender identification, and the first message must give a clear opt-out instruction. The supplied body ends with Reply STOP to unsubscribe.

STOP handling on toll-free numbers varies by carrier, so check how your sender number handles opt-outs before you use it. Do not test STOP or START in this exercise. Replies can trigger more carrier and Twilio messages, and restarting consent is not a way around an opt-out. The exercise has no workflow for incoming messages, so you are responsible for handling any reply or withdrawal yourself.

The script checks only the shape of each phone number. It does not check ownership, location, capability, or consent. A +1 prefix also covers Canada and other North American Numbering Plan destinations, so it does not prove that the recipient is in the US. You must confirm the real destination and the laws that apply. Do not change the regular expression to allow other countries. A US local ten-digit sender number is not a cheaper substitute for the verified toll-free sender. It needs its own approved setup, including A2P 10DLC registration.

Before you approve the send, review the current US pricing and the account's balance, geographic permissions, and spending controls. Twilio bills SMS by segment. Carrier fees, charges for processing failed messages where they apply, number rental, and registration costs are billed separately. Existing credits do not make the send free or approve it. No script property limits what Twilio charges. The script does not buy a number or change account settings, and it cannot cap your bill.

The body uses only a small set of GSM-7 characters that each count as one unit, and it stays under 160 units including its marker. As a result, the message should fit in one SMS segment, which is still a paid send. Smart quotes, emoji, or an extended GSM-7 character would change that calculation. GSM-7 is not the same character set as ASCII. After the send, the Message record's num_segments and pricing fields report what Twilio counted. They are not a quote you can get before sending (encoding limits).

Do not confuse trial and test credentials

Twilio's current trial has product-specific free units, geographic and verified-recipient restrictions, a 30-day lifetime, and a requirement to use predefined content. Custom SMS bodies are not allowed on the trial. Because this exercise sends a custom fictional body, it needs an already approved paid account. Upgrading is a separate billing decision.

Test credentials are different. A test Account SID and test Auth Token simulate supported operations without charging you, changing live account state, or connecting to real phone numbers. A simulated Messages POST does not show that your real sender number is approved, that a handset received anything, or that live billing will match. Test credentials do not support this example's GET of a single Message, and they do not produce real status callbacks. The script accepts only live API key credentials and has no test mode. Do not paste a Twilio magic test number into the live configuration.

Separate the credential roles

Three parties each authorize a different part of the exercise. You, as the account owner, authorize the Twilio resources and the recipient. Google authorizes the script's external request. Twilio separately authorizes each REST operation.

ValueRole in this example
Account SID, AC...Selects the owning account in /Accounts/{AccountSid}/Messages. It is an identifier, not a password. A parent account and its subaccount are not interchangeable.
CREATE API key SID, SK..., and its secretHTTP Basic username and password for the single Messages POST. Grant only twilio/messaging/messages/create.
READ API key SID and its different secretHTTP Basic credentials for a GET of a known Message. Grant only twilio/messaging/messages/read. Reads still work after you revoke the CREATE key.
Account Auth TokenA broad account credential, and the secret Twilio uses to sign webhooks. This project does not store or use it. An API key secret cannot verify webhook signatures.
Google external-request consentLets the Google user who runs the function use URL Fetch. It grants no Twilio permission and no permission to contact anyone.

With the account owner's permission, open Develop > API Keys & creds > API Keys & auth tokens in Twilio Console. In the legacy Console, use Account > Keys & Credentials > API keys & tokens. Select the intended account and US1 before you create keys. Create two Restricted keys with separate names, one for creating and one for reading, using the exact permissions above. The permission catalog separates read, for a known SID, from list, for a collection. Neither key needs permission to list, update, or delete messages, access media, manage numbers, use Voice, or administer the account.

Twilio shows each secret only once, so copy it straight into its own private Script Property. Credentials from one Twilio region do not work in another. The fixed api.twilio.com endpoint and this configuration target US1, and they do not promise where Twilio stores data (regional credentials). If your setup cannot use Restricted keys with these permissions, stop and resolve that with the account owner. Do not switch to a Standard key, a Main key, or the Account Auth Token instead, because each grants more access.

A Restricted create permission does not limit sends to one phone number or a dollar amount. The limits in the script do not stop someone who has the key from sending other messages. Keep the project private, and share it only with editors you trust. Script Properties keep secrets out of the source code, but project editors can still read and use them. Never put credentials into a URL, browser script, source file, log, screenshot, chat, or a filled-in configuration file that you commit. Do not log the Basic authorization header. Base64 encoding is reversible and is not encryption.

Install only the Apps Script files

Create a new standalone Apps Script project named Twilio one-message practice. Add Code.gs and Practice.gs. In Project Settings, turn on Show "appsscript.json" manifest file in editor and replace that manifest with the one below. Leave Services empty. You do not install a library, Node package, trigger, web app, API executable, or server.

appsscript.json
{
  "timeZone": "Etc/UTC",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"]
}

Download appsscript.json

The JSON below is a checklist of Script Properties to create. It is not an Apps Script settings file you can import, so do not add it to the project as another manifest. In Project Settings > Script Properties, create the six starting properties that it names. Fill in the real approved account SID, the sender and recipient numbers in E.164 form, and a short, truthful name for the sender. TWILIO_SENDER_LABEL allows 2 to 24 letters, digits, spaces, or hyphens and must start with a letter. If that is too short to identify the sender properly, do not use a misleading abbreviation to pass the check. Keep TWILIO_VARIANT set to baseline.

configuration.json
{
  "initialScriptProperties": {
    "TWILIO_ENVIRONMENT": "paid-us1",
    "TWILIO_ACCOUNT_SID": "",
    "TWILIO_FROM_PHONE": "",
    "TWILIO_TO_PHONE": "",
    "TWILIO_SENDER_LABEL": "",
    "TWILIO_VARIANT": "baseline"
  },
  "privateCredentialProperties": {
    "TWILIO_CREATE_KEY_SID": "",
    "TWILIO_CREATE_KEY_SECRET": "",
    "TWILIO_READ_KEY_SID": "",
    "TWILIO_READ_KEY_SECRET": ""
  },
  "createKeyPermissions": ["twilio/messaging/messages/create"],
  "readKeyPermissions": ["twilio/messaging/messages/read"],
  "approvalPropertiesAddedOnlyAfterIntentReview": [
    "TWILIO_CONFIRM_INTENT_ID",
    "TWILIO_SEND_CONFIRMATION",
    "TWILIO_APPROVAL_AT"
  ],
  "reconciliationPropertiesAddedOnlyAfterConsoleMatching": [
    "TWILIO_RECONCILE_INTENT_ID",
    "TWILIO_RECONCILE_MESSAGE_SID"
  ],
  "apiOrigin": "https://api.twilio.com",
  "apiVersion": "2010-04-01",
  "region": "US1",
  "senderType": "Approved SMS-capable US toll-free number owned by the selected paid account",
  "recipientBoundary": "One currently consenting adult practice owner on an approved US mobile number",
  "execution": "Manual Apps Script only; no callbacks, triggers, SDK installation or hosting",
  "note": "This is a configuration checklist, not an imported settings file. Add each named property privately in the Apps Script editor. Empty account, phone, identity or credential fields fail before sending. Never commit a filled copy."
}

Download configuration.json

The script cannot send while these values are empty. Add the four private credential properties only through your approved process for entering secrets. Do not add the approval or reconciliation properties yet. In Console, check that this dedicated practice number has no unrelated demo webhook, automatic reply, or other application attached. The request does not set StatusCallback, ApplicationSid, or MessagingServiceSid. It sets the approved number directly as From.

Practice.gs contains the fictional request line, the code that builds the body, and the explanations of each SMS status. Code.gs calls it, so the project needs both files. The sender identity is real. The workshop request is fictional.

Practice.gs
/**
 * Supplied fictional request data. The changed variant is a LOCAL preview exercise only.
 * @param {TwilioVariant} variant
 * @returns {string}
 */
function twilioPracticeLine_(variant) {
  if (variant === 'baseline') return 'REQ-001 map ready.';
  if (variant === 'changed') return 'REQ-001 map checked.';
  throw new Error('TWILIO_UNKNOWN_FICTIONAL_VARIANT');
}

/**
 * Only a small one-unit GSM-7 subset is accepted; no emoji, smart quotes or extended characters.
 * The actual consent-holding sender supplies its short identity, not a fictional organization.
 * @param {string} senderLabel @param {TwilioVariant} variant @param {string} id
 * @returns {string}
 */
function twilioBody_(senderLabel, variant, id) {
  if (!/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(senderLabel) || senderLabel.trim() !== senderLabel ||
      !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) throw new Error('TWILIO_BODY_INPUT');
  const body = senderLabel + ': Fictional workshop ' + twilioPracticeLine_(variant) +
    ' Ref ' + id + '. Reply STOP to unsubscribe.';
  if (body.length > 160 || !/^[A-Za-z0-9 .:-]+$/.test(body)) throw new Error('TWILIO_ONE_SEGMENT_BODY_REQUIRED');
  return body;
}

/** Describe only SMS-specific evidence. Never treat an unfamiliar channel status as delivery. @param {string} status @returns {string} */
function twilioStatusMeaning_(status) {
  switch (status) {
    case 'queued': return 'Twilio queued the SMS for its sender; not delivery.';
    case 'sending': return 'Twilio is dispatching upstream; not delivery.';
    case 'sent': return 'The nearest upstream carrier accepted it; not handset delivery.';
    case 'delivered': return 'Twilio has a delivery confirmation; not proof a person read it.';
    case 'undelivered': return 'Twilio received a non-delivery receipt; do not resend automatically.';
    case 'failed': return 'Twilio reports failure to send; do not resend automatically.';
    default: return 'Unexpected status for this direct SMS path; inspect without inferring delivery.';
  }
}

Download Practice.gs
Code.gs
/** @typedef {'baseline' | 'changed'} TwilioVariant */
/** @typedef {{accountSid: string, from: string, to: string, senderLabel: string, variant: TwilioVariant}} TwilioConfig */
/** @typedef {{sid: string, secret: string}} TwilioCredential */
/** @typedef {'prepared' | 'dispatching' | 'created' | 'rejected' | 'unknown' | 'reconciled'} TwilioIntentState */
/**
 * @typedef {{
 *   version: number,
 *   id: string,
 *   accountSid: string,
 *   from: string,
 *   to: string,
 *   senderLabel: string,
 *   variant: TwilioVariant,
 *   body: string,
 *   preparedAt: number,
 *   dispatchStartedAt: number | null,
 *   state: TwilioIntentState,
 *   messageSid: string | null,
 *   identityVerified: boolean,
 *   createHttpStatus: number | null,
 *   createErrorCode: number | null,
 *   lastStatus: string | null,
 *   lastObservedAt: number | null
 * }} TwilioIntent
 */
/** @typedef {{httpStatus: number, value: Record<string, unknown> | null, retryAfterSeconds: number | null}} TwilioReply */
const TWILIO_INTENT_KEY = 'TWILIO_SMS_INTENT_V1';
const TWILIO_CONFIRMATION = 'I checked current consent, sender approval and charges for this one SMS';

/** Local redacted preview only; no credential read, HTTP request or state write. @returns {void} */
function previewTwilioPracticeSms() {
  const config = twilioConfig_();
  const body = twilioBody_(config.senderLabel, config.variant, Utilities.getUuid().toLowerCase());
  console.log(JSON.stringify({stage: 'local_preview', variant: config.variant,
    from: twilioMask_(config.from), to: twilioMask_(config.to), body: '[redacted]',
    bodyCharacters: body.length, gsm7Units: body.length, predictedSegments: 1,
    createAttempts: 0, approvalClock: new Date().toISOString()}));
}

/** Save this project's one intent without contacting Twilio. Never replaces an existing record. @returns {void} */
function prepareTwilioPracticeSms() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    if (twilioLoadIntent_() !== null) throw new Error('TWILIO_INTENT_EXISTS: inspect; do not clear it to send again.');
    const config = twilioConfig_();
    if (config.variant !== 'baseline') throw new Error('TWILIO_RESTORE_BASELINE_BEFORE_PREPARING');
    const id = Utilities.getUuid().toLowerCase();
    /** @type {TwilioIntent} */
    const intent = {version: 1, id: id, accountSid: config.accountSid, from: config.from, to: config.to,
      senderLabel: config.senderLabel, variant: config.variant, body: twilioBody_(config.senderLabel, config.variant, id),
      preparedAt: Date.now(), dispatchStartedAt: null, state: 'prepared', messageSid: null,
      identityVerified: false, createHttpStatus: null, createErrorCode: null, lastStatus: null, lastObservedAt: null};
    twilioSaveIntent_(intent);
    twilioLogIntent_('prepared', intent);
  } finally { lock.releaseLock(); }
}

/**
 * One deliberately approved Messages POST. All non-prepared states refuse another create.
 * A durable local marker is not a Twilio idempotency key or a cross-service transaction.
 * @returns {void}
 */
function sendPreparedTwilioSms() {
  const deadline = Date.now() + 20000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    const intent = twilioLoadIntent_();
    if (intent === null || intent.state !== 'prepared') throw new Error('TWILIO_NO_UNSENT_PREPARED_INTENT');
    const config = twilioConfig_();
    if (config.accountSid !== intent.accountSid || config.from !== intent.from || config.to !== intent.to ||
        config.senderLabel !== intent.senderLabel || config.variant !== intent.variant ||
        twilioBody_(config.senderLabel, config.variant, intent.id) !== intent.body) throw new Error('TWILIO_CONFIG_CHANGED');
    twilioRequireApproval_(intent.id);
    const credential = twilioCredential_('CREATE');
    const form = 'To=' + encodeURIComponent(intent.to) + '&From=' + encodeURIComponent(intent.from) +
      '&Body=' + encodeURIComponent(intent.body) + '&ValidityPeriod=60';
    if (Date.now() + 1000 >= deadline) throw new Error('TWILIO_SETUP_DEADLINE_NO_CREATE');
    intent.state = 'dispatching';
    intent.dispatchStartedAt = Date.now();
    twilioSaveIntent_(intent);
    twilioLogIntent_('dispatch_possible', intent);
    /** @type {TwilioReply} */
    let reply;
    try { reply = twilioRequest_(intent.accountSid, credential, null, form, deadline); }
    catch (error) {
      intent.state = 'unknown';
      twilioSaveIntent_(intent);
      throw new Error('TWILIO_CREATE_OUTCOME_UNKNOWN: reconcile; never repost.');
    }
    intent.createHttpStatus = reply.httpStatus;
    intent.createErrorCode = twilioErrorCode_(reply.value === null ? null : reply.value.code);
    // Preserve a returned SID as a candidate BEFORE checking the remaining representation.
    const value = reply.value;
    if (value !== null && value.account_sid === intent.accountSid &&
        typeof value.sid === 'string' && /^SM[0-9a-fA-F]{32}$/.test(value.sid)) {
      intent.messageSid = value.sid;
      intent.state = 'unknown';
      twilioSaveIntent_(intent);
    }
    if (reply.httpStatus === 201 && value !== null && intent.messageSid !== null) {
      twilioVerifyIdentity_(value, intent, intent.messageSid, true);
      intent.identityVerified = true;
      intent.state = 'created';
      // Save confirmed identity even if a new/unusable status field prevents status inspection.
      twilioSaveIntent_(intent);
      intent.lastStatus = twilioStatus_(value.status);
      intent.lastObservedAt = Date.now();
    } else if (intent.messageSid === null && [400, 401, 403, 404, 405, 422, 429].indexOf(reply.httpStatus) !== -1) {
      intent.state = 'rejected';
    } else {
      intent.state = 'unknown';
    }
    twilioSaveIntent_(intent);
    twilioLogIntent_('create_result', intent);
    console.log(JSON.stringify({stage: 'create_response', httpStatus: reply.httpStatus,
      code: intent.createErrorCode, retryAfterSeconds: reply.retryAfterSeconds}));
    if (intent.state !== 'created') throw new Error('TWILIO_CREATE_NOT_CONFIRMED: inspect the original intent; no retry.');
  } finally { lock.releaseLock(); }
}

/** Read redacted local evidence only, never the raw property store. @returns {void} */
function inspectTwilioSmsIntent() {
  const intent = twilioLoadIntent_();
  if (intent === null) console.log(JSON.stringify({stage: 'no_intent'}));
  else twilioLogIntent_('saved_intent', intent);
}

/**
 * One independent GET for the saved SID, using only the READ key and saved intent.
 * A failed read never discards the original create receipt or enables another POST.
 * @returns {void}
 */
function readKnownTwilioMessage() {
  const deadline = Date.now() + 20000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    const intent = twilioLoadIntent_();
    if (intent === null || intent.messageSid === null) throw new Error('TWILIO_KNOWN_SID_REQUIRED');
    const reply = twilioRequest_(intent.accountSid, twilioCredential_('READ'), intent.messageSid, null, deadline);
    const value = twilioReadOk_(reply);
    twilioVerifyIdentity_(value, intent, intent.messageSid, !intent.identityVerified);
    if (!intent.identityVerified) { intent.identityVerified = true; intent.state = 'reconciled'; }
    // Keep identity before optional status/diagnostic parsing, too.
    twilioSaveIntent_(intent);
    twilioRecordObservation_(intent, value);
  } finally { lock.releaseLock(); }
}

/**
 * After human Console matching, fetch ONE candidate SID and prove its identity against the intent.
 * No list/search API, create, callback or replacement of a saved SID.
 * @returns {void}
 */
function reconcileTwilioSmsFromConsole() {
  const deadline = Date.now() + 20000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    const intent = twilioLoadIntent_();
    const store = PropertiesService.getScriptProperties();
    const candidate = store.getProperty('TWILIO_RECONCILE_MESSAGE_SID');
    if (intent === null || (intent.state !== 'dispatching' && intent.state !== 'unknown') || intent.messageSid !== null ||
        store.getProperty('TWILIO_RECONCILE_INTENT_ID') !== intent.id ||
        typeof candidate !== 'string' || !/^SM[0-9a-fA-F]{32}$/.test(candidate)) throw new Error('TWILIO_RECONCILIATION_REQUIRED');
    const value = twilioReadOk_(twilioRequest_(intent.accountSid, twilioCredential_('READ'), candidate, null, deadline));
    twilioVerifyIdentity_(value, intent, candidate, true);
    intent.messageSid = candidate;
    intent.identityVerified = true;
    intent.state = 'reconciled';
    twilioSaveIntent_(intent);
    twilioRecordObservation_(intent, value);
  } finally { lock.releaseLock(); }
}

/** @param {TwilioIntent} intent @param {Record<string, unknown>} value @returns {void} */
function twilioRecordObservation_(intent, value) {
  const status = twilioStatus_(value.status);
  const errorCode = twilioErrorCode_(value.error_code);
  const segments = typeof value.num_segments === 'string' && /^[0-9]{1,5}$/.test(value.num_segments) ? value.num_segments : null;
  const price = typeof value.price === 'string' && /^-?[0-9]{1,8}(\.[0-9]{1,8})?$/.test(value.price) ? value.price : null;
  const priceUnit = typeof value.price_unit === 'string' && /^[A-Za-z]{3}$/.test(value.price_unit) ? value.price_unit : null;
  intent.lastStatus = status;
  intent.lastObservedAt = Date.now();
  twilioSaveIntent_(intent);
  console.log(JSON.stringify({stage: 'message_observation', intentId: intent.id, messageSid: intent.messageSid,
    status: status, meaning: twilioStatusMeaning_(status), observedAt: new Date(intent.lastObservedAt).toISOString(),
    errorCode: errorCode, numSegments: segments, price: price, priceUnit: priceUnit,
    body: '[redacted]', from: twilioMask_(intent.from), to: twilioMask_(intent.to)}));
}

/** @returns {TwilioConfig} */
function twilioConfig_() {
  const store = PropertiesService.getScriptProperties();
  const accountSid = store.getProperty('TWILIO_ACCOUNT_SID');
  const from = store.getProperty('TWILIO_FROM_PHONE');
  const to = store.getProperty('TWILIO_TO_PHONE');
  const senderLabel = store.getProperty('TWILIO_SENDER_LABEL');
  const variant = store.getProperty('TWILIO_VARIANT');
  if (store.getProperty('TWILIO_ENVIRONMENT') !== 'paid-us1' || typeof accountSid !== 'string' ||
      !/^AC[0-9a-fA-F]{32}$/.test(accountSid) || typeof from !== 'string' || !/^\+1(800|833|844|855|866|877|888)[0-9]{7}$/.test(from) ||
      typeof to !== 'string' || !/^\+1[2-9][0-9]{2}[2-9][0-9]{6}$/.test(to) || from === to ||
      typeof senderLabel !== 'string' || !/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(senderLabel) || senderLabel.trim() !== senderLabel ||
      (variant !== 'baseline' && variant !== 'changed')) throw new Error('TWILIO_LOCAL_CONFIG_REQUIRED');
  // Shapes do not prove paid account status, US destination, SMS capability, approval or consent.
  return {accountSid: accountSid, from: from, to: to, senderLabel: senderLabel, variant: variant};
}

/** @param {'CREATE' | 'READ'} purpose @returns {TwilioCredential} */
function twilioCredential_(purpose) {
  const store = PropertiesService.getScriptProperties();
  const sid = store.getProperty('TWILIO_' + purpose + '_KEY_SID');
  const secret = store.getProperty('TWILIO_' + purpose + '_KEY_SECRET');
  if (typeof sid !== 'string' || !/^SK[0-9a-fA-F]{32}$/.test(sid) || typeof secret !== 'string' ||
      secret.length < 16 || secret.length > 256 || /[\u0000-\u0020\u007f]/.test(secret)) throw new Error('TWILIO_RESTRICTED_KEY_REQUIRED');
  return {sid: sid, secret: secret};
}

/** @param {string} id @returns {void} */
function twilioRequireApproval_(id) {
  const store = PropertiesService.getScriptProperties();
  const approvalAt = store.getProperty('TWILIO_APPROVAL_AT');
  const time = approvalAt === null ? NaN : Date.parse(approvalAt);
  const age = Date.now() - time;
  if (store.getProperty('TWILIO_CONFIRM_INTENT_ID') !== id || store.getProperty('TWILIO_SEND_CONFIRMATION') !== TWILIO_CONFIRMATION ||
      !Number.isFinite(time) || new Date(time).toISOString() !== approvalAt || age < 0 || age > 15 * 60 * 1000) {
    throw new Error('TWILIO_FRESH_EXPLICIT_APPROVAL_REQUIRED');
  }
}

/**
 * Fixed US1 origin and 2010-04-01 API. Exactly POST collection or GET known SMS SID.
 * @param {string} accountSid @param {TwilioCredential} credential
 * @param {string | null} messageSid @param {string | null} form @param {number} deadline
 * @returns {TwilioReply}
 */
function twilioRequest_(accountSid, credential, messageSid, form, deadline) {
  if (!/^AC[0-9a-fA-F]{32}$/.test(accountSid) || (messageSid === null) !== (form !== null) ||
      (messageSid !== null && !/^SM[0-9a-fA-F]{32}$/.test(messageSid))) throw new Error('TWILIO_REQUEST_SHAPE');
  const seconds = Math.min(15, Math.floor((deadline - Date.now()) / 1000));
  if (seconds < 1) throw new Error('TWILIO_REQUEST_DEADLINE');
  const url = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages' +
    (messageSid === null ? '' : '/' + messageSid) + '.json';
  /** @type {UrlFetchApp.HTTPResponse} */
  let response;
  try {
    response = UrlFetchApp.fetch(url, {
      method: messageSid === null ? 'post' : 'get',
      headers: {Authorization: 'Basic ' + Utilities.base64Encode(credential.sid + ':' + credential.secret, Utilities.Charset.UTF_8),
        Accept: 'application/json'},
      followRedirects: false, muteHttpExceptions: true, validateHttpsCertificates: true, timeoutSeconds: seconds,
      ...(form === null ? {} : {contentType: 'application/x-www-form-urlencoded; charset=utf-8', payload: form}),
    });
  } catch (error) { throw new Error('TWILIO_TRANSPORT_OR_TIMEOUT: do not log the original exception.'); }
  if (Date.now() > deadline) throw new Error('TWILIO_RESPONSE_DEADLINE');
  const httpStatus = response.getResponseCode();
  const headers = twilioObject_(response.getAllHeaders());
  const retry = twilioHeader_(headers, 'retry-after');
  const retryAfterSeconds = retry !== null && /^[0-9]{1,8}$/.test(retry) ? Number(retry) : null;
  const type = twilioHeader_(headers, 'content-type');
  /** @type {Record<string, unknown> | null} */
  let value = null;
  const text = response.getContentText('UTF-8');
  // URL Fetch already downloaded this body. This bounds parsing, not transport bytes.
  if (type !== null && type.split(';')[0].trim().toLowerCase() === 'application/json' && text.length > 0 &&
      text.length <= 32768 && Utilities.newBlob(text).getBytes().length <= 32768) {
    try { value = twilioObject_(JSON.parse(text)); } catch (error) { value = null; }
  }
  if (Date.now() > deadline) throw new Error('TWILIO_PARSE_DEADLINE');
  return {httpStatus: httpStatus, value: value, retryAfterSeconds: retryAfterSeconds};
}

/** @param {TwilioReply} reply @returns {Record<string, unknown>} */
function twilioReadOk_(reply) {
  if (reply.httpStatus === 200 && reply.value !== null) return reply.value;
  console.error(JSON.stringify({stage: 'status_read_failed', httpStatus: reply.httpStatus,
    code: twilioErrorCode_(reply.value === null ? null : reply.value.code), retryAfterSeconds: reply.retryAfterSeconds}));
  throw new Error('TWILIO_READ_NOT_CONFIRMED: saved create evidence is unchanged.');
}

/** @param {Record<string, unknown>} value @param {TwilioIntent} intent @param {string} sid @param {boolean} requireContent @returns {void} */
function twilioVerifyIdentity_(value, intent, sid, requireContent) {
  if (value.sid !== sid || value.account_sid !== intent.accountSid || value.direction !== 'outbound-api' ||
      value.api_version !== '2010-04-01' || value.num_media !== '0') throw new Error('TWILIO_MESSAGE_IDENTITY_MISMATCH');
  if (requireContent) {
    const created = typeof value.date_created === 'string' ? Date.parse(value.date_created) : NaN;
    if (value.from !== intent.from || value.to !== intent.to || value.body !== intent.body ||
        intent.dispatchStartedAt === null || !Number.isFinite(created) ||
        Math.abs(created - intent.dispatchStartedAt) > 5 * 60 * 1000) throw new Error('TWILIO_MESSAGE_MATCH_NOT_PROVEN');
  }
}

/** @param {unknown} value @returns {string} */
function twilioStatus_(value) {
  if (typeof value !== 'string' || !/^[a-z_]{1,32}$/.test(value)) throw new Error('TWILIO_STATUS_NOT_READABLE');
  return value;
}

/** @param {unknown} value @returns {number | null} */
function twilioErrorCode_(value) {
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= 99999999 ? value : null;
}

/** @param {unknown} value @returns {Record<string, unknown> | null} */
function twilioObject_(value) {
  return value !== null && typeof value === 'object' && !Array.isArray(value) ? /** @type {Record<string, unknown>} */ (value) : null;
}

/** @param {Record<string, unknown> | null} headers @param {string} name @returns {string | null} */
function twilioHeader_(headers, name) {
  if (headers === null) return null;
  const names = Object.keys(headers).filter((key) => key.toLowerCase() === name);
  if (names.length !== 1) return null;
  const value = headers[names[0]];
  return typeof value === 'string' ? value : null;
}

/** @param {string} phone @returns {string} */
function twilioMask_(phone) { return '[redacted]...' + phone.slice(-4); }

/** @param {string} stage @param {TwilioIntent} intent @returns {void} */
function twilioLogIntent_(stage, intent) {
  console.log(JSON.stringify({stage: stage, intentId: intent.id, state: intent.state,
    messageSid: intent.messageSid, identityVerified: intent.identityVerified, lastStatus: intent.lastStatus,
    lastObservedAt: intent.lastObservedAt, createHttpStatus: intent.createHttpStatus, createErrorCode: intent.createErrorCode,
    from: twilioMask_(intent.from), to: twilioMask_(intent.to), body: '[redacted]', bodyCharacters: intent.body.length}));
}

/** @returns {TwilioIntent | null} */
function twilioLoadIntent_() {
  const raw = PropertiesService.getScriptProperties().getProperty(TWILIO_INTENT_KEY);
  if (raw === null) return null;
  if (raw.length > 4000) throw new Error('TWILIO_INTENT_INVALID: retain the original record.');
  /** @type {Record<string, unknown> | null} */
  let value;
  try { value = twilioObject_(JSON.parse(raw)); } catch (error) { throw new Error('TWILIO_INTENT_INVALID_JSON'); }
  if (value === null) throw new Error('TWILIO_INTENT_INVALID');
  const state = value.state;
  const variant = value.variant;
  if (value.version !== 1 || typeof value.id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value.id) ||
      typeof value.accountSid !== 'string' || !/^AC[0-9a-fA-F]{32}$/.test(value.accountSid) ||
      typeof value.from !== 'string' || !/^\+1(800|833|844|855|866|877|888)[0-9]{7}$/.test(value.from) ||
      typeof value.to !== 'string' || !/^\+1[2-9][0-9]{2}[2-9][0-9]{6}$/.test(value.to) || value.from === value.to ||
      typeof value.senderLabel !== 'string' || !/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(value.senderLabel) ||
      (variant !== 'baseline' && variant !== 'changed') || typeof value.body !== 'string' ||
      value.body !== twilioBody_(value.senderLabel, variant, value.id) ||
      typeof value.preparedAt !== 'number' || !Number.isSafeInteger(value.preparedAt) || value.preparedAt <= 0 ||
      !twilioNullableTime_(value.dispatchStartedAt) || !twilioNullableTime_(value.lastObservedAt) ||
      (state !== 'prepared' && state !== 'dispatching' && state !== 'created' && state !== 'rejected' && state !== 'unknown' && state !== 'reconciled') ||
      typeof value.identityVerified !== 'boolean' ||
      (value.messageSid !== null && (typeof value.messageSid !== 'string' || !/^SM[0-9a-fA-F]{32}$/.test(value.messageSid))) ||
      (value.createHttpStatus !== null && (typeof value.createHttpStatus !== 'number' || !Number.isInteger(value.createHttpStatus) || value.createHttpStatus < 100 || value.createHttpStatus > 599)) ||
      (value.createErrorCode !== null && twilioErrorCode_(value.createErrorCode) === null) ||
      (value.lastStatus !== null && (typeof value.lastStatus !== 'string' || !/^[a-z_]{1,32}$/.test(value.lastStatus))) ||
      ((state === 'prepared') !== (value.dispatchStartedAt === null)) ||
      ((state === 'created' || state === 'reconciled') !== value.identityVerified) ||
      (value.identityVerified && value.messageSid === null) ||
      (state === 'rejected' && value.messageSid !== null) ||
      (state === 'prepared' && (value.messageSid !== null || value.createHttpStatus !== null || value.createErrorCode !== null || value.lastStatus !== null)) ||
      (state === 'dispatching' && value.messageSid !== null) ||
      (state === 'created' && value.createHttpStatus !== 201) ||
      (value.lastStatus !== null && !value.identityVerified) ||
      ((value.lastStatus === null) !== (value.lastObservedAt === null))) throw new Error('TWILIO_INTENT_INVALID: do not reset it.');
  return {version: 1, id: value.id, accountSid: value.accountSid, from: value.from, to: value.to,
    senderLabel: value.senderLabel, variant: variant, body: value.body, preparedAt: value.preparedAt,
    dispatchStartedAt: value.dispatchStartedAt, state: state, messageSid: value.messageSid, identityVerified: value.identityVerified,
    createHttpStatus: value.createHttpStatus, createErrorCode: /** @type {number | null} */ (value.createErrorCode),
    lastStatus: value.lastStatus, lastObservedAt: value.lastObservedAt};
}

/** @param {unknown} value @returns {value is number | null} */
function twilioNullableTime_(value) { return value === null || (typeof value === 'number' && Number.isSafeInteger(value) && value > 0); }

/** @param {TwilioIntent} intent @returns {void} */
function twilioSaveIntent_(intent) {
  const raw = JSON.stringify(intent);
  if (Utilities.newBlob(raw).getBytes().length > 4000) throw new Error('TWILIO_INTENT_STORAGE_BOUND');
  try { PropertiesService.getScriptProperties().setProperty(TWILIO_INTENT_KEY, raw); }
  catch (error) { throw new Error('TWILIO_LOCAL_SAVE_FAILED: possible dispatch remains uncertain; never repost.'); }
}

Download Code.gs

Preview, change, and restore before preparing

Before you run anything, predict the baseline result: zero create attempts, both phone numbers masked, the body redacted, and one segment. Then run previewTwilioPracticeSms in the Apps Script editor and check those fields. The preview reads neither credential and does not call Twilio. Google may still ask you to grant the project's declared external-request scope. Granting it does not make the preview send a request.

Change only TWILIO_VARIANT to changed. The fictional line changes from REQ-001 map ready. to REQ-001 map checked. Predict two more body characters, still one segment, and still zero create attempts. Preview again and compare the counts. Then set the variant back to baseline and preview once more. The last character count should match the first. Do not change a real recipient to cause a failure. The preview redacts the whole text, so review the exact template in Practice.gs and the real sender name privately, not in shared logs.

Run prepareTwilioPracticeSms once. It refuses to run with the changed variant and refuses to replace a saved message record. While holding a script lock, it saves the record as TWILIO_SMS_INTENT_V1. It does not contact Twilio. Run inspectTwilioSmsIntent to see a redacted summary and the record's UUID. The saved record holds the full approved phone numbers and body so the script can match them later. It never holds an API key or secret. Treat the property as sensitive even though the request itself is fictional.

Open Script Properties and check the saved record privately: the full sender and recipient numbers, the sender name, the fictional text, the opt-out instruction, and the UUID marker. Do not edit the record. Confirm that your consent and the sender approval are still current and that you approve the one possible live charge. Then add:

  • TWILIO_CONFIRM_INTENT_ID: exactly the saved record's UUID.

  • TWILIO_SEND_CONFIRMATION: exactly I checked current consent, sender approval and charges for this one SMS.

  • TWILIO_APPROVAL_AT: a fresh ISO timestamp from the approvalClock field of another local preview, copied only after those checks.

The approval must be no more than 15 minutes old and must not be in the future. This is a local check on how recent the approval is. It does not record electronic consent. If the approval expires while the record is still prepared, repeat the real checks before you renew it. If you change any configuration that would alter the account, destination, or body, sendPreparedTwilioSms refuses to send.

Make one create attempt

Do not run the send function more than once. If anything goes wrong after this step, do not send again. Inspect the saved record and use the read functions below. Clearing or editing the record, copying the project, or sending directly with the key would bypass the script's guard and send a new message.

After the approval above, select sendPreparedTwilioSms and run it once. It sends one form-encoded POST to:

Source
https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages.json

The form contains only To, From, Body, and ValidityPeriod=60. ValidityPeriod limits how long, in seconds, the message may wait in Twilio's outgoing queue before it is sent. It cannot recall a message and does not promise delivery to the handset within 60 seconds. The request uses ordinary HTTPS certificate validation and follows no redirects, and the script never retries it. The script allows 20 seconds for the whole request, including setup and response parsing, and sets URL Fetch's timeoutSeconds to at most 15. Saving the result locally can still take longer. A timeout cannot undo a request that Twilio already received.

The script saves dispatching, then attempts the POST, then saves the result. Because of that first save, running the function again does not send the same approved message a second time. Every state other than prepared blocks another POST, including rejected.

Local stateWhat you know and what to do
preparedThe script has not attempted a send. Check the configuration, the credentials, and the fresh approval before the one permitted attempt.
dispatchingThe script saved dispatching before it tried the POST, and nothing replaced it. The execution may have stopped before reaching Twilio, or Twilio may have created the message. Treat the outcome as unknown.
createdTwilio returned HTTP 201 with a matching account, SMS SID, direction, body, sender, recipient, and a plausible creation time. A Message resource exists, but that does not mean it was delivered.
rejectedTwilio returned a recognized HTTP refusal without a Message SID. The exercise still does not retry or create another record.
unknownThe response did not show whether Twilio created the message, for example after a timeout, a server error, a response the script could not parse, or fields that did not match. The script may keep a returned SID as an unverified candidate.
reconciledA separate GET of a known SID matched the original record after an uncertain result. Read its Twilio status.

Run inspectTwilioSmsIntent after the attempt, even if the editor showed an error. The script saves a valid SID first, then checks the rest of the response and saves the verified Message details, and only then reads the status. An unfamiliar or malformed status does not make it discard a known Message. If a save fails after Twilio created the message, the earlier dispatching value may be all that remains, because Script Properties and Twilio do not change together as one transaction. The UUID in the SMS helps people match the message to the record. It is not a Twilio idempotency header and does not make delivery happen exactly once.

Do not test the repeat guard by approving another send. Check that the record is no longer prepared. To practice repeating an action, run the read function again instead. Running sendPreparedTwilioSms a second time would stop before making any HTTP request.

Read the same Message SID independently

Once a SID is saved, run readKnownTwilioMessage. It uses only the READ key and the saved record. It does not use the CREATE key, the current draft properties, or the approval timestamp. It makes one GET:

Source
https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}.json

readKnownTwilioMessage requires HTTP 200 and a JSON object whose account and Message SID match the saved record. A SID that was saved as an unverified candidate must also match the original body, full phone numbers, and creation time. Once the Message is verified, later reads compare only the SID and account, so you do not need to keep the message text forever. The function never lists the account's messages and never polls automatically.

Read status and meaning together:

Twilio statusWhat the status tells you
queuedTwilio accepted the API request and queued the message for its sender number.
sendingTwilio is passing the message to an upstream carrier.
sentThe nearest upstream carrier accepted it. This does not show that the handset received it.
deliveredTwilio received delivery confirmation from the upstream carrier and, where available, the destination handset. This still does not show that anyone read it.
undeliveredA receipt reports that the message was not delivered. Inspect the error and the account's records. Do not resend automatically.
failedTwilio reports that it could not send the message. Fixing the configuration does not approve another message.

The Message API's accepted status belongs to Messaging Service sends, which this example does not use because it sets From directly. Its read status applies to RCS and WhatsApp read receipts, not ordinary SMS. The script logs an unexpected status with a warning and does not treat it as delivery. The status can change between reads, and the example does not promise a particular final status or a delivery deadline (Message status values).

After a pause, run readKnownTwilioMessage again. Do not run sendPreparedTwilioSms. Predict that the SID stays the same while observedAt changes. status, errorCode, numSegments, or pricing may change as Twilio receives carrier updates. A null price means the price is missing or not filled in yet. It does not mean the message was free. The API can report a signed decimal price. Check its currency and the account's billing records instead of treating the field as a final price.

To confirm that reading works without the CREATE key, ask the account owner to revoke the dedicated CREATE key in Console after the attempt. Remove only its two local credential properties and the three approval properties, and keep the READ key and the original record. Another read of the known SID should still work, and it sends no second SMS. The GET cannot show that a person saw the message. Only checking the handset can show that.

Reconcile uncertainty without another SMS

If the saved record has a SID but is still unknown, run readKnownTwilioMessage to check that candidate. If the record has no SID, do not assume that an empty API response means no message exists.

With approved Console access:

  1. Open the selected account's Messaging logs. Search by the recorded attempt time, sender and recipient numbers, and full body containing the record's UUID. Do not export unrelated logs.

  2. If exactly one Message clearly matches, copy its SM... SID into TWILIO_RECONCILE_MESSAGE_SID. Copy the original UUID into TWILIO_RECONCILE_INTENT_ID. If there is no single clear match, stop and leave the outcome unresolved.

  3. Run reconcileTwilioSmsFromConsole once.

The function accepts only a dispatching record, or an unknown record with no saved SID. It makes one GET with the READ key and checks the candidate's exact original content and creation time before saving reconciled.

Do not send a replacement if the candidate is wrong, the read fails, the message content is redacted or expired, the Console results are unclear, or nothing matches. Leave the outcome unresolved and keep the original record. The script accepts a creation time within five minutes of the recorded attempt. That window is a matching check only. Console may take longer than that to show the message, so a quick empty search does not prove that nothing was sent. Do not delete the record to make the exercise runnable again.

Read failures without leaking the response

Twilio reports an HTTP status and, separately, a JSON error code. The script logs the numeric HTTP status, the numeric error code when it is within the expected range, and a numeric Retry-After value when present. It never logs raw response text, headers, Basic credentials, error_message, full phone numbers, or the body. Even a failed request can echo sensitive input, so do not replace those redacted errors with console.log(response.getContentText()) or log the original URL Fetch exception.

HTTP 401 or 403 suggests a problem with the credential, account, region, or permission. Error 21606 means the configured From number cannot send messages for that account. Error 21610 means the recipient has opted out. Do not ask them to resubscribe so that you can finish a coding exercise. Invalid destinations and carrier filtering can cause Twilio to reject the attempt or report failed or undelivered later. Use error text and codes to diagnose the problem, not to trigger another send.

For HTTP 429 with code 20429, Twilio documents that it did not process the request and that you may retry after backing off. This exercise is stricter. It records rejected and does not retry the POST. After you have waited as the rate-limit response asks, you may repeat a GET by hand, because a GET cannot create a message.

The script treats server errors, HTTP timeouts, and malformed successful responses as unknown outcomes, not as failures that are safe to retry. The script refuses to parse a response body larger than 32 KiB, but URL Fetch has already downloaded the body by then, so this does not limit network bytes. A failed status read keeps the earlier create result and does not reset the record to prepared.

Why there is no callback receiver

For one message that you check by hand, a GET of the known SID is enough. It needs no extra hosted service and no stored Account Auth Token, so the request sets no callback address. Do not place a voice call to troubleshoot an undelivered SMS. A call costs money, reaches the recipient, and needs its own consent and its own TwiML setup.

A production callback receiver needs different security checks. Twilio signs each callback in the X-Twilio-Signature header using the Account Auth Token, the exact public request URL, and the request parameters it sent. The API key used for outgoing REST requests cannot validate that signature. Twilio recommends its official helper library because callback parameters can change. Validation must use the exact URL configured in Twilio and every applicable parameter. A rebuilt localhost URL, a subset of fields, or a hand-written HMAC will not work (webhook security).

Apps Script's documented doPost(e) event provides form and body fields but does not expose arbitrary request headers such as X-Twilio-Signature. Do not invent e.headers, and do not accept unsigned callbacks in an Apps Script web app. Validating Twilio webhooks requires an HTTPS server that exposes raw headers. In Apps Script, read the known Message SID with the READ key instead.

Revoke the keys and keep the record

Stop running sendPreparedTwilioSms and make sure no execution is still running. Remove the three approval properties. Revoke the dedicated CREATE key in Console. Deleting its local secret does not revoke it. You can keep the READ key while you inspect or reconcile the original message. When you finish reviewing, revoke that key too, then remove its two local credential properties.

Keep TWILIO_SMS_INTENT_V1 while the outcome is uncertain or while you still need the record. When you no longer need it, remove only this example's named draft, confirmation, reconciliation, and credential properties.

Revoking a key or deleting a Message record cannot recall an SMS that was already sent or remove it from a handset. ValidityPeriod applies only while a message is still in Twilio's outgoing queue. A phone number you keep active continues to cost monthly rental. Release it in Console after you confirm that nothing else uses it.

Next, read GitHub issues and Actions events.

Project files

Complete source files for this chapter's examples.

Create one approved fictional SMS and read its known Message SID

Code.gs
/** @typedef {'baseline' | 'changed'} TwilioVariant */
/** @typedef {{accountSid: string, from: string, to: string, senderLabel: string, variant: TwilioVariant}} TwilioConfig */
/** @typedef {{sid: string, secret: string}} TwilioCredential */
/** @typedef {'prepared' | 'dispatching' | 'created' | 'rejected' | 'unknown' | 'reconciled'} TwilioIntentState */
/**
 * @typedef {{
 *   version: number,
 *   id: string,
 *   accountSid: string,
 *   from: string,
 *   to: string,
 *   senderLabel: string,
 *   variant: TwilioVariant,
 *   body: string,
 *   preparedAt: number,
 *   dispatchStartedAt: number | null,
 *   state: TwilioIntentState,
 *   messageSid: string | null,
 *   identityVerified: boolean,
 *   createHttpStatus: number | null,
 *   createErrorCode: number | null,
 *   lastStatus: string | null,
 *   lastObservedAt: number | null
 * }} TwilioIntent
 */
/** @typedef {{httpStatus: number, value: Record<string, unknown> | null, retryAfterSeconds: number | null}} TwilioReply */
const TWILIO_INTENT_KEY = 'TWILIO_SMS_INTENT_V1';
const TWILIO_CONFIRMATION = 'I checked current consent, sender approval and charges for this one SMS';

/** Local redacted preview only; no credential read, HTTP request or state write. @returns {void} */
function previewTwilioPracticeSms() {
  const config = twilioConfig_();
  const body = twilioBody_(config.senderLabel, config.variant, Utilities.getUuid().toLowerCase());
  console.log(JSON.stringify({stage: 'local_preview', variant: config.variant,
    from: twilioMask_(config.from), to: twilioMask_(config.to), body: '[redacted]',
    bodyCharacters: body.length, gsm7Units: body.length, predictedSegments: 1,
    createAttempts: 0, approvalClock: new Date().toISOString()}));
}

/** Save this project's one intent without contacting Twilio. Never replaces an existing record. @returns {void} */
function prepareTwilioPracticeSms() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    if (twilioLoadIntent_() !== null) throw new Error('TWILIO_INTENT_EXISTS: inspect; do not clear it to send again.');
    const config = twilioConfig_();
    if (config.variant !== 'baseline') throw new Error('TWILIO_RESTORE_BASELINE_BEFORE_PREPARING');
    const id = Utilities.getUuid().toLowerCase();
    /** @type {TwilioIntent} */
    const intent = {version: 1, id: id, accountSid: config.accountSid, from: config.from, to: config.to,
      senderLabel: config.senderLabel, variant: config.variant, body: twilioBody_(config.senderLabel, config.variant, id),
      preparedAt: Date.now(), dispatchStartedAt: null, state: 'prepared', messageSid: null,
      identityVerified: false, createHttpStatus: null, createErrorCode: null, lastStatus: null, lastObservedAt: null};
    twilioSaveIntent_(intent);
    twilioLogIntent_('prepared', intent);
  } finally { lock.releaseLock(); }
}

/**
 * One deliberately approved Messages POST. All non-prepared states refuse another create.
 * A durable local marker is not a Twilio idempotency key or a cross-service transaction.
 * @returns {void}
 */
function sendPreparedTwilioSms() {
  const deadline = Date.now() + 20000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    const intent = twilioLoadIntent_();
    if (intent === null || intent.state !== 'prepared') throw new Error('TWILIO_NO_UNSENT_PREPARED_INTENT');
    const config = twilioConfig_();
    if (config.accountSid !== intent.accountSid || config.from !== intent.from || config.to !== intent.to ||
        config.senderLabel !== intent.senderLabel || config.variant !== intent.variant ||
        twilioBody_(config.senderLabel, config.variant, intent.id) !== intent.body) throw new Error('TWILIO_CONFIG_CHANGED');
    twilioRequireApproval_(intent.id);
    const credential = twilioCredential_('CREATE');
    const form = 'To=' + encodeURIComponent(intent.to) + '&From=' + encodeURIComponent(intent.from) +
      '&Body=' + encodeURIComponent(intent.body) + '&ValidityPeriod=60';
    if (Date.now() + 1000 >= deadline) throw new Error('TWILIO_SETUP_DEADLINE_NO_CREATE');
    intent.state = 'dispatching';
    intent.dispatchStartedAt = Date.now();
    twilioSaveIntent_(intent);
    twilioLogIntent_('dispatch_possible', intent);
    /** @type {TwilioReply} */
    let reply;
    try { reply = twilioRequest_(intent.accountSid, credential, null, form, deadline); }
    catch (error) {
      intent.state = 'unknown';
      twilioSaveIntent_(intent);
      throw new Error('TWILIO_CREATE_OUTCOME_UNKNOWN: reconcile; never repost.');
    }
    intent.createHttpStatus = reply.httpStatus;
    intent.createErrorCode = twilioErrorCode_(reply.value === null ? null : reply.value.code);
    // Preserve a returned SID as a candidate BEFORE checking the remaining representation.
    const value = reply.value;
    if (value !== null && value.account_sid === intent.accountSid &&
        typeof value.sid === 'string' && /^SM[0-9a-fA-F]{32}$/.test(value.sid)) {
      intent.messageSid = value.sid;
      intent.state = 'unknown';
      twilioSaveIntent_(intent);
    }
    if (reply.httpStatus === 201 && value !== null && intent.messageSid !== null) {
      twilioVerifyIdentity_(value, intent, intent.messageSid, true);
      intent.identityVerified = true;
      intent.state = 'created';
      // Save confirmed identity even if a new/unusable status field prevents status inspection.
      twilioSaveIntent_(intent);
      intent.lastStatus = twilioStatus_(value.status);
      intent.lastObservedAt = Date.now();
    } else if (intent.messageSid === null && [400, 401, 403, 404, 405, 422, 429].indexOf(reply.httpStatus) !== -1) {
      intent.state = 'rejected';
    } else {
      intent.state = 'unknown';
    }
    twilioSaveIntent_(intent);
    twilioLogIntent_('create_result', intent);
    console.log(JSON.stringify({stage: 'create_response', httpStatus: reply.httpStatus,
      code: intent.createErrorCode, retryAfterSeconds: reply.retryAfterSeconds}));
    if (intent.state !== 'created') throw new Error('TWILIO_CREATE_NOT_CONFIRMED: inspect the original intent; no retry.');
  } finally { lock.releaseLock(); }
}

/** Read redacted local evidence only, never the raw property store. @returns {void} */
function inspectTwilioSmsIntent() {
  const intent = twilioLoadIntent_();
  if (intent === null) console.log(JSON.stringify({stage: 'no_intent'}));
  else twilioLogIntent_('saved_intent', intent);
}

/**
 * One independent GET for the saved SID, using only the READ key and saved intent.
 * A failed read never discards the original create receipt or enables another POST.
 * @returns {void}
 */
function readKnownTwilioMessage() {
  const deadline = Date.now() + 20000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    const intent = twilioLoadIntent_();
    if (intent === null || intent.messageSid === null) throw new Error('TWILIO_KNOWN_SID_REQUIRED');
    const reply = twilioRequest_(intent.accountSid, twilioCredential_('READ'), intent.messageSid, null, deadline);
    const value = twilioReadOk_(reply);
    twilioVerifyIdentity_(value, intent, intent.messageSid, !intent.identityVerified);
    if (!intent.identityVerified) { intent.identityVerified = true; intent.state = 'reconciled'; }
    // Keep identity before optional status/diagnostic parsing, too.
    twilioSaveIntent_(intent);
    twilioRecordObservation_(intent, value);
  } finally { lock.releaseLock(); }
}

/**
 * After human Console matching, fetch ONE candidate SID and prove its identity against the intent.
 * No list/search API, create, callback or replacement of a saved SID.
 * @returns {void}
 */
function reconcileTwilioSmsFromConsole() {
  const deadline = Date.now() + 20000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY');
  try {
    const intent = twilioLoadIntent_();
    const store = PropertiesService.getScriptProperties();
    const candidate = store.getProperty('TWILIO_RECONCILE_MESSAGE_SID');
    if (intent === null || (intent.state !== 'dispatching' && intent.state !== 'unknown') || intent.messageSid !== null ||
        store.getProperty('TWILIO_RECONCILE_INTENT_ID') !== intent.id ||
        typeof candidate !== 'string' || !/^SM[0-9a-fA-F]{32}$/.test(candidate)) throw new Error('TWILIO_RECONCILIATION_REQUIRED');
    const value = twilioReadOk_(twilioRequest_(intent.accountSid, twilioCredential_('READ'), candidate, null, deadline));
    twilioVerifyIdentity_(value, intent, candidate, true);
    intent.messageSid = candidate;
    intent.identityVerified = true;
    intent.state = 'reconciled';
    twilioSaveIntent_(intent);
    twilioRecordObservation_(intent, value);
  } finally { lock.releaseLock(); }
}

/** @param {TwilioIntent} intent @param {Record<string, unknown>} value @returns {void} */
function twilioRecordObservation_(intent, value) {
  const status = twilioStatus_(value.status);
  const errorCode = twilioErrorCode_(value.error_code);
  const segments = typeof value.num_segments === 'string' && /^[0-9]{1,5}$/.test(value.num_segments) ? value.num_segments : null;
  const price = typeof value.price === 'string' && /^-?[0-9]{1,8}(\.[0-9]{1,8})?$/.test(value.price) ? value.price : null;
  const priceUnit = typeof value.price_unit === 'string' && /^[A-Za-z]{3}$/.test(value.price_unit) ? value.price_unit : null;
  intent.lastStatus = status;
  intent.lastObservedAt = Date.now();
  twilioSaveIntent_(intent);
  console.log(JSON.stringify({stage: 'message_observation', intentId: intent.id, messageSid: intent.messageSid,
    status: status, meaning: twilioStatusMeaning_(status), observedAt: new Date(intent.lastObservedAt).toISOString(),
    errorCode: errorCode, numSegments: segments, price: price, priceUnit: priceUnit,
    body: '[redacted]', from: twilioMask_(intent.from), to: twilioMask_(intent.to)}));
}

/** @returns {TwilioConfig} */
function twilioConfig_() {
  const store = PropertiesService.getScriptProperties();
  const accountSid = store.getProperty('TWILIO_ACCOUNT_SID');
  const from = store.getProperty('TWILIO_FROM_PHONE');
  const to = store.getProperty('TWILIO_TO_PHONE');
  const senderLabel = store.getProperty('TWILIO_SENDER_LABEL');
  const variant = store.getProperty('TWILIO_VARIANT');
  if (store.getProperty('TWILIO_ENVIRONMENT') !== 'paid-us1' || typeof accountSid !== 'string' ||
      !/^AC[0-9a-fA-F]{32}$/.test(accountSid) || typeof from !== 'string' || !/^\+1(800|833|844|855|866|877|888)[0-9]{7}$/.test(from) ||
      typeof to !== 'string' || !/^\+1[2-9][0-9]{2}[2-9][0-9]{6}$/.test(to) || from === to ||
      typeof senderLabel !== 'string' || !/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(senderLabel) || senderLabel.trim() !== senderLabel ||
      (variant !== 'baseline' && variant !== 'changed')) throw new Error('TWILIO_LOCAL_CONFIG_REQUIRED');
  // Shapes do not prove paid account status, US destination, SMS capability, approval or consent.
  return {accountSid: accountSid, from: from, to: to, senderLabel: senderLabel, variant: variant};
}

/** @param {'CREATE' | 'READ'} purpose @returns {TwilioCredential} */
function twilioCredential_(purpose) {
  const store = PropertiesService.getScriptProperties();
  const sid = store.getProperty('TWILIO_' + purpose + '_KEY_SID');
  const secret = store.getProperty('TWILIO_' + purpose + '_KEY_SECRET');
  if (typeof sid !== 'string' || !/^SK[0-9a-fA-F]{32}$/.test(sid) || typeof secret !== 'string' ||
      secret.length < 16 || secret.length > 256 || /[\u0000-\u0020\u007f]/.test(secret)) throw new Error('TWILIO_RESTRICTED_KEY_REQUIRED');
  return {sid: sid, secret: secret};
}

/** @param {string} id @returns {void} */
function twilioRequireApproval_(id) {
  const store = PropertiesService.getScriptProperties();
  const approvalAt = store.getProperty('TWILIO_APPROVAL_AT');
  const time = approvalAt === null ? NaN : Date.parse(approvalAt);
  const age = Date.now() - time;
  if (store.getProperty('TWILIO_CONFIRM_INTENT_ID') !== id || store.getProperty('TWILIO_SEND_CONFIRMATION') !== TWILIO_CONFIRMATION ||
      !Number.isFinite(time) || new Date(time).toISOString() !== approvalAt || age < 0 || age > 15 * 60 * 1000) {
    throw new Error('TWILIO_FRESH_EXPLICIT_APPROVAL_REQUIRED');
  }
}

/**
 * Fixed US1 origin and 2010-04-01 API. Exactly POST collection or GET known SMS SID.
 * @param {string} accountSid @param {TwilioCredential} credential
 * @param {string | null} messageSid @param {string | null} form @param {number} deadline
 * @returns {TwilioReply}
 */
function twilioRequest_(accountSid, credential, messageSid, form, deadline) {
  if (!/^AC[0-9a-fA-F]{32}$/.test(accountSid) || (messageSid === null) !== (form !== null) ||
      (messageSid !== null && !/^SM[0-9a-fA-F]{32}$/.test(messageSid))) throw new Error('TWILIO_REQUEST_SHAPE');
  const seconds = Math.min(15, Math.floor((deadline - Date.now()) / 1000));
  if (seconds < 1) throw new Error('TWILIO_REQUEST_DEADLINE');
  const url = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages' +
    (messageSid === null ? '' : '/' + messageSid) + '.json';
  /** @type {UrlFetchApp.HTTPResponse} */
  let response;
  try {
    response = UrlFetchApp.fetch(url, {
      method: messageSid === null ? 'post' : 'get',
      headers: {Authorization: 'Basic ' + Utilities.base64Encode(credential.sid + ':' + credential.secret, Utilities.Charset.UTF_8),
        Accept: 'application/json'},
      followRedirects: false, muteHttpExceptions: true, validateHttpsCertificates: true, timeoutSeconds: seconds,
      ...(form === null ? {} : {contentType: 'application/x-www-form-urlencoded; charset=utf-8', payload: form}),
    });
  } catch (error) { throw new Error('TWILIO_TRANSPORT_OR_TIMEOUT: do not log the original exception.'); }
  if (Date.now() > deadline) throw new Error('TWILIO_RESPONSE_DEADLINE');
  const httpStatus = response.getResponseCode();
  const headers = twilioObject_(response.getAllHeaders());
  const retry = twilioHeader_(headers, 'retry-after');
  const retryAfterSeconds = retry !== null && /^[0-9]{1,8}$/.test(retry) ? Number(retry) : null;
  const type = twilioHeader_(headers, 'content-type');
  /** @type {Record<string, unknown> | null} */
  let value = null;
  const text = response.getContentText('UTF-8');
  // URL Fetch already downloaded this body. This bounds parsing, not transport bytes.
  if (type !== null && type.split(';')[0].trim().toLowerCase() === 'application/json' && text.length > 0 &&
      text.length <= 32768 && Utilities.newBlob(text).getBytes().length <= 32768) {
    try { value = twilioObject_(JSON.parse(text)); } catch (error) { value = null; }
  }
  if (Date.now() > deadline) throw new Error('TWILIO_PARSE_DEADLINE');
  return {httpStatus: httpStatus, value: value, retryAfterSeconds: retryAfterSeconds};
}

/** @param {TwilioReply} reply @returns {Record<string, unknown>} */
function twilioReadOk_(reply) {
  if (reply.httpStatus === 200 && reply.value !== null) return reply.value;
  console.error(JSON.stringify({stage: 'status_read_failed', httpStatus: reply.httpStatus,
    code: twilioErrorCode_(reply.value === null ? null : reply.value.code), retryAfterSeconds: reply.retryAfterSeconds}));
  throw new Error('TWILIO_READ_NOT_CONFIRMED: saved create evidence is unchanged.');
}

/** @param {Record<string, unknown>} value @param {TwilioIntent} intent @param {string} sid @param {boolean} requireContent @returns {void} */
function twilioVerifyIdentity_(value, intent, sid, requireContent) {
  if (value.sid !== sid || value.account_sid !== intent.accountSid || value.direction !== 'outbound-api' ||
      value.api_version !== '2010-04-01' || value.num_media !== '0') throw new Error('TWILIO_MESSAGE_IDENTITY_MISMATCH');
  if (requireContent) {
    const created = typeof value.date_created === 'string' ? Date.parse(value.date_created) : NaN;
    if (value.from !== intent.from || value.to !== intent.to || value.body !== intent.body ||
        intent.dispatchStartedAt === null || !Number.isFinite(created) ||
        Math.abs(created - intent.dispatchStartedAt) > 5 * 60 * 1000) throw new Error('TWILIO_MESSAGE_MATCH_NOT_PROVEN');
  }
}

/** @param {unknown} value @returns {string} */
function twilioStatus_(value) {
  if (typeof value !== 'string' || !/^[a-z_]{1,32}$/.test(value)) throw new Error('TWILIO_STATUS_NOT_READABLE');
  return value;
}

/** @param {unknown} value @returns {number | null} */
function twilioErrorCode_(value) {
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= 99999999 ? value : null;
}

/** @param {unknown} value @returns {Record<string, unknown> | null} */
function twilioObject_(value) {
  return value !== null && typeof value === 'object' && !Array.isArray(value) ? /** @type {Record<string, unknown>} */ (value) : null;
}

/** @param {Record<string, unknown> | null} headers @param {string} name @returns {string | null} */
function twilioHeader_(headers, name) {
  if (headers === null) return null;
  const names = Object.keys(headers).filter((key) => key.toLowerCase() === name);
  if (names.length !== 1) return null;
  const value = headers[names[0]];
  return typeof value === 'string' ? value : null;
}

/** @param {string} phone @returns {string} */
function twilioMask_(phone) { return '[redacted]...' + phone.slice(-4); }

/** @param {string} stage @param {TwilioIntent} intent @returns {void} */
function twilioLogIntent_(stage, intent) {
  console.log(JSON.stringify({stage: stage, intentId: intent.id, state: intent.state,
    messageSid: intent.messageSid, identityVerified: intent.identityVerified, lastStatus: intent.lastStatus,
    lastObservedAt: intent.lastObservedAt, createHttpStatus: intent.createHttpStatus, createErrorCode: intent.createErrorCode,
    from: twilioMask_(intent.from), to: twilioMask_(intent.to), body: '[redacted]', bodyCharacters: intent.body.length}));
}

/** @returns {TwilioIntent | null} */
function twilioLoadIntent_() {
  const raw = PropertiesService.getScriptProperties().getProperty(TWILIO_INTENT_KEY);
  if (raw === null) return null;
  if (raw.length > 4000) throw new Error('TWILIO_INTENT_INVALID: retain the original record.');
  /** @type {Record<string, unknown> | null} */
  let value;
  try { value = twilioObject_(JSON.parse(raw)); } catch (error) { throw new Error('TWILIO_INTENT_INVALID_JSON'); }
  if (value === null) throw new Error('TWILIO_INTENT_INVALID');
  const state = value.state;
  const variant = value.variant;
  if (value.version !== 1 || typeof value.id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value.id) ||
      typeof value.accountSid !== 'string' || !/^AC[0-9a-fA-F]{32}$/.test(value.accountSid) ||
      typeof value.from !== 'string' || !/^\+1(800|833|844|855|866|877|888)[0-9]{7}$/.test(value.from) ||
      typeof value.to !== 'string' || !/^\+1[2-9][0-9]{2}[2-9][0-9]{6}$/.test(value.to) || value.from === value.to ||
      typeof value.senderLabel !== 'string' || !/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(value.senderLabel) ||
      (variant !== 'baseline' && variant !== 'changed') || typeof value.body !== 'string' ||
      value.body !== twilioBody_(value.senderLabel, variant, value.id) ||
      typeof value.preparedAt !== 'number' || !Number.isSafeInteger(value.preparedAt) || value.preparedAt <= 0 ||
      !twilioNullableTime_(value.dispatchStartedAt) || !twilioNullableTime_(value.lastObservedAt) ||
      (state !== 'prepared' && state !== 'dispatching' && state !== 'created' && state !== 'rejected' && state !== 'unknown' && state !== 'reconciled') ||
      typeof value.identityVerified !== 'boolean' ||
      (value.messageSid !== null && (typeof value.messageSid !== 'string' || !/^SM[0-9a-fA-F]{32}$/.test(value.messageSid))) ||
      (value.createHttpStatus !== null && (typeof value.createHttpStatus !== 'number' || !Number.isInteger(value.createHttpStatus) || value.createHttpStatus < 100 || value.createHttpStatus > 599)) ||
      (value.createErrorCode !== null && twilioErrorCode_(value.createErrorCode) === null) ||
      (value.lastStatus !== null && (typeof value.lastStatus !== 'string' || !/^[a-z_]{1,32}$/.test(value.lastStatus))) ||
      ((state === 'prepared') !== (value.dispatchStartedAt === null)) ||
      ((state === 'created' || state === 'reconciled') !== value.identityVerified) ||
      (value.identityVerified && value.messageSid === null) ||
      (state === 'rejected' && value.messageSid !== null) ||
      (state === 'prepared' && (value.messageSid !== null || value.createHttpStatus !== null || value.createErrorCode !== null || value.lastStatus !== null)) ||
      (state === 'dispatching' && value.messageSid !== null) ||
      (state === 'created' && value.createHttpStatus !== 201) ||
      (value.lastStatus !== null && !value.identityVerified) ||
      ((value.lastStatus === null) !== (value.lastObservedAt === null))) throw new Error('TWILIO_INTENT_INVALID: do not reset it.');
  return {version: 1, id: value.id, accountSid: value.accountSid, from: value.from, to: value.to,
    senderLabel: value.senderLabel, variant: variant, body: value.body, preparedAt: value.preparedAt,
    dispatchStartedAt: value.dispatchStartedAt, state: state, messageSid: value.messageSid, identityVerified: value.identityVerified,
    createHttpStatus: value.createHttpStatus, createErrorCode: /** @type {number | null} */ (value.createErrorCode),
    lastStatus: value.lastStatus, lastObservedAt: value.lastObservedAt};
}

/** @param {unknown} value @returns {value is number | null} */
function twilioNullableTime_(value) { return value === null || (typeof value === 'number' && Number.isSafeInteger(value) && value > 0); }

/** @param {TwilioIntent} intent @returns {void} */
function twilioSaveIntent_(intent) {
  const raw = JSON.stringify(intent);
  if (Utilities.newBlob(raw).getBytes().length > 4000) throw new Error('TWILIO_INTENT_STORAGE_BOUND');
  try { PropertiesService.getScriptProperties().setProperty(TWILIO_INTENT_KEY, raw); }
  catch (error) { throw new Error('TWILIO_LOCAL_SAVE_FAILED: possible dispatch remains uncertain; never repost.'); }
}

Practice.gs

Download file
Practice.gs
/**
 * Supplied fictional request data. The changed variant is a LOCAL preview exercise only.
 * @param {TwilioVariant} variant
 * @returns {string}
 */
function twilioPracticeLine_(variant) {
  if (variant === 'baseline') return 'REQ-001 map ready.';
  if (variant === 'changed') return 'REQ-001 map checked.';
  throw new Error('TWILIO_UNKNOWN_FICTIONAL_VARIANT');
}

/**
 * Only a small one-unit GSM-7 subset is accepted; no emoji, smart quotes or extended characters.
 * The actual consent-holding sender supplies its short identity, not a fictional organization.
 * @param {string} senderLabel @param {TwilioVariant} variant @param {string} id
 * @returns {string}
 */
function twilioBody_(senderLabel, variant, id) {
  if (!/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(senderLabel) || senderLabel.trim() !== senderLabel ||
      !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) throw new Error('TWILIO_BODY_INPUT');
  const body = senderLabel + ': Fictional workshop ' + twilioPracticeLine_(variant) +
    ' Ref ' + id + '. Reply STOP to unsubscribe.';
  if (body.length > 160 || !/^[A-Za-z0-9 .:-]+$/.test(body)) throw new Error('TWILIO_ONE_SEGMENT_BODY_REQUIRED');
  return body;
}

/** Describe only SMS-specific evidence. Never treat an unfamiliar channel status as delivery. @param {string} status @returns {string} */
function twilioStatusMeaning_(status) {
  switch (status) {
    case 'queued': return 'Twilio queued the SMS for its sender; not delivery.';
    case 'sending': return 'Twilio is dispatching upstream; not delivery.';
    case 'sent': return 'The nearest upstream carrier accepted it; not handset delivery.';
    case 'delivered': return 'Twilio has a delivery confirmation; not proof a person read it.';
    case 'undelivered': return 'Twilio received a non-delivery receipt; do not resend automatically.';
    case 'failed': return 'Twilio reports failure to send; do not resend automatically.';
    default: return 'Unexpected status for this direct SMS path; inspect without inferring delivery.';
  }
}

appsscript.json

Download file
appsscript.json
{
  "timeZone": "Etc/UTC",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"]
}

configuration.json

Download file
configuration.json
{
  "initialScriptProperties": {
    "TWILIO_ENVIRONMENT": "paid-us1",
    "TWILIO_ACCOUNT_SID": "",
    "TWILIO_FROM_PHONE": "",
    "TWILIO_TO_PHONE": "",
    "TWILIO_SENDER_LABEL": "",
    "TWILIO_VARIANT": "baseline"
  },
  "privateCredentialProperties": {
    "TWILIO_CREATE_KEY_SID": "",
    "TWILIO_CREATE_KEY_SECRET": "",
    "TWILIO_READ_KEY_SID": "",
    "TWILIO_READ_KEY_SECRET": ""
  },
  "createKeyPermissions": ["twilio/messaging/messages/create"],
  "readKeyPermissions": ["twilio/messaging/messages/read"],
  "approvalPropertiesAddedOnlyAfterIntentReview": [
    "TWILIO_CONFIRM_INTENT_ID",
    "TWILIO_SEND_CONFIRMATION",
    "TWILIO_APPROVAL_AT"
  ],
  "reconciliationPropertiesAddedOnlyAfterConsoleMatching": [
    "TWILIO_RECONCILE_INTENT_ID",
    "TWILIO_RECONCILE_MESSAGE_SID"
  ],
  "apiOrigin": "https://api.twilio.com",
  "apiVersion": "2010-04-01",
  "region": "US1",
  "senderType": "Approved SMS-capable US toll-free number owned by the selected paid account",
  "recipientBoundary": "One currently consenting adult practice owner on an approved US mobile number",
  "execution": "Manual Apps Script only; no callbacks, triggers, SDK installation or hosting",
  "note": "This is a configuration checklist, not an imported settings file. Add each named property privately in the Apps Script editor. Empty account, phone, identity or credential fields fail before sending. Never commit a filled copy."
}