Bitcoin lightning machine-to-machine API payments

The Bitcoin lightning network is growing quickly. The lightning network is an exciting second layer protocol on top of the Bitcoin network that allows to send real near-instant payments and is perfectly suited for micro-/nano-transactions.

The tools already work great and make it super easy for developers to integrate with the lightning network.

I’ve lately experimented with it and built a demo to show machine-to-machine API payments. It allows the server to request a payment from the client; the client can automatically pay the invoice to access the resource from the server.

The basic workflow is as follows:

  1. Client sends a request to the server
  2. Server response with an invoice
  3. Client pays and sends a proof to the server
  4. Server responds with the requested resource

To make it easy for the developer all this can happen in the background so the payment logic can be abstracted and hidden from the developer.

Here is a small ruby application that exposes an endpoint to convert markdown to pdf but requires the client to pay 100 satoshi (currently 0.44 cent) per request.

You can find the code here on GitHub. And I made a short video showing how it works:

Introducing rack-lightning

To make it easy for every ruby developer to add lightning payment requests to any ruby application I've written rack-lightning.

rack-lightning is a rack middleware that handles the lightning invoice creation and validation on the server.

A full usage example can be found on GitHub, but it is not more than adding one line of rack code:


use Rack::Lightning, { price: 100 } 

Have a look at the GitHub page for more information.


Introducing lightning faraday middleware

And to make it easy on the client side I've written a faraday middleware that handles the payment requests on the client: faraday_ln_paywall

The middleware handles the payment of the invoice. Her is a quick useage example:


# initialize a client
client = Faraday.new(:url => 'https://lightning-2pdf.herokuapp.com/') do |faraday|
  faraday.use FaradayLnPaywall::Middleware, { max_amount: 100 }
  faraday.adapter  Faraday.default_adapter
end

# use the client to do API calls:
puts client.post("/convert/pdf", "# Hallo Welt").body

Head over to the GitHub repository for more information.


Similar projects

A few years back I did something similar with pure bitcoin.

And an exciting project is lightning.ws that does something similar in Go