This commit is contained in:
matst80
2024-11-14 22:53:32 +01:00
parent 0870a37d90
commit 69d92716c3
10 changed files with 283 additions and 47 deletions

View File

@@ -1,9 +1,11 @@
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"os"
"strconv"
messages "git.tornberg.me/go-cart-actor/proto"
@@ -198,6 +200,50 @@ func (s *PoolServer) HandleAddRequest(w http.ResponseWriter, r *http.Request) er
return s.WriteResult(w, reply)
}
var (
APIUsername = os.Getenv("KLARNA_API_USERNAME")
APIPassword = os.Getenv("KLARNA_API_PASSWORD")
)
func (s *PoolServer) HandleCheckout(w http.ResponseWriter, r *http.Request) error {
id := r.PathValue("id")
reply, err := s.pool.Process(ToCartId(id), Message{
Type: CreateCheckoutOrderType,
Content: &messages.CreateCheckoutOrder{
Terms: "https://tornberg.me/terms",
Checkout: "https://tornberg.me/checkout",
Confirmation: "https://tornberg.me/confirmation",
Push: "https://cart.tornberg.me/push",
},
})
if err != nil {
return err
}
if reply.StatusCode != 200 {
return s.WriteResult(w, reply)
}
req, err := http.NewRequest("POST", "https://api.playground.klarna.com/checkout/v3/orders", bytes.NewReader(reply.Payload))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
req.SetBasicAuth(APIUsername, APIPassword)
res, err := http.DefaultClient.Do(req)
if nil != err {
return err
}
buf := new(bytes.Buffer)
buf.ReadFrom(res.Body)
w.Write(buf.Bytes())
return nil
}
func (s *PoolServer) Serve() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /{id}", ErrorHandler(s.HandleGet))
@@ -208,5 +254,7 @@ func (s *PoolServer) Serve() *http.ServeMux {
mux.HandleFunc("POST /{id}/delivery", ErrorHandler(s.HandleSetDelivery))
mux.HandleFunc("DELETE /{id}/delivery/{deliveryId}", ErrorHandler(s.HandleRemoveDelivery))
mux.HandleFunc("PUT /{id}/delivery/{deliveryId}/pickupPoint", ErrorHandler(s.HandleSetPickupPoint))
mux.HandleFunc("GET /{id}/checkout", ErrorHandler(s.HandleCheckout))
return mux
}