Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const cors = require('cors')
- const bodyParser = require('body-parser')
- const CashPay = require('@developers.cash/cash-pay-server-js')
- const catalog = require('./public/catalog.json')
- async function main() {
- const app = express()
- app.use(express.static('public'))
- app.use(bodyParser.json())
- app.use(cors())
- // This will pull the Public Key from the pay.infra.cash server
- let webhook = new CashPay.Webhook()
- await webhook.addTrusted('https://pay.infra.cash')
- // Let's store a list of Orders as InvoiceID:Status pairs.
- let orders = {}
- app.post('/request-invoice', async (req, res) => {
- // Don't trust the browser to send correct prices and item details. Use the item id and read from the catalog directly.
- let items = req.body.cart.map(cartItem =>
- catalog.find((catalogItem) => cartItem.id === catalogItem.id)
- )
- // Calculate the total amount due
- let total = items.reduce((total, item) => total += item.price, 0)
- // Set the parameters of the invoice
- let invoice = new CashPay.Invoice()
- invoice.addAddress('bitcoincash:qplf0j8krjrsv95v0t3zj9dc4rcutw5khyy8dc80fu', `${total}USD`)
- .setWebhook(['broadcasting', 'broadcasted', 'confirmed'], 'https://store.example.developers.cash/webhook')
- .setPrivateData({
- customer: req.body.customer, // Customer details
- items: items
- })
- // Actually create the invoice
- await invoice.create()
- // Create an entry for this InvoiceID in our list of orders
- orders[invoice.invoice.id] = 'pending'
- // Return the invoice (this method will omit sensitive data (unless 'true' is passed as a param)
- return res.send(invoice.getPayload())
- })
- app.post('/webhook', async (req, res) => {
- try {
- // An exception will be thrown if signature does not match
- await webhook.verifySignature(req.body, req.headers)
- // The type of event (e.g. broadcasting, broadcasted or confirmed)
- let eventType = req.body.event
- let invoice = req.body.invoice
- // Make sure this invoice was created by us
- if (typeof orders[invoice.id] === 'undefined') {
- throw new Error(`${eventType}: Invoice ${invoice.id} does not exist in our orders.`)
- }
- // Mark the invoice as broadcasting/broadcasted/confirmed
- orders[invoice.id] = eventType
- // Get the data associated with the invoice
- let data = JSON.parse(invoice.options.privateData)
- // Output event type and list of items to console
- console.log(`${data.customer.email} ${eventType}:`)
- console.log(` ${data.customer.comments}`)
- data.items.forEach(item => { console.log(` ${item.id}: ${item.title}`) })
- // You must send a 200 response, otherwise CashPay will throw an error
- res.status(200).send('Success')
- } catch(err) {
- console.log(err)
- res.status(500).send(err.message)
- }
- })
- let server = app.listen(8080, function () {
- console.log('Server is now running on Port 8080')
- })
- }
- main();
Add Comment
Please, Sign In to add comment