-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.go
More file actions
543 lines (442 loc) · 18.9 KB
/
Copy pathcheckout.go
File metadata and controls
543 lines (442 loc) · 18.9 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Package checkout provides a production-grade Go client for the Checkout.com API.
//
// # Quickstart
//
// c := checkout.New(checkout.Config{
// Prefix: os.Getenv("CHECKOUT_PREFIX"),
// AccessKeyID: os.Getenv("CHECKOUT_ACCESS_KEY_ID"),
// AccessKeySecret: os.Getenv("CHECKOUT_ACCESS_KEY_SECRET"),
// })
//
// payment, err := c.Payments().Request(ctx, payments.Request{
// Amount: 10_000,
// Currency: "GBP",
// Source: map[string]any{"type": "token", "token": "tok_..."},
// })
//
// # Package layout
//
// - [github.com/iamkanishka/checkout-go] — this package: [New], [Config], [Client]
// - [github.com/iamkanishka/checkout-go/payments] — Payments, Flow, Links, Hosted, Contexts, Setups, Methods
// - [github.com/iamkanishka/checkout-go/vault] — Tokens, Instruments, Customers, Transfers, Balances, Forex, and more
// - [github.com/iamkanishka/checkout-go/disputes] — Disputes, Workflows
// - [github.com/iamkanishka/checkout-go/issuing] — Cards, Cardholders, Controls, Platforms, Identity
// - [github.com/iamkanishka/checkout-go/webhook] — VerifyWebhook
// - [github.com/iamkanishka/checkout-go/errs] — APIError
// - [github.com/iamkanishka/checkout-go/option] — RequestOption
package checkout
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strings"
"time"
"github.com/iamkanishka/checkout-go/errs"
"github.com/iamkanishka/checkout-go/internal/auth"
"github.com/iamkanishka/checkout-go/internal/idempotency"
"github.com/iamkanishka/checkout-go/internal/retry"
"github.com/iamkanishka/checkout-go/option"
"github.com/iamkanishka/checkout-go/disputes"
"github.com/iamkanishka/checkout-go/issuing"
"github.com/iamkanishka/checkout-go/payments"
"github.com/iamkanishka/checkout-go/vault"
"github.com/iamkanishka/checkout-go/webhook"
)
// Version is the current SDK version, sent in the User-Agent header.
const Version = "1.0.0"
// Environment selects the target API environment.
type Environment int
const (
// Production targets https://{prefix}.api.checkout.com.
Production Environment = iota
// Sandbox targets https://{prefix}.api.sandbox.checkout.com.
Sandbox
)
// RetryConfig is an alias for [retry.Config], re-exported for convenience.
type RetryConfig = retry.Config
// Config is the configuration for [New].
// Only [Config.Prefix] is required; all other fields have sensible defaults.
type Config struct {
// Prefix is the first 8 characters of your client_id, excluding "cli_".
// Required. Find it: Dashboard → Settings → Account details → Connection settings.
Prefix string
// Environment selects production (default) or sandbox.
Environment Environment
// AccessKeyID and AccessKeySecret are your OAuth 2.0 credentials (recommended).
// When both are set, tokens are fetched, cached, and auto-refreshed.
AccessKeyID string
AccessKeySecret string
// SecretKey is a static secret API key (sk_...).
// Used when OAuth credentials are not configured.
SecretKey string
// PublicKey is for client-side tokenization only (pk_...).
PublicKey string
// PrivateLink routes all requests through AWS PrivateLink.
// Base URL becomes https://pl-{prefix}.api.checkout.com.
PrivateLink bool
// IdempotencyKeyPrefix is prepended to auto-generated idempotency keys.
IdempotencyKeyPrefix string
// Timeout is the per-request HTTP timeout. Default: 30s.
Timeout time.Duration
// Retry controls automatic retry behaviour.
Retry RetryConfig
// HTTPClient injects a custom *http.Client (for mTLS, proxies, tracing).
HTTPClient *http.Client
// Logger receives structured output. Defaults to slog.Default().
Logger *slog.Logger
// UserAgent overrides the User-Agent header. Defaults to "checkout-go/{Version}".
UserAgent string
}
// Client is the Checkout.com API client.
// Create one with [New] and reuse it — safe for concurrent use.
type Client struct {
cfg Config
httpClient *http.Client
tokenSrc *auth.TokenSource
log *slog.Logger
}
// New creates a Client from cfg. Panics if cfg.Prefix is empty.
func New(cfg Config) *Client {
if cfg.Prefix == "" {
panic("checkout: Config.Prefix is required (first 8 chars of your client_id)")
}
if cfg.Timeout == 0 {
cfg.Timeout = 30 * time.Second
}
if cfg.Retry.MaxAttempts == 0 {
cfg.Retry = retry.Default()
}
if cfg.UserAgent == "" {
cfg.UserAgent = "checkout-go/" + Version
}
hc := cfg.HTTPClient
if hc == nil {
hc = &http.Client{
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20,
IdleConnTimeout: 90 * time.Second,
},
}
}
hc.Timeout = cfg.Timeout
lg := cfg.Logger
if lg == nil {
lg = slog.Default()
}
c := &Client{cfg: cfg, httpClient: hc, log: lg}
if cfg.AccessKeyID != "" && cfg.AccessKeySecret != "" {
c.tokenSrc = auth.New(cfg.AccessKeyID, cfg.AccessKeySecret, c.authURL(), hc, lg)
}
return c
}
// ── URL helpers ──────────────────────────────────────────────────────────────
func (c *Client) apiURL() string {
var sb strings.Builder
sb.WriteString("https://")
if c.cfg.PrivateLink {
sb.WriteString("pl-")
}
sb.WriteString(c.cfg.Prefix)
if c.cfg.Environment == Sandbox {
sb.WriteString(".api.sandbox.checkout.com")
} else {
sb.WriteString(".api.checkout.com")
}
return sb.String()
}
func (c *Client) authURL() string {
if c.cfg.Environment == Sandbox {
return "https://" + c.cfg.Prefix + ".access.sandbox.checkout.com/connect/token"
}
return "https://" + c.cfg.Prefix + ".access.checkout.com/connect/token"
}
// ── Service accessors ────────────────────────────────────────────────────────
// Payments returns the Payments service (Request, Capture, Refund, Void, …).
func (c *Client) Payments() *payments.Service { return payments.New(c) }
// Flow returns the Flow hosted-payment-sessions service.
func (c *Client) Flow() *payments.FlowService { return payments.NewFlow(c) }
// PaymentLinks returns the Payment Links service.
func (c *Client) PaymentLinks() *payments.LinksService { return payments.NewLinks(c) }
// HostedPayments returns the Hosted Payments Page service.
func (c *Client) HostedPayments() *payments.HostedService { return payments.NewHosted(c) }
// PaymentContexts returns the Payment Contexts service.
func (c *Client) PaymentContexts() *payments.ContextsService { return payments.NewContexts(c) }
// PaymentSetups returns the Payment Setups service.
func (c *Client) PaymentSetups() *payments.SetupsService { return payments.NewSetups(c) }
// PaymentMethods returns the Payment Methods service.
func (c *Client) PaymentMethods() *payments.MethodsService { return payments.NewMethods(c) }
// Tokens returns the Tokens (card tokenization) service.
func (c *Client) Tokens() *vault.TokensService { return vault.NewTokens(c) }
// Instruments returns the Instruments (payment vault) service.
func (c *Client) Instruments() *vault.InstrumentsService { return vault.NewInstruments(c) }
// Customers returns the Customers service.
func (c *Client) Customers() *vault.CustomersService { return vault.NewCustomers(c) }
// Transfers returns the Transfers service.
func (c *Client) Transfers() *vault.TransfersService { return vault.NewTransfers(c) }
// Balances returns the Balances service.
func (c *Client) Balances() *vault.BalancesService { return vault.NewBalances(c) }
// Forex returns the FX Rates service.
func (c *Client) Forex() *vault.ForexService { return vault.NewForex(c) }
// CardMetadata returns the Card Metadata service.
func (c *Client) CardMetadata() *vault.CardMetadataService { return vault.NewCardMetadata(c) }
// NetworkTokens returns the Network Tokens service.
func (c *Client) NetworkTokens() *vault.NetworkTokensService { return vault.NewNetworkTokens(c) }
// AccountUpdater returns the Standalone Account Updater service.
func (c *Client) AccountUpdater() *vault.AccountUpdaterService { return vault.NewAccountUpdater(c) }
// ApplePay returns the Apple Pay setup service.
func (c *Client) ApplePay() *vault.ApplePayService { return vault.NewApplePay(c) }
// GooglePay returns the Google Pay setup service.
func (c *Client) GooglePay() *vault.GooglePayService { return vault.NewGooglePay(c) }
// Forward returns the Forward API and vault secrets service.
func (c *Client) Forward() *vault.ForwardService { return vault.NewForward(c) }
// Sessions returns the Standalone 3DS Sessions service.
func (c *Client) Sessions() *vault.SessionsService { return vault.NewSessions(c) }
// Reports returns the Reports service.
func (c *Client) Reports() *vault.ReportsService { return vault.NewReports(c) }
// FinancialActions returns the Financial Actions service.
func (c *Client) FinancialActions() *vault.FinancialActionsService {
return vault.NewFinancialActions(c)
}
// Compliance returns the Compliance Requests service.
func (c *Client) Compliance() *vault.ComplianceService { return vault.NewCompliance(c) }
// AgenticCommerce returns the Agentic Commerce Protocol service.
func (c *Client) AgenticCommerce() *vault.AgenticCommerceService {
return vault.NewAgenticCommerce(c)
}
// Disputes returns the Disputes service.
func (c *Client) Disputes() *disputes.Service { return disputes.New(c) }
// Workflows returns the Workflows service.
func (c *Client) Workflows() *disputes.WorkflowsService { return disputes.NewWorkflows(c) }
// Cardholders returns the Card Issuing Cardholders service.
func (c *Client) Cardholders() *issuing.CardholdersService { return issuing.NewCardholders(c) }
// CardholderAccessTokens returns the Cardholder Access Tokens service.
func (c *Client) CardholderAccessTokens() *issuing.AccessTokensService {
return issuing.NewAccessTokens(c)
}
// Cards returns the Card Issuing Cards service.
func (c *Client) Cards() *issuing.CardsService { return issuing.NewCards(c) }
// Controls returns the Card Issuing Controls service.
func (c *Client) Controls() *issuing.ControlsService { return issuing.NewControls(c) }
// ControlProfiles returns the Control Profiles service.
func (c *Client) ControlProfiles() *issuing.ControlProfilesService {
return issuing.NewControlProfiles(c)
}
// ControlGroups returns the Control Groups service.
func (c *Client) ControlGroups() *issuing.ControlGroupsService { return issuing.NewControlGroups(c) }
// IssuingTransactions returns the Issuing Transactions service.
func (c *Client) IssuingTransactions() *issuing.TransactionsService {
return issuing.NewTransactions(c)
}
// IssuingDisputes returns the Issuing Disputes service.
func (c *Client) IssuingDisputes() *issuing.IssuingDisputesService {
return issuing.NewIssuingDisputes(c)
}
// IssuingSandbox returns the Card Testing simulation service (sandbox only).
func (c *Client) IssuingSandbox() *issuing.SandboxService { return issuing.NewSandbox(c) }
// PlatformEntities returns the Platform Entities service.
func (c *Client) PlatformEntities() *issuing.PlatformEntitiesService {
return issuing.NewPlatformEntities(c)
}
// PlatformPaymentInstruments returns the Platform Payment Instruments service.
func (c *Client) PlatformPaymentInstruments() *issuing.PlatformInstrumentsService {
return issuing.NewPlatformInstruments(c)
}
// PayoutSchedules returns the Payout Schedules service.
func (c *Client) PayoutSchedules() *issuing.PayoutSchedulesService {
return issuing.NewPayoutSchedules(c)
}
// ReserveRules returns the Reserve Rules service.
func (c *Client) ReserveRules() *issuing.ReserveRulesService { return issuing.NewReserveRules(c) }
// IdentityApplicants returns the Identity Applicants service.
func (c *Client) IdentityApplicants() *issuing.ApplicantsService {
return issuing.NewApplicants(c)
}
// IdentityVerification returns the Identity Verification service.
func (c *Client) IdentityVerification() *issuing.VerificationService {
return issuing.NewVerification(c)
}
// AMLScreening returns the AML Screening service.
func (c *Client) AMLScreening() *issuing.AMLService { return issuing.NewAML(c) }
// FaceAuth returns the Face Authentication service.
func (c *Client) FaceAuth() *issuing.FaceAuthService { return issuing.NewFaceAuth(c) }
// IDDocuments returns the ID Document Verification service.
func (c *Client) IDDocuments() *issuing.IDDocumentService { return issuing.NewIDDocuments(c) }
// ── Webhook helpers re-exported for convenience ──────────────────────────────
// VerifyWebhook verifies the HMAC-SHA256 signature of an inbound Checkout.com webhook.
// It is an alias for [webhook.Verify].
var VerifyWebhook = webhook.Verify
// ErrInvalidWebhookSignature is returned when verification fails.
// It is an alias for [webhook.ErrInvalidSignature].
var ErrInvalidWebhookSignature = webhook.ErrInvalidSignature
// WebhookEvent is the top-level structure of a Checkout.com webhook notification.
// It is an alias for [webhook.Event].
type WebhookEvent = webhook.Event
// ── HTTP engine (used by all sub-packages via the Executor interface) ─────────
// Executor is the interface that sub-packages use to make HTTP calls.
// The root *Client implements it; sub-packages accept it so they can be
// tested independently with a mock.
type Executor interface {
Get(ctx context.Context, path string, out any, opts ...option.RequestOption) error
Post(ctx context.Context, path string, body, out any, opts ...option.RequestOption) error
Put(ctx context.Context, path string, body, out any, opts ...option.RequestOption) error
Patch(ctx context.Context, path string, body, out any, opts ...option.RequestOption) error
Delete(ctx context.Context, path string, opts ...option.RequestOption) error
}
// Get executes a GET request.
func (c *Client) Get(ctx context.Context, path string, out any, opts ...option.RequestOption) error {
return c.do(ctx, http.MethodGet, path, nil, out, opts...)
}
// Post executes a POST request.
func (c *Client) Post(ctx context.Context, path string, body, out any, opts ...option.RequestOption) error {
return c.do(ctx, http.MethodPost, path, body, out, opts...)
}
// Put executes a PUT request.
func (c *Client) Put(ctx context.Context, path string, body, out any, opts ...option.RequestOption) error {
return c.do(ctx, http.MethodPut, path, body, out, opts...)
}
// Patch executes a PATCH request.
func (c *Client) Patch(ctx context.Context, path string, body, out any, opts ...option.RequestOption) error {
return c.do(ctx, http.MethodPatch, path, body, out, opts...)
}
// Delete executes a DELETE request.
func (c *Client) Delete(ctx context.Context, path string, opts ...option.RequestOption) error {
return c.do(ctx, http.MethodDelete, path, nil, nil, opts...)
}
// ── Core request loop ────────────────────────────────────────────────────────
func (c *Client) do(ctx context.Context, method, path string, body, out any, opts ...option.RequestOption) error {
ro := &option.Request{}
ro.Apply(opts)
idempKey := ro.IdempotencyKey
if idempKey == "" && idempotency.Required(method, path) {
idempKey = idempotency.NewKey(c.cfg.IdempotencyKeyPrefix)
}
var lastErr error
for attempt := 0; attempt < c.cfg.Retry.MaxAttempts; attempt++ {
if attempt > 0 {
delay := retry.Delay(attempt-1, c.cfg.Retry)
c.log.WarnContext(ctx, "checkout: retrying",
slog.Int("attempt", attempt),
slog.String("path", path),
slog.String("delay", delay.String()),
)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
}
lastErr = c.execute(ctx, method, path, body, out, idempKey)
if lastErr == nil {
return nil
}
var apiErr *errs.APIError
if asAPIError(lastErr, &apiErr) {
if !retry.Retryable(apiErr.StatusCode) {
return lastErr
}
if apiErr.StatusCode == http.StatusUnauthorized && c.tokenSrc != nil {
c.tokenSrc.Invalidate()
}
}
}
return lastErr
}
func (c *Client) execute(ctx context.Context, method, path string, body, out any, idempKey string) error {
var bodyReader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("checkout: marshal request: %w", err)
}
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.apiURL()+path, bodyReader)
if err != nil {
return fmt.Errorf("checkout: build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.cfg.UserAgent)
if idempKey != "" {
req.Header.Set("Cko-Idempotency-Key", idempKey)
}
tok, err := c.resolveAuth(ctx)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+tok)
c.log.DebugContext(ctx, "checkout →", slog.String("method", method), slog.String("path", path))
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("checkout: http: %w", err)
}
defer resp.Body.Close() //nolint:errcheck
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
if err != nil {
return fmt.Errorf("checkout: read response: %w", err)
}
c.log.DebugContext(ctx, "checkout ←",
slog.Int("status", resp.StatusCode),
slog.String("request-id", resp.Header.Get("Cko-Request-Id")),
)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return errs.Parse(resp.StatusCode, resp.Header.Get("Cko-Request-Id"), idempKey, respBody)
}
if out != nil && len(respBody) > 0 {
if err := json.Unmarshal(respBody, out); err != nil {
return fmt.Errorf("checkout: decode response: %w", err)
}
}
return nil
}
func (c *Client) resolveAuth(ctx context.Context) (string, error) {
if c.tokenSrc != nil {
return c.tokenSrc.Token(ctx)
}
if c.cfg.SecretKey != "" {
return c.cfg.SecretKey, nil
}
if c.cfg.PublicKey != "" {
return c.cfg.PublicKey, nil
}
return "", fmt.Errorf("checkout: no credentials configured")
}
// ── Helpers used by sub-packages ─────────────────────────────────────────────
// BuildQuery encodes a string map as a URL query string, omitting empty values.
// Exported so sub-packages can use it without re-implementing.
func BuildQuery(params map[string]string) string {
v := url.Values{}
for k, val := range params {
if val != "" {
v.Set(k, val)
}
}
if q := v.Encode(); q != "" {
return "?" + q
}
return ""
}
// Itoa converts n to its decimal string, returning "" for zero.
func Itoa(n int) string {
if n == 0 {
return ""
}
return fmt.Sprintf("%d", n)
}
func asAPIError(err error, target **errs.APIError) bool {
if ae, ok := err.(*errs.APIError); ok {
*target = ae
return true
}
return false
}
// BuildQuery is a method wrapper that sub-packages call via the Executor interface.
func (c *Client) BuildQuery(params map[string]string) string { return BuildQuery(params) }
// Itoa is a method wrapper that sub-packages call via the Executor interface.
func (c *Client) Itoa(n int) string { return Itoa(n) }