Today, you’ll implement functionality to send order confirmation emails and push notifications when users place an order. You’ll use Firebase Cloud Messaging (FCM) for notifications and Firebase Functions to handle sending emails via a third-party email service like SendGrid.
What You Will Do Today:
- Set up Firebase Cloud Messaging (FCM) for push notifications.
- Configure Firebase Functions to send order confirmation emails.
- Trigger notifications and emails when an order is placed.
Step 1: Setting Up Firebase Cloud Messaging
- Install Firebase Cloud Messaging in your React Native app:
npm install @react-native-firebase/messaging
- Update your
App.js
to handle notification registration:
// App.js
import React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { Alert, Platform } from 'react-native';
const requestFCMPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('FCM Permission granted.');
}
};
const handleNotification = async () => {
messaging().onMessage(async (remoteMessage) => {
Alert.alert('Order Update', remoteMessage.notification.body);
});
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Background notification:', remoteMessage);
});
};
export default function App() {
useEffect(() => {
requestFCMPermission();
handleNotification();
}, []);
return <YourNavigationStack />;
}
- Add an FCM Service Worker for Web Push Notifications (if you plan to extend support to web). In the
public
folder, createfirebase-messaging-sw.js
:
importScripts('https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.7/firebase-messaging.js');
firebase.initializeApp({
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
appId: 'YOUR_APP_ID',
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log('Received background message:', payload);
});
Step 2: Configure Firebase Functions for Emails
- Install the Firebase CLI if you haven’t already:
npm install -g firebase-tools
- Initialize Firebase Functions:
firebase init functions
- Install the SendGrid Node.js SDK to send emails:
cd functions
npm install @sendgrid/mail
- Add the email-sending logic in
functions/index.js
:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const sgMail = require('@sendgrid/mail');
admin.initializeApp();
sgMail.setApiKey('YOUR_SENDGRID_API_KEY');
exports.sendOrderConfirmationEmail = functions.firestore
.document('orders/{orderId}')
.onCreate(async (snapshot, context) => {
const order = snapshot.data();
const emailContent = `
<h1>Order Confirmation</h1>
<p>Thank you for your order!</p>
<p>Order ID: ${context.params.orderId}</p>
<p>Total Amount: $${order.amount.toFixed(2)}</p>
<p>Items:</p>
<ul>
${order.items.map((item) => `<li>${item.name} - $${item.price.toFixed(2)}</li>`).join('')}
</ul>
`;
const msg = {
to: order.userEmail, // User's email address
from: '[email protected]', // Your verified SendGrid sender email
subject: 'Order Confirmation',
html: emailContent,
};
try {
await sgMail.send(msg);
console.log('Order confirmation email sent.');
} catch (error) {
console.error('Error sending email:', error);
}
});
Step 3: Trigger Notifications and Emails on Order Creation
- Update the order-saving logic in
CheckoutScreen.js
to include the user’s email:
const handlePay = async () => {
const { error, paymentIntent } = await confirmPayment(clientSecret, {
type: 'Card',
billingDetails: { email: '[email protected]' },
});
if (error) {
Alert.alert('Payment failed', error.message);
} else if (paymentIntent) {
Alert.alert('Payment succeeded', 'Thank you for your purchase!');
// Save order details to Firestore
const order = {
userId: auth().currentUser.uid,
userEmail: auth().currentUser.email, // Add user email for email notifications
items: cart,
amount: cart.reduce((sum, item) => sum + item.price, 0),
createdAt: firestore.FieldValue.serverTimestamp(),
};
await firestore().collection('orders').add(order);
// Clear cart after successful payment
setCart([]);
await AsyncStorage.removeItem('cart');
navigation.navigate('OrderHistory');
}
};
Step 4: Testing Notifications and Emails
- Test Push Notifications:
- Add a new order from the app and check if a notification appears on the device.
- Test Email Notifications:
- Verify that an order confirmation email is sent to the user’s email address.
- Check the Firebase Functions logs to ensure the function runs successfully.
- Simulate Notifications:
- Send a test push notification from the Firebase Console under Cloud Messaging > Send your first message.
Summary
Today, you implemented order confirmation emails and push notifications for your e-commerce app. These features enhance user engagement by keeping users informed about their orders.
Tomorrow, you’ll add functionality for product reviews and ratings.