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();
Related
I have been given an assignment to fetch a JSON API, and also parse an XML feed URL and store their responses inside separate Firestore collections. I am not really good at cloud functions, but after lots of research, I have written the cloud function code below for the JSON API and it works well.
const functions = require("firebase-functions");
const axios = require("axios");
const admin = require("firebase-admin");
const api_token = "XXXXXXX";
const includes = "XXXXXX";
const url = "https://XXXXXXXXXXXXXX.com/?api_token=" + api_token + includes;
exports.allLeagues = functions.region('europe-west1').https.onRequest(async (req, res) => {
try {
let response = await axios.get(url);
var data = response.data.data;
for (let leagueData of data) {
await admin.firestore().collection("leagues").doc(leagueData.id.toString()).collection("all_data").doc(leagueData.id.toString()).set({
id : leagueData.id,
name : leagueData.name,
logo_path : leagueData.logo_path,
is_cup : leagueData.is_cup
});
}
console.log("Table complete...");
console.log("successful");
return res.status(200).json({ message: "successful" });
} catch(error) {
console.log("Error encountered: "+error);
return res.status(500).json({ error });
}
});
I am through with the JSON API. But for the XML feed, I don't know where to start. I have done lots of research to no avail. I found this on Stackoverflow but it doesn't address my need. Assuming this is my feed: https://www.feedforall.com/sample.xml , please how do I parse it and save the items inside Firestore?
Kindly help.
Thank you.
You can use rss-parser that can be used to fetch data from RSS feeds or parse from XML strings as shown below:
// npm install rss-parser
const Parser = require("rss-parser");
const parser = new Parser();
exports.rssFeedParser = functions.https.onRequest(
async (request, response) => {
const rssUrl = "https://www.feedforall.com/sample.xml";
const feed = await parser.parseURL(rssUrl);
const { items } = feed;
const batch = db.batch();
items.forEach((item) => {
const docRef = db.collection("rss").doc();
// restructure item if needed
batch.set(docRef, item);
});
await batch.commit();
response.send("Done");
}
);
Do note that you can add up to 500 documents only using Batched Writes as in the answer above. If your feed can return more than that, then you should create multiple batches of 500 or add them individually.
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
}
});
});
Why when i call this function Stripe generate 2 invoice?
I want to set a custom price % for the invoice and not using a fixed price as suggested on the documentation.
I want that the invoice is automatically payed by the customer.
exports = module.exports = functions.https.onRequest(
async (request, response) => {
let data = request.body;
var imponibile = 100;
const { stripe } = require("./stripe");
const { db } = require("./admin");
const invoiceItem = await stripe.invoiceItems.create({
customer: data.customerId,
description: data.description,
amount: imponibile,
currency: "eur",
});
const invoice = await stripe.invoices.create({
customer: data.customerId,
auto_advance: true, // Auto-finalize this draft after ~1 hour
collection_method: "charge_automatically",
});
const payinvoice = await stripe.invoices.pay(invoice.id);
return payinvoice;
}
);
Solved, the problem was that i was returning the actual payment function recursively.
Solution :
return respond.status(200).send('ok')
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.
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.