Add Payment Gateway to Firebase App

Rohan Lamb
2 min readMar 28, 2019

I love making projects on Firebase just because of its simplicity, features and it’s free to try almost every service.

It was okay making basic projects with Firebase until I came across a project in which I was going add Payment gateway.

Adding a payment gateway to website is such a pain in the ass. Every pro developer will recommend using custom Node or .NET server and handle stuff.

Why create a custom server just for Payment Gateway?

If we can implement most of the functionality like Authentication, Database, Notifications using firebase then why program a server just to make payments?

But there is a catch, to prevent order from tempering and possibly prevent man-in-middle attacks we have to generate SHA keys.

SHA keys can only be decrypted using the secret key which must not be stored or even passed directly to client app or website. So how do we do that using firebase?

Cloud Functions

Cloud Function is a little piece of code that can be ran on firebase server. Cloud functions support many languages including JavaScript, Typescript, Python etc. so choose one you mastered and go forward.

How to implement Razorpay Payments using Firebase?

  1. Initialise functions and write a function which which will trigger on http request. So now we can listen to http request and execute some code. In my case I used Express with CORS as middleware. Because browser is not going to let you make request to other origins.
  2. When order is created in firestore with uniqueId make a http request to the function created before and through function make a request to Razorpay order api to create order. This request must be done from server because the request has to be authorised with your keys which can only be stored in server. Also send auto_capture flag as 1 with payload. Which will make payment verification a lot easier.
  3. When the request is made correctly you will recieve response with razorpay_order_id & some other details. Now save that order_id to corresponding order we created earlier in firestore. At the same time send that id as response to very first request from browser.
  4. When order id received to client pass it to options object along with other order data which is listed on Razorpay docs. Now add that object along with handlers to launch function provided by Razorpay library.
  5. This will open payment window and when payment is completed the handler function will be called and now you can verify the order.
  6. Because we sent auto_capture flag with order request before we Razorpay send and encrypted hmac key which we can verify by calculating in another function in server.

Check out the repo for implementation-

--

--

Rohan Lamb

I am a Full Stack Developer. I love tinkering with computers. I listen music all the time. Love to watch anime.