-
Notifications
You must be signed in to change notification settings - Fork 1
/
server-btcpay.lua
84 lines (71 loc) · 2.93 KB
/
server-btcpay.lua
1
-- server.luadofile("credentials.lua")print("server code begin ---")local srv = net.createServer(net.TCP, 30)local function discardOldIPN(invoiceID, payload) local currentTime = rtctime.get() print("Current time", currentTime) local _, indexEndApiCallTime = string.find(payload, "\"currentTime\": ") local apiCallTime = string.sub(payload, indexEndApiCallTime, indexEndApiCallTime + 10) print("API call time", apiCallTime) if (currentTime - apiCallTime) > 10 then print(invoiceID, "IPN expired") print(currentTime - apiCallTime, "seconds old") return false end return trueendlocal function getInvoiceID(payload) local _, indexEndInvoiceID = string.find(payload, "id") if indexEndInvoiceID ~= nil then return string.match(payload, [["id":%s+"([^"]+)]]) endendlocal function onReceive(sck, payload) local invoiceID = getInvoiceID(payload) -- Get IPN code local _, indexEndCode = string.find(payload, "code") if indexEndCode ~= nil then local code = string.sub(payload, indexEndCode + 4, indexEndCode + 7) -- If invoice_completed IPN if code == '1006' then print(invoiceID, code, "IPN final") -- Discard old 1006 IPNs with timestamp comparison (10 sec difference max) -- currentTime and apiCallTime are supposed to be equal if discardOldIPN(invoiceID, payload) == false then return end -- Get invoice data local url = "https://btcpay.bitcoin-studio.com/invoices/" .. invoiceID local headers = "Accept: */*\r\nContent-Type: application/json\r\nAuthorization: Basic" .. BTCPAY_BASIC .. "\r\n" http.get(url, headers, function(code, res) if (code < 0) then print("HTTPS request failed with code", code) else print("HTTPS request success") local t = sjson.decode(res) print("Coffee selected", t.data.itemDesc) if(t.data.itemDesc == "Master Origin Ethiopia")then activateServo(2) elseif(t.data.itemDesc == "Fortissio Lungo")then activateServo(3) elseif(t.data.itemDesc == "Capriccio Espresso")then activateServo(4) elseif(t.data.itemDesc == "Arpeggio Intenso")then activateServo(5) elseif(t.data.itemDesc == "Caramelito Variation")then activateServo(6) end end end) else print(invoiceID, code, "IPN non-final") end end sck:send("HTTP/1.1 200 OK\r\n\r\n", function(sck) sck:close() end)endif srv then print("start listening on port 80...") srv:listen(80, function(conn) conn:on("receive", onReceive) end)endprint("server code end ---")