※ Lagom

Cloudflare

If you use a Cloudflare Worker on your platform, you need to integrate this function in your codebase to enable Lagom micro-payment.

This repository includes a full example showing you how to build and deploy a Worker that integrates with Lagom.

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
}