-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathchapa.go
107 lines (83 loc) · 2.2 KB
/
chapa.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
package chapa
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
const (
chapaAcceptPaymentV1APIURL = "https://api.chapa.co/v1/transaction/initialize"
chapaVerifyPaymentV1APIURL = "https://api.chapa.co/v1/transaction/verify/%v"
)
type (
ChapaAPI interface {
PaymentRequest(request *ChapaPaymentRequest) (*ChapaPaymentResponse, error)
Verify(txnRef string) (*ChapaVerifyResponse, error)
}
Chapa struct {
apiKey string
client *http.Client
}
)
func New(apiKey string) *Chapa {
return &Chapa{
apiKey: apiKey,
client: &http.Client{
Timeout: 1 * time.Minute,
},
}
}
func (c *Chapa) PaymentRequest(request *ChapaPaymentRequest) (*ChapaPaymentResponse, error) {
data, err := json.Marshal(request)
if err != nil {
return &ChapaPaymentResponse{}, err
}
req, err := http.NewRequest(http.MethodPost, chapaAcceptPaymentV1APIURL, bytes.NewBuffer(data))
if err != nil {
return &ChapaPaymentResponse{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Close = true
resp, err := c.client.Do(req)
if err != nil {
return &ChapaPaymentResponse{}, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return &ChapaPaymentResponse{}, err
}
var chapaPaymentResponse ChapaPaymentResponse
err = json.Unmarshal(body, &chapaPaymentResponse)
if err != nil {
return &ChapaPaymentResponse{}, err
}
return &chapaPaymentResponse, nil
}
func (c *Chapa) Verify(txnRef string) (*ChapaVerifyResponse, error) {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf(chapaVerifyPaymentV1APIURL, txnRef), nil)
if err != nil {
return &ChapaVerifyResponse{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Close = true
resp, err := c.client.Do(req)
if err != nil {
return &ChapaVerifyResponse{}, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return &ChapaVerifyResponse{}, err
}
var chapaVerifyResponse ChapaVerifyResponse
err = json.Unmarshal(body, &chapaVerifyResponse)
if err != nil {
return &ChapaVerifyResponse{}, err
}
return &chapaVerifyResponse, nil
}