lemonsqueezy.*CheckoutsService.Create   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 21
nop 4
dl 0
loc 33
rs 9.376
c 0
b 0
f 0
1
package lemonsqueezy
2
3
import (
4
	"context"
5
	"encoding/json"
6
	"net/http"
7
	"strconv"
8
)
9
10
// CheckoutsService is the API client for the `/v1/checkouts` endpoint
11
type CheckoutsService service
12
13
// Create a custom checkout.
14
//
15
// https://docs.lemonsqueezy.com/api/checkouts#create-a-checkout
16
func (service *CheckoutsService) Create(ctx context.Context, storeID int, variantID int, attributes *CheckoutCreateAttributes) (*CheckoutAPIResponse, *Response, error) {
17
	payload := map[string]any{
18
		"data": map[string]any{
19
			"type":       "checkouts",
20
			"attributes": attributes,
21
			"relationships": map[string]any{
22
				"store": map[string]any{
23
					"data": map[string]any{
24
						"id":   strconv.Itoa(storeID),
25
						"type": "stores",
26
					},
27
				},
28
				"variant": map[string]any{
29
					"data": map[string]any{
30
						"id":   strconv.Itoa(variantID),
31
						"type": "variants",
32
					},
33
				},
34
			},
35
		},
36
	}
37
38
	response, err := service.client.do(ctx, http.MethodPost, "/v1/checkouts", payload)
39
	if err != nil {
40
		return nil, response, err
41
	}
42
43
	checkout := new(CheckoutAPIResponse)
44
	if err = json.Unmarshal(*response.Body, checkout); err != nil {
45
		return nil, response, err
46
	}
47
48
	return checkout, response, nil
49
}
50
51
// Get the checkout with the given ID.
52
//
53
// https://docs.lemonsqueezy.com/api/checkouts#retrieve-a-checkout
54
func (service *CheckoutsService) Get(ctx context.Context, checkoutID string) (*CheckoutAPIResponse, *Response, error) {
55
	response, err := service.client.do(ctx, http.MethodGet, "/v1/checkouts/"+checkoutID)
56
	if err != nil {
57
		return nil, response, err
58
	}
59
60
	checkout := new(CheckoutAPIResponse)
61
	if err = json.Unmarshal(*response.Body, checkout); err != nil {
62
		return nil, response, err
63
	}
64
65
	return checkout, response, nil
66
}
67
68
// List returns a paginated list of checkouts.
69
//
70
// https://docs.lemonsqueezy.com/api/checkouts#list-all-checkouts
71
func (service *CheckoutsService) List(ctx context.Context) (*CheckoutsAPIResponse, *Response, error) {
72
	response, err := service.client.do(ctx, http.MethodGet, "/v1/checkouts")
73
	if err != nil {
74
		return nil, response, err
75
	}
76
77
	checkouts := new(CheckoutsAPIResponse)
78
	if err = json.Unmarshal(*response.Body, checkouts); err != nil {
79
		return nil, response, err
80
	}
81
82
	return checkouts, response, nil
83
}
84