I want to capture a payment and create a transfer immediately on a payment using Firebase Cloud Functions. The capture is happening correctly but the transfer is not being executed. What could be the reason?
Docs for reference: https://github.com/razorpay/razorpay-node/blob/master/examples/index.js
The following is the source code for my Firebase Cloud Function:
exports.CapturePayment = functions.database.ref('payment_id').onWrite((event) => {
const payment_id = event.data.val();
// Capture a particular payment
rzp.payments.capture(payment_id, 100000).then((data) => {
return event.data.ref.child('status').set(data);
console.log(data);
// Create transfers on a payment
rzp.payments.transfer(payment_id, {
transfers: [
{
account: 'acc_aldsfkas123123adsf',
amount: 100,
currency: 'INR'
}
]
}).then((data) => {
var db = admin.database();
var ref = db.ref("transfer");
return ref.update("Success");
console.log(data)
}).catch((error) => {
var db = admin.database();
var ref = db.ref("transfer");
return ref.update("Failure");
console.error(error)
})
// success
}).catch((error) => {
console.log(error);
// error
})
});
If you want to return the data in your initial call, but also do the transfer, just change it to the following:
// Capture a particular payment
rzp.payments.capture(payment_id, 100000).then((data) => {
const ret = event.data.ref.child('status').set(data);
console.log(data)
// Create transfers on a payment
rzp.payments.transfer(payment_id, {
transfers: [
{
account: 'acc_aldsfkas123123adsf',
amount: 100,
currency: 'INR'
}
]
})
return ret
})
The problem is that you were using return
before running your transfer function. Once a return
is hit, the code following it will never be run. By storing your desired return in a variable, you can do other work, and then return it.
Alternatively, you could run the code in a different order, as it looks like the two calls don't depend on each other.
Really though, you should be breaking all your async work out into single serving, and understandable functions that can be chained together for better readability. For example, your chain might look like this:
capturePayment(payment_id, 100000)
.then(updateDB)
.then(transfer)
.then(data => console.log('success'))
.catch(err => console.error(err))
Then all you have to ensure is that each of your chaining functions takes a single argument, that can be passed from the result of the previous.