You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bit4sat/ln/charge.go

125 lines
1.9 KiB
Go

package ln
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"time"
"github.com/gin-gonic/gin"
)
const (
CurMSat = iota
CurSat
CurUSD
)
const (
LNChargeAPIEnv = "LN_CHARGE_API"
LNChargeTokenEnv = "LN_CHARGE_TOKEN"
InfoEndpoint = "info"
InvoiceEndpoint = "invoice"
)
var (
LNCEndpoint string
LNChargeToken string
)
type Charge struct {
client *http.Client
}
func NewCharge() *Charge {
netTransport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
c := &http.Client{
Timeout: time.Second * 10,
Transport: netTransport,
}
return &Charge{
client: c,
}
}
func (c *Charge) Info() (gin.H, error) {
result := make(gin.H)
resp, err := c.client.Get(getUrl(InfoEndpoint))
if err != nil {
return nil, err
}
jsonDec := json.NewDecoder(resp.Body)
jsonDec.Decode(&result)
return result, nil
}
func (c *Charge) Invoice(amount float32, id string) (gin.H, error) {
result := make(gin.H)
reqData := gin.H{
"amount": amount,
"currency": "USD",
"description": fmt.Sprintf("bit4sat upload: %s", id),
}
jsonEnc, err := json.Marshal(reqData)
if err != nil {
return nil, err
}
resp, err := c.client.Post(getUrl(InvoiceEndpoint),
"application/json",
bytes.NewReader(jsonEnc))
if err != nil {
return nil, err
}
result = make(gin.H)
jsonDec := json.NewDecoder(resp.Body)
jsonDec.Decode(&result)
return result, nil
}
func getUrl(endpoint string) string {
url, err := url.Parse(fmt.Sprintf("http://api-token:%s@%s/%s",
LNChargeToken,
LNCEndpoint,
endpoint))
if err != nil {
log.Fatal(err)
}
return url.String()
}
func init() {
var set bool
LNCEndpoint, set = os.LookupEnv(LNChargeAPIEnv)
if !set {
log.Fatalf("%s not set", LNChargeAPIEnv)
}
LNChargeToken, set = os.LookupEnv(LNChargeTokenEnv)
if !set {
log.Fatalf("%s not set", LNChargeAPIEnv)
}
}