| 1 | package hbank |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/hmac" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // Callback is what HBank POSTs to a payment's callback URL right before charging the customer. HBank charges only |
| 17 | // if you answer 200 with {"resume": true} as application/json within 10 seconds. |
| 18 | // |
| 19 | // It's signed: check the HBank-Signature header with your business's signing secret (business settings → Callback |
| 20 | // URLs) before you approve, with VerifySignature or SignedCallbackHandler. Also check that ID and Amount match an order |
| 21 | // you created, and confirm with GetPayment before handing out goods. |
| 22 | type Callback struct { |
| 23 | ID int64 `json:"id"` |
| 24 | Amount json.Number `json:"amount"` |
| 25 | Currency string `json:"currency"` |
| 26 | Status string `json:"status"` |
| 27 | Description string `json:"description"` |
| 28 | } |
| 29 | |
| 30 | // CallbackAnswer is the JSON answer to a callback. |
| 31 | type CallbackAnswer struct { |
| 32 | Resume bool `json:"resume"` |
| 33 | Error string `json:"error,omitempty"` |
| 34 | } |
| 35 | |
| 36 | // Approve lets HBank charge the customer. |
| 37 | func Approve() CallbackAnswer { return CallbackAnswer{Resume: true} } |
| 38 | |
| 39 | // Refuse refuses the payment; the customer sees message (may be ""). |
| 40 | func Refuse(message string) CallbackAnswer { return CallbackAnswer{Resume: false, Error: message} } |
| 41 | |
| 42 | // ParseCallback reads a callback request body. It returns an *Error with Code "invalid_callback" if it isn't one. |
| 43 | func ParseCallback(body io.Reader) (*Callback, error) { |
| 44 | dec := json.NewDecoder(io.LimitReader(body, 1<<20)) |
| 45 | dec.UseNumber() |
| 46 | var cb Callback |
| 47 | if err := dec.Decode(&cb); err != nil { |
| 48 | return nil, &Error{Code: "invalid_callback", Message: err.Error(), Err: err} |
| 49 | } |
| 50 | if cb.ID <= 0 || cb.Amount == "" || cb.Currency == "" { |
| 51 | return nil, &Error{Code: "invalid_callback", Message: "missing id, amount or currency"} |
| 52 | } |
| 53 | return &cb, nil |
| 54 | } |
| 55 | |
| 56 | // SignatureTolerance is how old a callback's signature may be. |
| 57 | const SignatureTolerance = 5 * time.Minute |
| 58 | |
| 59 | // VerifySignature reports whether header (the request's HBank-Signature: "t=<unix time>,v1=<hex>") signs body (the raw |
| 60 | // request body, exactly as received) with secret, and was made within SignatureTolerance of now. |
| 61 | func VerifySignature(secret, header string, body []byte, now time.Time) bool { |
| 62 | if secret == "" || header == "" { |
| 63 | return false |
| 64 | } |
| 65 | var t, v1 string |
| 66 | for _, part := range strings.Split(header, ",") { |
| 67 | if k, v, ok := strings.Cut(part, "="); ok { |
| 68 | switch k { |
| 69 | case "t": |
| 70 | t = v |
| 71 | case "v1": |
| 72 | v1 = v |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | ts, err := strconv.ParseInt(t, 10, 64) |
| 77 | if err != nil { |
| 78 | return false |
| 79 | } |
| 80 | if d := now.Sub(time.Unix(ts, 0)); d > SignatureTolerance || d < -SignatureTolerance { |
| 81 | return false |
| 82 | } |
| 83 | mac := hmac.New(sha256.New, []byte(secret)) |
| 84 | mac.Write([]byte(t + ".")) |
| 85 | mac.Write(body) |
| 86 | return hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(v1)) |
| 87 | } |
| 88 | |
| 89 | // SignedCallbackHandler is CallbackHandler that first checks the HBank-Signature with your signing secret: a callback |
| 90 | // without a valid one is refused ("Invalid callback") before decide is called. |
| 91 | func SignedCallbackHandler(secret string, decide func(r *http.Request, cb *Callback) (CallbackAnswer, error)) http.Handler { |
| 92 | inner := CallbackHandler(decide) |
| 93 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 94 | body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) |
| 95 | if err != nil || !VerifySignature(secret, r.Header.Get("HBank-Signature"), body, time.Now()) { |
| 96 | w.Header().Set("Content-Type", "application/json") |
| 97 | w.WriteHeader(http.StatusOK) |
| 98 | _ = json.NewEncoder(w).Encode(Refuse("Invalid callback")) |
| 99 | return |
| 100 | } |
| 101 | r.Body = io.NopCloser(bytes.NewReader(body)) |
| 102 | inner.ServeHTTP(w, r) |
| 103 | }) |
| 104 | } |
| 105 | |
| 106 | // CallbackHandler returns an http.Handler for your callback URL; works with net/http, chi, gorilla/mux, and Gin or |
| 107 | // Echo via their WrapH helpers. decide returns the answer; an error refuses the payment with a generic message. |
| 108 | // |
| 109 | // mux.Handle("POST /hbank/callback", hbank.CallbackHandler(func(r *http.Request, cb *hbank.Callback) (hbank.CallbackAnswer, error) { |
| 110 | // order, err := orders.ByTransaction(r.Context(), cb.ID) |
| 111 | // if err != nil || order.Total != cb.Amount.String() { |
| 112 | // return hbank.Refuse("This order is no longer available"), err |
| 113 | // } |
| 114 | // return hbank.Approve(), nil |
| 115 | // })) |
| 116 | func CallbackHandler(decide func(r *http.Request, cb *Callback) (CallbackAnswer, error)) http.Handler { |
| 117 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 118 | answer := Refuse("Invalid callback") |
| 119 | if cb, err := ParseCallback(r.Body); err == nil { |
| 120 | if a, err := decide(r, cb); err != nil { |
| 121 | answer = Refuse("The shop couldn't confirm this order") |
| 122 | } else { |
| 123 | answer = a |
| 124 | } |
| 125 | } |
| 126 | w.Header().Set("Content-Type", "application/json") |
| 127 | w.WriteHeader(http.StatusOK) |
| 128 | _ = json.NewEncoder(w).Encode(answer) |
| 129 | }) |
| 130 | } |