UnhandledPromiseRejectionWarning: Error: `receipt` is mandatory razorpay - node.js

I'm following this documentation to create an order and they have clearly stated that the receipt is an optional parameter then why I'm getting
UnhandledPromiseRejectionWarning: Error: `receipt` is mandatory razorpay
here is the error
this is the code
const createOrder = async (req, res) => {
const amount = parseInt(req.body.amount) * 100;
const currency = req.body.currency;
var options = {
amount,
currency,
};
const instance = await razorpay.orders.create(options);
if (instance) {
const order_id = instance.id;
const transaction = new Transactions({ order_id, user_id,details:instance });
transaction.save();
res.status(200).json(instance);
}
};

This was a bug in the razorpay library that was fixed over a year ago.
Make sure you are using the latest version of the package. If the fix wasn't published, you could try using this commit directly:
npm i razorpay/razorpay-node#80044a4d1f54cdee6e8f5b81ddbcccba5812c175
If this doesn't work either, you could open an issue with the library on GitHub.

Related

Web3 getPastEvents Returned error: limit exceeded

I am using web3 function getPastEvents and I am getting error:
Returned error: limit exceeded
I also changed RPC url but same error occured their.
Is there any other way to get event data ?
this is my code:
const http = require("http");
const cron = require('node-cron');
const { randomBytes } = require("crypto");
const web3 = new Web3("https://bsc-dataseed.binance.org/");
//console.log("Hello This",web3);
//console.log("hello");
const dexABI =contractAbi;
const contract_address = "0xd19EA9d72828444BC7bAE231fBa66F8050e72b1b";
const contract = new web3.eth.Contract(dexABI, contract_address);
async function generateEventQuery(result) {
console.log(result);
return ;
}
http
.createServer((req, res) => {
web3.eth
.getBlockNumber()
.then((d) => {
let current_block = d;
console.log(current_block);
contract
.getPastEvents({
fromBlock: Number(23390147),
toBlock: Number(23390147)+100,
})
.then( async(events) => {
let resu = await generateEventQuery(events);
})
.catch((e) => {
console.log("Err",e)
res.write("Err:" + JSON.stringify(e));
res.end();
});
})
.catch((e) => e);
})
.listen(8080);
in the function getPastEvents() you have to take the first parameter as your event name which you want to fetch the data. The name should be as same as in your contract and passed into a string.
Actually, this is an RPC problem. I replaced https://bsc-dataseed.binance.org/ with https://bscrpc.com. Now it works properly.
Public RPC URLs like https://bsc-dataseed.binance.org/ or https://bscrpc.com have rate-limiting to prevent people from over using it.
It's fine for testing but in production you should use your own node or a blockchain API like Infura, Alchemy, QuickNode or any other.

Get data from firestore document and use in cloud function

In the user's collection, each user has a document with a customer_id.
I would like to retrieve this customer_id and use it to create a setup intent.
The following code has worked for me in the past. However, all of a sudden it throws the error:
Object is possibly 'undefined'
The error is on the following line under snapshot.data() in this line:
const customerId = snapshot.data().customer_id;
Here is the entire code snippet:
exports.createSetupIntent = functions.https.onCall(async (data, context) => {
const userId = data.userId;
const snapshot = await db
.collection("development")
.doc("development")
.collection("users")
.doc(userId).get();
const customerId = snapshot.data().customer_id;
const setupIntent = await stripe.setupIntents.create({
customer: customerId,
});
const clientSecret = setupIntent.client_secret;
const intentId = setupIntent.id;
return {
clientsecret: clientSecret,
intentId: intentId,
};
});
Any help is appreciated :)
this is because snapshot.data() may return undefined
there are 2 ways to solve this
first is assert as non-null, if you have high confident that the data exist
const customerId = snapshot.data()!.customer_id;
second if check for undefined
const customerId = snapshot.data()?.customer_id;
if(customerId){
// ....
}
I recommend the 2nd method, it is safer
I can see you are using a sub collection order,You need to loop through the snapshot data using the forEach loop.
const customerId = snapshot.data()
customerId.forEach((id)=> {
console.log(id.customer_id)
});
Try this out but.
The document you're trying to load may not exist, in which case calling data() on the snapshot will return null, and thus this line would give an error:
const customerId = snapshot.data().customer_id;
The solution is to check whether the document you loaded exists, and only then force to get the data from it:
if (snapshot.exists()) {
const customerId = snapshot.data()!.customer_id;
...
}
if you want to fetch user data from docId then you can use something like this:
const functions = require("firebase-functions");
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
db.settings({ timestampsInSnapshots: true });
exports.demoFunction = functions.https.onRequest((request, response) => {
var userId = request.body.userId;
db.collection("user").doc(userId).get().then(snapshot => {
if (snapshot) {
var data = snapshot.data();
// use data to get firestore data
var yourWantedData = data.name;
// use it in your functionality
}
});
});

