※ Lagom

Javascript

To integrate Lagom micro-payment directly on your NodeJS server, you can use the following function.

This is a function we use in our Cloudflare Worker example, and it’s directly usable without any further dependency.

async function CheckLagomPayment(request, page, amount) {
	const url = new URL(request.url)
	const lguid = url.searchParams.get('lguid')
	const lgts = url.searchParams.get('lgts')
	const lgsig = url.searchParams.get('lgsig')
	const lgid = url.searchParams.get('lgid')
	const lgamt = url.searchParams.get('lgamt')
	const verif = lguid + lgid + lgts + url.pathname + lgamt

	// check if timestamp is within 10 seconds
	const nowSec = Math.floor(Date.now() / 1000)
	if (nowSec > parseInt(lgts) + 10) {
		return false
	}

	// check amount and page are correct
	if (parseInt(lgamt) !== amount || page !== url.pathname) {
		return false
	}

	// check signature
	const hmac = await crypto.subtle.importKey('raw', new TextEncoder().encode(LAGOM_SECRET), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
	const signed = await crypto.subtle.sign('HMAC', hmac, new TextEncoder().encode(verif))
	const computed = Array.from(new Uint8Array(signed)).map(b => b.toString(16).padStart(2, '0')).join('')
	return lgsig === computed
}