shop.tonybtw.com

shop.tonybtw.com

https://git.tonybtw.com/shop.tonybtw.com.git git://git.tonybtw.com/shop.tonybtw.com.git
2,022 bytes raw
1
package lib
2
3
import (
4
	"encoding/json"
5
	"os"
6
7
	"github.com/stripe/stripe-go/v78"
8
	"github.com/stripe/stripe-go/v78/checkout/session"
9
	"github.com/stripe/stripe-go/v78/webhook"
10
)
11
12
func init() {
13
	stripe.Key = os.Getenv("STRIPE_SECRET_KEY")
14
}
15
16
type Stripe_Line_Item struct {
17
	Name     string
18
	Amount   int64
19
	Quantity int64
20
}
21
22
func Create_Checkout_Session(line_items []Stripe_Line_Item, success_url, cancel_url string) (*stripe.CheckoutSession, error) {
23
	params := &stripe.CheckoutSessionParams{
24
		PaymentMethodTypes: stripe.StringSlice([]string{"card"}),
25
		Mode:               stripe.String(string(stripe.CheckoutSessionModePayment)),
26
		SuccessURL:         stripe.String(success_url),
27
		CancelURL:          stripe.String(cancel_url),
28
		ShippingAddressCollection: &stripe.CheckoutSessionShippingAddressCollectionParams{
29
			AllowedCountries: stripe.StringSlice([]string{"US"}),
30
		},
31
	}
32
33
	for _, item := range line_items {
34
		params.LineItems = append(params.LineItems, &stripe.CheckoutSessionLineItemParams{
35
			PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
36
				Currency: stripe.String("usd"),
37
				ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
38
					Name: stripe.String(item.Name),
39
				},
40
				UnitAmount: stripe.Int64(item.Amount),
41
			},
42
			Quantity: stripe.Int64(item.Quantity),
43
		})
44
	}
45
46
	return session.New(params)
47
}
48
49
func Verify_Webhook(payload []byte, sig_header string) (map[string]interface{}, error) {
50
	webhook_secret := os.Getenv("STRIPE_WEBHOOK_SECRET")
51
	if webhook_secret == "" {
52
		var event map[string]interface{}
53
		if err := json.Unmarshal(payload, &event); err != nil {
54
			return nil, err
55
		}
56
		return event, nil
57
	}
58
59
	event, err := webhook.ConstructEvent(payload, sig_header, webhook_secret)
60
	if err != nil {
61
		return nil, err
62
	}
63
64
	var result map[string]interface{}
65
	if err := json.Unmarshal(event.Data.Raw, &result); err != nil {
66
		return nil, err
67
	}
68
69
	return map[string]interface{}{
70
		"type": event.Type,
71
		"data": map[string]interface{}{
72
			"object": result,
73
		},
74
	}, nil
75
}