Stripe Payments Made Easy: Checkout and Email Automation with SendGrid
Supercharge your online store with Stripe payments and SendGrid emails. Learn to create a frictionless checkout and automate email notifications, Your one-stop guide to e-commerce efficiency.
Outline
In this guide, we will integrate SendGrid for sending emails and Stripe for handling payments. By the end of this guide, you will have a fully functional backend server that can handle email notifications and payment processing.
Emails are essential for business processes as they provide a reliable way to communicate with customers, send notifications, and confirm transactions. Stripe, on the other hand, simplifies the process of accepting payments online, making it easier to manage financial transactions securely.
What You'll Learn
- Configuring environment variables for secure credential management
- Integrating SendGrid for sending emails
- Integrating Stripe for handling payments
- Creating and testing API endpoints using Postman
Try Kodaschool for free
Click below to sign up and get access to free web, android and iOs challenges.
Prerequisites
Node.js runtime
SendGrid API credentials (obtain from the SendGrid dashboard)
Postman or Any API Testing Platform
Stripe API credentials (obtain from the Stripe dashboard)
Configuration and Setup of project Environment
In the above snippet;
1. Create and navigate to the backend directory:
2. Initialize a new Node.js project
3. Install necessary dependencies:
Verify that you have the following in your package.json file;
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@sendgrid/mail": "^8.1.3",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"nodemon": "^3.1.7",
"stripe": "^17.2.0"
}
}
Add add this in the script object; "start":"nodemon index.js"
The command is meant to run our server file using the nodemon dependency we insatlled earlier.Nodemon automatiically restarts our server once any changes are detected in our directory
Lets create the files to be of use in our root directory using the baash shell;
touch index.js .gitignore .env
As of now you should be having the below folder structure;
Task 1.Accessing the Third-Party APIs Console Page
Sendgrid Dashboard
- Create an Account and login in your SendGrid Account
- Access the SendGrid Dashboard, select the Email API from the Menu Bar
- Click the Integration guide.
1. Select a Programming Language of your Choice for interracting with
sendGrid and click on Next at the bottom Left Corner.
2. Create an Api Key by assigning the api key a name
3. Copy the generated string and store it safely e.g in your .env file
Stripe Dashboard
1. Create an Account and login in your Stripe Dashboard
2. Toggle the Test Mode Button this ensures you have Enabled the
DevMode credentials thus avoiding Authorization Errors on stripe's
endpoints
3. Click on the Developers Link on the top right of the page to Navigate to the API Keys Section.
4. Copy both the Publishable key and Secret Key then Store the Keys in your .env File
On the services menu Bar select the Product Catalog and Click the Create Product Button .
Create a new product in stripe
1. A side panel eases in from the right side that allows you to proceed with
naming and adding other metadate eg image to your product
2 Attatch a price tag and and the unit quantity to the product
3. Specify it as a one time fee product and choose Flat-Rate as the pricing
Model
Your Click on Next and Save the information
Your product should be Visible on the product catalog page.
Navigate to the Checkout Documentation page and get started with stripecheckout
Lets wrap up the configurations by storing our file in our .env file
SENDGRID_APIKEY='SG.gv....'
STRIPE_SECRET_KEY="sk_test_51NG....."
STRIPE_PUBLIC_KEY="pk_test_51NG....."
DOMAIN="http://localhost:3000" //backend Local prt
FRONTEND_URL="http://localhost:5173" //frontend react app port
PORT=3000 //express Server port
Add the following in our .gitignore file
node_modules
.env
Task 2. Lets get our Feet wet
First and Foremost lets install this extension to generate a boilerplate of our express app.
Enable the extension and Type ess then Enter button
~Initial File Set up
//index.js
const express = require('express')
const app = express()
//add in the lines below
require('dotenv').config();
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const sendgridMail = require('@sendgrid/mail');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const cors = require('cors');
const corsOptions = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
allowedHeaders: 'Content-Type, Authorization'
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//substitute the hardcoded port number with this dynamic value
app.listen(port, () => {
console.log(`Server is Listening on port ${port}`)
})
~Send Email End point via sendgrid
I would like to recomend you to check also Mary Maina's article for more Insights on SendGrid
- to: It specifies the recipient of the email.
- from: It specifies the email address of the person or domain sending the email.
- subject: It specifies the title of the email content, providing recipients with an idea of what the email is about.
- text: This key represents the plain text content of the email.
- html: It specifies the main body of the email in HTML format. This content is typically displayed to recipients who prefer to view emails with HTML rendering enabled.
Request body:
1. email: Recipient's email address
2. service: Type of service booked
3. startTime: Scheduled start time
4. bill: Total cost
5. stripePaymentLink: URL for payment
app.post('/send-email', async (req, res) => {
const { email, service, startTime, bill, stripePaymentLink } = req.body;
const msg = {
to: email,
from: 'oendgrideerootemail@gmail.com',
subject: 'Booking Confirmation',
text: `Your ${service} session has been booked for ${startTime}. Your bill is $${bill.toFixed(2)}. Payment link: ${stripePaymentLink}`,
};
try {
await sendgridMail.send(msg);
console.log('Email sent successfully');
res.status(200).json({ success: true });
} catch (error) {
console.error('Error sending email:', error);
res.status(500).json({ success: false, error: error.toString() });
}
});
Code breakdown:
- Creates an email message with booking details
- Uses SendGrid to send the email
- Returns success (200) or error (500) status
~Trigger A checkout Session Event
Creating a Stripe Checkout Sessionstripe.checkout.sessions.create()
is the key function that integrates Stripe’s checkout functionality into your app.
payment_method_types: ['card']
This specifies that credit card payments are accepted.
mode: 'payment'
The payment mode is set to 'payment', which means the session will be used for one-time payments.
success_url & cancel_url
These URLs are defined to redirect the user based on the outcome of the transaction.
The success_url sends the user to a "Success" page,
The cancel_url sends them to a "Cancel" page.
Line_items
This defines the specific service being sold.
price_data
contains the price, currency, and a brief description of the service.
The price is multiplied by 100 because Stripe expects the amount in the smallest unit of the currency
SessionId
Once the session is successfully created, session.id is returned as a JSON response to the frontend, which can then redirect the user to complete the payment.
//index.js
app.post('/create-checkout-session', async (req, res) => {
const { amount, email, service } = req.body;
console.log('email for this user ', email);
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
mode: 'payment',
success_url: `${process.env.DOMAIN}/success?email=${encodeURIComponent(email)}&amount=${amount}&service=${encodeURIComponent(service)}&from_stripe=true`,
cancel_url: `${process.env.DOMAIN}/cancel&from_stripe=true`,
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Service Payment',
},
unit_amount: Math.round(amount * 100),
},
quantity: 1,
},
],
});
res.json({ sessionId: session.id });
} catch (error) {
console.error('Error creating Stripe session:', error);
res.status(500).json({ error: 'An error occurred' });
}
});
With Fingers crossed lets start the server
npm start
Yea buddy ! It works
Task 3. Creating and Testing API Endpoints
lets quickly head to postman and have verify if our endpoints
Lets Test the sendemail route
with the folowing request body in json format
Here is the http url used http://localhost:3000/send-email
We successfull get a 200 Success response
{
"email": "recipient@example.com",
"service": "Example Service",
"startTime": "2023-10-10T10:00:00Z",
"bill": 100.00,
"stripePaymentLink": "https://example.com/payment"
}
Here is an output from the console
Let test the create-checkout-session route
The response is a 200 OK which means a session has been created
Thus a payment can be mad efrom the front end.
Here is a link to the github Repo : https://github.com/IsoDevMate/react-stripe
Conclusion
In this guide, we set up a backend server using Node.js and JavaScript, integrated SendGrid for sending emails, and Stripe for handling payments
Follow up with part 2 on how to integrate the frontend using React.js.