Skip to Content
Technical Articles
Author's profile photo Andrew Lunde

Pay Bitcoin Per Request : Harnessing Lightning for Micropayments

Why Lightning is like a Bubblegum Machine




This blog post is an extension of concepts first explored in my blog series on the Theta Blockchain : The Case for Theta.  In the final installment of that series(Part 5), I attempted to show how the layer-1 off-chain micropayments features could be utilized to monetize a simple crypto rate fetching service.  Such a service would be critical to S/4 HANA Financials accounting in order to get up to date crypto spot pricing for reporting as well as historical pricing data in order to support forecasting and planning.  Currently SAP customers wishing to diversify their treasury holdings with alternatives to sovereign currencies could follow the strategy outlined below as a stop-gap measure, but I created the following as a proof-of-concept only and it is in no way intended to be considered an expression of any SAP recommended guidance and/or best practice.

Important Note:  To simplify this proof-of-concept effort, I assumed that the tax treatment of cryptocurrencies to be the same as that other sovereign currencies.  As of the writing of this blog post(August, 2023), this is only true in the case of El Salvador which passed legislation declaring Bitcoin(BTC) as legal tender in September of 2021.  Most jurisdictions at this time consider cryptocurrencies as property and are thus subject to income and capital gain/loss tax treatment.


Redefining the SaaS monetization scale:


But before getting into the technical details, I’d like to spectrum of monetization as it pertains to software and in particular software as a service.

Software has traditionally been sold under a license model.  Because software is easy to copy, a license protects the software provider(at least legally) from any unauthorized resale.  Software was typically installed on the user’s machine before it could be effectively evaluated to be sure it met the customer’s needs.  Short of some sort of return policy, the customer had to spend the full retail price and the effort to install it and the time to evaluate it before being able to evaluate its effectiveness for their specific case.

As software systems moved to the cloud, the method of paying for software shifted to subscriptions.  Now you didn’t have to pay as much up front, but your costs were recurring.  You still needed to pay at least a month’s worth of service and usually had to sign a contract or provided a payment method that the software provider could keep on file for recurring payments.  If you were dissatisfied, you could cancel, but how would you know your credit-card would not be hacked or if you’d continue to get invoices?  Another issue is that you often had to pay for a much broader set of features that you actually ended up using, so costs remained high and flexibility low.

If you haven’t caught on so far, SAP has been progressing along this journey of first charging for licenses(+annual maintenance), then to cloud subscriptions, and now even more options.  When customers wanted more flexibility and to constrain costs, SAP introduced Cloud Platform Enterprise Agreement(CPEA) that required an up-front payment of a quantity of services that the customer could then “work against” during the contact period using it for whatever they wanted.  Unfortunately, any unused allocation were lost if not used and overages were billed at retail rates.  Still for this to work it was necessary to have a legal billing relationship established and that’s a lot to ask if you just want to try something out.

In order to reduce the up front costs and term commitment of CPEA, a Pay-As-You-Go commercial model was introduced that even included a subset of “Free Tier” services such that if you were careful to build only using those services you could explore what SAP has to offer without running up a bill and only start paying when you got serious.  However, you were still required to effectively let SAP “have your card on file” for when you did.

Now I know that I’ve skipped over the Trial environment, but either it or the “Free Tier” services can be everything you need to explore and try things and decide completely what you want to pay for before you spend your first dime with SAP.  However, I contend that this still doesn’t cover all of a prospective customers needs and/or SAP’s marketing desires.  Sometimes you want to build with a real full-fledged service, no limits, no restrictions, no barriers AND you’re willing to pay for that service to be absolutely certain it’s going to work for you now and in the long term.  You don’t want to be locked into any contractual engagement and if you want to leave, you can leave at any time you want.  Oh, and did I mention that once you fall in love with the service and have spent many man-months building on it, you don’t want to have to move it to some other production system.  It should just work where it is.  On you other end of the sales funnel, you may want to be able to easily offer a “try before you buy” experience or maybe the marketing department wants to offer a coupon code for some initial usage etc.

How can you build a system to offer software as a service, get paid for every type of usage, and not have to enter into the commitment of any sort of contract?  Pay Bitcoin Per Request…

