Firebase Trigger Razorpay Intergration for Android

Viewed 850

I am creating an App Where user can buy coins and for that I have been trying to integrate Razorpay into my Android App since a long time now. Razorpay can directly be used in Android. It sends Success or Failure results for payment and I can act accordingly (adding points to database in this case). But the problem with this approach is that I have to write points (after success) to database from the app. Which means I have to give write access for points node to user app which is not a good idea. So I wanted to use Razorpay with Firebase Cloud Functions and searching for a long time I came across this tutorial which is for web. I am quite new to Cloud Functions and hence wanted a little help for Android.

Here is the Index.js code but For Web

const functions = require("firebase-functions");
var express = require("express");
var cors = require("cors");
var request = require("request");
const crypto = require("crypto");
const key = "----insert yout key here----";
const key_secret = "----- insert key secret here ----";

var app = express();

app.use(cors({ origin: true }));

app.post("/", (req, res) => {
  const amount = req.body.amount;

  //Allow Api Calls from local server
  const allowedOrigins = [
    "http://127.0.0.1:8080",
    "http://localhost:8080",
    "https://-------YourFirebaseApp-----.firebaseapp.com/"
  ];
  const origin = req.headers.origin;
  if (allowedOrigins.indexOf(origin) > -1) {
    res.setHeader("Access-Control-Allow-Origin", origin);
  }

  var options = {
    method: "POST",
    url: "https://api.razorpay.com/v1/orders",
    headers: {
      //There should be space after Basic else you get a BAD REQUEST error
      Authorization:
        "Basic " + new Buffer(key + ":" + key_secret).toString("base64")
    },
    form: {
      amount: amount,
      currency: "INR",
      receipt:
        "----- create a order in firestore and pass order_unique id here ---",
      payment_capture: 1
    }
  };

  request(options, function(error, response, body) {
    if (error) throw new Error(error);

    res.send(body);
  });
});

app.post("/confirmPayment", (req, res) => {
  const order = req.body;
  const text = order.razorpay_order_id + "|" + order.razorpay_payment_id;
  var signature = crypto
    .createHmac("sha256", key_secret)
    .update(text)
    .digest("hex");

  if (signature === order.razorpay_signature) {
    console.log("PAYMENT SUCCESSFULL");

    res.send("PAYMENT SUCCESSFULL");
  } else {
    res.send("something went wrong!");
    res.end();
  }
});

exports.paymentApi = functions.https.onRequest(app);
1 Answers

I think this will help you.

In my case, I am accessing items(Array of Product IDs) from the user's cart and reading the current price of the items then passing it as an argument to SendOrderId function which will return an OrderId to proceed.

The important thing to keep in mind is that you must have added razorpay in your dependencies inside package.json. You can do that by simply running

npm i razorpay 

inside your functions folder (Which include index.js) which will automatically add the dependency to your project

const functions = require("firebase-functions");
const admin = require('firebase-admin');
const Razorpay = require('razorpay')
const razorpay = new Razorpay({
    key_id: 'Your_razorpay_key_id',
    key_secret: 'your_secret'
})
admin.initializeApp();

function SendOrderId(amountData, response) {
  var options = {
      amount: amountData,  // amount in the smallest currency unit
      currency: "INR",
    };
    razorpay.orders.create(options, function(err, order) {
      console.log(order);
      response.send(order);
    });
}

exports.getOrderId = functions.https.onRequest((req, res) => {
  return admin.firestore().collection('Users').doc(req.query.uid).get().then(queryResult => {
    console.log(queryResult.data().Cart);
    admin.firestore().collectionGroup("Products").where('ProductId', 'in', queryResult.data().Cart).get().then(result => {
      var amount = 0;
      result.forEach(element => {
        amount += element.data().price;
      });
      SendOrderId(amount * 100, res);
    })
  })
});
Related