const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
// To avoid deployment errors, do not call admin.initializeApp() in your code
admin.initializeApp();
exports.paymentCheck = functions.region('us-central1')
.runWith({
timeoutSeconds: 120,
memory: '128MB'
})
.https.onCall(async (data, context) => {
try {
const dataRef = data.dataRef;
// Define the payment data
// Initialize the status variable
let status = '';
// Continuous loop to check payment status
do {
// Make an API call to check payment status
const apiUrl = `https://mercury-t2.phonepe.com/v3/transaction/${data.dataRef.merchantId}/${data.dataRef.transactionId}/status`;
const apiResponse = await axios.get(apiUrl, {
headers: {
'x-verify': data.dataRef.xVerify
}
});
// Log the API response
console.log('API Response:', apiResponse.data);
// Extract the status from the API response
status = apiResponse.data.paymentState;
// Perform other payment verification logic based on the API response
// ...
// Delay for 2 seconds before the next iteration
await new Promise(resolve => setTimeout(resolve, 2000));
} while (status !== 'COMPLETED' && status !== 'FAILED');
// If the status is 'Completed', call the updateOrCreateDoc function
if (status === 'COMPLETED') {
await updateOrCreateDoc(dataRef);
return "COMPLETED";
}
else if(status === 'FAILED'){
return "FAILED";
}
// Return a response based on the outcome
return "ERROR";
} catch (error) {
// Handle errors and return an appropriate response
console.error('Error processing paymentCheck:', error);
return "INTERNAL SERVER ERROR";
}
});
async function updateOrCreateDoc(dataRef) {
try {
// Get references to the Firestore collections
const firestore = admin.firestore();
const userRef = firestore.collection(dataRef.userRef);
const orderTargetRef = firestore.collection(dataRef.orderTargetRef);
// Use a transaction to update or create the documents atomically
await firestore.runTransaction(async (transaction) => {
// Read the user_canteenRef document
const canteenDocRef = userRef.doc(dataRef.userId).collection('user_canteenRef').doc(dataRef.canteenId);
const canteenDoc = await transaction.get(canteenDocRef);
const canteenData = canteenDoc.exists ? canteenDoc.data() : null;
// Update or create the user document
const userDoc = await transaction.get(userRef.doc(dataRef.userId));
const newTotalSales = (userDoc.exists ? userDoc.data().totalSales : 0) + dataRef.cartTotalAmount;
const newTotalOrder = (userDoc.exists ? userDoc.data().totalOrder : 0) + 1;
const newTotalQuantity = (userDoc.exists ? userDoc.data().totalQuantity : 0) + dataRef.totalFoodQuantity;
const updatedUserData = {
totalSales: newTotalSales,
totalOrder: newTotalOrder,
totalQuantity: newTotalQuantity,
};
transaction.set(userRef.doc(dataRef.userId), updatedUserData, { merge: true });
// Check and update offerTaken list
const offerIdIndex = userDoc.exists ? userDoc.data().offerId.indexOf(dataRef.offerId) : -1;
if (offerIdIndex !== -1 && canteenData && canteenData.discountApplied) {
const offerTaken = userDoc.exists ? userDoc.data().offerTaken : [];
// Increment the value at the index where offerId is found
if (offerIdIndex < offerTaken.length) {
offerTaken[offerIdIndex] = (offerTaken[offerIdIndex] || 0) + 1;
}
// Update the offerTaken list
transaction.set(userRef.doc(dataRef.userId), { offerTaken }, { merge: true });
}
// Update or create the orderTarget document
const orderTargetDoc = await transaction.get(orderTargetRef.doc(dataRef.orderTargetId));
const newTodayTotalOrder = (orderTargetDoc.exists ? orderTargetDoc.data().todayTotalOrder : 0) + 1;
const newTodayTotalSales = (orderTargetDoc.exists ? orderTargetDoc.data().todayTotalSales : 0) + dataRef.cartTotalAmount;
transaction.set(orderTargetRef.doc(dataRef.orderTargetId), {
todayTotalOrder: newTodayTotalOrder,
todayTotalSales: newTodayTotalSales,
}, { merge: true });
// Create a document in the "user_orderHistory" subcollection
const orderHistoryRef = userRef.doc(dataRef.userId).collection('user_orderHistory').doc();
const orderHistoryData = {
foodRef: dataRef.cartFoodRef,
orderTotal: dataRef.cartTotalAmount,
orderTotalPerFood: dataRef.cartFoodTotalAmount,
orderFoodPrice: dataRef.cartFoodPrice,
orderFoodName: dataRef.cartFoodName,
orderFoodQuantity: dataRef.cartQuantity,
orderFoodImage: dataRef.cartFoodImg,
orderTime: dataRef.orderTime,
orderStatus: 'In Queue',
orderInProgress: false,
orderCompleted: false,
orderTransactionId: dataRef.orderTransactionId,
totalFoodQuantity: dataRef.totalFoodQuantity,
orderPin: dataRef.orderPin,
customMessage: dataRef.customMessage,
method: dataRef.method,
originalAmount: dataRef.originalAmount,
};
transaction.set(orderHistoryRef, orderHistoryData);
// Create a document in the "orderQueue" subcollection
const orderQueueRef = orderTargetRef.doc(dataRef.orderTargetId).collection('orderQueue').doc();
const orderQueueData = {
cartFoodRef: dataRef.cartFoodRef,
cartTotalAmount: dataRef.cartTotalAmount,
cartFoodTotalAmount: dataRef.cartFoodTotalAmount,
cartFoodPrice: dataRef.cartFoodPrice,
cartFoodName: dataRef.cartFoodName,
cartQuantity: dataRef.cartQuantity,
cartFoodImage: dataRef.cartFoodImg,
orderTime: dataRef.orderTime,
orderTransactionId: dataRef.orderTransactionId,
totalFoodQuantity: dataRef.totalFoodQuantity,
orderPin: dataRef.orderPin,
customMessage: dataRef.customMessage,
method: dataRef.method,
originalAmount: dataRef.originalAmount,
createdBy: dataRef.createdBy,
creatorNumber: dataRef.creatorNumber,
userOrderHistoryRef: orderHistoryRef, // Reference to the user_orderHistory document
};
transaction.set(orderQueueRef, orderQueueData);
// Create a document in the "orderNotCompleted" subcollection
const orderNotCompletedRef = userRef.doc(dataRef.userId).collection('orderNotCompleted').doc();
const orderNotCompletedData = {
foodRef: dataRef.cartFoodRef,
orderTotal: dataRef.cartTotalAmount,
orderTotalPerFood: dataRef.cartFoodTotalAmount,
orderFoodPrice: dataRef.cartFoodPrice,
orderFoodName: dataRef.cartFoodName,
orderFoodQuantity: dataRef.cartQuantity,
orderFoodImage: dataRef.cartFoodImg,
orderTime: dataRef.orderTime,
orderStatus: 'In Queue',
orderInProgress: false,
orderCompleted: false,
orderTransactionId: dataRef.orderTransactionId,
totalFoodQuantity: dataRef.totalFoodQuantity,
};
transaction.set(orderNotCompletedRef, orderNotCompletedData);
console.log('Documents updated or created successfully');
});
} catch (error) {
console.error('Error updating or creating documents:', error);
throw error;
}
}
I dont know why it is happening do i have to do any changes to google cloud !