commit fe9a584f711ab0c34d6c40e14b30b9fd9e226e9a
parent ff129add4337a7b9baa1cd833e13ba5c620163d5
Author: Florian Dold <dold@taler.net>
Date: Wed, 18 Nov 2026 20:44:56 +0100
landing: add merchant samples for payments, products and tokens
Diffstat:
16 files changed, 795 insertions(+), 23 deletions(-)
diff --git a/README.md b/README.md
@@ -98,6 +98,10 @@ donations_url = https://donations.demo.taler.net/
[frontend-demo-landing]
http_serve = tcp
http_port = 8080
+enable_merchant_samples = no
+# Required only with enable_merchant_samples = yes
+# backend_url = https://backend.demo.taler.net/instances/landing-samples/
+# backend_apikey = secret-token:secret
[frontend-demo-blog]
http_serve = tcp
@@ -120,6 +124,43 @@ backend_apikey_tor = secret-token:secret
donau_url =
```
+### Merchant samples
+
+Enable `enable_merchant_samples = yes` in `[frontend-demo-landing]` to link
+the landing page to `/merchant-samples`. Set that section's `backend_url` and
+`backend_apikey` for a dedicated **landing samples** merchant instance. Grant
+the key `orders-read`, `orders-write`, `tokenfamilies-read`, and
+`tokenfamilies-write` permissions. The default is disabled.
+
+The landing process creates the `samples-coffee-coupon` discount family and
+the `samples-day-pass` subscription family at startup. It reuses compatible
+families on restart so tokens already in wallets can still be redeemed.
+Coupons use 30-day key validity. The merchant rounds day-pass key validity to a
+calendar day in its local time zone. Run the merchant backend with `TZ=UTC`
+for expiry at midnight UTC.
+While setup is pending, the samples page returns HTTP 503 with `Retry-After`.
+The main landing page remains available. Provisioning errors in the service
+log identify the affected family, and the process retries automatically.
+
+Configure the merchant backend to accept both the demo currency and CHF.
+Keep the demo exchange enabled and add `https://exchange.stage.taler-ops.ch/`
+as a trusted CHF exchange with its verified master public key. Configure a
+settlement account on the instance that **both exchanges can credit**. Each
+contract uses one payout account for all choices. The staging exchange
+requires a Swiss IBAN, so the demo-currency exchange must support transfers
+to that IBAN as well. See the [merchant operator manual](https://docs.taler.net/taler-merchant-manual.html#exchange).
+
+Each button creates a new order. Compare plain v0 and v1 payments, redeem
+a coffee coupon once, or open multiple exhibits with one day pass. The café
+basket includes three products with quantities and line prices. The coffee
+and croissant PNGs come from the GNU Taler iOS POS screenshot assets
+(©2022–25 Taler Systems S.A., GPL-3.0-or-later). For the
+two-currency tests, fund the wallet in the demo currency and in staging CHF.
+Buy a postcard in each currency, then earn a coupon in one currency and
+redeem it in the other. The fulfillment page shows the selected price.
+
+### Listener settings
+
Each section can instead listen on a Unix socket:
```ini
diff --git a/cmd/taler-merchant-demos/main.go b/cmd/taler-merchant-demos/main.go
@@ -83,20 +83,27 @@ func runWithOutput(args []string, stdout, stderr io.Writer) error {
opts := web.Options{
Shop: shop, Currency: currency, PublicURLs: publicURLs,
}
- if shop == "blog" {
- backendURL, err := cfg.Require("frontend-demo-blog", "backend_url")
+ samplesEnabled := shop == "landing" && strings.EqualFold(cfg.Get("frontend-demo-landing", "enable_merchant_samples"), "yes")
+ if samplesEnabled || shop == "blog" {
+ section := "frontend-demo-" + shop
+ backendURL, err := cfg.Require(section, "backend_url")
if err != nil {
return err
}
- apiKey, err := cfg.Require("frontend-demo-blog", "backend_apikey")
+ apiKey, err := cfg.Require(section, "backend_apikey")
if err != nil {
return err
}
- opts.BlogBackend, err = backend.New(backendURL, apiKey)
+ client, err := backend.New(backendURL, apiKey)
if err != nil {
return err
}
- opts.EnableTokens = strings.EqualFold(cfg.Get("frontend-demo-blog", "enable_tokens"), "yes")
+ if samplesEnabled {
+ opts.SamplesBackend = client
+ } else {
+ opts.BlogBackend = client
+ opts.EnableTokens = strings.EqualFold(cfg.Get(section, "enable_tokens"), "yes")
+ }
}
if shop == "donations" {
opts.DonationBackends = make(map[string]*backend.Client)
@@ -125,6 +132,11 @@ func runWithOutput(args []string, stdout, stderr io.Writer) error {
return err
}
defer cleanup()
+ if samplesEnabled {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go handler.ProvisionSamples(ctx)
+ }
server := &http.Server{
Handler: handler, ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second, WriteTimeout: 60 * time.Second,
diff --git a/cmd/taler-merchant-demos/main_test.go b/cmd/taler-merchant-demos/main_test.go
@@ -83,3 +83,25 @@ donations_url = https://donations.example/
t.Fatalf("public URLs = %#v", got)
}
}
+
+func TestSamplesConfiguration(t *testing.T) {
+ t.Setenv("TALER_MERCHANT_DEMOS_BASE_CONFIG", t.TempDir())
+ for _, tc := range []struct{ settings, want string }{
+ {"", "HTTP_PORT"},
+ {"enable_merchant_samples = no", "HTTP_PORT"},
+ {"enable_merchant_samples = yes", "BACKEND_URL"},
+ {"enable_merchant_samples = yes\nbackend_url = https://samples.example/", "BACKEND_APIKEY"},
+ {"enable_merchant_samples = yes\nbackend_url = https://samples.example/\nbackend_apikey = sample", "HTTP_PORT"},
+ } {
+ // A missing listen port ends startup after credentials have been checked.
+ path := filepath.Join(t.TempDir(), "demo.conf")
+ cfg := "[taler]\ncurrency=KUDOS\n[frontend-demo]\nlanding_url=http://localhost/\nbank_url=http://localhost/\nblog_url=http://localhost/\ndonations_url=http://localhost/\n[frontend-demo-landing]\n" + tc.settings
+ if err := os.WriteFile(path, []byte(cfg), 0600); err != nil {
+ t.Fatal(err)
+ }
+ err := run([]string{"-c", path, "landing"})
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("%q: %v", tc.settings, err)
+ }
+ }
+}
diff --git a/internal/backend/types.go b/internal/backend/types.go
@@ -42,11 +42,24 @@ type OrderChoice struct {
Outputs []OrderOutput `json:"outputs,omitempty"`
}
+// Product is an item supplied directly in the order. Prices are totals for
+// the given quantity, one per currency.
+type Product struct {
+ Name string `json:"product_name"`
+ Description string `json:"description"`
+ UnitQuantity string `json:"unit_quantity"`
+ Prices []string `json:"prices"`
+ PricesAreNet bool `json:"prices_are_net"`
+ Image string `json:"image,omitempty"`
+}
+
// Order contains the Merchant order fields used by the demo applications.
type Order struct {
+ OrderID string `json:"order_id,omitempty"`
Version int `json:"version,omitempty"`
Amount string `json:"amount,omitempty"`
Choices []OrderChoice `json:"choices,omitempty"`
+ Products []Product `json:"products,omitempty"`
Extra OrderExtra `json:"extra"`
FulfillmentURL string `json:"fulfillment_url"`
PublicReorderURL string `json:"public_reorder_url,omitempty"`
@@ -91,6 +104,21 @@ type OrderStatusResponse struct {
OrderStatusURL string `json:"order_status_url,omitempty"`
}
+// SelectedAmount returns the price of the alternative selected by the wallet.
+func (s OrderStatusResponse) SelectedAmount() (string, bool) {
+ terms := s.ContractTerms
+ switch terms.Version {
+ case 0:
+ return terms.Amount, terms.Amount != ""
+ case 1:
+ if s.ChoiceIndex != nil && *s.ChoiceIndex >= 0 && *s.ChoiceIndex < len(terms.Choices) {
+ amount := terms.Choices[*s.ChoiceIndex].Amount
+ return amount, amount != ""
+ }
+ }
+ return "", false
+}
+
// OrderHistory is returned by GET private/orders.
type OrderHistory struct {
Orders []OrderHistoryEntry `json:"orders"`
diff --git a/internal/web/app.go b/internal/web/app.go
@@ -19,6 +19,7 @@ import (
"sort"
"strconv"
"strings"
+ "sync/atomic"
"git.taler.net/taler-merchant-demos/internal/backend"
)
@@ -45,6 +46,7 @@ type Options struct {
Currency string
PublicURLs PublicURLs
BlogBackend *backend.Client
+ SamplesBackend *backend.Client
DonationBackends map[string]*backend.Client
DonauURL string
EnableTokens bool
@@ -52,13 +54,14 @@ type Options struct {
// App serves one configured demo.
type App struct {
- opts Options
- catalogs catalogs
- articles articleLibrary
- templates map[string]*template.Template
- static http.Handler
- mux *http.ServeMux
- routes *http.ServeMux
+ samplesReady atomic.Bool
+ opts Options
+ catalogs catalogs
+ articles articleLibrary
+ templates map[string]*template.Template
+ static http.Handler
+ mux *http.ServeMux
+ routes *http.ServeMux
}
type language struct {
@@ -117,6 +120,7 @@ type links struct {
}
type page struct {
+ LanguagePath string
Lang string
Title string
Active string
@@ -188,7 +192,7 @@ func (a *App) loadTemplates() error {
if err != nil {
return err
}
- names := []string{"error", "landing", "donations-index", "donations-checkout", "donations-provider", "donations-fulfillment", "blog-index", "blog-article", "blog-confirm-refund", "blog-refunded"}
+ names := []string{"error", "landing", "merchant-samples", "sample-receipt", "donations-index", "donations-checkout", "donations-provider", "donations-fulfillment", "blog-index", "blog-article", "blog-confirm-refund", "blog-refunded"}
funcs := template.FuncMap{
"tr": func(lang, message string) string { return a.catalogs.translate(lang, message) },
"trHTML": func(lang, message string) template.HTML {
@@ -548,7 +552,7 @@ func externalURLWithQuery(r *http.Request) string {
return result
}
-func newSessionID() (string, error) {
+func randomID() (string, error) {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
return "", err
diff --git a/internal/web/assets/static/coffee.png b/internal/web/assets/static/coffee.png
Binary files differ.
diff --git a/internal/web/assets/static/croissant.png b/internal/web/assets/static/croissant.png
Binary files differ.
diff --git a/internal/web/blog.go b/internal/web/blog.go
@@ -82,7 +82,7 @@ func (a *App) article(w http.ResponseWriter, r *http.Request) {
return
}
var err error
- session, err = newSessionID()
+ session, err = randomID()
if err != nil {
a.renderError(w, r, http.StatusInternalServerError, lang, "Could not create a browser session", err)
return
@@ -278,12 +278,9 @@ func (a *App) refundAmount(order backend.OrderStatusResponse) (string, bool) {
if order.Refunded || order.ContractTerms.RefundDeadline.Seconds <= time.Now().Unix() {
return "", false
}
- amount := order.ContractTerms.Amount
- if order.ContractTerms.Version == 1 {
- if order.ChoiceIndex == nil || *order.ChoiceIndex < 0 || *order.ChoiceIndex >= len(order.ContractTerms.Choices) {
- return "", false
- }
- amount = order.ContractTerms.Choices[*order.ChoiceIndex].Amount
+ amount, ok := order.SelectedAmount()
+ if !ok {
+ return "", false
}
value, ok := strings.CutPrefix(amount, a.opts.Currency+":")
if !ok || value == "" || strings.Trim(value, "0.") == "" {
diff --git a/internal/web/landing.go b/internal/web/landing.go
@@ -7,6 +7,7 @@ import (
)
type landingContent struct {
+ SamplesEnabled bool
Currency string
BankRegisterURL string
BankPublicAccountsURL string
@@ -16,6 +17,9 @@ type landingContent struct {
func (a *App) registerLandingRoutes() {
a.handleGet("/{lang}/{$}", a.landing)
+ if a.opts.SamplesBackend != nil {
+ a.registerSamplesRoutes()
+ }
}
func (a *App) landing(w http.ResponseWriter, r *http.Request) {
@@ -39,7 +43,8 @@ func (a *App) landing(w http.ResponseWriter, r *http.Request) {
return base + "/" + url.PathEscape(lang)
}
content := landingContent{
- Currency: a.opts.Currency, BankRegisterURL: bankRegister,
+ SamplesEnabled: a.opts.SamplesBackend != nil,
+ Currency: a.opts.Currency, BankRegisterURL: bankRegister,
BankPublicAccountsURL: bankPublic,
BlogURL: localizedMerchant(a.opts.PublicURLs.Blog),
DonationsURL: localizedMerchant(a.opts.PublicURLs.Donations),
diff --git a/internal/web/merchant_samples.go b/internal/web/merchant_samples.go
@@ -0,0 +1,204 @@
+package web
+
+import (
+ _ "embed"
+ "encoding/base64"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "git.taler.net/taler-merchant-demos/internal/backend"
+)
+
+func (a *App) registerSamplesRoutes() {
+ a.mux.HandleFunc("GET /merchant-samples", func(w http.ResponseWriter, r *http.Request) {
+ lang := a.bestLanguage(r.Header.Get("Accept-Language"))
+ w.Header().Add("Vary", "Accept-Language")
+ http.Redirect(w, r, forwardedPrefix(r)+"/"+lang+"/merchant-samples", http.StatusFound)
+ })
+ a.handleGet("/{lang}/merchant-samples", a.whenSamplesReady(a.samples))
+ a.handlePost("/{lang}/merchant-samples/orders", a.whenSamplesReady(a.createSampleOrder))
+ a.handleGet("/{lang}/merchant-samples/receipts/{id}", a.whenSamplesReady(a.sampleReceipt))
+}
+
+func (a *App) whenSamplesReady(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if !a.samplesReady.Load() {
+ w.Header().Set("Retry-After", "5")
+ a.renderError(w, r, http.StatusServiceUnavailable, requestLang(r), "Merchant samples are starting up. Please try again shortly.", nil)
+ return
+ }
+ next(w, r)
+ }
+}
+
+func (a *App) samplePage(r *http.Request, content any) page {
+ p := a.makePage(r, requestLang(r), "Merchant samples", content)
+ p.HeaderTitle = p.Title
+ p.HeaderURL = forwardedPrefix(r) + "/" + p.Lang + "/merchant-samples"
+ p.HeaderText = a.translatedHTML(p.Lang, "Try payments, discounts and subscriptions with your Taler wallet.")
+ p.LanguagePath = strings.TrimPrefix(r.URL.Path, "/"+p.Lang+"/")
+ return p
+}
+
+func (a *App) samples(w http.ResponseWriter, r *http.Request) {
+ a.render(w, "merchant-samples", a.samplePage(r, a.opts.Currency), http.StatusOK)
+}
+
+//go:embed assets/static/coffee.png
+var coffeePNG []byte
+
+//go:embed assets/static/croissant.png
+var croissantPNG []byte
+
+func (a *App) sampleOrder(lang, sample string) (backend.Order, bool) {
+ currency := a.opts.Currency
+ order := backend.Order{Version: 1}
+ couponOut := []backend.OrderOutput{{Type: "token", TokenFamilySlug: couponSlug}}
+ couponIn := []backend.OrderInput{{Type: "token", TokenFamilySlug: couponSlug}}
+ passOut := []backend.OrderOutput{{Type: "token", TokenFamilySlug: passSlug}}
+ fullPrice := a.catalogs.translate(lang, "Full price")
+ switch sample {
+ case "pay-v0", "pay-v1", "postcard":
+ order.Summary = a.catalogs.translate(lang, "Postcard")
+ if sample == "pay-v0" {
+ order.Version = 0
+ order.Amount = currency + ":1"
+ } else {
+ order.Choices = []backend.OrderChoice{{Amount: currency + ":1"}}
+ if sample == "postcard" {
+ order.Choices = append(order.Choices, backend.OrderChoice{Amount: "CHF:0.10"})
+ }
+ }
+ case "basket":
+ order.Summary = a.catalogs.translate(lang, "Café basket")
+ order.Choices = []backend.OrderChoice{{Amount: currency + ":7"}}
+ order.Products = []backend.Product{
+ {
+ Name: a.catalogs.translate(lang, "Coffee"),
+ Description: a.catalogs.translate(lang, "Freshly brewed coffee"),
+ UnitQuantity: "2", Prices: []string{currency + ":4"},
+ Image: "data:image/png;base64," + base64.StdEncoding.EncodeToString(coffeePNG),
+ },
+ {
+ Name: a.catalogs.translate(lang, "Croissant"),
+ Description: a.catalogs.translate(lang, "Butter croissant"),
+ UnitQuantity: "1", Prices: []string{currency + ":2"},
+ Image: "data:image/png;base64," + base64.StdEncoding.EncodeToString(croissantPNG),
+ },
+ {
+ Name: a.catalogs.translate(lang, "Tea"),
+ Description: a.catalogs.translate(lang, "Black tea"),
+ UnitQuantity: "1", Prices: []string{currency + ":1"},
+ },
+ }
+ case "earn", "earn-multi":
+ order.Summary = a.catalogs.translate(lang, "Coffee with a coupon")
+ order.Choices = []backend.OrderChoice{{Amount: currency + ":2", Outputs: couponOut}}
+ if sample == "earn-multi" {
+ order.Choices = append(order.Choices, backend.OrderChoice{Amount: "CHF:0.20", Outputs: couponOut})
+ }
+ case "redeem", "redeem-multi":
+ order.Summary = a.catalogs.translate(lang, "Coffee")
+ discounted := a.catalogs.translate(lang, "Use a coupon")
+ order.Choices = []backend.OrderChoice{
+ {Amount: currency + ":2", Description: fullPrice},
+ {Amount: currency + ":1", Description: discounted, Inputs: couponIn},
+ }
+ if sample == "redeem-multi" {
+ order.Choices = append(order.Choices,
+ backend.OrderChoice{Amount: "CHF:0.20", Description: fullPrice},
+ backend.OrderChoice{Amount: "CHF:0.10", Description: discounted, Inputs: couponIn},
+ )
+ }
+ case "pass":
+ order.Summary = a.catalogs.translate(lang, "Exhibit day pass")
+ order.Choices = []backend.OrderChoice{{Amount: currency + ":3", Outputs: passOut}}
+ case "admission":
+ order.Summary = a.catalogs.translate(lang, "Exhibit admission")
+ order.Choices = []backend.OrderChoice{
+ {Amount: currency + ":1", Description: fullPrice},
+ {
+ Amount: currency + ":0", Description: a.catalogs.translate(lang, "Use a day pass"),
+ Inputs: []backend.OrderInput{{Type: "token", TokenFamilySlug: passSlug}},
+ Outputs: passOut,
+ },
+ }
+ default:
+ return backend.Order{}, false
+ }
+ return order, true
+}
+
+func (a *App) createSampleOrder(w http.ResponseWriter, r *http.Request) {
+ lang := requestLang(r)
+ sample := r.PostFormValue("sample")
+ order, ok := a.sampleOrder(lang, sample)
+ if !ok {
+ a.renderError(w, r, http.StatusBadRequest, lang, "Unknown payment sample", nil)
+ return
+ }
+ id, err := randomID()
+ if err != nil {
+ a.renderError(w, r, http.StatusInternalServerError, lang, "Internal server error", err)
+ return
+ }
+ base := externalOrigin(r) + forwardedPrefix(r) + "/" + lang + "/merchant-samples"
+ order.OrderID = id
+ order.FulfillmentURL = base + "/receipts/" + id
+ order.PublicReorderURL = base
+ now := time.Now()
+ payDeadline := now.Add(5 * time.Minute).Unix()
+ if sample == "pass" || sample == "admission" {
+ // A checkout issued today must finish within today's pass period.
+ nextMidnight := now.UTC().Truncate(24 * time.Hour).Add(24 * time.Hour)
+ payDeadline = min(payDeadline, nextMidnight.Unix())
+ }
+ order.PayDeadline = backend.Timestamp{Seconds: payDeadline}
+ order.WireTransferDeadline = backend.Timestamp{Seconds: now.Add(2 * time.Hour).Unix()}
+ var created backend.PostOrderResponse
+ merchant := a.opts.SamplesBackend
+ if err := merchant.Post(r.Context(), "private/orders", backend.PostOrderRequest{Order: order, CreateToken: true}, &created); err != nil {
+ a.renderError(w, r, http.StatusBadGateway, lang, "Backend could not create the order", err)
+ return
+ }
+ if created.OrderID != id || created.Token == "" {
+ a.renderError(w, r, http.StatusBadGateway, lang, "Invalid order response from merchant", nil)
+ return
+ }
+ paymentURL := merchant.URL("orders/"+id, url.Values{"token": {created.Token}})
+ http.Redirect(w, r, paymentURL, http.StatusSeeOther)
+}
+
+var sampleOrderID = regexp.MustCompile(`^[0-9a-f]{32}$`)
+
+func (a *App) sampleReceipt(w http.ResponseWriter, r *http.Request) {
+ lang := requestLang(r)
+ id := r.PathValue("id")
+ if !sampleOrderID.MatchString(id) {
+ a.renderError(w, r, http.StatusNotFound, lang, "Page not found", nil)
+ return
+ }
+ var status backend.OrderStatusResponse
+ err := a.opts.SamplesBackend.Get(r.Context(), "private/orders/"+id, nil, &status)
+ if backendStatus(err, http.StatusNotFound) {
+ a.renderError(w, r, http.StatusNotFound, lang, "Page not found", nil)
+ return
+ }
+ if err != nil {
+ a.renderError(w, r, http.StatusBadGateway, lang, "Backend request failed", err)
+ return
+ }
+ if status.OrderStatus == "unpaid" || status.OrderStatus == "claimed" {
+ a.renderError(w, r, http.StatusPaymentRequired, lang, "This order is awaiting payment.", nil)
+ return
+ }
+ amount, ok := status.SelectedAmount()
+ if status.OrderStatus != "paid" || !ok {
+ a.renderError(w, r, http.StatusBadGateway, lang, "Invalid order response from merchant", nil)
+ return
+ }
+ a.render(w, "sample-receipt", a.samplePage(r, amount), http.StatusOK)
+}
diff --git a/internal/web/merchant_samples_test.go b/internal/web/merchant_samples_test.go
@@ -0,0 +1,304 @@
+package web
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "image/png"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "git.taler.net/taler-merchant-demos/internal/backend"
+)
+
+func sampleRequest(app *App, method, path, body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("X-Forwarded-Prefix", "/demo")
+ req.Header.Set("Accept-Language", "de")
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, req)
+ return rec
+}
+
+func sampleApp(t *testing.T, handler http.HandlerFunc) *App {
+ t.Helper()
+ opts := Options{Shop: "landing", Currency: "TESTKUDOS"}
+ if handler != nil {
+ server := httptest.NewServer(handler)
+ t.Cleanup(server.Close)
+ merchant, err := backend.New(server.URL+"/instances/landing-samples/", "samples-key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ opts.SamplesBackend = merchant
+ }
+ app, err := New(opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return app
+}
+
+func TestSamplesDisabled(t *testing.T) {
+ app := sampleApp(t, nil)
+ if strings.Contains(sampleRequest(app, "GET", "/en/", "").Body.String(), "merchant-samples") {
+ t.Fatal("samples advertised while disabled")
+ }
+ for _, path := range []string{"/merchant-samples", "/en/merchant-samples", "/en/merchant-samples/receipts/id"} {
+ if got := sampleRequest(app, "GET", path, "").Code; got != 404 {
+ t.Errorf("%s returned %d", path, got)
+ }
+ }
+ if got := sampleRequest(app, "POST", "/en/merchant-samples/orders", "sample=earn").Code; got != 404 {
+ t.Fatal(got)
+ }
+}
+
+func TestSamplesStartup(t *testing.T) {
+ // A concurrent process creates the coupon after our GET. The pass lookup
+ // then fails once. Neither event should require restarting the landing page.
+ stored := make(map[string]sampleFamily)
+ posts := make(map[string]int)
+ unavailable := make(chan struct{})
+ var failed bool
+ app := sampleApp(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer samples-key" {
+ t.Error("missing samples credential")
+ }
+ suffix := strings.TrimPrefix(r.URL.Path, "/instances/landing-samples/private/tokenfamilies")
+ switch r.Method {
+ case "GET":
+ slug := strings.TrimPrefix(suffix, "/")
+ if slug == passSlug && !failed {
+ failed = true
+ close(unavailable)
+ w.WriteHeader(503)
+ return
+ }
+ family, ok := stored[slug]
+ if !ok {
+ w.WriteHeader(404)
+ return
+ }
+ json.NewEncoder(w).Encode(struct {
+ sampleFamily
+ ValidBefore map[string]string `json:"valid_before"`
+ }{family, map[string]string{"t_s": "never"}})
+ case "POST":
+ if suffix != "" {
+ t.Errorf("unexpected POST %s", r.URL.Path)
+ }
+ var family sampleFamily
+ if err := json.NewDecoder(r.Body).Decode(&family); err != nil {
+ t.Error(err)
+ }
+ posts[family.Slug]++
+ stored[family.Slug] = family
+ if family.Slug == couponSlug {
+ w.WriteHeader(409)
+ return
+ }
+ w.WriteHeader(204)
+ default:
+ t.Errorf("unexpected request %s %s", r.Method, r.URL)
+ }
+ })
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ done := make(chan struct{})
+ go func() { app.ProvisionSamples(ctx); close(done) }()
+ select {
+ case <-unavailable:
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+ page := sampleRequest(app, "GET", "/de/", "")
+ if page.Code != 200 || !strings.Contains(page.Body.String(), "/demo/de/merchant-samples") {
+ t.Fatal("main landing unavailable")
+ }
+ for _, r := range []*httptest.ResponseRecorder{sampleRequest(app, "GET", "/de/merchant-samples", ""), sampleRequest(app, "POST", "/de/merchant-samples/orders", "sample=earn")} {
+ if r.Code != 503 || r.Header().Get("Retry-After") == "" {
+ t.Fatalf("pending page status %d", r.Code)
+ }
+ }
+ select {
+ case <-done:
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+ if !app.samplesReady.Load() {
+ t.Fatal("samples unavailable after retry")
+ }
+ // A fresh process reads the existing families and preserves issued tokens.
+ app.samplesReady.Store(false)
+ app.ProvisionSamples(ctx)
+ if !app.samplesReady.Load() || posts[couponSlug] != 1 || posts[passSlug] != 1 {
+ t.Fatalf("restart: posts %v", posts)
+ }
+ if stored[passSlug].Kind != "subscription" || stored[couponSlug].Kind != "discount" || stored[passSlug].Duration.Microseconds != (24*time.Hour).Microseconds() || stored[couponSlug].Duration.Microseconds != (30*24*time.Hour).Microseconds() {
+ t.Fatalf("wrong sample families: %v", stored)
+ }
+ wrong := stored[passSlug]
+ wrong.Kind = "discount"
+ if err := ensureSampleFamily(ctx, app.opts.SamplesBackend, wrong); err == nil {
+ t.Fatal("accepted incompatible family")
+ }
+ if got := sampleRequest(app, "GET", "/merchant-samples", "").Header().Get("Location"); got != "/demo/de/merchant-samples" {
+ t.Fatal(got)
+ }
+ page = sampleRequest(app, "GET", "/de/merchant-samples", "")
+ if page.Code != 200 || strings.Count(page.Body.String(), `name="sample"`) != 10 || !strings.Contains(page.Body.String(), `action="/demo/de/merchant-samples/orders"`) {
+ t.Fatal("missing sample actions")
+ }
+}
+
+func TestSampleCheckouts(t *testing.T) {
+ // Capture real JSON requests through the normal HTTP entry point.
+ orders := make(chan backend.PostOrderRequest, 1)
+ statuses := make(chan backend.OrderStatusResponse, 1)
+ app := sampleApp(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" && r.URL.Path == "/instances/landing-samples/private/orders" {
+ var order backend.PostOrderRequest
+ if err := json.NewDecoder(r.Body).Decode(&order); err != nil {
+ t.Error(err)
+ }
+ orders <- order
+ json.NewEncoder(w).Encode(backend.PostOrderResponse{OrderID: order.Order.OrderID, Token: "claim"})
+ } else if r.Method == "GET" && strings.HasPrefix(r.URL.Path, "/instances/landing-samples/private/orders/") {
+ json.NewEncoder(w).Encode(<-statuses)
+ } else {
+ t.Errorf("unexpected request %s %s", r.Method, r.URL)
+ w.WriteHeader(404)
+ }
+ })
+ app.samplesReady.Store(true)
+ type choice struct{ amount, input, output string }
+ const one = "TESTKUDOS:1"
+ const two = "TESTKUDOS:2"
+ ids := map[string]bool{}
+ for _, tc := range []struct {
+ name string
+ choices []choice
+ }{
+ {"basket", []choice{{"TESTKUDOS:7", "", ""}}},
+ {"pay-v0", nil}, {"pay-v1", []choice{{one, "", ""}}}, {"earn", []choice{{two, "", couponSlug}}},
+ {"redeem", []choice{{two, "", ""}, {one, couponSlug, ""}}},
+ {"pass", []choice{{"TESTKUDOS:3", "", passSlug}}}, {"admission", []choice{{one, "", ""}, {"TESTKUDOS:0", passSlug, passSlug}}},
+ {"postcard", []choice{{one, "", ""}, {"CHF:0.10", "", ""}}},
+ {"earn-multi", []choice{{two, "", couponSlug}, {"CHF:0.20", "", couponSlug}}},
+ {"redeem-multi", []choice{{two, "", ""}, {one, couponSlug, ""}, {"CHF:0.20", "", ""}, {"CHF:0.10", couponSlug, ""}}},
+ {"admission", []choice{{one, "", ""}, {"TESTKUDOS:0", passSlug, passSlug}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := sampleRequest(app, "POST", "/en/merchant-samples/orders", "sample="+tc.name)
+ if rec.Code != 303 {
+ t.Fatalf("checkout %d %s", rec.Code, rec.Body)
+ }
+ request := <-orders
+ order := request.Order
+ if tc.name == "basket" {
+ checkBasketProducts(t, order.Products)
+ } else if len(order.Products) != 0 {
+ t.Fatalf("unexpected products for %s", tc.name)
+ }
+ id := order.OrderID
+ if !sampleOrderID.MatchString(id) || ids[id] {
+ t.Fatal("invalid or reused ID", id)
+ }
+ ids[id] = true
+ location, err := url.Parse(rec.Header().Get("Location"))
+ if err != nil || location.Path != "/instances/landing-samples/orders/"+id || location.Query().Get("token") != "claim" || !request.CreateToken {
+ t.Fatal(location)
+ }
+ receipt := "/en/merchant-samples/receipts/" + id
+ if order.FulfillmentURL != "http://example.com/demo"+receipt || order.Summary == "" {
+ t.Fatal(order)
+ }
+ var got []choice
+ for _, c := range order.Choices {
+ row := choice{amount: c.Amount}
+ for _, i := range c.Inputs {
+ if i.Type != "token" {
+ t.Fatal(i)
+ }
+ row.input += i.TokenFamilySlug
+ }
+ for _, o := range c.Outputs {
+ if o.Type != "token" {
+ t.Fatal(o)
+ }
+ row.output += o.TokenFamilySlug
+ }
+ got = append(got, row)
+ }
+ if !reflect.DeepEqual(got, tc.choices) {
+ t.Fatalf("choices %v, want %v", got, tc.choices)
+ }
+ status := backend.OrderStatusResponse{OrderStatus: "paid", ContractTerms: backend.ContractTerms{Version: order.Version, Amount: order.Amount, Choices: order.Choices}}
+ amount := one
+ if tc.choices == nil {
+ if order.Version != 0 || order.Amount != one {
+ t.Fatal(order)
+ }
+ } else {
+ if order.Version != 1 || order.Amount != "" {
+ t.Fatal(order)
+ }
+ last := len(tc.choices) - 1
+ status.ChoiceIndex = &last
+ amount = tc.choices[last].amount
+ }
+ statuses <- status
+ page := sampleRequest(app, "GET", receipt, "")
+ if page.Code != 200 || !strings.Contains(page.Body.String(), "Paid "+amount) {
+ t.Fatalf("receipt for %s: %d", amount, page.Code)
+ }
+ })
+ }
+ if got := sampleRequest(app, "POST", "/en/merchant-samples/orders", "sample=unknown").Code; got != 400 {
+ t.Fatalf("unknown sample %d", got)
+ }
+}
+
+func checkBasketProducts(t *testing.T, products []backend.Product) {
+ t.Helper()
+ want := []struct{ name, quantity, price, imageFile string }{
+ {"Coffee", "2", "TESTKUDOS:4", "coffee.png"},
+ {"Croissant", "1", "TESTKUDOS:2", "croissant.png"},
+ {"Tea", "1", "TESTKUDOS:1", ""},
+ }
+ if len(products) != len(want) {
+ t.Fatalf("got %d products, want %d", len(products), len(want))
+ }
+ for i, item := range want {
+ p := products[i]
+ if p.Name != item.name || p.UnitQuantity != item.quantity || !reflect.DeepEqual(p.Prices, []string{item.price}) || p.Description == "" || p.PricesAreNet {
+ t.Errorf("invalid line item %d: %s, quantity %s, prices %v", i, p.Name, p.UnitQuantity, p.Prices)
+ }
+ if item.imageFile == "" {
+ if p.Image != "" {
+ t.Errorf("unexpected image for %s", p.Name)
+ }
+ continue
+ }
+ encoded, ok := strings.CutPrefix(p.Image, "data:image/png;base64,")
+ data, err := base64.StdEncoding.DecodeString(encoded)
+ if !ok || err != nil {
+ t.Fatalf("invalid image URL for %s", p.Name)
+ }
+ if _, err := png.Decode(bytes.NewReader(data)); err != nil {
+ t.Fatal(err)
+ }
+ preview, err := Assets.ReadFile("assets/static/" + item.imageFile)
+ if err != nil || !bytes.Equal(preview, data) {
+ t.Errorf("image for %s differs from preview", p.Name)
+ }
+ }
+}
diff --git a/internal/web/sample_families.go b/internal/web/sample_families.go
@@ -0,0 +1,100 @@
+package web
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log"
+ "net/http"
+ "time"
+
+ "git.taler.net/taler-merchant-demos/internal/backend"
+)
+
+const (
+ couponSlug = "samples-coffee-coupon"
+ passSlug = "samples-day-pass"
+)
+
+type sampleFamily struct {
+ Slug string `json:"slug"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Kind string `json:"kind"`
+ Duration backend.RelativeTime `json:"duration"`
+ Granularity backend.RelativeTime `json:"validity_granularity"`
+ StartOffset backend.RelativeTime `json:"start_offset"`
+ ValidAfter backend.Timestamp `json:"valid_after"`
+}
+
+// ProvisionSamples keeps the landing page available while the dedicated
+// merchant starts up. The caller runs it in a goroutine tied to the server.
+func (a *App) ProvisionSamples(ctx context.Context) {
+ day := backend.RelativeTime{Microseconds: (24 * time.Hour).Microseconds()}
+ midnight := backend.Timestamp{Seconds: time.Now().UTC().Truncate(24 * time.Hour).Unix()}
+ families := []sampleFamily{
+ {
+ Slug: couponSlug, Kind: "discount", Name: "Coffee coupon",
+ Description: "A discount on one coffee.",
+ Duration: backend.RelativeTime{Microseconds: 30 * day.Microseconds},
+ Granularity: day, ValidAfter: midnight,
+ },
+ {
+ Slug: passSlug, Kind: "subscription", Name: "Exhibit day pass",
+ Description: "Admission until midnight UTC.",
+ Duration: day, Granularity: day, ValidAfter: midnight,
+ },
+ }
+ for _, family := range families {
+ delay := time.Second
+ for {
+ err := ensureSampleFamily(ctx, a.opts.SamplesBackend, family)
+ if err == nil {
+ break
+ }
+ if ctx.Err() != nil {
+ return
+ }
+ log.Printf("provision merchant samples family %s: %v (retry in %s)", family.Slug, err, delay)
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(delay):
+ }
+ delay = min(2*delay, time.Minute)
+ }
+ }
+ a.samplesReady.Store(true)
+}
+
+func ensureSampleFamily(ctx context.Context, client *backend.Client, want sampleFamily) error {
+ const path = "private/tokenfamilies"
+ var got struct {
+ sampleFamily
+ ValidBefore struct {
+ Seconds json.RawMessage `json:"t_s"`
+ } `json:"valid_before"`
+ }
+ read := func() error { return client.Get(ctx, path+"/"+want.Slug, nil, &got) }
+ err := read()
+ if backendStatus(err, http.StatusNotFound) {
+ err = client.Post(ctx, path, want, nil)
+ if !backendStatus(err, http.StatusConflict) {
+ return err
+ }
+ // Another landing process may have created this slug after our lookup.
+ err = read()
+ }
+ if err != nil {
+ return err
+ }
+ if got.Kind != want.Kind || got.Duration != want.Duration ||
+ got.Granularity != want.Granularity || got.StartOffset != want.StartOffset {
+ return errors.New("existing family has incompatible kind, duration, granularity or offset")
+ }
+ today := time.Now().UTC().Truncate(24 * time.Hour).Unix()
+ if got.ValidAfter.Seconds > today || string(got.ValidBefore.Seconds) != `"never"` {
+ return errors.New("existing family must cover the current validity period and be open-ended")
+ }
+ return nil
+}
diff --git a/internal/web/templates/base.gohtml b/internal/web/templates/base.gohtml
@@ -106,7 +106,7 @@
<div class="language-switcher">
<button class="language-button" id="language-button" type="button" aria-controls="language-menu" aria-expanded="false">{{.LanguageName}}</button>
<div class="language-menu" id="language-menu" hidden>
- {{range .Languages}}{{if ne .Code $.Lang}}<a href="{{$.Prefix}}/{{.Code}}/">{{.Name}}</a>{{end}}{{end}}
+ {{range .Languages}}{{if ne .Code $.Lang}}<a href="{{$.Prefix}}/{{.Code}}/{{$.LanguagePath}}">{{.Name}}</a>{{end}}{{end}}
</div>
</div>
</div>
diff --git a/internal/web/templates/landing.gohtml b/internal/web/templates/landing.gohtml
@@ -18,6 +18,7 @@
<div class="action-row">
<a class="button button-secondary" href="{{.Content.BlogURL}}">{{tr .Lang "Essay Shop"}}{{template "link-icon"}}</a>
<a class="button button-secondary" href="{{.Content.DonationsURL}}">{{tr .Lang "Donations"}}{{template "link-icon"}}</a>
+ {{if .Content.SamplesEnabled}}<a class="button button-secondary" href="{{.Prefix}}/{{.Lang}}/merchant-samples">{{tr .Lang "Merchant samples"}}</a>{{end}}
</div>
</article>
<article class="step-card">
diff --git a/internal/web/templates/merchant-samples.gohtml b/internal/web/templates/merchant-samples.gohtml
@@ -0,0 +1,48 @@
+{{define "content"}}
+<form method="post" action="{{.HeaderURL}}/orders" class="step-list">
+ <article class="step-card">
+ <h2>{{tr .Lang "Plain payment"}}</h2>
+ <p>{{trf .Lang "Buy the same postcard for 1 {currency} using either contract format." "currency" .Content}}</p>
+ <div class="action-row">
+ <button class="button button-secondary" name="sample" value="pay-v0">{{tr .Lang "Buy postcard"}} (v0)</button>
+ <button class="button button-secondary" name="sample" value="pay-v1">{{tr .Lang "Buy postcard"}} (v1)</button>
+ </div>
+ </article>
+ <article class="step-card">
+ <h2>{{tr .Lang "Café basket"}}</h2>
+ <img src="{{.StaticPrefix}}coffee.png" width="64" height="64" alt="{{tr .Lang "Coffee"}}">
+ <img src="{{.StaticPrefix}}croissant.png" width="64" height="64" alt="{{tr .Lang "Croissant"}}">
+ <p>{{trf .Lang "Buy two coffees, a croissant and a tea for {amount}. Open the product list in your wallet to see the quantities, prices and images." "amount" (printf "7 %s" .Content)}}</p>
+ <div class="action-row"><button class="button button-secondary" name="sample" value="basket">{{tr .Lang "Buy café basket"}}</button></div>
+ </article>
+ <article class="step-card">
+ <h2>{{tr .Lang "One-use discount"}}</h2>
+ <p>{{trf .Lang "Buy a coffee for 2 {currency} to earn a coupon. Spend it once to get another coffee for 1 {currency}." "currency" .Content}}</p>
+ <div class="action-row">
+ <button class="button button-secondary" name="sample" value="earn">{{tr .Lang "Earn a coupon"}}</button>
+ <button class="button button-secondary" name="sample" value="redeem">{{tr .Lang "Buy another coffee"}}</button>
+ </div>
+ </article>
+ <article class="step-card">
+ <h2>{{tr .Lang "Exhibit day pass"}}</h2>
+ <p>{{trf .Lang "Pay 1 {currency} per visit or buy a pass for 3 {currency}. Use the pass for repeat visits until midnight UTC." "currency" .Content}}</p>
+ <div class="action-row">
+ <button class="button button-secondary" name="sample" value="pass">{{tr .Lang "Buy a day pass"}}</button>
+ <button class="button button-secondary" name="sample" value="admission">{{tr .Lang "Open an exhibit"}}</button>
+ </div>
+ </article>
+ <article class="step-card">
+ <h2>{{tr .Lang "Two-currency payment"}}</h2>
+ <p>{{trf .Lang "Choose the postcard price in your wallet. Pay 1 {currency} or CHF 0.10." "currency" .Content}}</p>
+ <div class="action-row"><button class="button button-secondary" name="sample" value="postcard">{{tr .Lang "Buy postcard"}}</button></div>
+ </article>
+ <article class="step-card">
+ <h2>{{tr .Lang "Cross-currency discount"}}</h2>
+ <p>{{trf .Lang "Earn a coffee coupon for 2 {currency} or CHF 0.20. Use it in either currency to pay 1 {currency} or CHF 0.10 for the next coffee." "currency" .Content}}</p>
+ <div class="action-row">
+ <button class="button button-secondary" name="sample" value="earn-multi">{{tr .Lang "Earn a coupon"}}</button>
+ <button class="button button-secondary" name="sample" value="redeem-multi">{{tr .Lang "Buy another coffee"}}</button>
+ </div>
+ </article>
+</form>
+{{end}}
diff --git a/internal/web/templates/sample-receipt.gohtml b/internal/web/templates/sample-receipt.gohtml
@@ -0,0 +1,6 @@
+{{define "content"}}
+ <article class="step-card">
+ <h2>{{trf .Lang "Paid {amount}" "amount" .Content}}</h2>
+ <a class="button button-secondary" href="{{.HeaderURL}}">{{tr .Lang "Merchant samples"}}</a>
+ </article>
+{{end}}