Seamlessly Integrate Chargebee Subscriptions with Node.js Using Hosted Pages



Introduction:
In today's rapidly evolving digital landscape, managing subscriptions efficiently is crucial for any business looking to scale. Chargebee provides a powerful, out-of-the-box solution for subscription management, allowing you to handle billing, customer sign-ups, and renewals with ease. In this guide, we will walk through the process of integrating Chargebee's hosted pages into your Node.js application, enabling a seamless, user-friendly subscription experience for your customers.
Prerequisites
A Chargebee account with items, items prices, and basic settings configured.
Hosted pages enabled, with basic customization to match your brand's look and feel.
A Chargebee site name and API key, which are available in the Chargebee dashboard under the API settings.
Node and npm installed
If you haven’t set this up yet, check out our detailed guide here on how to configure Chargebee items, prices, and other initial settings
What Are Hosted Pages?
Hosted Pages are pre-built, customizable web pages provided by Chargebee that allow you to manage various subscription-related activities such as customer sign-ups, payments, and account management without needing to build these functionalities from scratch. Hosted pages offer a secure, PCI-compliant way to handle sensitive information like payment details, freeing you from the complexities of implementing and maintaining your own subscription and billing forms
Why Use Hosted Pages?
Using hosted pages allows you to leverage Chargebee’s expertise in subscription management, enabling a smooth and professional checkout experience. This not only reduces the development overhead but also enhances customer trust by providing a secure and reliable interface for managing their subscriptions.
Setting Up Your Environment
Before integrating Chargebee’s hosted pages into your Node.js application, you need to set up your development environment. This section will guide you through setting up a new Node.js project and configuring it for Chargebee integration.
Step 1: Initialize a New Node.js Project:
Create a Project Directory:
mkdir chargebee-integration cd chargebee-integrationInitialize the Project:
cd chargebee-integrationInstall Necessary Dependencies:
npm install chargebee dotenv express
Step 2: Configure Environment Variables :
Configure .env file:
CHARGEBEE_SITE=your_chargebee_site_name CHARGEBEE_API_KEY=your_chargebee_api_keyLoad Environment Variables in Your Application:
require('dotenv').config(); const chargebee = require('chargebee'); chargebee.configure({ site: process.env.CHARGEBEE_SITE, api_key: process.env.CHARGEBEE_API_KEY, }); console.log('Chargebee configured with site:', process.env.CHARGEBEE_SITE);
Step 3: Set Up Basic Express Server :
Create a Basic Server::
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Chargebee Integration with Node.js'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });- Run your server with:
node index.js
Creating a Subscription with Hosted Pages:
After setting up your environment, the next crucial step is to create a subscription router in your application. This will manage all the subscription related activites in your node application
Create a Subscription router file:
mkdir router cd router touch subscriptions.jsInitialize the router:
const express = require('express'); const router = express.Router(); const chargebee = require('chargebee'); chargebee.configure({ site: process.env.CHARGEBEE_SITE, api_key: process.env.CHARGEBEE_API_KEY, });Define the Route for Creating Subscriptions :
// POST /subscriptions/create router.post('/create', async (req, res) => { try { const { priceId, customerId} = req.body; const session = await chargebee.hosted_page.checkout_new_for_items({ redirect_url: "your frontend url to redirect on successfull payment", cancel_url: "your frontend url to redirect on unsuccessfull payment", embed: true, subscription_items: [ { item_price_id: priceId, quantity: 1 }], customer: { id: customerId } }).request(); // Redirect to the hosted page URL res.json({ hostedPageUrl: response.hosted_page.url }); } catch (error) { console.error('Error creating subscription:', error); res.status(500).send('Error creating subscription'); } })
Note: A subscription is recorded in Chargebee only if the entire payment is successful. This ensures that subscriptions are only activated when the full payment is received.
Handling Successful Checkouts Using Webhooks
Once a payment is successfully processed, you can listen for Chargebee's webhook events to handle the outcome in your application. Webhooks allow your system to receive real-time notifications from Chargebee whenever specific events occur, such as a successful checkout or payment.
Step 1: Configure Webhooks in Chargebee
To handle successful checkouts, first, configure your webhook settings in Chargebee:
Go to your Chargebee Dashboard.
Navigate to Settings> Configure Webhooks.
Create a new webhook, specifying the event types you want to listen to,you can refer to this link to check all the events provided by the chargebee
Provide the URL of your server endpoint that will handle these events.
Step 2: Create an Endpoint to Receive Webhooks
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const CHARGEBEE_WEBHOOKS_REQUEST_ORIGINS = [ '3.209.65.25', '3.215.11.205', '3.228.118.137', '3.229.12.56', '3.230.149.90', '3.231.198.174', '3.231.48.173', '3.233.249.52', '18.210.240.138', '18.232.249.243', '34.195.242.184', '34.206.183.55', '35.168.199.245', '52.203.173.152', '52.205.125.34', '52.45.227.101', '54.158.181.196', '54.163.233.122', '54.166.107.32', '54.84.202.184',]
app.post('/webhooks/chargebee', (req, res) => {
const event = req.body;
const requestIp = req.headers['x-real-ip'] || req.headers['x-forwarded-for']
// Handle the event based on the event type
if (event.event_type === 'payment_success') {
const invoice = event.content.invoice;
// Process the successful payment (e.g., activate subscription, send receipt)
console.log(`Payment successful for Invoice ID: ${invoice.id}`);
// Your custom logic here...
}else if(event.event_type=='subscription_created'){
const subscription = event.content.subscription;
console.log(`Subscription created successfully: ${subscription.id}`);
}
// Respond with a 200 status to acknowledge receipt
res.status(200).send('Webhook received');
});
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const CHARGEBEE_WEBHOOKS_REQUEST_ORIGINS = [ '3.209.65.25', '3.215.11.205', '3.228.118.137', '3.229.12.56', '3.230.149.90', '3.231.198.174', '3.231.48.173', '3.233.249.52', '18.210.240.138', '18.232.249.243', '34.195.242.184', '34.206.183.55', '35.168.199.245', '52.203.173.152', '52.205.125.34', '52.45.227.101', '54.158.181.196', '54.163.233.122', '54.166.107.32', '54.84.202.184',]
app.post('/webhooks/chargebee', (req, res) => {
const event = req.body;
const requestIp = req.headers['x-real-ip'] || req.headers['x-forwarded-for']
// Handle the event based on the event type
if (event.event_type === 'payment_success') {
const invoice = event.content.invoice;
// Process the successful payment (e.g., activate subscription, send receipt)
console.log(`Payment successful for Invoice ID: ${invoice.id}`);
// Your custom logic here...
}else if(event.event_type=='subscription_created'){
const subscription = event.content.subscription;
console.log(`Subscription created successfully: ${subscription.id}`);
}
// Respond with a 200 status to acknowledge receipt
res.status(200).send('Webhook received');
});Note: Depending on the region of your chargbee configured during setup the request origins will change the above code is for us region. Following link contains the request origins for different region
References:
https://apidocs.chargebee.com/docs/api/hosted_pages?lang=node#create_checkout_for_a_new_subscription
Conclusion
Integrating Chargebee with your application using hosted pages and webhooks simplifies subscription management and ensures a seamless payment experience for users. By leveraging Chargebee’s hosted checkout pages, you can securely handle payments without needing to manage sensitive customer information directly. Furthermore, using webhooks allows you to automate critical processes such as activating subscriptions, sending notifications, and updating your database in real-time after successful payments