Parte 2 (Backend) - Aprende a crear una tienda virtual Blockchain aceptando ERC20 token
Seguimos creando nuestra tienda blockchain con solidity, react, node y otras tecnologías. en el día de hoy nos toca programar el backend la cual será desarrollado con Node usando el framework Express, vamos a conectarnos con la blockchain de ethereum para escuchar los eventos y generar el id de pago, estaremos usando MongoDb como gestor de database. así que manos a la obra.
BD.js
const mongoose = require("mongoose");
mongoose.connect("URL_HERE_MONGODBATLAS", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const paymentSchema = new mongoose.Schema({
id: String,
itemId: String,
paid: Boolean,
});
const Payment = mongoose.model("Payment", paymentSchema);
module.exports = { Payment };
SERVER.js
const express = require("express");
const cors = require("cors");
const ethers = require("ethers");
const { Payment } = require("./db");
const PaymentProcessor = require("../build/contracts/PaymentProcessor.json");
const items = {
1: { id: "1", url: "http://urlToDownloadItem1" },
2: { id: "2", url: "http://urlToDownloadItem2" },
};
const app = express();
app.use(cors());
app.get("/api/getPaymentId/:itemId", async (req, res) => {
const id = (Math.random() * 10000).toFixed(0);
await Payment.create({
id,
itemId: req.params.itemId,
paid: false,
});
res.send({ id });
});
app.get("/api/getItemUrl/:paymentId", async (req, res) => {
const payment = await Payment.findOne({ id: req.params.paymentId });
if (payment && payment.paid) {
return res.send({ url: items[payment.itemId].url });
} else {
return res.send({ url: "" });
}
});
app.listen(4000, () => {
console.log("Server on port 4000");
});
const listenToEvents = () => {
const provider = new ethers.providers.JsonRpcProvider(
"https://localhost:9545"
);
const networkId = "5777";
const paymentProcessor = new ethers.Contract(
PaymentProcessor.networks[networkId].address,
PaymentProcessor.abi,
provider
);
paymentProcessor.on("PaymentDone", async (payer, amount, paymentId, date) => {
console.log(from ${payer} amount ${amount} paymentId ${paymentId} date ${new Date(date * 1000).toLocaleDateString()});
const payment = await Payment.findOne({ id: paymentId });
if (payment) {
payment.paid = true;
await payment.save();
}
});
};
listenToEvents();
#solidity #nodejs #reactjs #mongodb #expressjs #ethers
▶️ 3Speak
Leave Parte 2 (Backend) - Aprende a crear una tienda virtual Blockchain aceptando ERC20 token to:
Read more #programming posts
Best Posts From jfdesousa7
We have not curated any of jfdesousa7's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From jfdesousa7
- Today is selfie day 😌
- Strolling through "el Laguito" Park 🍃
- Probando la nueva actualizacion de NextJS 13
- Tennis day in the club (San Miguel / Maturin)
- My innocent puppy
- Aprende a subir tu aplicacion de NextJs a un Hosting Compartido (Cpanel)
- Severance - Everyone Should Watch the Absolute Best Show on Apple TV Plus
- Tutorial - React Redux App + Solidity desde cero. Metamask-Ethers
- Tutorial - Breve Introducción a Redux
- Parte 2 (Backend) - Aprende a crear una tienda virtual Blockchain aceptando ERC20 token