/
coin_payments.go
157 lines (134 loc) · 3.83 KB
/
coin_payments.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package payments
import (
"bytes"
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
"github.com/bcmk/siren/lib"
"github.com/shopspring/decimal"
)
// CoinPaymentsAPI implements CoinPayments API
type CoinPaymentsAPI struct {
nonce int64
publicKey string
privateKey string
httpClient *http.Client
apiURL string
ipnURL string
debug bool
}
// NewCoinPaymentsAPI returns new CoinPaymentsAPI object
func NewCoinPaymentsAPI(publicKey, privateKey, ipnURL string, timeoutSeconds int, debug bool) *CoinPaymentsAPI {
return &CoinPaymentsAPI{
nonce: time.Now().UnixNano(),
publicKey: publicKey,
privateKey: privateKey,
httpClient: &http.Client{Timeout: time.Duration(timeoutSeconds) * time.Second},
apiURL: "https://www.coinpayments.net/api.php",
ipnURL: ipnURL,
debug: debug,
}
}
type kv struct {
k string
v string
}
func calcHMAC(message, secret string) string {
hash := hmac.New(sha512.New, []byte(secret))
_, err := hash.Write([]byte(message))
lib.CheckErr(err)
return hex.EncodeToString(hash.Sum(nil))
}
func (api *CoinPaymentsAPI) coinpaymentsMethod(method string, additionalParams []kv) (body []byte, err error) {
now := time.Now().UnixNano()
if now > api.nonce {
api.nonce = now
}
params := []kv{
{"version", "1"},
{"cmd", method},
{"key", api.publicKey},
{"nonce", strconv.FormatInt(api.nonce, 10)},
{"format", "json"}}
params = append(params, additionalParams...)
values := url.Values{}
for _, i := range params {
values.Set(i.k, i.v)
}
payload := values.Encode()
req, err := http.NewRequest("POST", api.apiURL, bytes.NewBuffer([]byte(payload)))
if err != nil {
return nil, fmt.Errorf("cannot create request: %v", err)
}
api.nonce++
hash := calcHMAC(payload, api.privateKey)
req.Header.Set("HMAC", hash)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if api.debug {
lib.Ldbg("creating transaction: %s", payload)
lib.Ldbg("headers: %v", req.Header)
}
res, err := api.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("cannot perform request: %w", err)
}
defer lib.CloseBody(res.Body)
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("cannot read body: %w", err)
}
if api.debug {
lib.Ldbg("got response: %s", string(body))
}
return
}
// Transaction represents CoinPayments transaction
type Transaction struct {
Amount decimal.Decimal `json:"amount"`
Address string `json:"address"`
DestTag flex `json:"dest_tag"`
TXNID string `json:"txn_id"`
ConfirmsNeeded string `json:"confirms_needed"`
Timeout uint32 `json:"timeout"`
CheckoutURL string `json:"checkout_url"`
StatusURL string `json:"status_url"`
QRCodeURL string `json:"qrcode_url"`
}
type transactionResponse struct {
Error string `json:"error"`
Result transactionWrapper `json:"result"`
}
// CreateTransaction creates transaction object
func (api *CoinPaymentsAPI) CreateTransaction(amount int, currency string, email string, transactionUUID string) (res *Transaction, err error) {
body, err := api.coinpaymentsMethod("create_transaction", []kv{
{"amount", strconv.Itoa(amount)},
{"currency1", "USD"},
{"currency2", currency},
{"buyer_email", email},
{"ipn_url", api.ipnURL},
{"custom", transactionUUID},
})
if err != nil {
return
}
parse := &transactionResponse{}
if err = json.Unmarshal(body, parse); err != nil {
return nil, fmt.Errorf(`cannot unmarshal "%s", %w`, string(body), err)
}
if parse.Error != "ok" {
return nil, errors.New(parse.Error)
}
if parse.Result.Transaction == nil {
return nil, fmt.Errorf(`cannot unmarshal "%s", %w`, string(body), err)
}
res = parse.Result.Transaction
return
}