Now I’m presuming your service is in the form of an API, but the same mechanism applies no matter what you want to charge for(CPU, storage, bandwith, forecasts, stock picks, paragraphs of GenAI created masters thesis).  The key feature that makes this viable is the ability to receive a request, provide some value, generate an invoice, get paid for that invoice, return the results of the value to the requestor in under 30 seconds.  Why 30?  Because a typical HTTP request will time out after about 30 seconds.


A primer on Bitcoins’ Layer-2 Lightning:


As described in part 5 of my Theta blog series, the type of micropayments just described are accomplishable using the Theta Layer-1 off-chain micropayment feature.  With Bitcoin being the predominant crypto currency and with institutional and enterprise investors becoming more interested in taking on Bitcoin not only as a diversifying asset but also means of settlement, it would be desirable if Bitcoin could also be used for micropayments.  The Bitcoin Layer-2 Lightning Network indeed provides a similar capability albeit implemented a bit differently.

Both blockchains require that some amount of value be “tied up” before hand in order to facilitate the micropayment functionality.  In the case of Theta, it’s a “reserve” on the mainnet, on Lightning, it’s opening a “payment channel”.  I won’t get into the details of Lightning Network as there are many resources that can explain it better than I.  The salient point is that a special “open channel” transaction is created on the mainnet chain that includes a secondary “close channel” transaction that will be activated later when the 2 parties want to “settle up” their balances. While on Theta a future time(block time) is given to trigger the settlement of the reserve, on Lightning the 2 parties cooperatively(or forcibly) decide when to close the channel.  While the mechanism is open the micropayments can flow without any interaction by (or knowledge of) their respective mainnet blockchains.  The micropayments flow at network speed and are considered “settled” once paid(Theta users must decide when to take an aggregate micropayment back on-chain for payment but is free to do so during the reserve’s lifetime).

In the case of the Lightning Network, this can happen in the matter of a few seconds and completely withing the context of an API call and that’s what makes this approach viable from a monetization standpoint.


Lightning Process Flow:


When a lightning node want’s to get paid, it creates an encoded invoice for an amount.  It then sends that invoice(through the network) to the node responsible for payment.  The paying node then pays the invoice and the promised value is delivered(not necessarily to the paying node as we’ll see shortly).  Lightning channels are opened between Lightning nodes and it’s not important that the invoicing nodes have a direct channel between each other, only that they are on the network and discoverable.

The following flow diagram is a simplified view of the process.

┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐
│  Service   │ │  Service   │ │   Payee    │ │   Payer    │
│  Consumer  │ │  Provider  │ │   Node     │ │   Node     │
└────────────┘ └────────────┘ └────────────┘ └────────────┘
      │              │              │              │
      │              │              │              │
      ├───Request───►│              │              │
      │              │              │              │
      │           Do Work           │              │
      │              │              │              │             
      │              ├─────Bill────►│              │              
      │              │              │              │
      │              │       Create Invoice        │
      │              │              │              │
      │              │              ├───Invoice───►│               
      │              │              │              │
      │              │              │         Pay Invoice
      │              │              │              │
      │              │              │◄──Payment────│              
      │              │              │              │
      │              │      Receive Payment        │
      │              │              │              │
      │              │◄────ACK──────│              │              
      │              │              │              │
      │         Prep Results        │              │
      │              │              │              │
      │◄──Response───│              │              │               
      │              │              │              │

Use Case + Demo:

I really wanted to demonstrate the viability of this process in a real-world enterprise context so I picked SAP S/4 Hana Financial as my service consumer.  If SAP enterprise customers wanted to take on Bitcoin as an investment asset, they’d want a way to pull in the latest price of Bitcoin in relation to the sovereign currency that they use for their accounting.  Crypto Exchanges such as Binance provide such an API, and I could wrap that up and provide it in a Datafeed format that S/4 Hana is already designed to consume.  I am not a UI designer by trade so forgive the ugly HTML interface.  The point is to show that the mechanism works end to end in a timely way.

In order to keep this post from getting too long, I won’t get into every detail here.  If you’re interested, you can take a look at the fully functional project on github under the CryptoAssetsSubleger repo.

As mentioned at the top of this post, I’m pretending that BTC is a valid currency and treating it as such in S/4 Hana.  In order to do this you need to define a new currency, set it’s decimal precision, set it’s conversion ratios, associate it with your datafeed as a currency pair that is being provided etc.

