Membership: one pay-what-you-want Supporter tier replaces Bronze–Diamond #2

Merged
eric merged 1 commits from pay-what-you-want into main 2026-11-18 20:58:59 +00:00
12 changed files with 450 additions and 102 deletions
+17 -5
View File
@@ -246,11 +246,23 @@ metadata, Discourse integration, or existing subscriptions.
| Membership | Monthly USD | Existing live Price ID | Proposed dedicated LDAP group |
| --- | ---: | --- | --- |
| Level 0 · Open Lab | Free | — | — |
| Level 1 · Bronze | $4 | `price_1Rgv4xC5KPXqTvVLfMd6z7wn` | `www-level-1` |
| Level 2 · Silver | $8 | `price_1Rgv5QC5KPXqTvVLv1PaHWb5` | `www-level-2` |
| Level 3 · Gold | $16 | `price_1Rgv5rC5KPXqTvVL8Ol8sMUf` | `www-level-3` |
| Level 4 · Platinum | $32 | `price_1Rgv6FC5KPXqTvVL39mAxYjm` | `www-level-4` |
| Level 5 · Diamond | $64 | `price_1Rgv6mC5KPXqTvVLkcmznWZa` | `www-level-5` |
| Level 1 · Supporter (was Bronze) | Pay what you want, $3–$500 (suggested $8) | `price_1Rgv4xC5KPXqTvVLfMd6z7wn` (Bronze, $4) | `www-level-1` |
| Level 2 · Silver (retired) | $8 | `price_1Rgv5QC5KPXqTvVLv1PaHWb5` | `www-level-2` |
| Level 3 · Gold (retired) | $16 | `price_1Rgv5rC5KPXqTvVL8Ol8sMUf` | `www-level-3` |
| Level 4 · Platinum (retired) | $32 | `price_1Rgv6FC5KPXqTvVL39mAxYjm` | `www-level-4` |
| Level 5 · Diamond (retired) | $64 | `price_1Rgv6mC5KPXqTvVLkcmznWZa` | `www-level-5` |
**Pay what you want (2026-11-18).** Supporter is the only tier offered. Members
choose a monthly amount between `min_usd` and `max_usd`; Checkout creates a
monthly USD Price for that amount on the Subscription product
(`pay_what_you_want.product_id`), and billing sync accepts only such Prices
(right product, USD, monthly, within the bounds). The original Bronze Price
stays as `price_id`, so existing Bronze subscriptions continue as Supporter.
Retired tiers (`"hidden": true`) are not offered and cannot be bought, but
existing subscriptions and prepaid crypto terms on them keep their access until
they end. SHKeeper prepayments use the same bounds, with the member's chosen
amount stored on the invoice. Benefits are the same at every amount; there are
no giveaways.
Every account has a non-null `membership_level`: new/free accounts start at 0,
and synchronization records the highest currently valid paid level. The former
+2 -2
View File
@@ -304,14 +304,14 @@
<div class="project-mark service-mark"><img src="https://discourse.eom.dev/uploads/default/optimized/1X/_129430568242d1b7f853bb13ebea28b3f6af4e7_2_32x32.png" width="32" height="32" loading="lazy" decoding="async" alt=""></div>
<p class="card-kicker">Free · Level 0 and above</p>
<h3>Discourse · Forums</h3>
<p>Talk about the music, films, and projects. Bronze and above also get exclusive member content.</p>
<p>Talk about the music, films, and projects. Supporters also get supporter-only posts.</p>
<a class="text-link" href="https://discourse.eom.dev/">Visit the forum <span aria-hidden="true">→</span></a>
</article>
<article class="project-card service-card">
<div class="project-mark service-mark"><img src="/static/favicon.svg" width="32" height="32" loading="lazy" decoding="async" alt=""></div>
<p class="card-kicker">Free · Level 0 and above</p>
<h3>Harmony · Chat, voice &amp; video</h3>
<p>Hang out in community servers and channels, hop into voice and video calls, and follow posts from across the fediverse. Bronze and above also get exclusive member content.</p>
<p>Hang out in community servers and channels, hop into voice and video calls, and follow posts from across the fediverse. Supporters also get supporter-only posts.</p>
<a class="text-link" href="https://harmony.eom.dev/">Open Harmony <span aria-hidden="true">→</span></a>
</article>
<article class="project-card service-card">
+23
View File
@@ -160,6 +160,29 @@ for key, tier in MEMBERSHIP_TIERS.items():
raise ValueError
except (InvalidOperation, ValueError, TypeError):
raise ImproperlyConfigured(f"Tier {key} usd_amount must be a positive USD amount with at most two decimals.") from None
# Pay what you want: members choose a monthly amount in [min_usd, max_usd];
# checkout creates that Price on product_id. price_id stays the tier's
# original fixed Price, so existing subscriptions to it keep working.
if "pay_what_you_want" in tier:
pwyw = tier["pay_what_you_want"]
try:
if not isinstance(pwyw, dict) or not isinstance(pwyw.get("product_id"), str) or not re.fullmatch(r"prod_[A-Za-z0-9]+", pwyw["product_id"]):
raise ValueError
amounts = []
for name in ("min_usd", "suggested_usd", "max_usd"):
if not isinstance(pwyw.get(name), str):
raise ValueError
amount = Decimal(pwyw[name])
if not amount.is_finite() or amount != amount.quantize(Decimal("0.01")):
raise ValueError
amounts.append(amount)
if not Decimal("1.00") <= amounts[0] <= amounts[1] <= amounts[2] <= Decimal("10000.00"):
raise ValueError
except (InvalidOperation, ValueError, TypeError):
raise ImproperlyConfigured(f"Tier {key} pay_what_you_want needs a Stripe product_id and string USD amounts with 1.00 <= min_usd <= suggested_usd <= max_usd <= 10000.00.") from None
# Hidden tiers keep honouring existing subscriptions but are not offered.
if not isinstance(tier.get("hidden", False), bool):
raise ImproperlyConfigured(f"Tier {key} hidden must be true or false.")
# Separate from Stripe tiers so free accounts can receive service benefits too.
from members.service_groups import validate_service_groups
+4 -1
View File
@@ -11,7 +11,7 @@ from django.utils import timezone
from .directory import reconcile_groups
from .models import Account, CryptoInvoice, ManagedGroup, Subscription, WebhookEvent
from . import shkeeper
from . import pricing, shkeeper
from .service_groups import configured_groups
logger = logging.getLogger(__name__)
@@ -72,6 +72,9 @@ def refresh_billing(account):
data = items.get("data") or []
price_id = _id(data[0].get("price")) if len(data) == 1 and not items.get("has_more") else None
tier = prices.get(price_id, "")
if not tier and price_id:
# Pay-what-you-want subscriptions each have their own Price.
tier = next((key for key, config in settings.MEMBERSHIP_TIERS.items() if pricing.is_pwyw(config) and pricing.accepts_price(config, data[0].get("price"))), "")
eligible = tier and sub.get("status") in {"active", "past_due"} and not sub.get("pause_collection")
paid_until = _paid_until(api, sub, price_id, now) if eligible else None
if paid_until and sub.get("cancel_at"):
+59
View File
@@ -0,0 +1,59 @@
"""Pay-what-you-want amounts: one validated place for checkout, crypto and billing."""
from decimal import Decimal, InvalidOperation
CENT = Decimal("0.01")
def _id(value):
return value.get("id") if isinstance(value, dict) else value
def is_pwyw(tier):
return bool(tier.get("pay_what_you_want"))
def bounds(tier):
"""(minimum, suggested, maximum) monthly USD amounts."""
options = tier["pay_what_you_want"]
return Decimal(options["min_usd"]), Decimal(options["suggested_usd"]), Decimal(options["max_usd"])
def parse_amount(tier, raw):
"""The member's chosen monthly USD amount, or None if it is not a valid choice."""
if not isinstance(raw, str):
return None
try:
amount = Decimal(raw.strip().removeprefix("$"))
except InvalidOperation:
return None
low, _suggested, high = bounds(tier)
if not amount.is_finite() or amount != amount.quantize(CENT) or not low <= amount <= high:
return None
return amount.quantize(CENT)
def cents(amount):
return int(amount * 100)
def accepts_price(tier, price):
"""True only for a Stripe Price this tier's checkout could have created.
Pay-what-you-want checkouts create a monthly USD Price on the tier's
product. Anything else on that product (other currencies, intervals or
amounts outside the bounds) grants nothing.
"""
if not isinstance(price, dict):
return False
recurring = price.get("recurring") or {}
amount = price.get("unit_amount")
low, _suggested, high = bounds(tier)
return (
_id(price.get("product")) == tier["pay_what_you_want"]["product_id"]
and price.get("currency") == "usd"
and recurring.get("interval") == "month"
and recurring.get("interval_count", 1) == 1
and isinstance(amount, int) and not isinstance(amount, bool)
and cents(low) <= amount <= cents(high)
)
@@ -0,0 +1,210 @@
"""Pay-what-you-want Supporter membership: checkout, crypto, billing and settings."""
import json
import os
import runpy
from datetime import timedelta
from decimal import Decimal
from pathlib import Path
from unittest.mock import MagicMock, patch
from django.core.exceptions import ImproperlyConfigured
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils import timezone
from members import billing, pricing
from members.models import CryptoInvoice, Subscription
from .test_membership import DN, GROUP, OTHER_GROUP, account, paged
PWYW = {"product_id": "prod_lab", "min_usd": "3.00", "suggested_usd": "8.00", "max_usd": "500.00"}
TIERS = {
"supporter": {"label": "Supporter", "level": 1, "price_id": "price_bronze", "price_label": "Pay what you want", "pay_what_you_want": PWYW, "group_dn": GROUP},
"retired": {"label": "Diamond", "level": 2, "price_id": "price_diamond", "price_label": "$64 / month", "usd_amount": "64.00", "hidden": True, "group_dn": OTHER_GROUP},
}
SHKEEPER = {"SHKEEPER_ENABLED": True, "SHKEEPER_URL": "https://pay.example.org", "SHKEEPER_API_KEY": "test-only-key", "SHKEEPER_CA_CERT_FILE": "", "SHKEEPER_CURRENCIES": ["BTC", "XMR"]}
def price(**changes):
return {"id": "price_adhoc", "product": "prod_lab", "currency": "usd", "unit_amount": 1250, "recurring": {"interval": "month", "interval_count": 1}, **changes}
class AmountParsingTests(SimpleTestCase):
tier = TIERS["supporter"]
def test_accepts_amounts_within_bounds(self):
for raw, expected in (("3", "3.00"), ("8.00", "8.00"), (" $12.5 ", "12.50"), ("500", "500.00")):
with self.subTest(raw=raw):
self.assertEqual(pricing.parse_amount(self.tier, raw), Decimal(expected))
def test_rejects_out_of_bounds_and_malformed_amounts(self):
for raw in ("2.99", "500.01", "0", "-5", "8.001", "NaN", "Infinity", "1e3", "", "eight", None, ["8"]):
with self.subTest(raw=raw):
self.assertIsNone(pricing.parse_amount(self.tier, raw))
def test_only_prices_checkout_could_create_are_accepted(self):
self.assertTrue(pricing.accepts_price(self.tier, price()))
self.assertTrue(pricing.accepts_price(self.tier, price(product={"id": "prod_lab"})))
for changes in ({"product": "prod_other"}, {"currency": "eur"}, {"unit_amount": 299}, {"unit_amount": 50001},
{"unit_amount": None}, {"unit_amount": True}, {"recurring": {"interval": "year"}},
{"recurring": {"interval": "month", "interval_count": 3}}, {"recurring": None}):
with self.subTest(changes=changes):
self.assertFalse(pricing.accepts_price(self.tier, price(**changes)))
self.assertFalse(pricing.accepts_price(self.tier, "price_adhoc"))
@override_settings(MEMBERSHIP_TIERS=TIERS, STRIPE_PORTAL_CONFIGURATION="bpc_test")
class CheckoutTests(TestCase):
def setUp(self):
self.member = account(stripe_customer="cus_alice")
session = self.client.session
session["account_id"] = str(self.member.pk)
session.save()
def test_page_offers_only_visible_tier_with_amount_field(self):
response = self.client.get("/members/")
self.assertContains(response, 'name="amount"')
self.assertContains(response, 'value="8.00"')
self.assertContains(response, "Supporter")
self.assertNotContains(response, "$64 / month")
self.assertNotContains(response, "/members/checkout/retired/")
self.assertNotContains(response, "giveaway")
def test_retired_subscription_keeps_its_label(self):
Subscription.objects.create(stripe_id="sub_old", account=self.member, tier="retired", status="active", paid_until=timezone.now() + timedelta(days=3))
self.assertContains(self.client.get("/members/"), "Diamond · active")
@patch("members.views.billing.client")
def test_chosen_amount_becomes_monthly_price_on_product(self, api_factory):
api = api_factory.return_value
api.subscriptions.list.return_value = paged([])
api.checkout.sessions.create.return_value = {"id": "cs_new", "url": "https://checkout.stripe.com/c/pay/new"}
response = self.client.post("/members/checkout/supporter/", {"amount": "12.50", "price_id": "price_attacker"})
self.assertEqual(response.status_code, 302)
params = api.checkout.sessions.create.call_args.args[0]
self.assertEqual(params["line_items"], [{"price_data": {"currency": "usd", "product": "prod_lab", "unit_amount": 1250, "recurring": {"interval": "month"}}, "quantity": 1}])
self.assertEqual(params["customer"], "cus_alice")
self.assertTrue(api.checkout.sessions.create.call_args.kwargs["options"]["idempotency_key"].endswith("-1250"))
@patch("members.views.billing.client")
def test_invalid_amount_never_reaches_stripe(self, api_factory):
for amount in ("2", "501", "abc", ""):
with self.subTest(amount=amount):
self.assertContains(self.client.post("/members/checkout/supporter/", {"amount": amount}), "Enter a monthly amount from $3.00 to $500.00 USD.")
self.assertContains(self.client.post("/members/checkout/supporter/"), "Choose an amount")
api_factory.assert_not_called()
@patch("members.views.billing.client")
def test_retired_tier_cannot_be_bought(self, api_factory):
self.assertEqual(self.client.post("/members/checkout/retired/").status_code, 404)
api_factory.assert_not_called()
@patch("members.views.billing.client")
def test_open_session_reused_for_same_amount_and_replaced_for_new_amount(self, api_factory):
api = api_factory.return_value
api.subscriptions.list.return_value = paged([])
type(self.member).objects.filter(pk=self.member.pk).update(checkout_id="cs_open")
api.checkout.sessions.retrieve.return_value = {"status": "open", "amount_total": 800, "url": "https://checkout.stripe.com/c/pay/open"}
self.assertEqual(self.client.post("/members/checkout/supporter/", {"amount": "8"})["Location"], "https://checkout.stripe.com/c/pay/open")
api.checkout.sessions.create.assert_not_called()
api.checkout.sessions.create.return_value = {"id": "cs_new", "url": "https://checkout.stripe.com/c/pay/new"}
self.assertEqual(self.client.post("/members/checkout/supporter/", {"amount": "20"})["Location"], "https://checkout.stripe.com/c/pay/new")
api.checkout.sessions.expire.assert_called_once_with("cs_open")
self.assertEqual(api.checkout.sessions.create.call_args.args[0]["line_items"][0]["price_data"]["unit_amount"], 2000)
@override_settings(MEMBERSHIP_TIERS=TIERS)
class BillingTests(TestCase):
def setUp(self):
self.member = account(stripe_customer="cus_alice")
self.end = int((timezone.now() + timedelta(days=30)).timestamp())
def api(self, item_price):
sub = {"id": "sub_alice", "customer": "cus_alice", "livemode": False, "metadata": {"membership_account": str(self.member.pk)}, "status": "active", "items": {"data": [{"price": item_price}], "has_more": False}, "cancel_at_period_end": False}
invoice = {"id": "in_paid", "customer": "cus_alice", "status": "paid", "livemode": False, "parent": {"subscription_details": {"subscription": "sub_alice"}}}
line = {"amount": item_price.get("unit_amount", 400), "parent": {"subscription_item_details": {"subscription": "sub_alice"}}, "pricing": {"price_details": {"price": item_price["id"]}}, "period": {"start": int(timezone.now().timestamp()) - 60, "end": self.end}}
api = MagicMock()
api.subscriptions.list.return_value = paged([sub])
api.invoices.list.return_value = paged([invoice])
api.invoices.line_items.list.return_value = paged([line])
return api
@patch("members.billing.reconcile_groups", return_value=DN)
@patch("members.billing.client")
def test_pay_what_you_want_subscription_grants_supporter(self, factory, ldap):
factory.return_value = self.api(price())
self.assertTrue(billing.sync_account(self.member.pk))
self.assertEqual(Subscription.objects.get().tier, "supporter")
self.assertEqual(ldap.call_args.args[1], {GROUP})
@patch("members.billing.reconcile_groups", return_value=DN)
@patch("members.billing.client")
def test_original_fixed_price_and_retired_tier_still_honoured(self, factory, ldap):
for price_id, tier, group in (("price_bronze", "supporter", GROUP), ("price_diamond", "retired", OTHER_GROUP)):
with self.subTest(price_id=price_id):
factory.return_value = self.api({"id": price_id})
billing.sync_account(self.member.pk)
self.assertEqual(Subscription.objects.get().tier, tier)
self.assertEqual(ldap.call_args.args[1], {group})
@patch("members.billing.reconcile_groups", return_value=DN)
@patch("members.billing.client")
def test_foreign_or_out_of_bounds_price_grants_nothing(self, factory, ldap):
for changes in ({"product": "prod_other"}, {"unit_amount": 100}, {"currency": "eur"}):
with self.subTest(changes=changes):
factory.return_value = self.api(price(**changes))
billing.sync_account(self.member.pk)
self.assertEqual(Subscription.objects.get().tier, "")
self.assertEqual(ldap.call_args.args[1], set())
@override_settings(MEMBERSHIP_TIERS=TIERS, **SHKEEPER)
class CryptoTests(TestCase):
def setUp(self):
self.member = account()
session = self.client.session
session["account_id"] = str(self.member.pk)
session.save()
def test_form_asks_for_amount(self):
response = self.client.get("/members/crypto/checkout/supporter/")
self.assertContains(response, 'name="amount"')
self.assertContains(response, "Pay what you want")
self.assertEqual(self.client.get("/members/crypto/checkout/retired/").status_code, 404)
@patch("members.shkeeper.request")
def test_chosen_amount_is_the_invoice_amount(self, request):
request.return_value = {"status": "success", "id": 61, "wallet": "bc1-test-wallet", "amount": "0.0001", "recalculate_after": 0}
self.client.post("/members/crypto/checkout/supporter/", {"crypto": "BTC", "amount": "15", "usd_amount": "0.01"})
self.assertEqual(CryptoInvoice.objects.get().usd_amount, Decimal("15.00"))
def test_invalid_amount_rejected(self):
for amount in ("1", "9999", "x"):
with self.subTest(amount=amount):
self.assertEqual(self.client.post("/members/crypto/checkout/supporter/", {"crypto": "BTC", "amount": amount}).status_code, 400)
self.assertFalse(CryptoInvoice.objects.exists())
class SettingsTests(SimpleTestCase):
settings_file = str(Path(__file__).absolute().parents[2] / "config" / "settings.py")
def load(self, tiers):
with patch.dict(os.environ, {"MEMBERSHIP_TIERS_JSON": json.dumps(tiers), "MEMBERSHIP_SERVICE_GROUPS_JSON": "{}"}):
return runpy.run_path(self.settings_file)
def test_valid_and_deployed_tiers_load(self):
self.assertEqual(self.load(TIERS)["MEMBERSHIP_TIERS"], TIERS)
deployed = json.loads((Path(__file__).absolute().parents[2] / "tiers.eom.json").read_text(encoding="utf-8"))
self.assertEqual(self.load(deployed)["MEMBERSHIP_TIERS"], deployed)
self.assertEqual([key for key, tier in deployed.items() if not tier.get("hidden")], ["level-1"])
self.assertFalse(any("giveaway" in benefit.casefold() for benefit in deployed["level-1"]["benefits"]))
def test_invalid_pay_what_you_want_rejected(self):
for change in ({"product_id": "price_x"}, {"min_usd": 3}, {"min_usd": "0.50"}, {"min_usd": "9.00"},
{"max_usd": "20000.00"}, {"suggested_usd": "8.001"}, {"max_usd": None}):
with self.subTest(change=change), self.assertRaises(ImproperlyConfigured):
self.load({"supporter": {**TIERS["supporter"], "pay_what_you_want": {**PWYW, **change}}})
for bad in ([], "yes"):
with self.subTest(bad=bad), self.assertRaises(ImproperlyConfigured):
self.load({"supporter": {**TIERS["supporter"], "pay_what_you_want": bad}})
with self.assertRaises(ImproperlyConfigured):
self.load({"retired": {**TIERS["retired"], "hidden": "yes"}})
@@ -91,10 +91,13 @@ class ServiceDisplayTests(TestCase):
deployed = yaml.safe_load(role.read_text(encoding="utf-8"))["www_membership_tiers"]
for key, tier in tiers.items():
self.assertEqual(tier.get("hidden", False), deployed[key].get("hidden", False))
self.assertEqual(tier.get("pay_what_you_want"), deployed[key].get("pay_what_you_want"))
if tier.get("hidden"):
continue # retired tiers are never shown
self.assertEqual(tier["description"], deployed[key]["description"])
self.assertEqual(tier["benefits"], deployed[key]["benefits"])
self.assertIn(f"{tier['label']}-tier giveaways", tier["benefits"])
self.assertFalse(any("exclusive to" in benefit.casefold() for benefit in tier["benefits"]))
self.assertFalse(any("giveaway" in benefit.casefold() for benefit in tier["benefits"]))
def test_homepage_lists_services_with_clear_access_labels(self):
root = Path(__file__).absolute().parents[3]
@@ -187,7 +190,8 @@ class ServiceDisplayTests(TestCase):
self.assertContains(response, "Plus all previous benefits")
self.assertNotContains(response, "except tier-exclusive giveaways")
self.assertContains(response, "Support independent projects and the community</li><li>Plus all previous benefits</li>")
self.assertContains(response, "How do membership giveaways work?")
self.assertNotContains(response, "giveaway")
self.assertContains(response, "What happened to Bronze, Silver, Gold, Platinum and Diamond?")
self.assertContains(response, 'href="https://element.eom.dev/"')
self.assertContains(response, 'src="https://element.eom.dev/vector-icons/144.5a63bf2.png"')
self.assertIn("https://element.eom.dev", response["Content-Security-Policy"])
+33 -10
View File
@@ -23,7 +23,7 @@ from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.http import require_GET, require_POST, require_http_methods
from . import billing, directory, newsletter, profiles, shkeeper
from . import billing, directory, newsletter, pricing, profiles, shkeeper
from .forms import PasswordForm, RegistrationForm, SocialRegistrationForm
from .service_groups import configured_groups, service_access_catalog
from .profile_forms import CurrentPasswordForm, ProfileEmailForm, ProfileForm, ProfilePasswordForm
@@ -77,10 +77,12 @@ def home(request):
invoices = CryptoInvoice.objects.filter(account=account).order_by("-created_at")[:20] if account else []
# Presentation copies only: never mutate authorization/payment settings.
tiers = settings.MEMBERSHIP_TIERS
services = service_access_catalog(tiers, settings.MEMBERSHIP_SERVICE_GROUPS)
# Hidden (retired) tiers still label existing subscriptions but are not offered.
offered = {key: tier for key, tier in tiers.items() if not tier.get("hidden")}
services = service_access_catalog(offered, settings.MEMBERSHIP_SERVICE_GROUPS)
# Public total across every level (free and paid); never a per-tier breakdown.
member_count = Account.objects.count()
return page(request, account=account, tiers=tiers, services=services, subscriptions=subscriptions, crypto_invoices=invoices, shkeeper_enabled=settings.SHKEEPER_ENABLED, now=timezone.now(), member_count=member_count)
return page(request, account=account, tiers=offered, all_tiers=tiers, services=services, subscriptions=subscriptions, crypto_invoices=invoices, shkeeper_enabled=settings.SHKEEPER_ENABLED, now=timezone.now(), member_count=member_count)
@require_http_methods(["GET", "POST"])
@@ -574,8 +576,14 @@ def stripe_redirect(url, host):
@account_required
def checkout(request, tier):
config = settings.MEMBERSHIP_TIERS.get(tier)
if not config:
if not config or config.get("hidden"):
return HttpResponse(status=404)
amount = None
if pricing.is_pwyw(config):
amount = pricing.parse_amount(config, request.POST.get("amount"))
if amount is None:
low, _suggested, high = pricing.bounds(config)
return page(request, title="Choose an amount", message=f"Enter a monthly amount from ${low} to ${high} USD.")
if limited("checkout", str(request.member.pk), 20):
return HttpResponse(status=429)
try:
@@ -595,16 +603,25 @@ def checkout(request, tier):
if account.checkout_id:
session = api.checkout.sessions.retrieve(account.checkout_id)
if session.get("status") == "open":
return stripe_redirect(session["url"], "checkout.stripe.com")
if amount is None or session.get("amount_total") == pricing.cents(amount):
return stripe_redirect(session["url"], "checkout.stripe.com")
# A different amount was chosen: retire the old session first.
api.checkout.sessions.expire(account.checkout_id)
account.checkout_key = uuid.uuid4()
if amount is None:
line_item = {"price": config["price_id"], "quantity": 1}
idempotency_key = f"member-checkout-{account.pk}-{account.checkout_key}"
else:
line_item = {"price_data": {"currency": "usd", "product": config["pay_what_you_want"]["product_id"], "unit_amount": pricing.cents(amount), "recurring": {"interval": "month"}}, "quantity": 1}
idempotency_key = f"member-checkout-{account.pk}-{account.checkout_key}-{pricing.cents(amount)}"
session = api.checkout.sessions.create({
"mode": "subscription", "customer": account.stripe_customer,
"line_items": [{"price": config["price_id"], "quantity": 1}],
"line_items": [line_item],
"client_reference_id": str(account.pk),
"subscription_data": {"metadata": {"membership_account": str(account.pk)}},
"success_url": settings.PUBLIC_URL + reverse("members:home") + "?checkout=complete",
"cancel_url": settings.PUBLIC_URL + reverse("members:home"),
}, options={"idempotency_key": f"member-checkout-{account.pk}-{account.checkout_key}"})
}, options={"idempotency_key": idempotency_key})
account.checkout_id = session["id"]
account.save(update_fields=["checkout_id", "checkout_key"])
return stripe_redirect(session["url"], "checkout.stripe.com")
@@ -652,13 +669,19 @@ def webhook(request):
@account_required
def crypto_checkout(request, tier):
config = settings.MEMBERSHIP_TIERS.get(tier)
if not settings.SHKEEPER_ENABLED or not config or not config.get("usd_amount"):
if not settings.SHKEEPER_ENABLED or not config or config.get("hidden") or not (config.get("usd_amount") or pricing.is_pwyw(config)):
return HttpResponse(status=404)
pwyw = pricing.bounds(config) if pricing.is_pwyw(config) else None
if request.method == "GET":
return render(request, "crypto_checkout.html", {"tier": config, "tier_key": tier, "currencies": settings.SHKEEPER_CURRENCIES})
return render(request, "crypto_checkout.html", {"tier": config, "tier_key": tier, "currencies": settings.SHKEEPER_CURRENCIES, "pwyw": pwyw})
crypto = request.POST.get("crypto", "")
if crypto not in settings.SHKEEPER_CURRENCIES:
return HttpResponse("Choose an available cryptocurrency.", status=400)
usd_amount = config.get("usd_amount")
if pwyw:
usd_amount = pricing.parse_amount(config, request.POST.get("amount"))
if usd_amount is None:
return HttpResponse(f"Enter an amount from ${pwyw[0]} to ${pwyw[2]} USD.", status=400)
if limited("crypto-checkout", str(request.member.pk), 20):
return HttpResponse(status=429)
try:
@@ -680,7 +703,7 @@ def crypto_checkout(request, tier):
return page(request, title="Stripe checkout is still open", message="Finish or let the existing Stripe Checkout expire before changing payment providers.")
if CryptoInvoice.objects.filter(account=account, access_end__gt=timezone.now()).exclude(tier=tier).exists():
return page(request, title="Another prepaid tier is active", message="Renew the same tier, or wait for the current prepaid membership to expire before changing tiers.")
invoice = CryptoInvoice.objects.create(account=account, tier=tier, crypto=crypto, usd_amount=config["usd_amount"])
invoice = CryptoInvoice.objects.create(account=account, tier=tier, crypto=crypto, usd_amount=usd_amount)
remember_groups(account)
# Reserve/commit UUID BEFORE API call, so retries and worker recovery
# use the same external ID if the process dies after invoice creation.
+3 -1
View File
@@ -1,10 +1,12 @@
{% extends "crypto_base.html" %}
{% block content %}
<h1>Prepay {{ tier.label }}</h1>
<p class="tier-price">${{ tier.usd_amount }} USD <span>/ one calendar month</span></p>
{% if pwyw %}<p class="tier-price">Pay what you want <span>/ one calendar month</span></p>{% else %}<p class="tier-price">${{ tier.usd_amount }} USD <span>/ one calendar month</span></p>{% endif %}
<p>Pay once with cryptocurrency. This is <strong>not an automatically renewing subscription</strong>. Renewing the same tier adds one calendar month after your current prepaid term ends.</p>
<form method="post">
{% csrf_token %}
{% if pwyw %}<p><label for="amount">Amount for one month (USD, ${{ pwyw.0 }}–${{ pwyw.2 }})</label>
<input id="amount" name="amount" type="number" inputmode="decimal" min="{{ pwyw.0 }}" max="{{ pwyw.2 }}" step="0.01" value="{{ pwyw.1 }}" required></p>{% endif %}
<p><label for="crypto">Cryptocurrency and network</label>
<select id="crypto" name="crypto" required>{% for currency in currencies %}<option value="{{ currency }}">{{ currency }}</option>{% endfor %}</select></p>
<p class="member-small">Choose carefully. Tokens on different networks are not interchangeable. SHKeeper supplies the deposit address and crypto amount. Configured processor fees or exchange-rate changes may affect the required amount.</p>
+12 -10
View File
@@ -48,7 +48,7 @@
<p class="eyebrow">Music, films, projects &amp; shared worlds</p>
<h1>Support the work.<br>Get closer to what’s next.</h1>
{% if member_count %}<p class="member-count"><strong>{{ member_count }}</strong> member{{ member_count|pluralize }} and counting</p>{% endif %}
<p class="member-intro">Membership supports my music, films, writing, open-source projects, and game servers. Join the community for free, or choose a paid tier to support the work and receive the benefits listed below.</p>
<p class="member-intro">Membership supports my music, films, writing, open-source projects, and game servers. Join the community for free, or support the lab with whatever amount feels right each month.</p>
{% if account %}
<div class="member-panel account-panel">
<div><p class="eyebrow">Your eom.dev account · Membership level {{ account.membership_level }}</p><h2>{{ account.uid }}</h2><p>{{ account.email }}</p></div>
@@ -60,10 +60,10 @@
</div>
{% if request.GET.checkout %}<p role="status" class="member-notice">Thanks for supporting the work. Your membership benefits become available once Stripe confirms payment and your account access updates.</p>{% endif %}
{% for subscription in subscriptions %}
<p class="member-notice">{% for key, tier in tiers.items %}{% if key == subscription.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ subscription.status }}{% if subscription.paid_until > now %} · Paid access through {{ subscription.paid_until|date:"M j, Y H:i T" }}{% else %} · No current paid access{% endif %}{% if subscription.cancel_at_period_end %} · Does not renew{% endif %}</p>
<p class="member-notice">{% for key, tier in all_tiers.items %}{% if key == subscription.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ subscription.status }}{% if subscription.paid_until > now %} · Paid access through {{ subscription.paid_until|date:"M j, Y H:i T" }}{% else %} · No current paid access{% endif %}{% if subscription.cancel_at_period_end %} · Does not renew{% endif %}</p>
{% endfor %}
{% for invoice in crypto_invoices %}
<p class="member-notice">SHKeeper · {% for key, tier in tiers.items %}{% if key == invoice.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ invoice.status }}{% if invoice.access_end > now %} · Prepaid term {{ invoice.access_start|date:"M j, Y" }}–{{ invoice.access_end|date:"M j, Y" }}{% endif %} · <a href="{% url 'members:crypto_invoice' invoice.id %}">View crypto invoice</a></p>
<p class="member-notice">SHKeeper · {% for key, tier in all_tiers.items %}{% if key == invoice.tier %}{{ tier.label }}{% endif %}{% empty %}Membership{% endfor %} · {{ invoice.status }}{% if invoice.access_end > now %} · Prepaid term {{ invoice.access_start|date:"M j, Y" }}–{{ invoice.access_end|date:"M j, Y" }}{% endif %} · <a href="{% url 'members:crypto_invoice' invoice.id %}">View crypto invoice</a></p>
{% endfor %}
<p class="member-small">Membership access updates automatically, usually within a few minutes. Signing out here does not sign you out of other eom.dev services.</p>
{% else %}
@@ -74,12 +74,12 @@
{% endif %}
</section>
<section aria-labelledby="tiers-heading">
<div class="section-heading"><p class="eyebrow">Your support, your choice</p><h2 id="tiers-heading">Choose how to take part</h2><p>Public recordings, writing, and source code remain available without a paid membership. Your support helps fund creative time, recording, travel, and independent publishing.</p><p>Paid benefits build by level: Bronze adds exclusive Discourse and Harmony content; Silver adds previews when available; Gold adds project-topic polls and occasional feedback sessions. Compare the full benefits below.</p></div>
<div class="section-heading"><p class="eyebrow">Your support, your choice</p><h2 id="tiers-heading">Choose how to take part</h2><p>Public recordings, writing, and source code remain available without a paid membership. Your support helps fund creative time, recording, travel, and independent publishing.</p><p>I work in bursts, not on a schedule. The work ships as drops when it's ready: a game build, a song, a film, a write-up. Supporters keep the lab running between drops, choose their own monthly amount, and get the same benefits whatever they give.</p></div>
<div class="member-grid">
<article class="member-panel tier-card free-tier">
<p class="card-kicker">Level 0 · The starting point</p><h3>Open Lab</h3><p class="tier-price">Free <span>/ always</span></p>
<p>Join the community without a subscription.</p>
<ul><li>Games hosted on eom.dev</li><li>Open Lab-tier giveaways</li></ul>
<ul><li>Games hosted on eom.dev</li><li>Public build logs, source code and drops</li></ul>
{% if not account %}<a class="button button-secondary" href="{% url 'members:register' %}">Join the community</a>{% else %}<p class="tier-footnote">Your free account is ready.</p>{% endif %}
</article>
{% for key, tier in tiers.items %}
@@ -87,8 +87,10 @@
<p class="card-kicker">Level {{ tier.level }}</p><h3>{{ tier.label }}</h3><p class="tier-price">{{ tier.price_label }}</p>
<p>{{ tier.description|default:"Support the independent work and community." }}</p>
<ul>{% for benefit in tier.benefits %}<li>{{ benefit }}</li>{% empty %}<li>Support independent projects and the community</li>{% endfor %}<li>Plus all previous benefits</li></ul>
{% if account %}<div class="tier-payment-actions"><form action="{% url 'members:checkout' key %}" method="post">{% csrf_token %}<button class="button button-primary" type="submit">Subscribe with Stripe</button></form>
{% if shkeeper_enabled and tier.usd_amount %}<a class="button button-secondary" href="{% url 'members:crypto_checkout' key %}">Pay with crypto</a>{% endif %}</div>{% else %}<a class="button button-primary" href="{% url 'members:register' %}">Create an account to join</a>{% endif %}
{% if account %}{% if tier.pay_what_you_want %}<div class="tier-payment-actions"><form action="{% url 'members:checkout' key %}" method="post">{% csrf_token %}<p><label for="amount-{{ key }}">Your monthly amount (USD)</label> <input id="amount-{{ key }}" name="amount" type="number" inputmode="decimal" min="{{ tier.pay_what_you_want.min_usd }}" max="{{ tier.pay_what_you_want.max_usd }}" step="0.01" value="{{ tier.pay_what_you_want.suggested_usd }}" required></p><button class="button button-primary" type="submit">Subscribe with Stripe</button></form>
{% if shkeeper_enabled %}<a class="button button-secondary" href="{% url 'members:crypto_checkout' key %}">Pay with crypto</a>{% endif %}</div>
{% else %}<div class="tier-payment-actions"><form action="{% url 'members:checkout' key %}" method="post">{% csrf_token %}<button class="button button-primary" type="submit">Subscribe with Stripe</button></form>
{% if shkeeper_enabled and tier.usd_amount %}<a class="button button-secondary" href="{% url 'members:crypto_checkout' key %}">Pay with crypto</a>{% endif %}</div>{% endif %}{% else %}<a class="button button-primary" href="{% url 'members:register' %}">Create an account to join</a>{% endif %}
</article>
{% empty %}<div class="member-panel"><h3>Paid memberships are coming soon.</h3><p>You can create your free account now. Paid tiers will appear when their prices and groups are configured.</p></div>{% endfor %}
</div>
@@ -103,10 +105,10 @@
<section class="member-faq" aria-labelledby="membership-faq">
<h2 id="membership-faq">Before you join</h2>
<details><summary>Do I need a paid membership to watch, read, or play?</summary><p>No. Public videos, writing, and source code can be explored without a paid membership. A free Open Lab (Level 0) account includes access to games hosted on eom.dev, and paid members can play too. No paid-exclusive game servers are currently included.</p></details>
<details><summary>How do membership giveaways work?</summary><p>Giveaways are associated with a membership tier. Higher tiers include giveaway benefits from lower tiers, including Open Lab. Each giveaway's rules will list its availability, dates, prizes and any eligibility restrictions. Membership does not guarantee a prize.</p></details>
<details><summary>What do membership polls influence?</summary><p>Gold (Level 3) and above can share preferences about future project topics and experiments. Platinum (Level 4) and Diamond (Level 5) also receive separate polls about the direction of eom.dev itself. Results inform my decisions; they are not binding commitments or guarantees of particular features.</p></details>
<details><summary>How much should I give?</summary><p>Whatever feels right. Every amount gets the same benefits. To change your amount later, cancel in Manage billing, and once that membership ends, subscribe again with the new amount.</p></details>
<details><summary>What happened to Bronze, Silver, Gold, Platinum and Diamond?</summary><p>They are now one pay-what-you-want Supporter membership. If you already have one of those memberships, nothing changes: it keeps working until you cancel it. To switch to an amount you choose, cancel in Manage billing, and once it ends, subscribe again as a Supporter.</p></details>
<details><summary>What happens when a membership ends?</summary><p>Your free eom.dev account stays. Member-only access ends when your paid membership expires. An immediate cancellation removes that access once your membership status updates.</p></details>
<details><summary>Where do members connect?</summary><p>On Discourse, Harmony and Mastodon, which come with every membership level, including the free one. Bronze and above also receive exclusive content on Discourse and Harmony.</p></details>
<details><summary>Where do members connect?</summary><p>On Discourse, Harmony and Mastodon, which come with every membership level, including the free one. Supporters also receive supporter-only posts on Discourse and Harmony.</p></details>
<details><summary>Can I change or cancel a plan?</summary><p>Use Manage billing after signing in. The billing portal offers the changes enabled for your plan. Cancellation at period end keeps access through the paid expiry date.</p></details>
{% if shkeeper_enabled %}<details><summary>How do crypto memberships renew?</summary><p>SHKeeper payments prepay one calendar month, without automatic charges. Create a new invoice for each renewal. Confirmed payment on the same tier extends its prepaid term. Partial or unconfirmed payments do not grant access. Do not send renewal funds to an old invoice address.</p></details>{% endif %}
</section>
+78 -69
View File
@@ -1,69 +1,78 @@
{
"level-1": {
"level": 1,
"label": "Bronze",
"price_id": "price_1Rgv4xC5KPXqTvVLfMd6z7wn",
"price_label": "$4 USD / month",
"usd_amount": "4.00",
"group_dn": "cn=Level 1,ou=Memberships,dc=eom,dc=dev",
"description": "Go beyond the public feed.",
"benefits": [
"Exclusive Discourse and Harmony content, including work-in-progress updates",
"Bronze-tier giveaways",
"Optional credit on the community supporters page"
]
},
"level-2": {
"level": 2,
"label": "Silver",
"price_id": "price_1Rgv5QC5KPXqTvVLv1PaHWb5",
"price_label": "$8 USD / month",
"usd_amount": "8.00",
"group_dn": "cn=Level 2,ou=Memberships,dc=eom,dc=dev",
"description": "Try new work before release.",
"benefits": [
"Silver-tier giveaways",
"Early previews, playtests and listening sessions when available"
]
},
"level-3": {
"level": 3,
"label": "Gold",
"price_id": "price_1Rgv5rC5KPXqTvVL8Ol8sMUf",
"price_label": "$16 USD / month",
"usd_amount": "16.00",
"group_dn": "cn=Level 3,ou=Memberships,dc=eom,dc=dev",
"description": "Help shape the next experiment.",
"benefits": [
"Gold-tier giveaways",
"Member polls on future project topics and experiments",
"Invitations to occasional small-group feedback sessions"
]
},
"level-4": {
"level": 4,
"label": "Platinum",
"price_id": "price_1Rgv6FC5KPXqTvVL39mAxYjm",
"price_label": "$32 USD / month",
"usd_amount": "32.00",
"group_dn": "cn=Level 4,ou=Memberships,dc=eom,dc=dev",
"description": "Have a voice in the platform's direction.",
"benefits": [
"Platinum-tier giveaways",
"Exclusive platform-direction polls"
]
},
"level-5": {
"level": 5,
"label": "Diamond",
"price_id": "price_1Rgv6mC5KPXqTvVLkcmznWZa",
"price_label": "$64 USD / month",
"usd_amount": "64.00",
"group_dn": "cn=Level 5,ou=Memberships,dc=eom,dc=dev",
"description": "Give the independent work its biggest boost.",
"benefits": [
"Diamond-tier giveaways",
"Optional Diamond credit on the supporters page"
]
}
}
{
"level-1": {
"level": 1,
"label": "Supporter",
"price_id": "price_1Rgv4xC5KPXqTvVLfMd6z7wn",
"price_label": "Pay what you want \u00b7 from $3 USD / month",
"pay_what_you_want": {
"product_id": "prod_Sc9N5J0vNAdLCn",
"min_usd": "3.00",
"suggested_usd": "8.00",
"max_usd": "500.00"
},
"group_dn": "cn=Level 1,ou=Memberships,dc=eom,dc=dev",
"description": "Keep the lab running between drops, at whatever monthly amount feels right. Every amount gets the same benefits.",
"benefits": [
"Optional thanks in the credits of every drop",
"Supporter-only posts on Discourse and Harmony, including work in progress",
"Early builds and playtests when they exist"
]
},
"level-2": {
"level": 2,
"label": "Silver",
"price_id": "price_1Rgv5QC5KPXqTvVLv1PaHWb5",
"price_label": "$8 USD / month",
"usd_amount": "8.00",
"hidden": true,
"group_dn": "cn=Level 2,ou=Memberships,dc=eom,dc=dev",
"description": "Try new work before release.",
"benefits": [
"Silver-tier giveaways",
"Early previews, playtests and listening sessions when available"
]
},
"level-3": {
"level": 3,
"label": "Gold",
"price_id": "price_1Rgv5rC5KPXqTvVL8Ol8sMUf",
"price_label": "$16 USD / month",
"usd_amount": "16.00",
"hidden": true,
"group_dn": "cn=Level 3,ou=Memberships,dc=eom,dc=dev",
"description": "Help shape the next experiment.",
"benefits": [
"Gold-tier giveaways",
"Member polls on future project topics and experiments",
"Invitations to occasional small-group feedback sessions"
]
},
"level-4": {
"level": 4,
"label": "Platinum",
"price_id": "price_1Rgv6FC5KPXqTvVL39mAxYjm",
"price_label": "$32 USD / month",
"usd_amount": "32.00",
"hidden": true,
"group_dn": "cn=Level 4,ou=Memberships,dc=eom,dc=dev",
"description": "Have a voice in the platform's direction.",
"benefits": [
"Platinum-tier giveaways",
"Exclusive platform-direction polls"
]
},
"level-5": {
"level": 5,
"label": "Diamond",
"price_id": "price_1Rgv6mC5KPXqTvVLkcmznWZa",
"price_label": "$64 USD / month",
"usd_amount": "64.00",
"hidden": true,
"group_dn": "cn=Level 5,ou=Memberships,dc=eom,dc=dev",
"description": "Give the independent work its biggest boost.",
"benefits": [
"Diamond-tier giveaways",
"Optional Diamond credit on the supporters page"
]
}
}
+2 -1
View File
@@ -269,7 +269,8 @@ test('homepage groups creative sections before the library and membership distin
assert.ok(positions.every((position, index) => position >= 0 && (!index || position > positions[index - 1])));
const template = await readFile(new URL('membership/templates/members.html', repository), 'utf8');
assert.match(template, /services included at your membership level/u);
assert.match(template, /Bronze adds exclusive Discourse and Harmony content; Silver adds previews when available; Gold adds project-topic polls/u);
assert.match(template, /I work in bursts, not on a schedule/u);
assert.doesNotMatch(template, /giveaway/iu);
assert.ok(template.indexOf('class="member-grid"') < template.indexOf('Community services by level'));
assert.match(template, /No paid-exclusive game servers are currently included/u);
assert.match(template, /There is no fixed release schedule/u);