In this tutorial, we will explore how to enhance customer experience (CX) by implementing omnichannel strategies. The goal is to provide a unified and seamless customer experience across various touchpoints and platforms, such as:
- Websites
- Mobile apps
- Chatbots
- Social media
Key Objectives:
- Integrate multiple channels into a single customer experience.
- Implement real-time customer support through live chat.
- Enable contextual engagement (i.e., knowing where the customer is on their journey).
- Implement personalized communication across channels (e.g., email, push notifications, etc.).
We will use the following tools:
- Flask for the backend web service.
- Socket.IO for real-time communication (e.g., live chat).
- SQLite for storing customer and interaction data.
- Jinja2 for rendering personalized content on webpages.
- Push notifications to notify customers about important events.
- Flask-Mail to send personalized emails.
Step 1: Set Up the Environment
First, install the required libraries.
bashCopy codepip install Flask Flask-SQLAlchemy Flask-SocketIO Flask-Mail
- Flask-SQLAlchemy: ORM for interacting with the SQLite database.
- Flask-SocketIO: For real-time communication like live chat.
- Flask-Mail: For sending emails to customers.
- Flask-WTF: For handling forms securely.
Step 2: Design the Database Schema
We need to store the customer’s interactions, information, and any chat messages in a database. We will create a simple schema to store:
- Customer: Basic customer details.
- Interaction: Track interactions like chat messages, emails sent, etc.
- ChatSession: Track live chat sessions.
models.py
– SQLAlchemy Models
pythonCopy codefrom flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
# Customer Model
class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
interactions = db.relationship('Interaction', backref='customer', lazy=True)
def __repr__(self):
return f'<Customer {self.name}>'
# Interaction Model (Chat, Email, Social Media)
class Interaction(db.Model):
id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.String(500), nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=False)
channel = db.Column(db.String(50)) # e.g., "Email", "Live Chat", "Social Media"
def __repr__(self):
return f'<Interaction {self.id}>'
# Chat Session Model (For live chats)
class ChatSession(db.Model):
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=False)
session_start = db.Column(db.DateTime, default=datetime.utcnow)
messages = db.relationship('Interaction', backref='chat_session', lazy=True)
def __repr__(self):
return f'<ChatSession {self.id}>'
Explanation:
- Customer: Stores customer details.
- Interaction: Stores each interaction a customer has, whether it’s via chat, email, or social media.
- ChatSession: A dedicated model to track live chat sessions.
Step 3: Implement the Flask Application
Now, let’s create the Flask app and add routes for each channel.
app.py
– Flask Application
pythonCopy codefrom flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO, emit
from flask_mail import Mail, Message
from models import db, Customer, Interaction, ChatSession
from datetime import datetime
import os
app = Flask(__name__)
# Flask Configurations
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///customers.db'
app.config['SECRET_KEY'] = 'secret!'
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
# Initialize extensions
db.init_app(app)
socketio = SocketIO(app)
mail = Mail(app)
# Routes for the application
# Homepage
@app.route('/')
def index():
return render_template('index.html')
# Register customer (for demonstration purposes)
@app.route('/register', methods=['POST'])
def register():
name = request.form['name']
email = request.form['email']
customer = Customer(name=name, email=email)
db.session.add(customer)
db.session.commit()
return redirect(url_for('index'))
# Live Chat Route
@app.route('/chat/<customer_id>', methods=['GET'])
def chat(customer_id):
customer = Customer.query.get(customer_id)
return render_template('chat.html', customer=customer)
# Email Route - Send Personalized Email
@app.route('/send-email/<customer_id>', methods=['POST'])
def send_email(customer_id):
customer = Customer.query.get(customer_id)
subject = request.form['subject']
body = request.form['body']
# Create and send email
msg = Message(subject, recipients=[customer.email], body=body)
mail.send(msg)
# Log interaction
interaction = Interaction(message=body, customer_id=customer.id, channel="Email")
db.session.add(interaction)
db.session.commit()
return redirect(url_for('index'))
# Live Chat (SocketIO)
@socketio.on('send_message')
def handle_message(data):
message = data['message']
customer_id = data['customer_id']
# Log chat message to Interaction table
interaction = Interaction(message=message, customer_id=customer_id, channel="Live Chat")
db.session.add(interaction)
db.session.commit()
# Broadcast message to the customer (in real-time)
emit('receive_message', {'message': message}, room=customer_id)
# SocketIO: Connect customer to live chat
@socketio.on('connect')
def handle_connect():
customer_id = request.args.get('customer_id')
join_room(customer_id)
print(f"Customer {customer_id} joined the chat.")
# SocketIO: Disconnect customer from live chat
@socketio.on('disconnect')
def handle_disconnect():
customer_id = request.args.get('customer_id')
print(f"Customer {customer_id} disconnected.")
# Run the Flask app
if __name__ == '__main__':
socketio.run(app, debug=True)
Explanation:
- Flask-SocketIO is used for live chat functionality, allowing real-time interaction between customers and support agents.
- Flask-Mail is configured to send personalized emails to customers.
- We have a
/chat/<customer_id>
route that opens a live chat session for the customer. /send-email/<customer_id>
route is for sending personalized emails to the customer.- SocketIO Events:
send_message
: Handles sending messages in the live chat.connect
: Handles customer connection to the live chat.disconnect
: Handles customer disconnection from the live chat.
Step 4: Frontend for Customer Interaction
We will create two key pages:
- Home Page: Simple registration form to simulate customer entry.
- Chat Page: A real-time chat page for interacting with the customer.
templates/index.html
– Homepage
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Omnichannel Customer Experience</title>
</head>
<body>
<h1>Register as a Customer</h1>
<form action="/register" method="POST">
<input type="text" name="name" placeholder="Enter Name" required>
<input type="email" name="email" placeholder="Enter Email" required>
<button type="submit">Register</button>
</form>
<hr>
<h1>Send Email to Customer</h1>
<form action="/send-email/{{ customer.id }}" method="POST">
<input type="text" name="subject" placeholder="Email Subject" required>
<textarea name="body" placeholder="Email Body" required></textarea>
<button type="submit">Send Email</button>
</form>
</body>
</html>
templates/chat.html
– Chat Page
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Customer Chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.min.js"></script>
</head>
<body>
<h1>Chat with Customer Service</h1>
<div id="messages"></div
Leave a Reply