refactor/checkout (#8)
Co-authored-by: matst80 <mats.tornberg@gmail.com> Reviewed-on: #8 Co-authored-by: Mats Törnberg <mats@tornberg.me> Co-committed-by: Mats Törnberg <mats@tornberg.me>
This commit was merged in pull request #8.
This commit is contained in:
228
cmd/checkout/adyen-handlers.go
Normal file
228
cmd/checkout/adyen-handlers.go
Normal file
@@ -0,0 +1,228 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/actor"
|
||||
"git.k6n.net/go-cart-actor/pkg/cart"
|
||||
"git.k6n.net/go-cart-actor/pkg/proxy"
|
||||
messages "git.k6n.net/go-cart-actor/proto/checkout"
|
||||
adyenCheckout "github.com/adyen/adyen-go-api-library/v21/src/checkout"
|
||||
"github.com/adyen/adyen-go-api-library/v21/src/common"
|
||||
"github.com/adyen/adyen-go-api-library/v21/src/hmacvalidator"
|
||||
"github.com/adyen/adyen-go-api-library/v21/src/webhook"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type SessionRequest struct {
|
||||
SessionId string `json:"sessionId"`
|
||||
SessionResult string `json:"sessionResult"`
|
||||
SessionData string `json:"sessionData,omitempty"`
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) AdyenSessionHandler(w http.ResponseWriter, r *http.Request, cartId cart.CartId) error {
|
||||
|
||||
grain, err := s.Get(r.Context(), uint64(cartId))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
meta := GetCheckoutMetaFromRequest(r)
|
||||
sessionData, err := BuildAdyenCheckoutSession(grain, meta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service := s.adyenClient.Checkout()
|
||||
req := service.PaymentsApi.SessionsInput().CreateCheckoutSessionRequest(*sessionData)
|
||||
res, _, err := service.PaymentsApi.Sessions(r.Context(), req)
|
||||
// apply checkout started
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.WriteResult(w, res)
|
||||
} else {
|
||||
payload := &SessionRequest{}
|
||||
if err := json.NewDecoder(r.Body).Decode(payload); err != nil {
|
||||
return err
|
||||
}
|
||||
service := s.adyenClient.Checkout()
|
||||
req := service.PaymentsApi.GetResultOfPaymentSessionInput(payload.SessionId).SessionResult(payload.SessionResult)
|
||||
res, _, err := service.PaymentsApi.GetResultOfPaymentSession(r.Context(), req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.WriteResult(w, res)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func getCheckoutIdFromNotificationItem(item webhook.NotificationRequestItem) (uint64, error) {
|
||||
cartId, ok := cart.ParseCartId(item.MerchantReference)
|
||||
if !ok {
|
||||
return 0, errors.New("invalid cart id")
|
||||
}
|
||||
return uint64(cartId), nil
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) AdyenHookHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var notificationRequest webhook.Webhook
|
||||
service := s.adyenClient.Checkout()
|
||||
if err := json.NewDecoder(r.Body).Decode(¬ificationRequest); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
cartHostMap := make(map[actor.Host][]webhook.NotificationItem)
|
||||
for _, notificationItem := range *notificationRequest.NotificationItems {
|
||||
item := notificationItem.NotificationRequestItem
|
||||
log.Printf("Recieved notification event code: %s, %+v", item.EventCode, item)
|
||||
|
||||
isValid := hmacvalidator.ValidateHmac(item, hmacKey)
|
||||
if !isValid {
|
||||
log.Printf("notification hmac not valid %s, %v", item.EventCode, item)
|
||||
http.Error(w, "Invalid HMAC", http.StatusUnauthorized)
|
||||
return
|
||||
} else {
|
||||
switch item.EventCode {
|
||||
case "CAPTURE":
|
||||
log.Printf("Capture status: %v", item.Success)
|
||||
// dataBytes, err := json.Marshal(item)
|
||||
// if err != nil {
|
||||
// log.Printf("error marshaling item: %v", err)
|
||||
// http.Error(w, "Error marshaling item", http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
//s.ApplyAnywhere(r.Context(),0, &messages.PaymentEvent{PaymentId: item.PspReference, Success: item.Success, Name: item.EventCode, Data: &pbany.Any{Value: dataBytes}})
|
||||
case "AUTHORISATION":
|
||||
|
||||
cartId, err := getCheckoutIdFromNotificationItem(item)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
//s.Apply()
|
||||
|
||||
if host, ok := s.OwnerHost(uint64(cartId)); ok {
|
||||
cartHostMap[host] = append(cartHostMap[host], notificationItem)
|
||||
continue
|
||||
}
|
||||
|
||||
grain, err := s.Get(r.Context(), uint64(cartId))
|
||||
if err != nil {
|
||||
log.Printf("Error getting cart: %v", err)
|
||||
http.Error(w, "Cart not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
meta := GetCheckoutMetaFromRequest(r)
|
||||
pspReference := item.PspReference
|
||||
uid := uuid.New().String()
|
||||
ref := uuid.New().String()
|
||||
req := service.ModificationsApi.CaptureAuthorisedPaymentInput(pspReference).IdempotencyKey(uid).PaymentCaptureRequest(adyenCheckout.PaymentCaptureRequest{
|
||||
Amount: adyenCheckout.Amount{
|
||||
Currency: meta.Currency,
|
||||
Value: grain.CartTotalPrice.IncVat,
|
||||
},
|
||||
MerchantAccount: "ElgigantenECOM",
|
||||
Reference: &ref,
|
||||
})
|
||||
res, _, err := service.ModificationsApi.CaptureAuthorisedPayment(r.Context(), req)
|
||||
if err != nil {
|
||||
log.Printf("Error capturing payment: %v", err)
|
||||
} else {
|
||||
log.Printf("Payment captured successfully: %+v", res)
|
||||
s.Apply(r.Context(), uint64(cartId), &messages.OrderCreated{
|
||||
OrderId: res.PaymentPspReference,
|
||||
Status: item.EventCode,
|
||||
})
|
||||
}
|
||||
default:
|
||||
log.Printf("Unknown event code: %s", item.EventCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
var failed bool = false
|
||||
var lastMock *proxy.MockResponseWriter
|
||||
for host, items := range cartHostMap {
|
||||
notificationRequest.NotificationItems = &items
|
||||
bodyBytes, err := json.Marshal(notificationRequest)
|
||||
if err != nil {
|
||||
log.Printf("error marshaling notification: %+v", err)
|
||||
continue
|
||||
}
|
||||
customBody := bytes.NewReader(bodyBytes)
|
||||
mockW := proxy.NewMockResponseWriter()
|
||||
handled, err := host.Proxy(0, mockW, r, customBody)
|
||||
if err != nil {
|
||||
log.Printf("proxy failed for %s: %+v", host.Name(), err)
|
||||
failed = true
|
||||
lastMock = mockW
|
||||
} else if handled {
|
||||
log.Printf("notification proxied to %s", host.Name())
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
w.WriteHeader(lastMock.StatusCode)
|
||||
w.Write(lastMock.Body.Bytes())
|
||||
} else {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) AdyenReturnHandler(w http.ResponseWriter, r *http.Request) {
|
||||
log.Println("Redirect received")
|
||||
|
||||
service := s.adyenClient.Checkout()
|
||||
|
||||
req := service.PaymentsApi.GetResultOfPaymentSessionInput(r.URL.Query().Get("sessionId"))
|
||||
|
||||
res, httpRes, err := service.PaymentsApi.GetResultOfPaymentSession(r.Context(), req)
|
||||
log.Printf("got payment session %+v", res)
|
||||
|
||||
dreq := service.PaymentsApi.PaymentsDetailsInput()
|
||||
dreq = dreq.PaymentDetailsRequest(adyenCheckout.PaymentDetailsRequest{
|
||||
Details: adyenCheckout.PaymentCompletionDetails{
|
||||
RedirectResult: common.PtrString(r.URL.Query().Get("redirectResult")),
|
||||
Payload: common.PtrString(r.URL.Query().Get("payload")),
|
||||
},
|
||||
})
|
||||
|
||||
dres, httpRes, err := service.PaymentsApi.PaymentsDetails(r.Context(), dreq)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
log.Printf("Payment details response: %+v", dres)
|
||||
|
||||
if !common.IsNil(dres.PspReference) && *dres.PspReference != "" {
|
||||
var redirectURL string
|
||||
// Conditionally handle different result codes for the shopper
|
||||
switch *dres.ResultCode {
|
||||
case "Authorised":
|
||||
redirectURL = "/result/success"
|
||||
case "Pending", "Received":
|
||||
redirectURL = "/result/pending"
|
||||
case "Refused":
|
||||
redirectURL = "/result/failed"
|
||||
default:
|
||||
reason := ""
|
||||
if dres.RefusalReason != nil {
|
||||
reason = *dres.RefusalReason
|
||||
} else {
|
||||
reason = *dres.ResultCode
|
||||
}
|
||||
log.Printf("Payment failed: %s", reason)
|
||||
redirectURL = fmt.Sprintf("/result/error?reason=%s", url.QueryEscape(reason))
|
||||
}
|
||||
http.Redirect(w, r, redirectURL, http.StatusFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(httpRes.StatusCode)
|
||||
json.NewEncoder(w).Encode(httpRes.Status)
|
||||
}
|
||||
64
cmd/checkout/amqp-order-handler.go
Normal file
64
cmd/checkout/amqp-order-handler.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type AmqpOrderHandler struct {
|
||||
conn *amqp.Connection
|
||||
queue *amqp.Queue
|
||||
}
|
||||
|
||||
func NewAmqpOrderHandler(conn *amqp.Connection) *AmqpOrderHandler {
|
||||
return &AmqpOrderHandler{
|
||||
conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AmqpOrderHandler) DefineQueue() error {
|
||||
ch, err := h.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open a channel: %w", err)
|
||||
}
|
||||
defer ch.Close()
|
||||
|
||||
queue, err := ch.QueueDeclare(
|
||||
"order-queue", // name
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to declare an exchange: %w", err)
|
||||
}
|
||||
h.queue = &queue
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *AmqpOrderHandler) OrderCompleted(body []byte) error {
|
||||
ch, err := h.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open a channel: %w", err)
|
||||
}
|
||||
defer ch.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
return ch.PublishWithContext(ctx,
|
||||
"", // exchange
|
||||
h.queue.Name, // routing key
|
||||
false, // mandatory
|
||||
false, // immediate
|
||||
amqp.Publishing{
|
||||
//DeliveryMode: amqp.,
|
||||
ContentType: "application/json",
|
||||
Body: body,
|
||||
})
|
||||
|
||||
}
|
||||
65
cmd/checkout/cart-client.go
Normal file
65
cmd/checkout/cart-client.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/cart"
|
||||
)
|
||||
|
||||
type CartClient struct {
|
||||
httpClient *http.Client
|
||||
baseUrl string
|
||||
}
|
||||
|
||||
func NewCartClient(baseUrl string) *CartClient {
|
||||
return &CartClient{
|
||||
httpClient: &http.Client{Timeout: 10 * time.Second},
|
||||
baseUrl: baseUrl,
|
||||
}
|
||||
}
|
||||
|
||||
// func (c *CartClient) ApplyMutation(cartId cart.CartId, mutation proto.Message) error {
|
||||
// url := fmt.Sprintf("%s/internal/cart/%s/mutation", c.baseUrl, cartId.String())
|
||||
// data, err := proto.Marshal(mutation)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// req, err := http.NewRequest("POST", url, bytes.NewReader(data))
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// req.Header.Set("Content-Type", "application/protobuf")
|
||||
// resp, err := c.httpClient.Do(req)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// defer resp.Body.Close()
|
||||
// if resp.StatusCode != http.StatusOK {
|
||||
// return fmt.Errorf("cart mutation failed: %s", resp.Status)
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
|
||||
func (s *CartClient) getCartGrain(ctx context.Context, cartId cart.CartId) (*cart.CartGrain, error) {
|
||||
// Call cart service to get grain
|
||||
url := fmt.Sprintf("%s/cart/byid/%d", s.baseUrl, cartId.String())
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("failed to get cart: %s", resp.Status)
|
||||
}
|
||||
var grain cart.CartGrain
|
||||
err = json.NewDecoder(resp.Body).Decode(&grain)
|
||||
return &grain, err
|
||||
}
|
||||
208
cmd/checkout/checkout_builder.go
Normal file
208
cmd/checkout/checkout_builder.go
Normal file
@@ -0,0 +1,208 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/cart"
|
||||
"git.k6n.net/go-cart-actor/pkg/checkout"
|
||||
adyenCheckout "github.com/adyen/adyen-go-api-library/v21/src/checkout"
|
||||
"github.com/adyen/adyen-go-api-library/v21/src/common"
|
||||
)
|
||||
|
||||
// CheckoutMeta carries the external / URL metadata required to build a
|
||||
// Klarna CheckoutOrder from a CartGrain snapshot. It deliberately excludes
|
||||
// any Klarna-specific response fields (HTML snippet, client token, etc.).
|
||||
type CheckoutMeta struct {
|
||||
SiteUrl string
|
||||
// Terms string
|
||||
// Checkout string
|
||||
// Confirmation string
|
||||
ClientIp string
|
||||
Country string
|
||||
Currency string // optional override (defaults to "SEK" if empty)
|
||||
Locale string // optional override (defaults to "sv-se" if empty)
|
||||
}
|
||||
|
||||
// BuildCheckoutOrderPayload converts the current cart grain + meta information
|
||||
// into a CheckoutOrder domain struct and returns its JSON-serialized payload
|
||||
// (to send to Klarna) alongside the structured CheckoutOrder object.
|
||||
//
|
||||
// This function is PURE: it does not perform any network I/O or mutate the
|
||||
// grain. The caller is responsible for:
|
||||
//
|
||||
// 1. Choosing whether to create or update the Klarna order.
|
||||
// 2. Invoking KlarnaClient.CreateOrder / UpdateOrder with the returned payload.
|
||||
// 3. Applying an InitializeCheckout mutation (or equivalent) with the
|
||||
// resulting Klarna order id + status.
|
||||
//
|
||||
// If you later need to support different tax rates per line, you can extend
|
||||
// CartItem / Delivery to expose that data and propagate it here.
|
||||
func BuildCheckoutOrderPayload(grain *checkout.CheckoutGrain, meta *CheckoutMeta) ([]byte, *CheckoutOrder, error) {
|
||||
if grain == nil {
|
||||
return nil, nil, fmt.Errorf("nil grain")
|
||||
}
|
||||
if meta == nil {
|
||||
return nil, nil, fmt.Errorf("nil checkout meta")
|
||||
}
|
||||
|
||||
currency := meta.Currency
|
||||
if currency == "" {
|
||||
currency = "SEK"
|
||||
}
|
||||
locale := meta.Locale
|
||||
if locale == "" {
|
||||
locale = "sv-se"
|
||||
}
|
||||
country := meta.Country
|
||||
if country == "" {
|
||||
country = "SE" // sensible default; adjust if multi-country support changes
|
||||
}
|
||||
|
||||
lines := make([]*Line, 0, len(grain.CartState.Items)+len(grain.Deliveries))
|
||||
|
||||
// Item lines
|
||||
for _, it := range grain.CartState.Items {
|
||||
if it == nil {
|
||||
continue
|
||||
}
|
||||
lines = append(lines, &Line{
|
||||
Type: "physical",
|
||||
Reference: it.Sku,
|
||||
Name: it.Meta.Name,
|
||||
Quantity: int(it.Quantity),
|
||||
UnitPrice: int(it.Price.IncVat),
|
||||
TaxRate: it.Tax, // TODO: derive if variable tax rates are introduced
|
||||
QuantityUnit: "st",
|
||||
TotalAmount: int(it.TotalPrice.IncVat),
|
||||
TotalTaxAmount: int(it.TotalPrice.TotalVat()),
|
||||
ImageURL: fmt.Sprintf("https://www.elgiganten.se%s", it.Meta.Image),
|
||||
})
|
||||
}
|
||||
|
||||
total := cart.NewPrice()
|
||||
total.Add(*grain.CartState.TotalPrice)
|
||||
|
||||
// Delivery lines
|
||||
for _, d := range grain.Deliveries {
|
||||
if d == nil || d.Price.IncVat <= 0 {
|
||||
continue
|
||||
}
|
||||
//total.Add(d.Price)
|
||||
lines = append(lines, &Line{
|
||||
Type: "shipping_fee",
|
||||
Reference: d.Provider,
|
||||
Name: "Delivery",
|
||||
Quantity: 1,
|
||||
UnitPrice: int(d.Price.IncVat),
|
||||
TaxRate: 2500,
|
||||
QuantityUnit: "st",
|
||||
TotalAmount: int(d.Price.IncVat),
|
||||
TotalTaxAmount: int(d.Price.TotalVat()),
|
||||
})
|
||||
}
|
||||
|
||||
order := &CheckoutOrder{
|
||||
PurchaseCountry: country,
|
||||
PurchaseCurrency: currency,
|
||||
Locale: locale,
|
||||
OrderAmount: int(total.IncVat),
|
||||
OrderTaxAmount: int(total.TotalVat()),
|
||||
OrderLines: lines,
|
||||
MerchantReference1: grain.Id.String(),
|
||||
MerchantURLS: &CheckoutMerchantURLS{
|
||||
Terms: fmt.Sprintf("%s/terms", meta.SiteUrl),
|
||||
Checkout: fmt.Sprintf("%s/checkout?order_id={checkout.order.id}", meta.SiteUrl),
|
||||
Confirmation: fmt.Sprintf("%s/confirmation/{checkout.order.id}", meta.SiteUrl),
|
||||
Notification: "https://cart.k6n.net/notification",
|
||||
Validation: "https://cart.k6n.net/validate",
|
||||
Push: "https://cart.k6n.net/push?order_id={checkout.order.id}",
|
||||
},
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(order)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("marshal checkout order: %w", err)
|
||||
}
|
||||
|
||||
return payload, order, nil
|
||||
}
|
||||
|
||||
func GetCheckoutMetaFromRequest(r *http.Request) *CheckoutMeta {
|
||||
host := getOriginalHost(r)
|
||||
country := getCountryFromHost(host)
|
||||
return &CheckoutMeta{
|
||||
ClientIp: getClientIp(r),
|
||||
SiteUrl: fmt.Sprintf("https://%s", host),
|
||||
Country: country,
|
||||
Currency: getCurrency(country),
|
||||
Locale: getLocale(country),
|
||||
}
|
||||
}
|
||||
|
||||
func BuildAdyenCheckoutSession(grain *checkout.CheckoutGrain, meta *CheckoutMeta) (*adyenCheckout.CreateCheckoutSessionRequest, error) {
|
||||
if grain == nil {
|
||||
return nil, fmt.Errorf("nil grain")
|
||||
}
|
||||
if meta == nil {
|
||||
return nil, fmt.Errorf("nil checkout meta")
|
||||
}
|
||||
|
||||
currency := meta.Currency
|
||||
if currency == "" {
|
||||
currency = "SEK"
|
||||
}
|
||||
country := meta.Country
|
||||
if country == "" {
|
||||
country = "SE"
|
||||
}
|
||||
|
||||
lineItems := make([]adyenCheckout.LineItem, 0, len(grain.CartState.Items)+len(grain.Deliveries))
|
||||
|
||||
// Item lines
|
||||
for _, it := range grain.CartState.Items {
|
||||
if it == nil {
|
||||
continue
|
||||
}
|
||||
lineItems = append(lineItems, adyenCheckout.LineItem{
|
||||
Quantity: common.PtrInt64(int64(it.Quantity)),
|
||||
AmountIncludingTax: common.PtrInt64(it.TotalPrice.IncVat),
|
||||
Description: common.PtrString(it.Meta.Name),
|
||||
AmountExcludingTax: common.PtrInt64(it.TotalPrice.ValueExVat()),
|
||||
TaxAmount: common.PtrInt64(it.TotalPrice.TotalVat()),
|
||||
TaxPercentage: common.PtrInt64(int64(it.Tax)),
|
||||
})
|
||||
}
|
||||
total := cart.NewPrice()
|
||||
total.Add(*grain.CartState.TotalPrice)
|
||||
|
||||
// Delivery lines
|
||||
for _, d := range grain.Deliveries {
|
||||
if d == nil || d.Price.IncVat <= 0 {
|
||||
continue
|
||||
}
|
||||
lineItems = append(lineItems, adyenCheckout.LineItem{
|
||||
Quantity: common.PtrInt64(1),
|
||||
AmountIncludingTax: common.PtrInt64(d.Price.IncVat),
|
||||
Description: common.PtrString("Delivery"),
|
||||
AmountExcludingTax: common.PtrInt64(d.Price.ValueExVat()),
|
||||
TaxPercentage: common.PtrInt64(25),
|
||||
})
|
||||
}
|
||||
|
||||
return &adyenCheckout.CreateCheckoutSessionRequest{
|
||||
Reference: grain.Id.String(),
|
||||
Amount: adyenCheckout.Amount{
|
||||
Value: total.IncVat,
|
||||
Currency: currency,
|
||||
},
|
||||
CountryCode: common.PtrString(country),
|
||||
MerchantAccount: "ElgigantenECOM",
|
||||
Channel: common.PtrString("Web"),
|
||||
ShopperIP: common.PtrString(meta.ClientIp),
|
||||
ReturnUrl: fmt.Sprintf("%s/adyen-return", meta.SiteUrl),
|
||||
LineItems: lineItems,
|
||||
}, nil
|
||||
|
||||
}
|
||||
65
cmd/checkout/k8s-host-discovery.go
Normal file
65
cmd/checkout/k8s-host-discovery.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/actor"
|
||||
"git.k6n.net/go-cart-actor/pkg/checkout"
|
||||
"git.k6n.net/go-cart-actor/pkg/discovery"
|
||||
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/rest"
|
||||
)
|
||||
|
||||
func GetDiscovery() discovery.Discovery {
|
||||
if podIp == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
config, kerr := rest.InClusterConfig()
|
||||
|
||||
if kerr != nil {
|
||||
log.Fatalf("Error creating kubernetes client: %v\n", kerr)
|
||||
}
|
||||
client, err := kubernetes.NewForConfig(config)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating client: %v\n", err)
|
||||
}
|
||||
timeout := int64(30)
|
||||
return discovery.NewK8sDiscovery(client, v1.ListOptions{
|
||||
LabelSelector: "actor-pool=checkout",
|
||||
TimeoutSeconds: &timeout,
|
||||
})
|
||||
}
|
||||
|
||||
func UseDiscovery(pool actor.GrainPool[*checkout.CheckoutGrain]) {
|
||||
|
||||
go func(hw discovery.Discovery) {
|
||||
if hw == nil {
|
||||
log.Print("No discovery service available")
|
||||
return
|
||||
}
|
||||
ch, err := hw.Watch()
|
||||
if err != nil {
|
||||
log.Printf("Discovery error: %v", err)
|
||||
return
|
||||
}
|
||||
for evt := range ch {
|
||||
if evt.Host == "" {
|
||||
continue
|
||||
}
|
||||
switch evt.IsReady {
|
||||
case false:
|
||||
if pool.IsKnown(evt.Host) {
|
||||
log.Printf("Host %s is not ready, removing", evt.Host)
|
||||
pool.RemoveHost(evt.Host)
|
||||
}
|
||||
default:
|
||||
if !pool.IsKnown(evt.Host) {
|
||||
log.Printf("Discovered host %s", evt.Host)
|
||||
pool.AddRemoteHost(evt.Host)
|
||||
}
|
||||
}
|
||||
}
|
||||
}(GetDiscovery())
|
||||
}
|
||||
142
cmd/checkout/klarna-client.go
Normal file
142
cmd/checkout/klarna-client.go
Normal file
@@ -0,0 +1,142 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type KlarnaClient struct {
|
||||
Url string
|
||||
UserName string
|
||||
Password string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewKlarnaClient(url, userName, password string) *KlarnaClient {
|
||||
return &KlarnaClient{
|
||||
Url: url,
|
||||
UserName: userName,
|
||||
Password: password,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
KlarnaPlaygroundUrl = "https://api.playground.klarna.com"
|
||||
)
|
||||
|
||||
func (k *KlarnaClient) GetOrder(ctx context.Context, orderId string) (*CheckoutOrder, error) {
|
||||
req, err := http.NewRequest("GET", k.Url+"/checkout/v3/orders/"+orderId, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
spanCtx, span := tracer.Start(ctx, "Get klarna order")
|
||||
defer span.End()
|
||||
req = req.WithContext(spanCtx)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.SetBasicAuth(k.UserName, k.Password)
|
||||
|
||||
res, err := k.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
return k.getOrderResponse(res)
|
||||
}
|
||||
|
||||
func (k *KlarnaClient) getOrderResponse(res *http.Response) (*CheckoutOrder, error) {
|
||||
var err error
|
||||
var klarnaOrderResponse CheckoutOrder
|
||||
if res.StatusCode >= 200 && res.StatusCode <= 299 {
|
||||
err = json.NewDecoder(res.Body).Decode(&klarnaOrderResponse)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &klarnaOrderResponse, nil
|
||||
}
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err == nil {
|
||||
log.Println(string(body))
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("%s", res.Status)
|
||||
}
|
||||
|
||||
func (k *KlarnaClient) CreateOrder(ctx context.Context, reader io.Reader) (*CheckoutOrder, error) {
|
||||
//bytes.NewReader(reply.Payload)
|
||||
req, err := http.NewRequest("POST", k.Url+"/checkout/v3/orders", reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
spanCtx, span := tracer.Start(ctx, "Create klarna order")
|
||||
defer span.End()
|
||||
req = req.WithContext(spanCtx)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.SetBasicAuth(k.UserName, k.Password)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
return k.getOrderResponse(res)
|
||||
}
|
||||
|
||||
func (k *KlarnaClient) UpdateOrder(ctx context.Context, orderId string, reader io.Reader) (*CheckoutOrder, error) {
|
||||
//bytes.NewReader(reply.Payload)
|
||||
req, err := http.NewRequest("POST", fmt.Sprintf("%s/checkout/v3/orders/%s", k.Url, orderId), reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
spanCtx, span := tracer.Start(ctx, "Update klarna order")
|
||||
defer span.End()
|
||||
req = req.WithContext(spanCtx)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.SetBasicAuth(k.UserName, k.Password)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if nil != err {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
return k.getOrderResponse(res)
|
||||
}
|
||||
|
||||
func (k *KlarnaClient) AbortOrder(ctx context.Context, orderId string) error {
|
||||
req, err := http.NewRequest("POST", fmt.Sprintf("%s/checkout/v3/orders/%s/abort", k.Url, orderId), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spanCtx, span := tracer.Start(ctx, "Abort klarna order")
|
||||
defer span.End()
|
||||
req = req.WithContext(spanCtx)
|
||||
req.SetBasicAuth(k.UserName, k.Password)
|
||||
|
||||
_, err = http.DefaultClient.Do(req)
|
||||
return err
|
||||
}
|
||||
|
||||
// ordermanagement/v1/orders/{order_id}/acknowledge
|
||||
func (k *KlarnaClient) AcknowledgeOrder(ctx context.Context, orderId string) error {
|
||||
req, err := http.NewRequest("POST", fmt.Sprintf("%s/ordermanagement/v1/orders/%s/acknowledge", k.Url, orderId), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
spanCtx, span := tracer.Start(ctx, "Acknowledge klarna order")
|
||||
defer span.End()
|
||||
req = req.WithContext(spanCtx)
|
||||
id := uuid.New()
|
||||
|
||||
req.SetBasicAuth(k.UserName, k.Password)
|
||||
req.Header.Add("Klarna-Idempotency-Key", id.String())
|
||||
|
||||
_, err = http.DefaultClient.Do(req)
|
||||
return err
|
||||
}
|
||||
242
cmd/checkout/klarna-handlers.go
Normal file
242
cmd/checkout/klarna-handlers.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/cart"
|
||||
"git.k6n.net/go-cart-actor/pkg/checkout"
|
||||
messages "git.k6n.net/go-cart-actor/proto/checkout"
|
||||
"github.com/matst80/go-redis-inventory/pkg/inventory"
|
||||
)
|
||||
|
||||
/*
|
||||
*
|
||||
*
|
||||
* s.CheckoutHandler(func(order *CheckoutOrder, w http.ResponseWriter) error {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Permissions-Policy", "payment=(self \"https://js.stripe.com\" \"https://m.stripe.network\" \"https://js.playground.kustom.co\")")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err := fmt.Fprintf(w, tpl, order.HTMLSnippet)
|
||||
return err
|
||||
})
|
||||
*/
|
||||
|
||||
func (s *CheckoutPoolServer) KlarnaHtmlCheckoutHandler(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error {
|
||||
|
||||
orderId := r.URL.Query().Get("order_id")
|
||||
var order *CheckoutOrder
|
||||
var err error
|
||||
if orderId == "" {
|
||||
order, err = s.CreateOrUpdateCheckout(r, checkoutId)
|
||||
if err != nil {
|
||||
logger.Error("unable to create klarna session", "error", err)
|
||||
return err
|
||||
}
|
||||
// s.ApplyKlarnaPaymentStarted(r.Context(), order, checkoutId)
|
||||
|
||||
}
|
||||
order, err = s.klarnaClient.GetOrder(r.Context(), orderId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Permissions-Policy", "payment=(self \"https://js.stripe.com\" \"https://m.stripe.network\" \"https://js.playground.kustom.co\")")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = fmt.Fprintf(w, tpl, order.HTMLSnippet)
|
||||
return err
|
||||
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) KlarnaConfirmationHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
orderId := r.PathValue("order_id")
|
||||
order, err := s.klarnaClient.GetOrder(r.Context(), orderId)
|
||||
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Apply ConfirmationViewed mutation
|
||||
cartId, ok := cart.ParseCartId(order.MerchantReference1)
|
||||
if ok {
|
||||
s.Apply(r.Context(), uint64(cartId), &messages.ConfirmationViewed{})
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if order.Status == "checkout_complete" {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "cartid",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
Expires: time.Unix(0, 0),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintf(w, tpl, order.HTMLSnippet)
|
||||
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) KlarnaValidationHandler(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("Klarna order validation, method: %s", r.Method)
|
||||
if r.Method != "POST" {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
order := &CheckoutOrder{}
|
||||
err := json.NewDecoder(r.Body).Decode(order)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
logger.InfoContext(r.Context(), "Klarna order validation received", "order_id", order.ID, "cart_id", order.MerchantReference1)
|
||||
grain, err := s.getGrainFromKlarnaOrder(r.Context(), order)
|
||||
if err != nil {
|
||||
logger.ErrorContext(r.Context(), "Unable to get grain from klarna order", "error", err.Error())
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
s.reserveInventory(r.Context(), grain)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) KlarnaNotificationHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
log.Printf("Klarna order notification, method: %s", r.Method)
|
||||
logger.InfoContext(r.Context(), "Klarna order notification received", "method", r.Method)
|
||||
if r.Method != "POST" {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
order := &CheckoutOrder{}
|
||||
err := json.NewDecoder(r.Body).Decode(order)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
log.Printf("Klarna order notification: %s", order.ID)
|
||||
logger.InfoContext(r.Context(), "Klarna order notification received", "order_id", order.ID)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) KlarnaPushHandler(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("Klarna order confirmation push, method: %s", r.Method)
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
orderId := r.URL.Query().Get("order_id")
|
||||
log.Printf("Order confirmation push: %s", orderId)
|
||||
|
||||
order, err := s.klarnaClient.GetOrder(r.Context(), orderId)
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Error creating request: %v\n", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
grain, err := s.getGrainFromKlarnaOrder(r.Context(), order)
|
||||
if err != nil {
|
||||
logger.ErrorContext(r.Context(), "Unable to get grain from klarna order", "error", err.Error())
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if s.inventoryService != nil {
|
||||
inventoryRequests := getInventoryRequests(grain.CartState.Items)
|
||||
err = s.inventoryService.ReserveInventory(r.Context(), inventoryRequests...)
|
||||
|
||||
if err != nil {
|
||||
logger.WarnContext(r.Context(), "placeorder inventory reservation failed")
|
||||
w.WriteHeader(http.StatusNotAcceptable)
|
||||
return
|
||||
}
|
||||
s.Apply(r.Context(), uint64(grain.Id), &messages.InventoryReserved{
|
||||
Id: grain.Id.String(),
|
||||
Status: "success",
|
||||
})
|
||||
}
|
||||
|
||||
// err = confirmOrder(r.Context(), order, orderHandler)
|
||||
// if err != nil {
|
||||
// log.Printf("Error confirming order: %v\n", err)
|
||||
// w.WriteHeader(http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
|
||||
// err = triggerOrderCompleted(r.Context(), a.server, order)
|
||||
// if err != nil {
|
||||
// log.Printf("Error processing cart message: %v\n", err)
|
||||
// w.WriteHeader(http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
err = s.klarnaClient.AcknowledgeOrder(r.Context(), orderId)
|
||||
if err != nil {
|
||||
log.Printf("Error acknowledging order: %v\n", err)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
var tpl = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>s10r testing - checkout</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
%s
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
func getLocationId(item *cart.CartItem) inventory.LocationID {
|
||||
if item.StoreId == nil || *item.StoreId == "" {
|
||||
return "se"
|
||||
}
|
||||
return inventory.LocationID(*item.StoreId)
|
||||
}
|
||||
|
||||
func getInventoryRequests(items []*cart.CartItem) []inventory.ReserveRequest {
|
||||
var requests []inventory.ReserveRequest
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
requests = append(requests, inventory.ReserveRequest{
|
||||
InventoryReference: &inventory.InventoryReference{
|
||||
SKU: inventory.SKU(item.Sku),
|
||||
LocationID: getLocationId(item),
|
||||
},
|
||||
Quantity: uint32(item.Quantity),
|
||||
})
|
||||
}
|
||||
return requests
|
||||
}
|
||||
|
||||
func (a *CheckoutPoolServer) getGrainFromKlarnaOrder(ctx context.Context, order *CheckoutOrder) (*checkout.CheckoutGrain, error) {
|
||||
cartId, ok := cart.ParseCartId(order.MerchantReference1)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid cart id in order reference: %s", order.MerchantReference1)
|
||||
}
|
||||
grain, err := a.Get(ctx, uint64(cartId))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get cart grain: %w", err)
|
||||
}
|
||||
return grain, nil
|
||||
}
|
||||
169
cmd/checkout/klarna-types.go
Normal file
169
cmd/checkout/klarna-types.go
Normal file
@@ -0,0 +1,169 @@
|
||||
package main
|
||||
|
||||
type (
|
||||
LineType string
|
||||
|
||||
// CheckoutOrder type is the request structure to create a new order from the Checkout API
|
||||
CheckoutOrder struct {
|
||||
ID string `json:"order_id,omitempty"`
|
||||
PurchaseCountry string `json:"purchase_country"`
|
||||
PurchaseCurrency string `json:"purchase_currency"`
|
||||
Locale string `json:"locale"`
|
||||
Status string `json:"status,omitempty"`
|
||||
BillingAddress *Address `json:"billing_address,omitempty"`
|
||||
ShippingAddress *Address `json:"shipping_address,omitempty"`
|
||||
OrderAmount int `json:"order_amount"`
|
||||
OrderTaxAmount int `json:"order_tax_amount"`
|
||||
OrderLines []*Line `json:"order_lines"`
|
||||
Customer *CheckoutCustomer `json:"customer,omitempty"`
|
||||
MerchantURLS *CheckoutMerchantURLS `json:"merchant_urls"`
|
||||
HTMLSnippet string `json:"html_snippet,omitempty"`
|
||||
MerchantReference1 string `json:"merchant_reference1,omitempty"`
|
||||
MerchantReference2 string `json:"merchant_reference2,omitempty"`
|
||||
StartedAt string `json:"started_at,omitempty"`
|
||||
CompletedAt string `json:"completed_at,omitempty"`
|
||||
LastModifiedAt string `json:"last_modified_at,omitempty"`
|
||||
Options *CheckoutOptions `json:"options,omitempty"`
|
||||
Attachment *Attachment `json:"attachment,omitempty"`
|
||||
ExternalPaymentMethods []*PaymentProvider `json:"external_payment_methods,omitempty"`
|
||||
ExternalCheckouts []*PaymentProvider `json:"external_checkouts,omitempty"`
|
||||
ShippingCountries []string `json:"shipping_countries,omitempty"`
|
||||
ShippingOptions []*ShippingOption `json:"shipping_options,omitempty"`
|
||||
MerchantData string `json:"merchant_data,omitempty"`
|
||||
GUI *GUI `json:"gui,omitempty"`
|
||||
MerchantRequested *AdditionalCheckBox `json:"merchant_requested,omitempty"`
|
||||
SelectedShippingOption *ShippingOption `json:"selected_shipping_option,omitempty"`
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
ErrorMessages []string `json:"error_messages,omitempty"`
|
||||
}
|
||||
|
||||
// GUI type wraps the GUI options
|
||||
GUI struct {
|
||||
Options []string `json:"options,omitempty"`
|
||||
}
|
||||
|
||||
// ShippingOption type is part of the CheckoutOrder structure, represent the shipping options field
|
||||
ShippingOption struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Promo string `json:"promo,omitempty"`
|
||||
Price int `json:"price"`
|
||||
TaxAmount int `json:"tax_amount"`
|
||||
TaxRate int `json:"tax_rate"`
|
||||
Preselected bool `json:"preselected,omitempty"`
|
||||
ShippingMethod string `json:"shipping_method,omitempty"`
|
||||
}
|
||||
|
||||
// PaymentProvider type is part of the CheckoutOrder structure, represent the ExternalPaymentMethods and
|
||||
// ExternalCheckouts field
|
||||
PaymentProvider struct {
|
||||
Name string `json:"name"`
|
||||
RedirectURL string `json:"redirect_url"`
|
||||
ImageURL string `json:"image_url,omitempty"`
|
||||
Fee int `json:"fee,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Countries []string `json:"countries,omitempty"`
|
||||
}
|
||||
|
||||
Attachment struct {
|
||||
ContentType string `json:"content_type"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
CheckoutOptions struct {
|
||||
AcquiringChannel string `json:"acquiring_channel,omitempty"`
|
||||
AllowSeparateShippingAddress bool `json:"allow_separate_shipping_address,omitempty"`
|
||||
ColorButton string `json:"color_button,omitempty"`
|
||||
ColorButtonText string `json:"color_button_text,omitempty"`
|
||||
ColorCheckbox string `json:"color_checkbox,omitempty"`
|
||||
ColorCheckboxCheckmark string `json:"color_checkbox_checkmark,omitempty"`
|
||||
ColorHeader string `json:"color_header,omitempty"`
|
||||
ColorLink string `json:"color_link,omitempty"`
|
||||
DateOfBirthMandatory bool `json:"date_of_birth_mandatory,omitempty"`
|
||||
ShippingDetails string `json:"shipping_details,omitempty"`
|
||||
TitleMandatory bool `json:"title_mandatory,omitempty"`
|
||||
AdditionalCheckbox *AdditionalCheckBox `json:"additional_checkbox"`
|
||||
RadiusBorder string `json:"radius_border,omitempty"`
|
||||
ShowSubtotalDetail bool `json:"show_subtotal_detail,omitempty"`
|
||||
RequireValidateCallbackSuccess bool `json:"require_validate_callback_success,omitempty"`
|
||||
AllowGlobalBillingCountries bool `json:"allow_global_billing_countries,omitempty"`
|
||||
}
|
||||
|
||||
AdditionalCheckBox struct {
|
||||
Text string `json:"text"`
|
||||
Checked bool `json:"checked"`
|
||||
Required bool `json:"required"`
|
||||
}
|
||||
|
||||
CheckoutMerchantURLS struct {
|
||||
// URL of merchant terms and conditions. Should be different than checkout, confirmation and push URLs.
|
||||
// (max 2000 characters)
|
||||
Terms string `json:"terms"`
|
||||
|
||||
// URL of merchant checkout page. Should be different than terms, confirmation and push URLs.
|
||||
// (max 2000 characters)
|
||||
Checkout string `json:"checkout"`
|
||||
|
||||
// URL of merchant confirmation page. Should be different than checkout and confirmation URLs.
|
||||
// (max 2000 characters)
|
||||
Confirmation string `json:"confirmation"`
|
||||
|
||||
// URL that will be requested when an order is completed. Should be different than checkout and
|
||||
// confirmation URLs. (max 2000 characters)
|
||||
Push string `json:"push"`
|
||||
// URL that will be requested for final merchant validation. (must be https, max 2000 characters)
|
||||
Validation string `json:"validation,omitempty"`
|
||||
|
||||
// URL for shipping option update. (must be https, max 2000 characters)
|
||||
ShippingOptionUpdate string `json:"shipping_option_update,omitempty"`
|
||||
|
||||
// URL for shipping, tax and purchase currency updates. Will be called on address changes.
|
||||
// (must be https, max 2000 characters)
|
||||
AddressUpdate string `json:"address_update,omitempty"`
|
||||
|
||||
// URL for notifications on pending orders. (max 2000 characters)
|
||||
Notification string `json:"notification,omitempty"`
|
||||
|
||||
// URL for shipping, tax and purchase currency updates. Will be called on purchase country changes.
|
||||
// (must be https, max 2000 characters)
|
||||
CountryChange string `json:"country_change,omitempty"`
|
||||
}
|
||||
|
||||
CheckoutCustomer struct {
|
||||
// DateOfBirth in string representation 2006-01-02
|
||||
DateOfBirth string `json:"date_of_birth"`
|
||||
}
|
||||
|
||||
// Address type define the address object (json serializable) being used for the API to represent billing &
|
||||
// shipping addresses
|
||||
Address struct {
|
||||
GivenName string `json:"given_name,omitempty"`
|
||||
FamilyName string `json:"family_name,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
StreetAddress string `json:"street_address,omitempty"`
|
||||
StreetAddress2 string `json:"street_address2,omitempty"`
|
||||
PostalCode string `json:"postal_code,omitempty"`
|
||||
City string `json:"city,omitempty"`
|
||||
Region string `json:"region,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Country string `json:"country,omitempty"`
|
||||
}
|
||||
|
||||
Line struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Reference string `json:"reference,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Quantity int `json:"quantity"`
|
||||
QuantityUnit string `json:"quantity_unit,omitempty"`
|
||||
UnitPrice int `json:"unit_price"`
|
||||
TaxRate int `json:"tax_rate"`
|
||||
TotalAmount int `json:"total_amount"`
|
||||
TotalDiscountAmount int `json:"total_discount_amount,omitempty"`
|
||||
TotalTaxAmount int `json:"total_tax_amount"`
|
||||
MerchantData string `json:"merchant_data,omitempty"`
|
||||
ProductURL string `json:"product_url,omitempty"`
|
||||
ImageURL string `json:"image_url,omitempty"`
|
||||
}
|
||||
)
|
||||
196
cmd/checkout/main.go
Normal file
196
cmd/checkout/main.go
Normal file
@@ -0,0 +1,196 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/actor"
|
||||
"git.k6n.net/go-cart-actor/pkg/checkout"
|
||||
"git.k6n.net/go-cart-actor/pkg/proxy"
|
||||
"github.com/adyen/adyen-go-api-library/v21/src/adyen"
|
||||
"github.com/adyen/adyen-go-api-library/v21/src/common"
|
||||
"github.com/matst80/go-redis-inventory/pkg/inventory"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
)
|
||||
|
||||
var (
|
||||
grainSpawns = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "checkout_grain_spawned_total",
|
||||
Help: "The total number of spawned checkout grains",
|
||||
})
|
||||
)
|
||||
|
||||
func init() {
|
||||
os.Mkdir("data", 0755)
|
||||
}
|
||||
|
||||
type App struct {
|
||||
pool *actor.SimpleGrainPool[checkout.CheckoutGrain]
|
||||
server *CheckoutPoolServer
|
||||
klarnaClient *KlarnaClient
|
||||
cartClient *CartClient // For internal communication to cart
|
||||
}
|
||||
|
||||
var podIp = os.Getenv("POD_IP")
|
||||
var name = os.Getenv("POD_NAME")
|
||||
var amqpUrl = os.Getenv("AMQP_URL")
|
||||
var redisAddress = os.Getenv("REDIS_ADDRESS")
|
||||
var redisPassword = os.Getenv("REDIS_PASSWORD")
|
||||
var cartInternalUrl = os.Getenv("CART_INTERNAL_URL") // e.g., http://cart-service:8081
|
||||
|
||||
func main() {
|
||||
|
||||
controlPlaneConfig := actor.DefaultServerConfig()
|
||||
|
||||
reg := checkout.NewCheckoutMutationRegistry(checkout.NewCheckoutMutationContext())
|
||||
reg.RegisterProcessor(
|
||||
actor.NewMutationProcessor(func(ctx context.Context, g *checkout.CheckoutGrain) error {
|
||||
g.Version++
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: redisAddress,
|
||||
Password: redisPassword,
|
||||
DB: 0,
|
||||
})
|
||||
inventoryService, err := inventory.NewRedisInventoryService(rdb)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating inventory service: %v\n", err)
|
||||
}
|
||||
|
||||
diskStorage := actor.NewDiskStorage[checkout.CheckoutGrain]("data", reg)
|
||||
|
||||
poolConfig := actor.GrainPoolConfig[checkout.CheckoutGrain]{
|
||||
MutationRegistry: reg,
|
||||
Storage: diskStorage,
|
||||
Spawn: func(ctx context.Context, id uint64) (actor.Grain[checkout.CheckoutGrain], error) {
|
||||
_, span := tracer.Start(ctx, fmt.Sprintf("Spawn checkout id %d", id))
|
||||
defer span.End()
|
||||
grainSpawns.Inc()
|
||||
|
||||
ret := checkout.NewCheckoutGrain(id, 0, 0, time.Now(), nil) // version to be set later
|
||||
return ret, nil
|
||||
},
|
||||
Destroy: func(grain actor.Grain[checkout.CheckoutGrain]) error {
|
||||
return nil
|
||||
},
|
||||
SpawnHost: func(host string) (actor.Host, error) {
|
||||
return proxy.NewRemoteHost[checkout.CheckoutGrain](host)
|
||||
},
|
||||
TTL: 1 * time.Hour, // Longer TTL for checkout
|
||||
PoolSize: 65535,
|
||||
Hostname: podIp,
|
||||
}
|
||||
|
||||
pool, err := actor.NewSimpleGrainPool(poolConfig)
|
||||
if err != nil {
|
||||
log.Fatalf("Error creating checkout pool: %v\n", err)
|
||||
}
|
||||
|
||||
adyenClient := adyen.NewClient(&common.Config{
|
||||
ApiKey: os.Getenv("ADYEN_API_KEY"),
|
||||
Environment: common.TestEnv,
|
||||
})
|
||||
|
||||
klarnaClient := NewKlarnaClient(KlarnaPlaygroundUrl, os.Getenv("KLARNA_API_USERNAME"), os.Getenv("KLARNA_API_PASSWORD"))
|
||||
|
||||
cartClient := NewCartClient(cartInternalUrl)
|
||||
|
||||
syncedServer := NewCheckoutPoolServer(pool, fmt.Sprintf("%s, %s", name, podIp), klarnaClient, cartClient, adyenClient)
|
||||
syncedServer.inventoryService = inventoryService
|
||||
|
||||
mux := http.NewServeMux()
|
||||
debugMux := http.NewServeMux()
|
||||
|
||||
if amqpUrl == "" {
|
||||
log.Fatalf("no connection to amqp defined")
|
||||
}
|
||||
|
||||
grpcSrv, err := actor.NewControlServer[*checkout.CheckoutGrain](controlPlaneConfig, pool)
|
||||
if err != nil {
|
||||
log.Fatalf("Error starting control plane gRPC server: %v\n", err)
|
||||
}
|
||||
defer grpcSrv.GracefulStop()
|
||||
|
||||
UseDiscovery(pool)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
|
||||
otelShutdown, err := setupOTelSDK(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("Unable to start otel %v", err)
|
||||
}
|
||||
|
||||
syncedServer.Serve(mux)
|
||||
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
grainCount, capacity := pool.LocalUsage()
|
||||
if grainCount >= capacity {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("grain pool at capacity"))
|
||||
return
|
||||
}
|
||||
if !pool.IsHealthy() {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("control plane not healthy"))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("ok"))
|
||||
})
|
||||
mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("ok"))
|
||||
})
|
||||
mux.HandleFunc("/livez", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("ok"))
|
||||
})
|
||||
|
||||
mux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("1.0.0"))
|
||||
})
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":8080",
|
||||
BaseContext: func(net.Listener) context.Context { return ctx },
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 20 * time.Second,
|
||||
Handler: otelhttp.NewHandler(mux, "/"),
|
||||
}
|
||||
|
||||
defer func() {
|
||||
fmt.Println("Shutting down due to signal")
|
||||
otelShutdown(context.Background())
|
||||
diskStorage.Close()
|
||||
pool.Close()
|
||||
}()
|
||||
|
||||
srvErr := make(chan error, 1)
|
||||
go func() {
|
||||
srvErr <- srv.ListenAndServe()
|
||||
}()
|
||||
|
||||
log.Print("Checkout server started at port 8080")
|
||||
|
||||
go http.ListenAndServe(":8081", debugMux)
|
||||
|
||||
select {
|
||||
case err = <-srvErr:
|
||||
log.Fatalf("Unable to start server: %v", err)
|
||||
case <-ctx.Done():
|
||||
stop()
|
||||
}
|
||||
}
|
||||
117
cmd/checkout/otel.go
Normal file
117
cmd/checkout/otel.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
|
||||
"go.opentelemetry.io/otel/log/global"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/sdk/log"
|
||||
"go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/trace"
|
||||
)
|
||||
|
||||
// setupOTelSDK bootstraps the OpenTelemetry pipeline.
|
||||
// If it does not return an error, make sure to call shutdown for proper cleanup.
|
||||
func setupOTelSDK(ctx context.Context) (func(context.Context) error, error) {
|
||||
var shutdownFuncs []func(context.Context) error
|
||||
var err error
|
||||
|
||||
// shutdown calls cleanup functions registered via shutdownFuncs.
|
||||
// The errors from the calls are joined.
|
||||
// Each registered cleanup will be invoked once.
|
||||
shutdown := func(ctx context.Context) error {
|
||||
var err error
|
||||
for _, fn := range shutdownFuncs {
|
||||
err = errors.Join(err, fn(ctx))
|
||||
}
|
||||
shutdownFuncs = nil
|
||||
return err
|
||||
}
|
||||
|
||||
// handleErr calls shutdown for cleanup and makes sure that all errors are returned.
|
||||
handleErr := func(inErr error) {
|
||||
err = errors.Join(inErr, shutdown(ctx))
|
||||
}
|
||||
|
||||
// Set up propagator.
|
||||
prop := newPropagator()
|
||||
otel.SetTextMapPropagator(prop)
|
||||
|
||||
// Set up trace provider.
|
||||
tracerProvider, err := newTracerProvider()
|
||||
if err != nil {
|
||||
handleErr(err)
|
||||
return shutdown, err
|
||||
}
|
||||
shutdownFuncs = append(shutdownFuncs, tracerProvider.Shutdown)
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
|
||||
// Set up meter provider.
|
||||
meterProvider, err := newMeterProvider()
|
||||
if err != nil {
|
||||
handleErr(err)
|
||||
return shutdown, err
|
||||
}
|
||||
shutdownFuncs = append(shutdownFuncs, meterProvider.Shutdown)
|
||||
otel.SetMeterProvider(meterProvider)
|
||||
|
||||
// Set up logger provider.
|
||||
loggerProvider, err := newLoggerProvider()
|
||||
if err != nil {
|
||||
handleErr(err)
|
||||
return shutdown, err
|
||||
}
|
||||
shutdownFuncs = append(shutdownFuncs, loggerProvider.Shutdown)
|
||||
global.SetLoggerProvider(loggerProvider)
|
||||
|
||||
return shutdown, err
|
||||
}
|
||||
|
||||
func newPropagator() propagation.TextMapPropagator {
|
||||
return propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
)
|
||||
}
|
||||
|
||||
func newTracerProvider() (*trace.TracerProvider, error) {
|
||||
traceExporter, err := otlptracegrpc.New(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tracerProvider := trace.NewTracerProvider(
|
||||
trace.WithBatcher(traceExporter,
|
||||
// Default is 5s. Set to 1s for demonstrative purposes.
|
||||
trace.WithBatchTimeout(time.Second)),
|
||||
)
|
||||
return tracerProvider, nil
|
||||
}
|
||||
|
||||
func newMeterProvider() (*metric.MeterProvider, error) {
|
||||
exporter, err := otlpmetricgrpc.New(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
provider := metric.NewMeterProvider(metric.WithReader(metric.NewPeriodicReader(exporter)))
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func newLoggerProvider() (*log.LoggerProvider, error) {
|
||||
logExporter, err := otlploggrpc.New(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
loggerProvider := log.NewLoggerProvider(
|
||||
log.WithProcessor(log.NewBatchProcessor(logExporter)),
|
||||
)
|
||||
return loggerProvider, nil
|
||||
}
|
||||
237
cmd/checkout/pool-server.go
Normal file
237
cmd/checkout/pool-server.go
Normal file
@@ -0,0 +1,237 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/actor"
|
||||
"git.k6n.net/go-cart-actor/pkg/cart"
|
||||
"git.k6n.net/go-cart-actor/pkg/checkout"
|
||||
messages "git.k6n.net/go-cart-actor/proto/checkout"
|
||||
|
||||
adyen "github.com/adyen/adyen-go-api-library/v21/src/adyen"
|
||||
"github.com/matst80/go-redis-inventory/pkg/inventory"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var (
|
||||
grainMutations = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "checkout_grain_mutations_total",
|
||||
Help: "The total number of mutations",
|
||||
})
|
||||
grainLookups = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "checkout_grain_lookups_total",
|
||||
Help: "The total number of lookups",
|
||||
})
|
||||
)
|
||||
|
||||
type CheckoutPoolServer struct {
|
||||
actor.GrainPool[*checkout.CheckoutGrain]
|
||||
pod_name string
|
||||
klarnaClient *KlarnaClient
|
||||
adyenClient *adyen.APIClient
|
||||
cartClient *CartClient
|
||||
inventoryService *inventory.RedisInventoryService
|
||||
}
|
||||
|
||||
func NewCheckoutPoolServer(pool actor.GrainPool[*checkout.CheckoutGrain], pod_name string, klarnaClient *KlarnaClient, cartClient *CartClient, adyenClient *adyen.APIClient) *CheckoutPoolServer {
|
||||
srv := &CheckoutPoolServer{
|
||||
GrainPool: pool,
|
||||
pod_name: pod_name,
|
||||
klarnaClient: klarnaClient,
|
||||
cartClient: cartClient,
|
||||
adyenClient: adyenClient,
|
||||
}
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) ApplyLocal(ctx context.Context, id checkout.CheckoutId, mutation ...proto.Message) (*actor.MutationResult[*checkout.CheckoutGrain], error) {
|
||||
return s.Apply(ctx, uint64(id), mutation...)
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) GetCheckoutHandler(w http.ResponseWriter, r *http.Request, id checkout.CheckoutId) error {
|
||||
grain, err := s.Get(r.Context(), uint64(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.WriteResult(w, grain)
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) WriteResult(w http.ResponseWriter, result any) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("X-Pod-Name", s.pod_name)
|
||||
if result == nil {
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
return nil
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
enc := json.NewEncoder(w)
|
||||
err := enc.Encode(result)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) CreateOrUpdateCheckout(r *http.Request, id checkout.CheckoutId) (*CheckoutOrder, error) {
|
||||
// Get cart state from cart service
|
||||
cartGrain, err := s.Get(r.Context(), uint64(id))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
meta := GetCheckoutMetaFromRequest(r)
|
||||
|
||||
payload, _, err := BuildCheckoutOrderPayload(cartGrain, meta)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
grain, err := s.Get(r.Context(), uint64(id))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if grain.OrderId != nil {
|
||||
return s.klarnaClient.UpdateOrder(r.Context(), *grain.OrderId, bytes.NewReader(payload))
|
||||
} else {
|
||||
return s.klarnaClient.CreateOrder(r.Context(), bytes.NewReader(payload))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) ApplyKlarnaPaymentStarted(ctx context.Context, klarnaOrder *CheckoutOrder, id checkout.CheckoutId) (*actor.MutationResult[*checkout.CheckoutGrain], error) {
|
||||
method := "checkout"
|
||||
return s.ApplyLocal(ctx, id, &messages.PaymentStarted{
|
||||
PaymentId: klarnaOrder.ID,
|
||||
Amount: int64(klarnaOrder.OrderAmount),
|
||||
Currency: klarnaOrder.PurchaseCurrency,
|
||||
Provider: "klarna",
|
||||
Method: &method,
|
||||
StartedAt: timestamppb.New(time.Now()),
|
||||
})
|
||||
}
|
||||
|
||||
// func (s *CheckoutPoolServer) CheckoutHandler(fn func(order *CheckoutOrder, w http.ResponseWriter) error) func(w http.ResponseWriter, r *http.Request) {
|
||||
// return CheckoutIdHandler(s.ProxyHandler(func(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error {
|
||||
// orderId := r.URL.Query().Get("order_id")
|
||||
// if orderId == "" {
|
||||
// order, err := s.CreateOrUpdateCheckout(r, checkoutId)
|
||||
// if err != nil {
|
||||
// logger.Error("unable to create klarna session", "error", err)
|
||||
// return err
|
||||
// }
|
||||
// s.ApplyKlarnaPaymentStarted(r.Context(), order, checkoutId)
|
||||
// return fn(order, w)
|
||||
// }
|
||||
// order, err := s.klarnaClient.GetOrder(r.Context(), orderId)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// return fn(order, w)
|
||||
// }))
|
||||
// }
|
||||
|
||||
var (
|
||||
tracer = otel.Tracer(name)
|
||||
hmacKey = os.Getenv("ADYEN_HMAC")
|
||||
meter = otel.Meter(name)
|
||||
logger = otelslog.NewLogger(name)
|
||||
proxyCalls metric.Int64Counter
|
||||
)
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
proxyCalls, err = meter.Int64Counter("proxy.calls",
|
||||
metric.WithDescription("Number of proxy calls"),
|
||||
metric.WithUnit("{calls}"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) Serve(mux *http.ServeMux) {
|
||||
handleFunc := func(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
|
||||
attr := attribute.String("http.route", pattern)
|
||||
mux.HandleFunc(pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
span := trace.SpanFromContext(r.Context())
|
||||
span.SetName(pattern)
|
||||
span.SetAttributes(attr)
|
||||
|
||||
labeler, _ := otelhttp.LabelerFromContext(r.Context())
|
||||
labeler.Add(attr)
|
||||
|
||||
handlerFunc(w, r)
|
||||
}))
|
||||
}
|
||||
handleFunc("/payment/adyen/session", CheckoutIdHandler(s.AdyenSessionHandler))
|
||||
handleFunc("/payment/adyen/push", s.AdyenHookHandler)
|
||||
handleFunc("/payment/adyen/return", s.AdyenReturnHandler)
|
||||
//handleFunc("/payment/adyen/cancel", s.AdyenCancelHandler)
|
||||
|
||||
handleFunc("/payment/klarna/validate", s.KlarnaValidationHandler)
|
||||
handleFunc("/payment/klarna/notification", s.KlarnaNotificationHandler)
|
||||
|
||||
conn, err := amqp.Dial(amqpUrl)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to connect to RabbitMQ: %v", err)
|
||||
}
|
||||
|
||||
orderHandler := NewAmqpOrderHandler(conn)
|
||||
orderHandler.DefineQueue()
|
||||
|
||||
handleFunc("GET /checkout", CheckoutIdHandler(s.ProxyHandler(s.KlarnaHtmlCheckoutHandler)))
|
||||
|
||||
handleFunc("GET /confirmation/{order_id}", s.KlarnaConfirmationHandler)
|
||||
|
||||
// handleFunc("GET /checkout", s.CheckoutHandler(func(order *CheckoutOrder, w http.ResponseWriter) error {
|
||||
// w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
// w.Header().Set("Permissions-Policy", "payment=(self \"https://js.stripe.com\" \"https://m.stripe.network\" \"https://js.playground.kustom.co\")")
|
||||
// w.WriteHeader(http.StatusOK)
|
||||
// _, err := fmt.Fprintf(w, tpl, order.HTMLSnippet)
|
||||
// return err
|
||||
// }))
|
||||
|
||||
handleFunc("GET /confirmation/{order_id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
orderId := r.PathValue("order_id")
|
||||
order, err := s.klarnaClient.GetOrder(r.Context(), orderId)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Apply ConfirmationViewed to checkout
|
||||
checkoutId := checkout.CheckoutId(cart.MustNewCartId()) // Need to resolve from order
|
||||
s.Apply(r.Context(), uint64(checkoutId), &messages.ConfirmationViewed{})
|
||||
|
||||
// Callback to cart
|
||||
|
||||
// cartId := cart.CartId(checkoutId) // Assuming same
|
||||
// s.cartClient.ApplyMutation(cartId, &messages.OrderCreated{OrderId: order.ID, Status: order.Status})
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintf(w, tpl, order.HTMLSnippet)
|
||||
})
|
||||
}
|
||||
115
cmd/checkout/utils.go
Normal file
115
cmd/checkout/utils.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.k6n.net/go-cart-actor/pkg/cart"
|
||||
"git.k6n.net/go-cart-actor/pkg/checkout"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
func getOriginalHost(r *http.Request) string {
|
||||
proxyHost := r.Header.Get("X-Forwarded-Host")
|
||||
if proxyHost != "" {
|
||||
return proxyHost
|
||||
}
|
||||
return r.Host
|
||||
}
|
||||
|
||||
func getClientIp(r *http.Request) string {
|
||||
ip := r.Header.Get("X-Forwarded-For")
|
||||
if ip == "" {
|
||||
ip = r.RemoteAddr
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func getCurrency(country string) string {
|
||||
if country == "no" {
|
||||
return "NOK"
|
||||
}
|
||||
return "SEK"
|
||||
}
|
||||
|
||||
func getLocale(country string) string {
|
||||
if country == "no" {
|
||||
return "nb-no"
|
||||
}
|
||||
return "sv-se"
|
||||
}
|
||||
|
||||
func getCountryFromHost(host string) string {
|
||||
if strings.Contains(strings.ToLower(host), "-no") {
|
||||
return "no"
|
||||
}
|
||||
if strings.Contains(strings.ToLower(host), "-se") {
|
||||
return "se"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (a *CheckoutPoolServer) reserveInventory(ctx context.Context, grain *checkout.CheckoutGrain) error {
|
||||
if a.inventoryService != nil {
|
||||
inventoryRequests := getInventoryRequests(grain.CartState.Items)
|
||||
_, err := a.inventoryService.ReservationCheck(ctx, inventoryRequests...)
|
||||
if err != nil {
|
||||
logger.WarnContext(ctx, "placeorder inventory check failed")
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CheckoutIdHandler(fn func(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var id checkout.CheckoutId
|
||||
raw := r.PathValue("id")
|
||||
if raw == "" {
|
||||
id = checkout.CheckoutId(cart.MustNewCartId())
|
||||
w.Header().Set("Set-Checkout-Id", id.String())
|
||||
} else {
|
||||
if parsedId, ok := cart.ParseCartId(raw); !ok {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte("checkout id is invalid"))
|
||||
return
|
||||
} else {
|
||||
id = checkout.CheckoutId(parsedId)
|
||||
}
|
||||
}
|
||||
|
||||
err := fn(w, r, id)
|
||||
if err != nil {
|
||||
log.Printf("Server error, not remote error: %v\n", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(err.Error()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CheckoutPoolServer) ProxyHandler(fn func(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error) func(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error {
|
||||
return func(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error {
|
||||
if ownerHost, ok := s.OwnerHost(uint64(checkoutId)); ok {
|
||||
ctx, span := tracer.Start(r.Context(), "proxy")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("checkoutid", checkoutId.String()))
|
||||
hostAttr := attribute.String("other host", ownerHost.Name())
|
||||
span.SetAttributes(hostAttr)
|
||||
logger.InfoContext(ctx, "checkout proxyed", "result", ownerHost.Name())
|
||||
proxyCalls.Add(ctx, 1, metric.WithAttributes(hostAttr))
|
||||
handled, err := ownerHost.Proxy(uint64(checkoutId), w, r, nil)
|
||||
|
||||
grainLookups.Inc()
|
||||
if err == nil && handled {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
_, span := tracer.Start(r.Context(), "own")
|
||||
span.SetAttributes(attribute.String("checkoutid", checkoutId.String()))
|
||||
defer span.End()
|
||||
return fn(w, r, checkoutId)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user