125 lines
1.9 KiB
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 int, id string) (gin.H, error) {
|
|
|
|
result := make(gin.H)
|
|
reqData := gin.H{
|
|
"amount": 10,
|
|
"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)
|
|
}
|
|
|
|
}
|