Integrate ONDC with just a few lines of code
Let's get some basics right,
- ONDC is a network, not an application/website.
- In order to use the network, you have to register with ONDC Registry.
- ONDC uses Async APIs.
- ONDC communication happens from server to server.
- ONDC spec has APIs (/search, /init, /track) and Callback APIs (/on_search, /on_init, /on_track)
- The participants of the network have to implement the APIs on their backend.
- Buyer apps will call the APIs and will get results on Callback APIs.
- Seller apps will respond to the call received on APIs.
So once all the participants have implemented the APIs on their backends, the applications can communicate with each other as the servers have common APIs and a common schema for the payload.
ONDC-Node
The ondc-node npm package helps you to be ONDC compliant quickly and easily.
Steps:
Install the ondc-node package in your node application
npm i ondc-node --save
Two ways,
- Use ondc-node express middleware to implement APIs on your backend.
- Use the package to make ONDC API calls.
Express Middleware
index.js
// import ondc
const ondc = require("ondc-node");
const express = require("express");// import handlers for the ONDC API calls
const handlers = require("./handlers");const app = express();
app.use(express.json());// Use ONDC Middleware to implement ONDC APIs in one line
// You can pass custom APIs handlers
// if handler does not exist a fallback handler will be usedapp.use("/ondc", ondc.Middleware(
{
"on_search": handlers["onSearch"],
"on_init": handlers[onInit],
...
}));
handlers.js
const onSearch = async (req, res) => {
// Use the req.body to find the result of search
let result = await Search(req.body); // The result should be in correct schema as per ONDC spec
res.status(200).send(result);
}const onInit = async (req, res) => {
// Use the req.body to init a transaction (create transactionId)
let result = await Init(req.body); // The result should be in correct schema as per ONDC spec
res.status(200).send(result);
}module.exports = {
onSearch,
onInit
}
That's it, now your app supports ONDC & can participate in the network.
As we discussed for Buyer, Seller, Logistics, etc the APIs which will be actually used are different, nonetheless, every participant needs to implement all the APIs.
Making ONDC API calls
//import ondc
const ondc = require('ondc-node');// Initialize ONDC
const instance = new ondc.ONDC({
host: "http://localhost:5000",
bapId: "bap.com",
bapUri: "https://bap.com/beckn",
bppId: "bpp.com",
bppUri: "https://bpp.com/beckn",
country: "IND",
city: "std:080",
ttl: "P1M"
});// Making a search call to gateway
const response = await instance.search({
"item": {
"descriptor": {
"name": "ABC Aata"
}
},
"fulfillment": {
"end": {
"location":
{
"gps": "12.4535445,77.9283792"
}
}
}
});
Hope this was helpful. Please share your comments and suggestions to improve the package.
Happy hacking!!!