SMS 2FA and Verification Codes
To send verification codes by SMS, your application creates the code, stores a hash with an expiry time and sends the text through the curl-sms API. curl-sms delivers the SMS; generating and checking codes stays in your app, where you control the rules.
Example (Python)
import hashlib
import os
import secrets
import time
import requests
def send_login_code(phone: str, attempt_id: str) -> dict:
code = f"{secrets.randbelow(1_000_000):06d}"
resp = requests.post(
"https://curl-sms.com/api/sms/send",
headers={
"Authorization": f"Bearer {os.environ['CURLSMS_KEY']}",
"Idempotency-Key": f"login-{attempt_id}",
},
json={"receiver": phone, "body": f"Your code is {code}. It expires in 10 minutes."},
timeout=10,
)
resp.raise_for_status()
# Store only the hash and the expiry, never the plain code.
return {
"hash": hashlib.sha256(code.encode()).hexdigest(),
"expires_at": time.time() + 600,
"sms_id": resp.json()["id"],
}
Compare the user's input with hmac.compare_digest against the stored hash, check expires_at, and delete the entry after a successful check.
Practical rules
- Idempotency: one
Idempotency-Keyper attempt. If the request times out, repeat it with the same key and the same text; the code is sent once. A new code means a new key. - Limit attempts: allow a few tries per code and a resend after 30 to 60 seconds, not instantly. This protects your balance against abuse.
- Short and plain: keep the text in GSM-7 (no emoji) so it fits one part of 160 characters.
- Status:
sentmeans the network accepted the SMS. Use theidor a webhook to show "code sent" or offer another channel onfailed. - Live sending requires a completed profile in your account. Test keys work right away and simulate the full flow.
Daily limits depend on your plan, see pricing. Errors such as daily_limit or stop_listed are explained under error codes.