111 lines
2.5 KiB
Go
111 lines
2.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"shop/internal/heleket"
|
|
"shop/internal/models"
|
|
)
|
|
|
|
const heleketWebhookIP = "31.133.220.8"
|
|
|
|
func (h *CustomerHandler) HeleketWebhook(w http.ResponseWriter, r *http.Request) {
|
|
if !h.heleket.Enabled() {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
host = r.RemoteAddr
|
|
}
|
|
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
|
|
host = fwd
|
|
}
|
|
if host != heleketWebhookIP && host != "" {
|
|
log.Printf("heleket webhook: note ip %s (expected %s)", host, heleketWebhookIP)
|
|
}
|
|
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
|
if err != nil {
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
payload, ok := heleket.VerifyWebhook(body, h.heleketAPIKey)
|
|
if !ok {
|
|
log.Printf("heleket webhook: invalid signature")
|
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
orderIDStr, _ := payload["order_id"].(string)
|
|
orderID, ok := heleket.ParseOrderExternalID(orderIDStr)
|
|
if !ok {
|
|
log.Printf("heleket webhook: unknown order_id %q", orderIDStr)
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
|
|
paymentStatus, _ := payload["payment_status"].(string)
|
|
if paymentStatus == "" {
|
|
if s, ok := payload["status"].(string); ok {
|
|
paymentStatus = s
|
|
}
|
|
}
|
|
|
|
ctx := r.Context()
|
|
orderStatus := heleket.MapPaymentStatus(paymentStatus)
|
|
if err := h.orders.UpdateHeleketStatus(ctx, orderID, paymentStatus, orderStatus); err != nil {
|
|
log.Printf("heleket webhook update: %v", err)
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
type orderPayPage struct {
|
|
shopPage
|
|
Order models.Order
|
|
}
|
|
|
|
func (h *CustomerHandler) OrderSuccess(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(r.PathValue("id"))
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
order, err := h.orders.GetByID(r.Context(), id)
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
p := orderPayPage{
|
|
shopPage: h.basePage(r, w, "Заказ #"+strconv.Itoa(order.ID)),
|
|
Order: order,
|
|
}
|
|
h.render(w, "order_success.html", p)
|
|
}
|
|
|
|
func (h *CustomerHandler) OrderPay(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(r.PathValue("id"))
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
order, err := h.orders.GetByID(r.Context(), id)
|
|
if err != nil || !order.IsHeleket() {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if order.HeleketPaymentURL != "" && !heleket.IsPaid(order.HeleketPaymentStatus) {
|
|
http.Redirect(w, r, order.HeleketPaymentURL, http.StatusSeeOther)
|
|
return
|
|
}
|
|
http.Redirect(w, r, "/order/"+strconv.Itoa(id)+"/success", http.StatusSeeOther)
|
|
}
|