GithubHelp home page GithubHelp logo

vivid-iov-labs / web-monetization-revenue-share Goto Github PK

View Code? Open in Web Editor NEW
6.0 4.0 0.0 14.84 MB

Using probabilistic revenue sharing model and a Solidity smart contract to support revenue sharing of Web Monetization micropayments between predefined recipients.

License: MIT License

JavaScript 100.00%
coil ilp ilp-payment javascript monetization web-monetization webmonetization interledger

web-monetization-revenue-share's Introduction

Web Monetization Revenue Sharing

Use web monetization probabilistic revenue sharing in the backend together with a smart contract.
Also able to include receipt verification.
This module uses as default smart contract connection settings for Infura.

Install

npm install web-monetization-revenue-share

Setup

Smart Contract ABI

You can find an example of a working Smart Contract here.

  • Get the ABI of your smart contract (make sure there is at least one payment pointer in the smart contract)

  • Store ABI in your project (eg: smartContractInfo.json)

    {
      "address": "yourSmartContractAddress",
      "ABI": [
        // your smart contract ABI
      ]
    }
    

Payment Pointers List

  • Create a list of payment pointers in case you don't want to use a smart contract (eg: paymentPointers.js)

    const pointers = {
      '$alice.example': 50,
      '$bob.example': 40,
      '$connie.example': 9,
      '$dave.example': 1
    }
    
    module.exports = pointers
    

Config File

  • Create a config file to store all the parameters required (eg: config.js)

    const config = {
      server: {
        port: 1337
      },
      useSmartContract: 'true',
      useReceiptVerification: 'false',
      paymentPointersPath: './paymentPointers',
      receiptVerification:{ 
        service: 'https://webmonetization.org/api/receipts/',
        verifier: 'https://webmonetization.org/api/receipts/verify'
      },
      smartContract: {
        provider: 'rinkeby', // use the network of your choice
        key: yourKeyForRinkeby, // eg: If using Infura to access rinkeby use your Infura Project Key here 
        smartContractInfoFilePath: './smartContractInfo.json'
      }
    };
    
    module.exports = config;
    

Use

const wmRevenueShare = require('web-monetization-revenue-share')
wmRevenueShare.setUp('/config')
const paymentPointerUrl = await wmRevenueShare.getPointerUrl()

Express Example

How to include it into your expressJS server.

server.js (on the backend)
var express = require('express');
var app = express();
const fetch = require("node-fetch");
var cors = require('cors')
const config = require('./config')
const wmRevenueShare = require('web-monetization-revenue-share')

app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use(cors())

const PORT = config.server.port;
app.listen(PORT, () => {
  console.log(`App is running on port ${PORT}`);
});

wmRevenueShare.setUp('./config')

// Your endpoint that you will reach from the frontend.
app.post('/verifyReceipt', async (req, res) => {
  const resp = await fetch(config.receiptVerification.verifier, {
    method: 'POST',
    body: req.body.receipt
  })

  const { amount } = await resp.json()
  console.log('Received ' + amount)

  // backend logic for new paid amount

  res.send({ message: 'ok', data: { received: amount } })
})

app.get('/', async function (req, res, next) {
  // is this request meant for Web Monetization?
  
  if (req.header('accept').includes('application/spsp4+json')) {
    console.log('Revenue sharing active')
    const paymentPointerUrl = await wmRevenueShare.getPointerUrl()
    console.log(`Payment pointer: ${paymentPointerUrl}`)

    // redirect to our chosen payment pointer so they get paid
    res.redirect(302, paymentPointerUrl)
  } else {
    // if the request is not for Web Monetization, do nothing
    console.log('Revenue sharing not active')
    next()
  }
})

index.ejs (on the frontend)

Your frontend could be hosted on a different server, if desired

<head>
  <meta name="monetization" content="https://your-deployed-server-instance-url/">  
  
  <!-- Use this script for receipt verification -->
  <script>

    if (document.monetization) {
      document.monetization.addEventListener('monetizationprogress', async event => {
        // A payment has been received.
        console.log('A payment has been received.')
        console.log(event.detail.receipt)

        // Connect to your site’s backend to validate the payment. This does NOT connect directly to the receipt verifier.
        const res = await fetch('https://your-deployed-server-instance-url/verifyReceipt', {
          method: 'POST',
          headers: {
            'content-type': 'application/json'
          },
          body: JSON.stringify({
            receipt: event.detail.receipt
          })
        })
      })
    }
  </script>
</head>

You may find a full working example here.

Test

Test the npm package

  • Download repository

    git clone https://github.com/Vivid-IOV-Labs/web-monetization-revenue-share.git
    
  • Install

    npm install
    
  • Run tests

    npm test
    

web-monetization-revenue-share's People

Contributors

ntzi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.