shop.tonybtw.com

shop.tonybtw.com

https://git.tonybtw.com/shop.tonybtw.com.git git://git.tonybtw.com/shop.tonybtw.com.git
1,729 bytes raw
1
package lib
2
3
import (
4
	"bytes"
5
	"encoding/json"
6
	"fmt"
7
	"io"
8
	"net/http"
9
	"os"
10
)
11
12
const printful_api_url = "https://api.printful.com"
13
14
type Printful_Order_Item struct {
15
	Variant_ID int `json:"variant_id"`
16
	Quantity   int `json:"quantity"`
17
}
18
19
type Printful_Order_Request struct {
20
	Recipient struct {
21
		Name    string `json:"name"`
22
		Address string `json:"address1"`
23
		City    string `json:"city"`
24
		State   string `json:"state_code"`
25
		Country string `json:"country_code"`
26
		Zip     string `json:"zip"`
27
	} `json:"recipient"`
28
	Items []Printful_Order_Item `json:"items"`
29
}
30
31
type Printful_Order_Response struct {
32
	Code   int `json:"code"`
33
	Result struct {
34
		ID int `json:"id"`
35
	} `json:"result"`
36
}
37
38
func Create_Printful_Order(order_request Printful_Order_Request) (*Printful_Order_Response, error) {
39
	api_key := os.Getenv("PRINTFUL_API_KEY")
40
	if api_key == "" {
41
		return nil, fmt.Errorf("PRINTFUL_API_KEY not set")
42
	}
43
44
	body, err := json.Marshal(order_request)
45
	if err != nil {
46
		return nil, err
47
	}
48
49
	req, err := http.NewRequest("POST", printful_api_url+"/orders", bytes.NewBuffer(body))
50
	if err != nil {
51
		return nil, err
52
	}
53
54
	req.Header.Set("Authorization", "Bearer "+api_key)
55
	req.Header.Set("Content-Type", "application/json")
56
57
	client := &http.Client{}
58
	resp, err := client.Do(req)
59
	if err != nil {
60
		return nil, err
61
	}
62
	defer resp.Body.Close()
63
64
	response_body, err := io.ReadAll(resp.Body)
65
	if err != nil {
66
		return nil, err
67
	}
68
69
	var printful_response Printful_Order_Response
70
	if err := json.Unmarshal(response_body, &printful_response); err != nil {
71
		return nil, err
72
	}
73
74
	if printful_response.Code != 200 {
75
		return nil, fmt.Errorf("printful API error: code %d", printful_response.Code)
76
	}
77
78
	return &printful_response, nil
79
}