The astute of you reading this will notice that I’m using a currency code MBTC instead of BTC.  This is due to a limitation on the width of the rate exchange table(TCURR).  Currently this table can only contain rates up to 4 digits to the left of the decimal point.  Since the price of BTC in USD is hovering around $30,000 and could likely go to 5 or even six decimal places, these values won’t fit. I’m actually storing rates as MilliBTC(MBTC) which is 1,000th of a BTC and then defining a ration of MBTC/BTC of 1000/1 to allow for BTC calculations.  This is internal S/4 HANA issues and shouldn’t affect our story today.

Once you’ve got all the S/4 side of things set up, you can generate a pull of data through your service by using transaction TBD4.



In order for the ensuing Lightning invoice to be paid we need to set up a client that will respond to an incoming invoice and pay it.  This is where a bit of a dilemma is presented.  Normally Lightning wallet software is designed so that a human user will manually take action to pay for an invoice.  This might be OK for a one-off request where there is someone waiting to trigger the payment, but doesn’t work for automatic or periodic payment requests.  In addition, we need a way to get the invoice to the anticipated payer.  To do this our service provider by providing a websocket channel to the payer’s browser that has a browser plugin that functions as a Lightning client.  Let’s see how that happens in this context.



We execute the request in S/4 Hana.



And we see that the websocket has sent the invoice to the browser page and the plugin has popped up prompting the user to pay the invoice.  I’m using a plugin called Alby in this case.


I use a web based Lightning Node tool called Thunderhub and we can see that indeed an invoice got created and was paid.



Once the user sees the notice and pays in the invoice, the process can continue.  But do you remember the 30 second timeout I mentioned at the beginning of this post?  If the payment isn’t received in time the requesting call will time out and get dropped.  We don’t want that to happen and that’s where the Alby plugin shines.  Once a web domain has been allowed for payments, Alby will allow you set a “budget” for payments against invoices from that domain and will make payments automatically for you up until you hit your budget(or revoke your approval).  Now as long as the payer keeps their browser open the websocket will continue to receive and pay invoices automatically.


We can now see that indeed our rates were fetched from our service and the results returned(and paid for) in just a few seconds.

In my experiments, it seems like the whole end-to-end flow usually takes about 3-5 seconds which is well under the 30 second threshold I was shooting for.  There may be more network between the various nodes and servers, but it’s a pretty promising result.




The fact that all of this can be performed for as little as a few satoshis(at the time of this post, the cost of a Satoshi was $0.0002954 USD or nearly 1/34th of a cent) per request and the settlement is final in the Lightning context without requiring any party to enter into a contractual agreement is amazing.

Time to monetize those lazy graduate students!


Partners: If you have a question, click here to ask it in the SAP Community . Be sure to tag it with Partnership and leave your company name in the question so that we can better assist you.


Assigned Tags

      You must be Logged on to comment or reply to a post.
      Author's profile photo Ryan Fleischmann
      Ryan Fleischmann

      Great blog per usual!

      One consideration to be cautious of is the reliability/suitability of the price data feed arriving from a single centralized exchange. Even the largest exchanges such as Binance can have market manipulations - especially when there's active buy/sell zones for different market orders on the specific exchange. Apart from this - when the 2 parties have to settle their books in their local fiat currency, there has to be an agreed upon market value for the BTC and a credibly neutral data source for such data.

      To make the price feed more predictably stable and fair in prod - this is what Chainlink price feeds are really good for and its what nearly all high-volume DeFi apps like Aave and Uniswap rely on. They collect and weigh data from multiple sources. I built a project last year that integrates the Chainlink price feeds to this same currency rate tracking in S/4. Check it out!

      Author's profile photo Andrew Lunde
      Andrew Lunde
      Blog Post Author


      You are indeed correct and thanks for pointing out this weakness.  I didn't get into the "authority" of the exchange being queried, or even more so the "auditibility" of it.  As you've probably noticed, the granularity of the quote may change depending on how far back in history you go.  If you query now, you might get the 15 minute delayed value, but if you ask for historical > 1 year, you might get the daily average value.  This starts to matter when you need precise and traceable data.  I've been working with a data provider called Lukka on this very topic.  I see from your github that you stash the results in IPFS for distribution which is cool as well.

      We should talk and compare notes.  -Andrew