How to get cryptocurrency's price in EUR Node.js?

As a example in coinbase-api I can get cryptocurrency's price this way:
const eth_eur = await publicClient.getProductOrderBook('ETH-EUR', { level: 1 });
As you can see, I need pair cryptocurrency - eur, and that's important. So, how can I do it using binance api?
I was trying to use something like this:
const price = await binance.futuresFundingRate("ETHUSDT");
But this is not what I need. I need price in euro.
You can use the "Current average price" endpoint (docs) for base currencies that have pair against EUR.
Example:
const axios = require('axios');
axios.get('https://api.binance.com/api/v3/avgPrice?symbol=BTCEUR').then(response => {
const body = response.data;
console.log(body.price);
});
You can get the exchange rate easily with superface npm package
Example
npm install #superfaceai/one-sdk
npx #superfaceai/cli install crypto/exchange-rate
const { SuperfaceClient } = require("#superfaceai/one-sdk");
const sdk = new SuperfaceClient();
async function run() {
// Load the installed profile
const profile = await sdk.getProfile("crypto/exchange-rate");
// Use the profile
const result = await profile.getUseCase("GetExchangeRate").perform({
from: "ETH",
to: "EUR",
});
console.log(result.unwrap());
}
run();

Express validator ".isEmpty()" not working

When I try to run my application I get an error saying that text boxes that are not empty are empty.
app.js:
https://pastebin.com/5pbVG7kq
index.hbs:
https://pastebin.com/neVV4X78
EDIT:
With express-validator, you need to use the "notEmpty()" function instead of validator's module "isEmpty()", which is not referenced in the readme.md. I tried it out with an empty string and without sending the parametr and it works fine in both cases.
OLD REPLY:
I'm facing the same issue with express-validator. I submitted the issue to the github respository so we have to wait for them to address the problem.
As a workaround in the meantime, you can use the isEmpty() function of the validator package directly.
var validator = require('validator');
validator.isEmpty(string) //returns true or false
Also note that validator only accepts a string value and it doesn't coerce the variable passed to it as opposed to express-validator, so you will need to handle the case when the parameter obtained via req.body.param is not sent.
Here is the link to the reported issue: https://github.com/ctavan/express-validator/issues/336
Hope this helps.
2019 express-validator
6.2.0
Here is what I use for now and it works perfect
app.js
const express = require('express');
const {createPost} = require('../controllers/post');
// Import check only form express-validator
const {check} = require('express-validator');
const router = express.Router();
router.post('/post',[
// Title
check('title').not().isEmpty().withMessage('Title is required.'),
check('title').isLength({
min:4,
max:150
}).withMessage('Title must be between 4 to 150 characters.'),
check('body').not().isEmpty().withMessage('Body is required.'),
check('body').isLength({
min:4,
max:2000
}).withMessage('body must be between 4 to 2000 characters.')
],createPost)
** Folder '../controllers/post'**
post.js
// Import validation result only from expres-validator
const {validationResult } = require('express-validator');
// Post model file with custom implementation.
const Post = require('../models/post');
exports.createPost = (req, res) => {
// Grab your validation errors here before making any CREATE operation to your database.
const errors = validationResult(req);
if (!errors.isEmpty()) {
const firstError = errors.array().map(error => error.msg)[0];
return res.status(400).json({ error: firstError });
}
const post = new Post({
title: req.body.title,
body: req.body.body
});
// Now you can safely save your data after check passes.
post.save()
.then(result => {
res.status(200).json({
post: result
})
});
};

Promisify all submethods on a node module

I'm trying to Promisify the stripe module but running into an issue.
If I run:
const stripe = Promise.promisifyAll(require('stripe')(secretKey));
const response = await stripe.accounts.retrieveAsync();
retrieveAsync isn't a function. I have to do something like this:
const accounts = Promise.promisifyAll(stripe.accounts);
const response = await accounts.retrieveAsync();
But obviously this doesn't scale well. How can I promisify all of the submethods of this module? Thanks
This seems to work:
let stripe = require('stripe')(secretKey);
Promise.promisifyAll(Object.getPrototypeOf(stripe));
Give a shot to it :
const stripe = Promise.promisifyAll(require('stripe')(secretKey));
const response = yield stripe.accounts.retrieve().promise();
It looks like that stripe v4.25 supports Promises, if you omit the callback.
With callback:
var stripe = require('stripe')('sk_test_XXX')
stripe.plans.retrieve('number_one_month', (err, res) => console.log(res))
{ id: 'number_one_month',
...
And with then():
stripe.plans.retrieve('number_one_month').then(console.log)
{ id: 'number_one_month',
...
But I didn't find it in the documentation.

Resources