summaryrefslogtreecommitdiff
path: root/c2ec/wallee-client.go
blob: a7f9f14036b4e8e88166b29c5032c25e85cddf35 (plain)
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha512"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

const WALLEE_AUTH_HEADER_VERSION = "x-mac-version"
const WALLEE_AUTH_HEADER_USERID = "x-mac-userid"
const WALLEE_AUTH_HEADER_TIMESTAMP = "x-mac-timestamp"
const WALLEE_AUTH_HEADER_MAC = "x-mac-value"

const WALLEE_READ_TRANSACTION_API = "/api/transaction/read"
const WALLEE_CREATE_REFUND_API = "/api/refund/refund"

const WALLEE_API_SPACEID_PARAM_NAME = "spaceId"

type WalleeCredentials struct {
	SpaceId            int    `json:"spaceId"`
	UserId             int    `json:"userId"`
	ApplicationUserKey string `json:"application-user-key"`
}

type WalleeClient struct {
	ProviderClient

	name        string
	baseUrl     string
	credentials *WalleeCredentials
}

func (wt *WalleeTransaction) AllowWithdrawal() bool {

	return strings.EqualFold(string(wt.State), string(StateFulfill))
}

func (wt *WalleeTransaction) AbortWithdrawal() bool {
	// guaranteed abortion is given when the state of
	// the transaction is a final state but not the
	// success case (which is FULFILL)
	return strings.EqualFold(string(wt.State), string(StateFailed)) ||
		strings.EqualFold(string(wt.State), string(StateVoided)) ||
		strings.EqualFold(string(wt.State), string(StateDecline))
}

func (wt *WalleeTransaction) FormatPayto() string {

	return fmt.Sprintf("payto://wallee-transaction/%d", wt.ID)
}

func (wt *WalleeTransaction) Bytes() []byte {

	reader, err := NewJsonCodec[WalleeTransaction]().Encode(wt)
	if err != nil {
		LogError("wallee-client", err)
		return make([]byte, 0)
	}
	bytes, err := io.ReadAll(reader)
	if err != nil {
		LogError("wallee-client", err)
		return make([]byte, 0)
	}
	return bytes
}

func (w *WalleeClient) SetupClient(p *Provider) error {

	cfg, err := ConfigForProvider(p.Name)
	if err != nil {
		return err
	}

	creds, err := parseCredentials(p.BackendCredentials, cfg)
	if err != nil {
		return err
	}

	w.name = p.Name
	w.baseUrl = p.BackendBaseURL
	w.credentials = creds

	PROVIDER_CLIENTS[w.name] = w

	return nil
}

func (w *WalleeClient) GetTransaction(transactionId string) (ProviderTransaction, error) {

	call := WALLEE_READ_TRANSACTION_API
	queryParams := map[string]string{
		WALLEE_API_SPACEID_PARAM_NAME: strconv.Itoa(w.credentials.SpaceId),
		"id":                          transactionId,
	}
	url := FormatUrl(call, map[string]string{}, queryParams)

	hdrs, err := w.prepareWalleeHeaders(url, HTTP_GET)
	if err != nil {
		return nil, err
	}

	t, status, err := HttpGet(url, hdrs, NewJsonCodec[WalleeTransaction]())
	if err != nil {
		return nil, err
	}
	if status != HTTP_OK {
		return nil, errors.New("no result")
	}
	return t, nil
}

func (sc *WalleeClient) FormatPayto(w *Withdrawal) string {

	return fmt.Sprintf("payto://wallee-transaction/%s", *w.ProviderTransactionId)
}

func (w *WalleeClient) Refund(transactionId string) error {

	call := WALLEE_CREATE_REFUND_API
	queryParams := map[string]string{
		WALLEE_API_SPACEID_PARAM_NAME: strconv.Itoa(w.credentials.SpaceId),
	}
	url := FormatUrl(call, map[string]string{}, queryParams)

	hdrs, err := w.prepareWalleeHeaders(url, HTTP_GET)
	if err != nil {
		return err
	}

	// TODO generate refund object. needs Completion and Transaction IDs
	refund := &WalleeRefund{
		Amount:            10,
		Completion:        10,
		ExternalID:        "",
		MerchantReference: "",
		Reductions:        []WalleeLineItemReduction{},
		Transaction:       10,
		Type:              "",
	}

	_, status, err := HttpPost[WalleeRefund, any](url, hdrs, refund, NewJsonCodec[WalleeRefund](), nil)
	if err != nil {
		LogError("wallee-client", err)
		return err
	}
	if status != HTTP_OK {
		return errors.New("no result")
	}
	return nil
}

func (w *WalleeClient) prepareWalleeHeaders(url string, method string) (map[string]string, error) {

	timestamp := time.Time.Unix(time.Now())

	base64Mac, err := calculateWalleeAuthToken(
		w.credentials.UserId,
		timestamp,
		method,
		url,
		w.credentials.ApplicationUserKey,
	)
	if err != nil {
		return nil, err
	}

	headers := map[string]string{
		WALLEE_AUTH_HEADER_VERSION:   "1",
		WALLEE_AUTH_HEADER_USERID:    strconv.Itoa(w.credentials.UserId),
		WALLEE_AUTH_HEADER_TIMESTAMP: strconv.Itoa(int(timestamp)),
		WALLEE_AUTH_HEADER_MAC:       base64Mac,
	}

	return headers, nil
}

func parseCredentials(raw string, cfg *C2ECProviderConfig) (*WalleeCredentials, error) {

	credsJson := make([]byte, len(raw))
	_, err := base64.StdEncoding.Decode(credsJson, []byte(raw))
	if err != nil {
		return nil, err
	}

	creds, err := NewJsonCodec[WalleeCredentials]().Decode(bytes.NewBuffer(credsJson))
	if err != nil {
		return nil, err
	}

	if !ValidPassword(cfg.CredentialsPassword, creds.ApplicationUserKey) {
		return nil, errors.New("invalid application user key")
	}

	// correct application user key.
	creds.ApplicationUserKey = cfg.CredentialsPassword
	return creds, nil
}

// This function calculates the authentication token according
// to the documentation of wallee:
// https://app-wallee.com/en-us/doc/api/web-service#_authentication
// the function returns the token in Base64 format.
func calculateWalleeAuthToken(
	userId int,
	unixTimestamp int64,
	httpMethod string,
	pathWithParams string,
	userKeyBase64 string,
) (string, error) {

	// Put together the correct formatted string
	// Version | UserId | Timestamp | Method | Path
	authMsgStr := fmt.Sprintf("%d|%d|%d|%s|%s",
		1, // version is static
		userId,
		unixTimestamp,
		httpMethod,
		pathWithParams,
	)

	authMsg := make([]byte, 0)
	if valid := utf8.ValidString(authMsgStr); !valid {

		// encode the string using utf8
		for _, r := range authMsgStr {
			rbytes := make([]byte, 4)
			utf8.EncodeRune(rbytes, r)
			authMsg = append(authMsg, rbytes...)
		}
	}

	key := make([]byte, base64.StdEncoding.DecodedLen(len(userKeyBase64)))
	_, err := base64.StdEncoding.Decode(key, []byte(userKeyBase64))
	if err != nil {
		LogError("wallee-client", err)
		return "", err
	}

	if len(key) != 32 {
		return "", errors.New("malformed secret")
	}

	macer := hmac.New(sha512.New, key)
	_, err = macer.Write(authMsg)
	if err != nil {
		LogError("wallee-client", err)
		return "", err
	}
	mac := make([]byte, 64)
	mac = macer.Sum(mac)

	return base64.StdEncoding.EncodeToString(mac), nil
}