-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
348 lines (283 loc) · 9.4 KB
/
client.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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package pingen
import (
"context"
"fmt"
"time"
log "github.com/sirupsen/logrus"
"github.com/go-resty/resty/v2"
)
type Client struct {
clientID string
clientSecret string
baseUrl string
identiyUrl string
organisationId string
bearer *AuthSuccess
bearerExpiry time.Time
httpClient *resty.Client
authClient *resty.Client
}
// Creates a new client struct.
func NewClient(clientID string, clientSecret string, useProd bool, organisationId string, ctx context.Context) (*Client, error) {
c := &Client{}
c.clientID = clientID
c.clientSecret = clientSecret
c.organisationId = organisationId
if useProd {
c.baseUrl = "https://api.v2.pingen.com"
c.identiyUrl = "https://identity.pingen.com"
} else {
c.baseUrl = "https://api-staging.v2.pingen.com"
c.identiyUrl = "https://identity-staging.pingen.com"
}
//order is important, auth needs to be initialized first
c.authClient = resty.New()
c.authClient.SetBaseURL(c.identiyUrl)
c.httpClient = resty.New()
c.httpClient.SetBaseURL(c.baseUrl)
c.httpClient.SetHeader("Accept", "application/json")
bearerToken, err := c.getBearer()
if err == nil {
c.httpClient.SetAuthToken(bearerToken)
} else {
return nil, err
}
return c, nil
}
// Requests a bearer token
func (c *Client) getBearer() (string, error) {
//Check if we have cached values
if !c.bearerExpiry.IsZero() && c.bearer != nil {
if c.bearerExpiry.Before(time.Now()) && c.bearer.AccessToken != "" {
//bearer not expired
return c.bearer.AccessToken, nil
}
}
authResult := &AuthSuccess{}
resp, err := c.authClient.R().
SetBody(map[string]interface{}{
"grant_type": "client_credentials",
"client_id": c.clientID,
"client_secret": c.clientSecret,
}).
SetResult(authResult).
Post("/auth/access-tokens")
if err != nil {
log.Errorf("Auth error: %v", err)
return "", fmt.Errorf("failed to get Bearer token, check your client credentials and if you use the correct environment. Error: %w", err)
}
if resp.IsError() {
log.Errorf("Auth error: %v", resp)
return "", fmt.Errorf("failed to get Bearer token, check your client credentials and if you use the correct environment. Error: %v", resp)
}
if err != nil || resp.StatusCode() != 200 {
log.Fatalf("auth code wrong: %v", err)
}
c.bearer = authResult
c.bearerExpiry = resp.ReceivedAt().Add(time.Second * time.Duration(c.bearer.ExpiresIn))
log.Debugf("got auth! " + c.bearerExpiry.String())
return c.bearer.AccessToken, nil
}
//Return a list of all letters
func (c *Client) ListLetters() (result *LetterList, err error) {
result = &LetterList{}
resp, err := c.httpClient.R().
SetResult(&result).
SetError(&ApiError{}).
Get(fmt.Sprintf("/organisations/%s/letters", c.organisationId))
if err != nil || resp.StatusCode() != 200 {
log.Errorf("ListLetters error: %v", err)
return nil, fmt.Errorf("listerror failed %w", err)
}
for _, v := range result.Data {
log.Debugf("Letter %s: State %s, FileName %s, to Addr [%s]",
v.ID, v.Attributes.Status, v.Attributes.FileOriginalName, v.Attributes.Address)
}
return result, nil
}
//Retrives details for one letter
func (c *Client) GetLetter(letterID string) (result *Letter, err error) {
result = &Letter{}
resp, err := c.httpClient.R().
SetResult(&result).
SetError(&ApiError{}).
Get(fmt.Sprintf("/organisations/%s/letters/%s", c.organisationId, letterID))
if err != nil {
log.Errorf("Error: %v", err)
return nil, fmt.Errorf("GetLetter failed %w", err)
}
if resp.IsError() {
errData := resp.Error().(*ApiError)
log.Errorf("Api error: %v", errData)
return nil, fmt.Errorf("GetLetter with api message: %v", errData.Errors)
}
log.Debugf("Letter %s: State %s, FileName %s, to Addr [%s]",
result.Data.ID, result.Data.Attributes.Status, result.Data.Attributes.FileOriginalName, result.Data.Attributes.Address)
return result, nil
}
// Tries to cancel the sending of a letter.
// If no error is returned the letter was canceled
func (c *Client) CancelLetter(letterID string) (err error) {
resp, err := c.httpClient.R().
SetError(&ApiError{}).
Patch(fmt.Sprintf("/organisations/%s/letters/%s/cancel", c.organisationId, letterID))
if err != nil {
log.Errorf("Error: %v", err)
return fmt.Errorf("CancelLetter failed %w", err)
}
if resp.IsError() {
errData := resp.Error().(*ApiError)
log.Errorf("Api error: %v", errData)
return fmt.Errorf("CancelLetter with api message: %v", errData.Errors)
}
log.Debugf("Letter %s canceled", letterID)
return nil
}
// Tries to delete a letter.
// If no error is returned the letter was deleted
func (c *Client) DeleteLetter(letterID string) (err error) {
resp, err := c.httpClient.R().
SetError(&ApiError{}).
Delete(fmt.Sprintf("/organisations/%s/letters/%s", c.organisationId, letterID))
if err != nil {
log.Errorf("Error: %v", err)
return fmt.Errorf("DeleteLetter failed %w", err)
}
if resp.IsError() {
errData := resp.Error().(*ApiError)
log.Errorf("Api error: %v", errData)
return fmt.Errorf("DeleteLetter with api message: %v", errData.Errors)
}
log.Debugf("Letter %s deleted", letterID)
return nil
}
//Upload process!
/*
Function that uploads the pdf file and creates a letter. Required letter data needs to be provided in createData.
--
createData.Data.Attributes.AddressPosition must be right or left
createData.Data.Attributes.DeliveryProduct can be empty, "fast", "cheap", "bulk", "premium", "registered", defaults to cheap
createData.Data.Attributes.PrintMode can be "simplex", "duplex", defaults to simplex
createData.Data.Attributes.PrintSpectrum can be "grayscale", "color", defaults to grayscale
createData.Data.Attributes.FileURL & createData.Data.Attributes.FileURLSignature will be autofilled.
*/
func (c *Client) CreateLetter(uploadPDF []byte, createData *CreateData) (result *Letter, err error) {
result = &Letter{}
validateCreateData(createData)
//get upload url
uploadData := &UploadData{}
resp, err := c.httpClient.R().
SetResult(uploadData).
SetError(&ApiError{}).
Get("file-upload")
if err != nil {
log.Errorf("Error: %v", err)
return nil, fmt.Errorf("UploadFile failed %w", err)
}
if resp.IsError() {
errData := resp.Error().(*ApiError)
log.Errorf("Api error: %v", errData)
return nil, fmt.Errorf("UploadFile with api message: %v", errData.Errors)
}
log.Debugf("Got file upload endpoint: url %s, sig %s", uploadData.Data.Attributes.URL, uploadData.Data.Attributes.URLSignature)
//upload file
//Important: NO AUTH HEADER
uploadClient := resty.New()
resp, err = uploadClient.R().
SetHeader("Content-Type", "application/pdf").
SetBody(uploadPDF).
Put(uploadData.Data.Attributes.URL)
if err != nil {
log.Errorf("Error: %v", err)
return nil, fmt.Errorf("UploadFile failed %w", err)
}
if resp.IsError() {
log.Errorf("Error: %v", resp)
return nil, fmt.Errorf("UploadFile failed %w", err)
}
log.Debugf("Uploaded file, resp code %d", resp.StatusCode())
//create the letter
createData.Data.Type = "letters"
createData.Data.Attributes.FileURL = uploadData.Data.Attributes.URL
createData.Data.Attributes.FileURLSignature = uploadData.Data.Attributes.URLSignature
//name
//addrees pos
//auto_send
//delivery_product
//print_mode
//print_spectrum
resp, err = c.httpClient.R().
SetHeader("Content-Type", "application/vnd.api+json").
SetBody(createData).
SetResult(result).
SetError(&ApiError{}).
Post(fmt.Sprintf("/organisations/%s/letters", c.organisationId))
if err != nil {
log.Errorf("Error: %v", err)
return nil, fmt.Errorf("UploadFile failed %w", err)
}
if resp.IsError() {
errData := resp.Error().(*ApiError)
log.Errorf("Api error: %v", errData)
return nil, fmt.Errorf("UploadFile with api message: %v", errData.Errors)
}
log.Debugf("Created letter: %s", result.Data.ID)
return result, nil
}
func validateCreateData(createData *CreateData) error {
if createData.Data.Attributes.PrintMode == "" {
createData.Data.Attributes.PrintMode = "simplex"
}
if createData.Data.Attributes.PrintSpectrum == "" {
createData.Data.Attributes.PrintSpectrum = "grayscale"
}
if createData.Data.Attributes.DeliveryProduct == "" {
createData.Data.Attributes.DeliveryProduct = "cheap"
}
if createData.Data.Attributes.AddressPosition != "left" &&
createData.Data.Attributes.AddressPosition != "right" {
return fmt.Errorf("addressPosition must be right or left")
}
return nil
}
/*
Function that sends a letter.
--
data.Data.Attributes.DeliveryProduct can be empty, "fast", "cheap", "bulk", "premium", "registered"
data.Data.Attributes.PrintMode can be empty, "simplex", "duplex"
data.Data.Attributes.PrintSpectrum can be empty, "grayscale", "color"
Data.Type & Data.ID will be autofilled
*/
func (c *Client) SendLetter(letterID string, data *SendData) (result *Letter, err error) {
result = &Letter{}
//todo validate senddata
data.Data.Type = "letters"
data.Data.ID = letterID
resp, err := c.httpClient.R().
SetHeader("Content-Type", "application/vnd.api+json").
SetBody(data).
SetError(&ApiError{}).
SetResult(result).
Patch(fmt.Sprintf("/organisations/%s/letters/%s/send", c.organisationId, letterID))
if err != nil {
log.Errorf("Error: %v", err)
return nil, fmt.Errorf("SendLetter failed %w", err)
}
if resp.IsError() {
errData := resp.Error().(*ApiError)
log.Errorf("Api error: %v", errData)
return nil, fmt.Errorf("SendLetter with api message: %v", errData.Errors)
}
log.Debugf("Letter %s sent", letterID)
return result, nil
}
/*
letter status:
valid
action_required
proccesing
printing
sent
undeliverable
unprintable
*/