WhatsApp Onboarding Automation for SaaS: How to Reduce Churn
Automate WhatsApp onboarding for your SaaS to reduce churn: nine trigger-based messages with Python code, reply routing, opt-out and the metrics to track.

To reduce churn with WhatsApp onboarding, send a few short messages that react to what each user does in your product: a welcome with one first step, a nudge if they haven't started after 24 hours, a tip for a feature they skipped, a heads-up before they hit a plan limit, and a check-in when they go quiet or are about to renew. The ones that matter most ask for a reply, and a person answers it. With Chatmaid, each message is one POST /v1/messages/send call from your backend, sent from your own WhatsApp number, and replies come back as message.received webhooks.
This guide, current as of October 2026, gives you the framework and the Python code (Flask, SQLAlchemy and Celery) for each message.
Why use WhatsApp for SaaS onboarding?
For many products, churn starts in the first days after signup, when a new user gets stuck and nobody notices. The usual fixes have gaps. Onboarding emails compete with everything else in the inbox. In-app tooltips only reach people who are already in the product. Help docs only help people who go looking.
The users you most need to reach are the ones who stopped logging in. A WhatsApp message reaches them in an app they open anyway, and it reads like a note from a person, so replying feels natural. That reply is the point: a user who tells you what's blocking them is a user you can still keep.
The WhatsApp onboarding framework
The goal is not to message users often. It's to send the right message at the right moment, triggered by what they do (or don't do), not by a calendar.
The framework has four stages:
- Activation: guide users to their first meaningful action.
- Habit formation: reinforce the behaviors that keep people coming back.
- Expansion: show users who are getting value what else the product can do.
- At-risk intervention: reach disengaged users before they cancel.
Here is every message in this guide and what triggers it:
| Stage | Message | Trigger |
|---|---|---|
| Activation | Welcome and first step | Signup with WhatsApp opt-in |
| Activation | Setup confirmation | First key action completed |
| Activation | 24-hour nudge | No key action 24 hours after signup |
| Habit formation | Feature tip | Feature unused 3 days after activation |
| Habit formation | Weekly summary | Monday morning, for users active in the last 7 days |
| Expansion | Usage heads-up | 80% of a monthly plan limit reached |
| Expansion | Feature suggestion | Behavior that fits a paid feature |
| At-risk | Check-in | 7 days without activity on a paid plan |
| At-risk | Pre-renewal | 7 days before renewal |
Setup: one send helper for every message
You need a Chatmaid Developers account and an API key from the dashboard. There is no Meta Business verification and no template approval. Keys that start with sk_test_ run in the free sandbox: add a number in sandbox mode (no QR scan), and sends from it are simulated, so nothing reaches WhatsApp. Keys that start with sk_live_ send real messages from your WhatsApp number, connected by scanning a QR code, and need the $7.99/month plan (see pricing). A key only sends from a number in its own mode, so CHATMAID_FROM_PHONE must be registered in the same mode as CHATMAID_API_KEY, or the API answers 404.
New to the API? The WhatsApp API quickstart for SaaS developers covers keys, numbers and error handling first.
Install the packages (the example uses PostgreSQL, Redis and Slack):
pip install flask flask-sqlalchemy celery redis requests slack_sdk psycopg2-binaryThe code follows Flask's Celery pattern, so every task runs inside the app context; the wiring comes after the reply handler. Everything up to the webhook goes in one file, onboarding.py. It starts with the user model and the fields the messages rely on:
# onboarding.py
import os
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
import requests
from celery import shared_task
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), nullable=False)
first_name = db.Column(db.String(100), nullable=False)
phone = db.Column(db.String(20)) # E.164, for example "+15557654321"
whatsapp_opt_in_at = db.Column(db.DateTime) # when they ticked the signup checkbox
whatsapp_opted_out = db.Column(db.Boolean, nullable=False, default=False)
created_at = db.Column(db.DateTime, nullable=False)
activated_at = db.Column(db.DateTime) # first key action
scheduled_reports_used_at = db.Column(db.DateTime)
last_active_at = db.Column(db.DateTime)
subscription_status = db.Column(db.String(20))
time_zone = db.Column(db.String(64)) # IANA name, e.g. "America/Chicago"Next comes the send helper. Every message in this guide goes through notify(), which checks consent before it queues anything and holds messages that would land at night:
# onboarding.py (continued)
CHATMAID_SEND_URL = "https://developers-api.chatmaid.net/v1/messages/send"
CHATMAID_API_KEY = os.environ["CHATMAID_API_KEY"] # sk_test_... or sk_live_...
CHATMAID_FROM_PHONE = os.environ["CHATMAID_FROM_PHONE"] # a number in the same mode as the key
# Sandbox and live sends share one idempotency key space, so keep them apart
KEY_PREFIX = "live" if CHATMAID_API_KEY.startswith("sk_live_") else "test"
# Your product's details
PRODUCT = "Acme"
APP_URL = "https://app.example.com"
FIRST_STEP = "connect your first data source"
FIRST_STEP_URL = f"{APP_URL}/onboarding/connect"
def utcnow():
# Naive UTC, to match DateTime columns stored without a time zone
return datetime.now(timezone.utc).replace(tzinfo=None)
class RetryableSend(Exception):
pass
def recorded_failure(response):
"""True when Chatmaid stored the message as failed: the error body names it."""
try:
return "messageId" in response.json()
except ValueError:
return False
@shared_task(
autoretry_for=(requests.ConnectionError, requests.Timeout, RetryableSend),
retry_backoff=60,
max_retries=5,
rate_limit="90/m",
)
def send_whatsapp_task(to, content, idempotency_key):
response = requests.post(
CHATMAID_SEND_URL,
headers={"Authorization": f"Bearer {CHATMAID_API_KEY}"},
json={
"fromPhoneId": CHATMAID_FROM_PHONE,
"to": to,
"content": content,
"idempotencyKey": f"{KEY_PREFIX}-{idempotency_key}",
},
timeout=30,
)
status = response.status_code
if (status == 429 or status >= 500) and not recorded_failure(response):
# Throttled, or no definite answer: safe to retry with the same key
raise RetryableSend(f"HTTP {status}")
response.raise_for_status()
return response.json()["data"]["id"]
def reachable():
"""Users who gave a number, opted in, and have not opted out."""
return User.query.filter(
User.phone.isnot(None),
User.whatsapp_opt_in_at.isnot(None),
User.whatsapp_opted_out.is_(False),
)
def send_at(user):
"""None between 8:00 and 21:00 in the user's time zone, otherwise 9:00 the next morning."""
local = datetime.now(ZoneInfo(user.time_zone or "UTC"))
if 8 <= local.hour < 21:
return None
morning = local.replace(hour=9, minute=0, second=0, microsecond=0)
return morning + timedelta(days=1) if local.hour >= 21 else morning
def notify(user, content, key, now=False):
"""Queue a WhatsApp message if this user can be messaged."""
if user.phone and user.whatsapp_opt_in_at and not user.whatsapp_opted_out:
eta = None if now else send_at(user)
send_whatsapp_task.apply_async((user.phone, content, key), eta=eta)A few details that matter here:
- Idempotency keys do the deduplication. If Chatmaid has already seen a key on your account, it returns the original message instead of sending again. A task can retry after a timeout, and a scheduled job can overlap its previous run, without anyone getting a message twice. Keys can be up to 64 characters. They are unique across your whole account, sandbox and live included: a key first used with an
sk_test_key returns that simulated message when ansk_live_key reuses it, and nothing is sent.KEY_PREFIXkeeps the two apart. - Retry only what was never sent. A 429 or 5xx response without a
messageIdmeans the request was throttled or never got a definite answer, so the task retries it with the same key. If Chatmaid did record the message, the key returns it instead of sending again. An error that includes amessageIdis a recorded failure, and the same key would only replay it.RATE_LIMITEDandSERVICE_UNAVAILABLEare worth resending later with a new key; aTIMEOUTmay already have been delivered, so check the message before resending; the rest need a fix first, such as reconnecting the number or correcting the recipient. The Flask notifications guide has a fuller retry plan, error code by error code. - Rate limits. The API allows 100 requests per minute by default. Celery applies
rate_limitper worker, so divide it across workers if you run several. - Quiet hours. WhatsApp messages buzz a personal phone, so
send_atholds anything that would arrive between 21:00 and 8:00 in the user's time zone until 9:00. Only the welcome and the setup confirmation passnow=True, because the user just acted.
On Node, the @chatmaid/sdk package makes the same call: new Chatmaid({ apiKey }).messages.send({ fromPhoneId, to, content, idempotencyKey }).
Stage 1: Activation messages
The first day or two after signup decides whether a user ever gets started. These three messages cover it.
Welcome and first step (right after signup)
Send it within seconds of signup, and make it one specific step, not a generic welcome.
def on_signup(user):
"""Call after the new user row is committed."""
notify(
user,
f"Hi {user.first_name}, welcome to {PRODUCT}.\n\n"
f"The fastest way to get started is to {FIRST_STEP}: {FIRST_STEP_URL}\n\n"
"Questions? Just reply to this message.",
key=f"welcome-{user.id}",
now=True,
)Setup confirmation (when they finish the first step)
When the user completes their first key action, mark them as activated and point to the next step.
def on_first_key_action(user):
"""Call when the user completes the action that counts as activation."""
if user.activated_at is not None:
return
user.activated_at = utcnow()
db.session.commit()
notify(
user,
"Done, you're set up.\n\n"
f"Next, invite your team so they can see your work: {APP_URL}/settings/team",
key=f"activated-{user.id}",
now=True,
)Call it from the view after the commit, not from a database event hook. A task queued during a flush can run before the transaction commits.
24-hour nudge (if they haven't started)
This job runs every hour and picks up users who signed up about a day ago and still haven't activated. The two-hour window overlaps the previous run on purpose, so a missed run doesn't skip anyone; the idempotency key stops the overlap from sending twice.
@shared_task(name="onboarding.nudge_unactivated")
def nudge_unactivated():
"""Runs hourly."""
cutoff = utcnow() - timedelta(hours=24)
users = reachable().filter(
User.created_at <= cutoff,
User.created_at > cutoff - timedelta(hours=2),
User.activated_at.is_(None),
).all()
for user in users:
notify(
user,
f"Hi {user.first_name}, you signed up for {PRODUCT} yesterday "
"but haven't started yet.\n\n"
f"The first step is to {FIRST_STEP}: {FIRST_STEP_URL}\n\n"
"What's getting in the way? Reply and I'll help.",
key=f"nudge-24h-{user.id}",
)Stage 2: Habit formation messages
Once a user has activated, the goal is a usage pattern. Look at your own data for the actions that retained users repeat, and nudge toward those.
Feature tip (day 3, if the feature is unused)
@shared_task(name="onboarding.feature_tip")
def feature_tip():
"""Runs hourly: users who activated 3 days ago and haven't tried scheduled reports."""
since = utcnow() - timedelta(days=3)
users = reachable().filter(
User.activated_at <= since,
User.activated_at > since - timedelta(hours=2),
User.scheduled_reports_used_at.is_(None),
).all()
for user in users:
notify(
user,
f"A quick tip for {PRODUCT}: scheduled reports send your numbers "
"to your team every week, so nobody has to ask for them.\n\n"
f"Set it up here: {APP_URL}/reports/schedule",
key=f"tip-reports-{user.id}",
)Weekly progress summary
People who can see their own progress have a reason to keep going. Send a short summary every Monday to users who were active in the past week.
def get_weekly_stats(user):
"""Replace with queries against your own tables."""
return {
"reports_created": 0,
"teammates_active": 0,
"next_step": f"share a report with a teammate: {APP_URL}/reports",
}
@shared_task(name="onboarding.weekly_summary")
def weekly_summary():
"""Runs every Monday morning."""
now = utcnow()
year, week, _ = now.isocalendar()
users = reachable().filter(User.last_active_at >= now - timedelta(days=7)).all()
for user in users:
stats = get_weekly_stats(user)
notify(
user,
f"Your week in {PRODUCT}:\n\n"
f"- {stats['reports_created']} reports created\n"
f"- {stats['teammates_active']} teammates active\n\n"
f"Something to try this week: {stats['next_step']}",
key=f"weekly-{user.id}-{year}-w{week}",
)get_weekly_stats is the one function you fill in yourself: return the two or three numbers that show progress in your product. The year and week in the key keep it to one summary per user per week.
Stage 3: Expansion messages
Users who get steady value are ready to hear about upgrades and paid features. On WhatsApp this works as a short, personal note at the moment it's relevant, not a banner.
Usage heads-up (at 80% of a plan limit)
def on_usage_recorded(user, before, after, limit):
"""Call when monthly usage moves from `before` to `after`."""
threshold = 0.8 * limit
if not before < threshold <= after:
return
notify(
user,
f"Hi {user.first_name}, you've used {after} of the {limit} projects "
"on your plan this month.\n\n"
f"Pro raises the limit so you don't get cut off: {APP_URL}/billing/upgrade",
key=f"usage-80-{user.id}-{utcnow():%Y-%m}",
)Checking that usage crossed the threshold, rather than sitting above it, keeps you from queuing a task on every action after 80%. The month in the key allows one heads-up per month.
Feature suggestion (when behavior fits a paid feature)
def suggest_feature(user, feature_slug, feature_name, reason):
"""Call when what the user does matches a paid feature."""
notify(
user,
f"{reason}\n\n"
f"{feature_name} would do that for you. It's in the Pro plan: "
f"{APP_URL}/features/{feature_slug}",
key=f"suggest-{user.id}-{feature_slug}",
)
# Example: a team that keeps growing could use single sign-on
# suggest_feature(user, "sso", "Single sign-on",
# "You've added 12 teammates this month.")Keep feature_slug short so the key stays under 64 characters.
Stage 4: At-risk intervention
Two signals are easy to act on: a paying user who stops showing up, and a renewal that's coming up.
Check-in after 7 days of inactivity
@shared_task(name="onboarding.check_in_inactive")
def check_in_inactive():
"""Runs hourly: paying users whose last activity was 7 days ago."""
since = utcnow() - timedelta(days=7)
users = reachable().filter(
User.last_active_at <= since,
User.last_active_at > since - timedelta(hours=2),
User.subscription_status == "active",
).all()
for user in users:
notify(
user,
f"Hi {user.first_name}, we haven't seen you in {PRODUCT} for a week.\n\n"
"Is something not working for you? Reply and I'll help sort it out.\n\n"
f"Log back in: {APP_URL}",
key=f"inactive-7d-{user.id}-{user.last_active_at:%Y%m%d}",
)The date of the last activity is part of the key, so a user who comes back and later goes quiet again gets a new check-in.
This message has one job: start a conversation. The user replies with what's blocking them, and someone on your team (or an AI agent) helps. Many inactive users are stuck on one thing you can fix in a single reply.
Pre-renewal message (7 days before)
Call this from the daily job where you already track upcoming renewals.
def before_renewal(user, plan_name, amount, renews_on):
"""Call 7 days before a subscription renews. renews_on is a date."""
notify(
user,
f"Hi {user.first_name}, your {plan_name} plan renews on "
f"{renews_on:%B} {renews_on.day} (${amount}/month).\n\n"
f"Is {PRODUCT} still working well for you? If anything could be better, "
"reply and tell me.",
key=f"renewal-{user.id}-{renews_on:%Y-%m-%d}",
)It gives users an easy way to raise a problem before they cancel, while you can still do something about it.
How do you handle replies?
The welcome, the nudge, the check-in and the pre-renewal message all ask for a reply, and people answer the others too, so you need somewhere for replies to go. In the Chatmaid dashboard, set an HTTPS webhook URL (use a tunnel in development, since plain http is rejected), subscribe to message.received, and copy the webhook secret. Each delivery carries an X-Chatmaid-Signature header (t=<timestamp>,v1=<hex>), an HMAC-SHA256 of <timestamp>.<raw body> signed with that secret.
The receiver below checks the signature, ignores group messages, and hands each reply to a Celery task so it can answer quickly:
# webhooks.py
import hashlib
import hmac
import os
from celery import shared_task
from flask import Blueprint, abort, request
from slack_sdk import WebClient
from onboarding import APP_URL, User, db, send_whatsapp_task, utcnow
webhook_bp = Blueprint("chatmaid", __name__)
WEBHOOK_SECRET = os.environ["CHATMAID_WEBHOOK_SECRET"]
slack = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
STOP_WORDS = {"stop", "unsubscribe"}
def valid_signature(raw_body, header):
try:
parts = dict(part.split("=", 1) for part in header.split(","))
signed = parts["t"].encode() + b"." + raw_body
except (AttributeError, KeyError, ValueError):
return False
expected = hmac.new(WEBHOOK_SECRET.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(parts.get("v1", "").encode(), expected.encode())
@webhook_bp.post("/webhooks/chatmaid")
def chatmaid_webhook():
raw_body = request.get_data()
if not valid_signature(raw_body, request.headers.get("X-Chatmaid-Signature")):
abort(401)
payload = request.get_json()
if payload["event"] == "message.received" and not payload["data"]["isGroup"]:
handle_reply.delay(payload["data"])
return {"received": True}
@shared_task
def handle_reply(data):
phone = data["from"]
text = (data.get("content") or "").strip()
command = text.strip(".!").lower()
user = User.query.filter_by(phone=phone).first()
if command in STOP_WORDS:
if user:
user.whatsapp_opted_out = True
db.session.commit()
send_whatsapp_task.delay(
phone,
"You won't get any more WhatsApp messages from us. "
"Reply START to turn them back on.",
f"optout-{data['messageId']}",
)
return
if user and user.whatsapp_opted_out and command == "start":
user.whatsapp_opted_out = False
db.session.commit()
send_whatsapp_task.delay(
phone, "WhatsApp messages are back on.", f"optin-{data['messageId']}"
)
return
who = user.email if user else phone
link = f"\n{APP_URL}/admin/users/{user.id}" if user else ""
slack.chat_postMessage(
channel="#customer-success",
text=f"WhatsApp reply from {who}:\n{text or '(' + data['type'] + ')'}{link}",
)
send_whatsapp_task.delay(
phone,
"Thanks, got it. Someone from our team will reply here shortly.",
f"ack-{phone}-{utcnow():%Y-%m-%d}",
)Some notes on the payload and on running this in production:
data.fromis the sender's number anddata.tois your connected number. Store user numbers in E.164 (+and country code) so the lookup matches.contentholds the text, or the caption for media, and can be empty;typesays what was sent (text,image,audioand so on).- The acknowledgement key includes the date, so a user who sends five messages in a row gets one "got it", not five.
- A failed webhook delivery is retried (up to 3 attempts in total), so the same event can arrive twice. The WhatsApp replies are protected by their keys; if duplicate Slack posts bother you, store
data.messageIdand skip ones you've already seen. - A retry carries the same signature as the first attempt, timestamp included. If you add a freshness check on
t, allow at least 15 minutes. - Inbound messages exist only on live connections, so the sandbox never produces
message.received. Test reply handling with a live number and your own phone. - The sending number is an ordinary WhatsApp account, so your team can also answer from the WhatsApp app on that phone. Those manual replies raise a
message.outgoingevent if you want to log them.
Instead of Slack, you can route replies to an AI agent first and hand off to a person when needed. See how to build a WhatsApp customer service agent with n8n or the LangChain version in Python. The webhook guide covers payloads and retries in more depth, and the full reference is in the webhook docs.
Run it: wire up the app, worker and scheduler
The app factory below registers the database, the webhook route from the previous section, and Celery, with the four periodic jobs in Celery's beat_schedule. Celery beat uses UTC unless you set its timezone option; that is fine here, because notify() holds night-time messages for each user's own time zone.
# app.py
from celery import Celery, Task
from celery.schedules import crontab
from flask import Flask
from onboarding import db
from webhooks import webhook_bp
def celery_init_app(app):
# From Flask's Celery guide: every task runs inside the app context
class FlaskTask(Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery_app = Celery(app.name, task_cls=FlaskTask)
celery_app.config_from_object(app.config["CELERY"])
celery_app.set_default()
app.extensions["celery"] = celery_app
return celery_app
def create_app():
app = Flask(__name__)
app.config.from_mapping(
SQLALCHEMY_DATABASE_URI="postgresql://localhost/acme",
CELERY={
"broker_url": "redis://localhost:6379/0",
"task_ignore_result": True,
# Night-time messages wait up to 12 hours (see send_at); with Redis,
# a task held longer than the visibility timeout is delivered again
"broker_transport_options": {"visibility_timeout": 13 * 3600},
"beat_schedule": {
"nudge-unactivated": {
"task": "onboarding.nudge_unactivated",
"schedule": crontab(minute=5),
},
"feature-tip": {
"task": "onboarding.feature_tip",
"schedule": crontab(minute=10),
},
"check-in-inactive": {
"task": "onboarding.check_in_inactive",
"schedule": crontab(minute=15),
},
"weekly-summary": {
"task": "onboarding.weekly_summary",
"schedule": crontab(minute=0, hour=9, day_of_week="mon"),
},
},
},
)
db.init_app(app)
app.register_blueprint(webhook_bp)
celery_init_app(app)
return appCelery's command line needs an app object, so add a small make_celery.py next to it:
# make_celery.py
from app import create_app
flask_app = create_app()
celery_app = flask_app.extensions["celery"]Then run a worker and the beat scheduler alongside your web server:
celery -A make_celery worker --loglevel INFO
celery -A make_celery beat --loglevel INFOHow do you handle opt-in and compliance?
Only message users who gave you their number and agreed to hear from you on WhatsApp. In practice:
- Add an explicit, unticked checkbox at signup, such as "Send me onboarding tips and product updates on WhatsApp".
- Store the consent with a timestamp (
whatsapp_opt_in_atabove). - Honor opt-out right away. The reply handler above stops all onboarding messages when a user sends STOP or UNSUBSCRIBE.
- Let users change the setting in their account preferences too.
Chatmaid sends from your own WhatsApp number, so the usual WhatsApp rules apply to it. Restrictions are very unlikely with normal use; they happen when an account behaves like spam, such as unsolicited bulk messages to people who don't have you saved. Message only users who opted in and expect to hear from you, and keep the volume to the few moments in this guide.
How do you measure the impact?
Hold back a random slice of opted-in signups from every message except the welcome, and compare them with everyone else over the same weeks. One line at the top of notify() does it: if user.id % 10 == 0 and not key.startswith("welcome-"): return. Then track:
- Activation rate: share of new users who complete the first key action within 24 hours.
- Day-7 retention: share of users still active after 7 days.
- Day-30 retention: share of users still active after 30 days.
- At-risk recovery rate: share of users who log back in within a week of the check-in.
- Pre-renewal save rate: share of users who raised a problem in reply and then renewed.
A holdout beats a before-and-after comparison, which also picks up seasonality, pricing changes and product releases. To check that messages arrive at all, subscribe to the message.delivered and message.read webhook events. read may never fire for recipients who turned off read receipts, so treat it as a lower bound.
Frequently asked questions
Do I need the WhatsApp Business API or Meta verification for this?
No. Chatmaid links your own WhatsApp number by scanning a QR code, so there is no Meta Business verification and no template approval. You send with one API call. The live plan is $7.99/month flat, and the sandbox is free.
Can I test the onboarding flow without messaging real users?
Yes. With an sk_test_ key, sends from a number added in sandbox mode are simulated and nothing reaches WhatsApp, so you can run every job against test data. The KEY_PREFIX in onboarding.py stops those test sends from blocking live ones for users with the same IDs. Replies are the exception: inbound messages only exist on live connections, so test the webhook with an sk_live_ key and your own phone.
What time of day should onboarding messages go out?
During the user's daytime. Store each user's time zone and hold anything that lands between 21:00 and 8:00 until 9:00 the next morning, as send_at does. Only the welcome and setup confirmation go out at once, because the user just acted.
Is there a limit on how many messages I can send?
The API allows 100 requests per minute by default, so pace bulk jobs like the weekly summary with a queue. The plan itself is a flat monthly price with no per-message or per-conversation fees.
Will automated onboarding messages get my WhatsApp number banned?
It's very unlikely with normal use. WhatsApp restricts accounts that behave like spam, such as sending unsolicited bulk messages to people who don't have you saved. Message only users who opted in, keep the volume low, and stop as soon as someone opts out.


