Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

Send an SMS verification code with Twilio Verify

See more Twilio Examples

Live SMS. When a user requests a code, pass their phone number in E.164 format (for example, +12025550123) and select the SMS channel. Create a Verify Service in the Twilio Console first. Supply its VA service SID and an API key with access to that service. For a live test, use a phone you control. Messaging and verification charges may apply.

Twilio generates the code and sends it to the phone. A pending response means the application can prompt for the code. Save the returned VE verification SID with the user and phone number that initiated the request, then use it to check the code entered by the user.

Twilio Verify API reference

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  // Obtain these credentials from the application's private configuration.
  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.basicAuth = true;
  http.login = 'YOUR_API_KEY_SID';
  http.password = 'YOUR_API_KEY_SECRET';

  // Both requests use the same Verify Service SID (VA...).
  final url = CkStringBuilder();
  url.append('https://verify.twilio.com/v2/Services/');
  url.append('YOUR_VERIFY_SERVICE_SID');
  url.append('/Verifications');

  final req = CkHttpRequest();
  req.httpVerb = 'POST';
  req.contentType = 'application/x-www-form-urlencoded';
  // Supply the number the user asked to verify. AddParam encodes the leading plus sign.
  req.addParam('To', 'PHONE_NUMBER_IN_E164_FORMAT');
  req.addParam('Channel', 'sms');

  final resp = CkHttpResponse();
  success = true;
  try {
    http.httpReq(url.getAsString(), req, resp);
  } on ChilkatException {
    success = false;
  }
  if (resp.statusCode == 0) {
    print('No response from Twilio. Check connectivity and TLS settings.');
    return;
  }

  final result = CkJsonObject();
  var parsed = true;
  try {
    result.load(resp.bodyStr);
  } on ChilkatException {
    parsed = false;
  }
  if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
    print('Twilio returned HTTP ${resp.statusCode}');
    if ((parsed) && (result.jsonTypeOf('code') == 2)) {
      print('Twilio error code: ${result.intOf('code')}');
    }

    return;
  }

  if ((!parsed) || (result.jsonTypeOf('status') != 1)) {
    print('Verification status missing from the response.');
    return;
  }

  final status = result.stringOf('status');
  if (status != 'pending') {
    print('Verification status: $status');
    return;
  }

  if ((result.jsonTypeOf('sid') != 1) || (result.stringOf('sid') == '')) {
    print('The pending response did not include a verification SID.');
    return;
  }

  // Save this SID with the pending attempt before prompting the user for the code.
  print('Pending verification SID: ${result.stringOf('sid')}');
}