WebLN examples in simple HTML/JS apps
WebLN provides that programmatic, permissioned interface for letting web applications to request payments from users (among other things). It gives web apps a simple JavaScript function to initiate a payment AND get a receipt in return to validate the payment. With WebLN developers have a native way to program payment flows into applications and because of the p2p nature of the lightning network no expensive payment service provider is required. This is also possible in a simple client side JavaScript application.
To show how this works and how to get started with WebLN here are two examples where I added payments to some random, nice community applications that are featured on Replit.
The first app is warms by MaxBittker. A fun little app that lets you draw moving lines. :) Try it, it's fun and looks great: https://warms.maxbittker.repl.co/
So we add some lines of JS to require the user a payment of 21 sats ( less than $1 cent) for drawing each a line. Here is my fork:
We request a payment in the drawEnd function. The implemention for this is in the payment.js file:
export async function requestPayment() {
if (!window.webln) {
alert("Use a modern webln enabled browser. For example with the getalby.com Browser Extension.");
return false;
}
// calling enable() to request permission from the user
await window.webln.enable();
const invoice = await requestInvoice();
// initiating the payment. The user will be prompted for confirmation
const response = await window.webln.sendPayment(invoice);
return !!response.preimage; // we just check for the preimage but don't validate it for now
}
That's it. This now asks to user to pay 21sats for each drawn line. You can try it here! (pro-tip: set a budget in Alby for auto-payments)
The second app is a simple image editor by Adarsh Giri who studies in class 8th in Jawahar Navodaya Vidyalaya Sinhachwar Ballia.
We use the same code as above and require the user to pay 21sats to download the edited image. Here is my fork with the WebLN code.
Those are quite simple, plain HTML/JS examples. The possibilities are endless. Never before it was possible to add such monetization options on web apps.
So, where do you add Lightning to your app?
Check out the WebLN guide: webln.guide
And install the Alby Extension to enable WebLN in your Browser.