From fc01b038b3529936fffc944d5c4dc70fd2963a16 Mon Sep 17 00:00:00 2001 From: DhanshCOSQ Date: Mon, 7 Apr 2025 20:03:20 +0530 Subject: [PATCH] Added cors createCashfreeOrder --- functions/package-lock.json | 1 + functions/package.json | 1 + functions/src/index.ts | 169 +++++++++++++++++++----------------- 3 files changed, 90 insertions(+), 81 deletions(-) diff --git a/functions/package-lock.json b/functions/package-lock.json index ac67f4d..8a295b3 100644 --- a/functions/package-lock.json +++ b/functions/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@types/node-fetch": "^2.6.12", "axios": "^1.8.4", + "cors": "^2.8.5", "firebase-admin": "^12.6.0", "firebase-functions": "^6.0.1", "form-data": "^4.0.1", diff --git a/functions/package.json b/functions/package.json index 5c20815..939628c 100644 --- a/functions/package.json +++ b/functions/package.json @@ -17,6 +17,7 @@ "dependencies": { "@types/node-fetch": "^2.6.12", "axios": "^1.8.4", + "cors": "^2.8.5", "firebase-admin": "^12.6.0", "firebase-functions": "^6.0.1", "form-data": "^4.0.1", diff --git a/functions/src/index.ts b/functions/src/index.ts index a26adc6..b250098 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -8,6 +8,7 @@ import * as os from 'os'; import * as path from 'path'; import * as fs from 'fs'; import * as https from 'https'; +import cors from 'cors'; import axios from "axios"; import { getStorage } from 'firebase-admin/storage'; const formData = require('form-data'); @@ -19,6 +20,9 @@ const twilio = require('twilio'); if (!admin.apps.length) { admin.initializeApp(); } + +const corsHandler = cors({ origin: true }); + export const sendEmailWithAttachment = onRequest({ region: '#{SERVICES_RGN}#' }, async (request: Request, response: express.Response) => { @@ -245,92 +249,95 @@ export const notifyInvitation = onDocumentCreated({ export const createCashfreeOrder = onRequest({ region: '#{SERVICES_RGN}#' }, async (request: Request, response: express.Response) => { - try { - const authHeader = request.headers.authorization; - if (!authHeader || !authHeader.startsWith('Bearer ')) { - response.status(401).json({ error: 'Unauthorized' }); - return; - } - const idToken = authHeader.split('Bearer ')[1]; - const decodedToken = await admin.auth().verifyIdToken(idToken); - const uid = decodedToken.uid; - - const { - amount, - customerName, - customerEmail, - customerPhone, - productInfo - } = request.body; - - if (!amount || !customerEmail || !customerPhone) { - response.status(400).json({ error: 'Missing required fields' }); - return; - } - - const clientId = process.env.CASHFREE_CLIENT_ID; - const clientSecret = process.env.CASHFREE_CLIENT_SECRET; - const isTest = true; - - const apiUrl = isTest - ? 'https://sandbox.cashfree.com/pg/orders' - : 'https://api.cashfree.com/pg/orders'; - - const orderId = `order_${Date.now()}_${uid.substring(0, 6)}`; - - const cashfreeResponse = await axios.post( - apiUrl, - { - order_id: orderId, - order_amount: amount, - order_currency: 'INR', - customer_details: { - customer_id: uid, - customer_name: customerName || 'Fitlien User', - customer_email: customerEmail, - customer_phone: customerPhone - }, - order_meta: { - return_url: `https://fitlien.com/payment/status?order_id={order_id}`, - // notify_url: `https://$filien.web.app/verifyCashfreePayment` - }, - order_note: productInfo || 'Fitlien Membership' - }, - { - headers: { - 'x-api-version': '2022-09-01', - 'x-client-id': clientId, - 'x-client-secret': clientSecret, - 'Content-Type': 'application/json' - } + return corsHandler(request, response, async () => { + try { + const authHeader = request.headers.authorization; + if (!authHeader || !authHeader.startsWith('Bearer ')) { + response.status(401).json({ error: 'Unauthorized' }); + return; } - ); - await admin.firestore().collection('payment_orders').doc(orderId).set({ - userId: uid, - amount: amount, - customerEmail: customerEmail, - customerPhone: customerPhone, - orderStatus: 'CREATED', - paymentGateway: 'Cashfree', - createdAt: new Date(), - ...cashfreeResponse.data - }); + const idToken = authHeader.split('Bearer ')[1]; + const decodedToken = await admin.auth().verifyIdToken(idToken); + const uid = decodedToken.uid; - response.json({ - order_id: cashfreeResponse.data.order_id, - payment_session_id: cashfreeResponse.data.payment_session_id - }); + const { + amount, + customerName, + customerEmail, + customerPhone, + productInfo + } = request.body; - logger.info(`Cashfree order created: ${orderId}`); - } catch (error: any) { - logger.error('Cashfree order creation error:', error); - response.status(500).json({ - error: 'Failed to create payment order', - details: error.response?.data || error.message - }); - } + if (!amount || !customerEmail || !customerPhone) { + response.status(400).json({ error: 'Missing required fields' }); + return; + } + + const clientId = process.env.CASHFREE_CLIENT_ID; + const clientSecret = process.env.CASHFREE_CLIENT_SECRET; + const isTest = true; + + const apiUrl = isTest + ? 'https://sandbox.cashfree.com/pg/orders' + : 'https://api.cashfree.com/pg/orders'; + + const orderId = `order_${Date.now()}_${uid.substring(0, 6)}`; + + const cashfreeResponse = await axios.post( + apiUrl, + { + order_id: orderId, + order_amount: amount, + order_currency: 'INR', + customer_details: { + customer_id: uid, + customer_name: customerName || 'Fitlien User', + customer_email: customerEmail, + customer_phone: customerPhone + }, + order_meta: { + return_url: `https://fitlien.com/payment/status?order_id={order_id}`, + // notify_url: `https://$filien.web.app/verifyCashfreePayment` + }, + order_note: productInfo || 'Fitlien Membership' + }, + { + headers: { + 'x-api-version': '2022-09-01', + 'x-client-id': clientId, + 'x-client-secret': clientSecret, + 'Content-Type': 'application/json' + } + } + ); + + await admin.firestore().collection('payment_orders').doc(orderId).set({ + userId: uid, + amount: amount, + customerEmail: customerEmail, + customerPhone: customerPhone, + orderStatus: 'CREATED', + paymentGateway: 'Cashfree', + createdAt: new Date(), + ...cashfreeResponse.data + }); + + response.json({ + order_id: cashfreeResponse.data.order_id, + payment_session_id: cashfreeResponse.data.payment_session_id + }); + + logger.info(`Cashfree order created: ${orderId}`); + } catch (error: any) { + logger.error('Cashfree order creation error:', error); + response.status(500).json({ + error: 'Failed to create payment order', + details: error.response?.data || error.message + }); + } + }); }); export const verifyCashfreePayment = onRequest({ -- 2.43.0