| 1 | package hbank |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | func fake(t *testing.T, handler func(path string, body map[string]any) (int, string)) *Client { |
| 16 | t.Helper() |
| 17 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 18 | if r.Header.Get("Authorization") != "Bearer test_key" { |
| 19 | w.WriteHeader(http.StatusForbidden) |
| 20 | io.WriteString(w, "Invalid API key") |
| 21 | return |
| 22 | } |
| 23 | var body map[string]any |
| 24 | _ = json.NewDecoder(r.Body).Decode(&body) |
| 25 | status, text := handler(r.URL.RequestURI(), body) |
| 26 | w.Header().Set("Content-Type", "application/json") |
| 27 | w.WriteHeader(status) |
| 28 | io.WriteString(w, text) |
| 29 | })) |
| 30 | t.Cleanup(srv.Close) |
| 31 | return New("test_key", WithBaseURL(srv.URL)) |
| 32 | } |
| 33 | |
| 34 | func TestCreatePaymentSendsAmountAsString(t *testing.T) { |
| 35 | c := fake(t, func(path string, body map[string]any) (int, string) { |
| 36 | if path != "/api/v1/payment/request" || body["amount"] != "24.90" || body["currency"] != "EUR" { |
| 37 | t.Errorf("unexpected request %s %v", path, body) |
| 38 | } |
| 39 | if _, ok := body["description"]; ok { |
| 40 | t.Errorf("empty description should be left out") |
| 41 | } |
| 42 | return 200, `{"success": true, "transaction_id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v"}` |
| 43 | }) |
| 44 | tid, err := c.CreatePayment(context.Background(), PaymentRequest{Amount: "24.90", Currency: "EUR"}) |
| 45 | if err != nil || tid != "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v" { |
| 46 | t.Fatalf("got %s, %v", tid, err) |
| 47 | } |
| 48 | if got := c.CheckoutURL(tid); !strings.HasSuffix(got, "/api/payment?tid=tx_8fK2mQ7xRb4Tn9WcYz3LpH6v") { |
| 49 | t.Errorf("checkout url %s", got) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func TestPaymentKeepsDigitsAndTimes(t *testing.T) { |
| 54 | c := fake(t, func(path string, _ map[string]any) (int, string) { |
| 55 | if strings.HasPrefix(path, "/api/v1/subscriptions/sub_Hk3Rt9WzQe5NcXa2LpVb7YdF") { |
| 56 | return 200, `{"success": true, "subscription": {"id": "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF", "status": "active", "amount": 9.99, "subscribed_at": "2026-10-03T09:12:44.1234567Z", "customer": {"name": "Ada"}}}` |
| 57 | } |
| 58 | return 200, `{"success": true, "transaction": {"id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "amount": 24.90, "refunded": 0.00, "status": "completed"}}` |
| 59 | }) |
| 60 | p, err := c.GetPayment(context.Background(), "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v") |
| 61 | if err != nil || p.Amount.String() != "24.90" || !p.Completed() { |
| 62 | t.Fatalf("got %+v, %v", p, err) |
| 63 | } |
| 64 | s, err := c.GetSubscription(context.Background(), "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF") |
| 65 | if err != nil || s.SubscribedAt == nil || s.SubscribedAt.Nanosecond() != 123456700 || s.Customer.Name != "Ada" { |
| 66 | t.Fatalf("got %+v, %v", s, err) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | func TestErrors(t *testing.T) { |
| 71 | c := fake(t, func(string, map[string]any) (int, string) { |
| 72 | return 409, `{"success": false, "error": "not_refundable", "message": "Already refunded."}` |
| 73 | }) |
| 74 | _, err := c.Refund(context.Background(), "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "", "") |
| 75 | var e *Error |
| 76 | if !errors.As(err, &e) || e.Code != "not_refundable" || e.Status != 409 || e.Message != "Already refunded." { |
| 77 | t.Fatalf("got %v", err) |
| 78 | } |
| 79 | _, err = New("nope", WithBaseURL(c.BaseURL)).ListSubscriptions(context.Background()) |
| 80 | if !IsCode(err, "invalid_api_key") { |
| 81 | t.Fatalf("got %v", err) |
| 82 | } |
| 83 | _, err = New("k", WithBaseURL("http://127.0.0.1:1")).Rate(context.Background(), "EUR", "USD") |
| 84 | if !IsCode(err, "connection_failed") { |
| 85 | t.Fatalf("got %v", err) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func TestCallbackHandler(t *testing.T) { |
| 90 | h := CallbackHandler(func(_ *http.Request, cb *Callback) (CallbackAnswer, error) { |
| 91 | if cb.Amount.String() == "24.90" { |
| 92 | return Approve(), nil |
| 93 | } |
| 94 | return Refuse("Wrong amount"), nil |
| 95 | }) |
| 96 | for body, want := range map[string]string{ |
| 97 | `{"id": 1, "amount": 24.90, "currency": "EUR"}`: `{"resume":true}`, |
| 98 | `{"id": 1, "amount": 5, "currency": "EUR"}`: `{"resume":false,"error":"Wrong amount"}`, |
| 99 | `{}`: `{"resume":false,"error":"Invalid callback"}`, |
| 100 | } { |
| 101 | rec := httptest.NewRecorder() |
| 102 | h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/cb", strings.NewReader(body))) |
| 103 | if rec.Code != 200 || strings.TrimSpace(rec.Body.String()) != want || rec.Header().Get("Content-Type") != "application/json" { |
| 104 | t.Errorf("%s: got %d %s", body, rec.Code, rec.Body.String()) |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | func TestVerifySignature(t *testing.T) { |
| 110 | body := []byte(`{"id":7310,"amount":24.9,"currency":"EUR","status":"awaiting_approval","description":"Order 1042"}`) |
| 111 | header := "t=1700000000,v1=fcfc30b9667c3a8e8aea68178c36716153e075f79c61521bf3586088d9877281" |
| 112 | now := time.Unix(1700000100, 0) |
| 113 | if !VerifySignature("hbcb_test", header, body, now) { |
| 114 | t.Fatal("valid signature refused") |
| 115 | } |
| 116 | if VerifySignature("hbcb_other", header, body, now) || VerifySignature("hbcb_test", header, []byte("{}"), now) || |
| 117 | VerifySignature("hbcb_test", header, body, time.Unix(1700000400, 0)) || VerifySignature("hbcb_test", "garbage", body, now) { |
| 118 | t.Fatal("invalid signature accepted") |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | func TestSubscriptionsCheckoutSendsIdsAndOffers(t *testing.T) { |
| 123 | c := fake(t, func(path string, body map[string]any) (int, string) { |
| 124 | items, _ := body["subscriptions"].([]any) |
| 125 | offer, _ := items[1].(map[string]any) |
| 126 | if path != "/api/v1/subscriptions/checkout" || len(items) != 2 || items[0] != "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF" || |
| 127 | offer["amount"] != "2.50" || offer["interval_count"] != float64(1) || body["callback_url"] != "https://shop.example/cb" { |
| 128 | t.Errorf("unexpected request %s %v", path, body) |
| 129 | } |
| 130 | if _, ok := offer["callback_url"]; ok { |
| 131 | t.Errorf("an offer carries no callback url") |
| 132 | } |
| 133 | if _, ok := body["description"]; ok { |
| 134 | t.Errorf("empty description should be left out") |
| 135 | } |
| 136 | return 200, `{"success": true, "transaction_id": "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v", "subscriptions": [{"id": "sub_Hk3Rt9WzQe5NcXa2LpVb7YdF"}, {"id": "sub_Q2"}]}` |
| 137 | }) |
| 138 | out, err := c.CreateSubscriptionsCheckout(context.Background(), SubscriptionsCheckoutRequest{ |
| 139 | Subscriptions: []SubscriptionCheckoutItem{ |
| 140 | ExistingSubscription("sub_Hk3Rt9WzQe5NcXa2LpVb7YdF"), |
| 141 | NewSubscription(SubscriptionRequest{Amount: "2.50", Currency: "EUR", Interval: "week", CallbackURL: "ignored"}), |
| 142 | }, |
| 143 | CallbackURL: "https://shop.example/cb", |
| 144 | }) |
| 145 | if err != nil || out.TransactionID != "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v" || len(out.Subscriptions) != 2 || out.Subscriptions[1].ID != "sub_Q2" { |
| 146 | t.Fatalf("got %+v, %v", out, err) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | func TestPaymentListsItsSubscriptions(t *testing.T) { |
| 151 | c := fake(t, func(string, map[string]any) (int, string) { |
| 152 | return 200, `{"success": true, "transaction": {"id": "tx_1", "amount": 7.50, "status": "completed", "subscription_id": null, "subscription_ids": ["sub_A", "sub_B"]}}` |
| 153 | }) |
| 154 | p, err := c.GetPayment(context.Background(), "tx_1") |
| 155 | if err != nil || len(p.SubscriptionIDs) != 2 || p.SubscriptionIDs[1] != "sub_B" || p.SubscriptionID != nil { |
| 156 | t.Fatalf("got %+v, %v", p, err) |
| 157 | } |
| 158 | } |