satdress-custom2/lnurl.go

104 lines
2.5 KiB
Go
Raw Normal View History

2021-08-13 16:21:00 +00:00
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
2022-01-18 23:50:47 +00:00
"strings"
2021-08-13 16:21:00 +00:00
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
)
func handleLNURL(w http.ResponseWriter, r *http.Request) {
2022-01-18 23:50:47 +00:00
username := mux.Vars(r)["user"]
2021-08-13 16:21:00 +00:00
2022-01-18 23:50:47 +00:00
domains := getDomains(s.Domain)
domain := ""
if len(domains) == 1 {
domain = domains[0]
} else {
hostname := r.URL.Host
if hostname == "" {
hostname = r.Host
}
for _, one := range getDomains(s.Domain) {
if strings.Contains(hostname, one) {
domain = one
break
}
}
if domain == "" {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("incorrect domain"))
return
}
}
params, err := GetName(username, domain)
2021-08-13 16:21:00 +00:00
if err != nil {
2022-01-18 23:50:47 +00:00
log.Error().Err(err).Str("name", username).Str("domain", domain).Msg("failed to get name")
2021-08-20 12:32:45 +00:00
json.NewEncoder(w).Encode(lnurl.ErrorResponse(fmt.Sprintf(
2022-01-18 23:50:47 +00:00
"failed to get name %s@%s", username, domain)))
2021-08-20 13:08:30 +00:00
return
2021-08-13 16:21:00 +00:00
}
2022-01-18 23:50:47 +00:00
log.Info().Str("username", username).Str("domain", domain).Msg("got lnurl request")
2021-08-13 16:21:00 +00:00
if amount := r.URL.Query().Get("amount"); amount == "" {
// check if the receiver accepts comments
var commentLength int64 = 0
// TODO: support webhook comments
// convert configured sendable amounts to integer
minSendable, err := strconv.ParseInt(params.MinSendable, 10, 64)
// set defaults
if err != nil {
minSendable = 1000
}
maxSendable, err := strconv.ParseInt(params.MaxSendable, 10, 64)
if err != nil {
maxSendable = 1000000000
}
2021-08-13 16:21:00 +00:00
json.NewEncoder(w).Encode(lnurl.LNURLPayResponse1{
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
2022-01-18 23:50:47 +00:00
Callback: fmt.Sprintf("https://%s/.well-known/lnurlp/%s", domain, username),
MinSendable: minSendable,
MaxSendable: maxSendable,
2021-08-13 16:21:00 +00:00
EncodedMetadata: makeMetadata(params),
CommentAllowed: commentLength,
Tag: "payRequest",
})
} else {
msat, err := strconv.Atoi(amount)
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("amount is not integer"))
return
}
bolt11, err := makeInvoice(params, msat, nil)
2021-08-13 16:21:00 +00:00
if err != nil {
json.NewEncoder(w).Encode(
lnurl.ErrorResponse("failed to create invoice: " + err.Error()))
return
}
json.NewEncoder(w).Encode(lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
PR: bolt11,
Routes: make([][]lnurl.RouteInfo, 0),
Disposable: lnurl.FALSE,
SuccessAction: lnurl.Action("Payment received!", ""),
})
// send webhook
go func() {
// TODO
}()
}
}