The boot record went through slog.Default() at Info and printed on every serve and migrate start. It now uses the plugin's diary component paymentgatewaysubscriptions at Debug.
golem15.paymentgatewaysubscriptions
The compiled subscriptions core for the SummerCMS payment gateway: subscription plans and subscriptions on the PHP tables, subscribers and gateways registered at build time, the six golem15.pgsub.* events, a gateway-neutral service that stores gateway state changes and answers access checks, the admin screens and a headless customer API.
import _ "git.golem15.com/golem15/sm-paymentgatewaysubscriptions-plugin"
Module git.golem15.com/golem15/sm-paymentgatewaysubscriptions-plugin, package pgsub, plugin ID golem15.paymentgatewaysubscriptions, requires golem15.paymentgateway and golem15.user.
Overview
The plugin ports the generic core of the WinterCMS Golem15.PaymentGatewaySubscriptions plugin. It contains no gateway code: a gateway plugin (Stripe lives in sm-pgstripe-plugin) implements contracts.Gateway, maps its own events onto contracts.Update and calls classes.Service.Apply, which stores the subscription and fires the events. A consuming plugin calls the same service to list plans, check a subscriber out, cancel, open the gateway's management page and check access. Administrators manage plans and inspect subscriptions in the admin (Admin); a frontend uses the JSON customer API for the logged-in user (Customer API).
Subscribers and gateways register at build time. A plugin that owns subscriber entities implements contracts.HasSubscribables (morph alias to contracts.SubscriberResolver); a gateway plugin implements contracts.HasSubscriptionGateways (identifier to contracts.Gateway). Boot collects both from every activated plugin into *contracts.Subscribers and *contracts.Gateways, publishes them and fails on a duplicate alias or identifier, naming both plugins. An alias no plugin registered is an error (contracts.ErrUnknownSubscriberType), never skipped.
Tables (PHP v2.4.0 names, one idempotent baseline migration 202610150001_create_golem15_pgsub_baseline, every statement IF NOT EXISTS):
golem15_pgsub_subscription_plans: the plans (models.SubscriptionPlan);stripe_prices,currency_pricesandfeaturesare JSONB;golem15_pgsub_subscriptions: the subscriptions (models.Subscription), keyed to a subscriber bysubscriber_type(a morph alias such asuser) andsubscriber_id(both nullable, as on PHP), with thestripe_statusCHECK over the eight statuses and aRESTRICTforeign key to the plan;golem15_pgsub_processed_webhook_events: the processed gateway event markers (models.ProcessedWebhookEvent, uniqueevent_id).
The two dormant usage and featured-placement tables of the PHP plugin are not created: they exist only where their owning plugin is installed, and its port creates them. The PHP plan seed is not carried over.
Migration 202610150002_add_stripe_customer_id_to_users adds users.stripe_customer_id (VARCHAR(255) NULL) and users_stripe_customer_id_index only when missing; its rollback is a no-op because the column may predate the plugin.
Features
-
Gateway-neutral state changes.
Service.Applyfinds the subscription by the gateway subscription id (locking the row) or starts one, sets the subscriber when both type and id are given, resolves the plan, stores the customer id, status (incompletewhen empty), gateway (stripewhen empty), periods, cancel flag and dates (canceled_at,ended_at,trial_ends_atonly when reported, never cleared), and fires the state-change events inside the caller's transaction. A row left without a plan or a subscriber is an error naming the gateway subscription id, so the gateway's job retries. -
Plan resolution.
Applylooks the plan up in this order, and a match by product or code is logged at Warn:- the plan whose
stripe_price_idorstripe_pricesmap holds the reported price id exactly (never a substring match); - the plan whose
stripe_product_idequalsUpdate.ProductID, the product of the subscribed price. It survives a re-price whose sync archived the old price; - any plan, active or not, whose code equals
Update.PlanCode, the plan code the checkout recorded.
When none matches, a stored row keeps its plan, and a new row is an error naming the price id, product id and plan code.
- the plan whose
-
The PHP event diff. In order:
reactivatedwhencancel_at_period_endgoes from true to false while active or trialing (checked before the status, so it can fire alone); nothing more when the status is unchanged;activatedon becoming active or trialing from neither (a new row counts);past_dueandcanceledon entering those statuses.ApplyDeletedsetscanceledandended_atand firescanceledwhen the row was not canceled before (PHP fired it unconditionally; with fresh-state retrieval an update job may already have stored and announced the cancellation). A subscription with no stored row yet answers an error wrappingclasses.ErrSubscriptionNotStoredwithout a change or an event, so the gateway's job rolls its marker back and retries the deletion after the creation is stored.ApplyInvoicechanges no row and firesinvoice.paidorinvoice.payment_failedwith a typed, PII-freecontracts.Invoice(an invoice of an unknown subscription is a logged no-op). -
Processed-event claim.
Service.ClaimEventinserts the marker withON CONFLICT (event_id) DO NOTHINGinside the caller's transaction and reports whether this caller claimed it. A gateway job claims first: the marker commits only with the change, a failed job rolls it back and is retried, and a concurrent duplicate waits on the unique key instead of firing the listeners twice.Service.EventProcessedis the cheap check a webhook runs before enqueueing. -
Access and grace.
Service.HasAccessanswers true for an active or trialing subscription, or a past_due one whose period end plusgrace_period_daysis still ahead.Service.InGracePeriodanswers the grace part alone; a subscription without a period end has no grace. -
Features. Plan features are opaque string keys (
SubscriptionPlan.HasFeature,Subscription.HasFeaturethrough the loaded plan,Service.HasFeature). The plugin defines no feature keys; applications declare their own. -
Checkout.
Service.Checkoutresolves the gateway (CheckoutOptions.Gateway, stripe when empty), creates the gateway customer when the subscriber has none and stores its id on the subscriber in a short transaction of its own, then asks the gateway for the checkout session. No transaction is held across a gateway call; call it outside one. The customer id is stored even when the request was cancelled after the gateway created the customer.Checkouthas no guard (PHP had none).Service.CheckoutGuarded, the customer-facing entry point, runs under the subscriber's session advisory lock (SubscriberLockKey), refuses withErrAlreadySubscribedwhile the subscriber has a subscription that blocks a checkout (Service.CheckoutBlocker: any status but canceled, incomplete_expired and incomplete), cancels the subscriber's incomplete subscriptions at their gateway immediately (a failed or abandoned first payment never blocks a retry and can no longer bill next to the new subscription), re-resolves the subscriber, expires the customer's open checkout sessions when the gateway implementscontracts.CheckoutSessionExpirer(so at most one payable session exists) and delegates toCheckout.Service.Applylogs at Error when a newly stored open subscription's subscriber already has another open one (two completed checkouts). -
Cancel, portal, sync.
Service.Cancelcancels at the period end or immediately; after a successful cancel at the period end it setscancel_at_period_endlocally without events. The gateway call and the local write run under the subscription'sSubscriptionLockKey, so a webhook job never applies a state retrieved before the cancel over the flag.Service.Portalopens the gateway's management page (classes.ErrNoCustomerwithout a customer id).Service.SyncSubscriptionrefreshes a subscription from its gateway without events, under the same per-subscription lock as the gateway's webhook job: it asks the gateway outside any transaction (throughcontracts.SubscriptionRetrieverwhen the gateway implements it), then re-reads the rowFOR UPDATEand writes only the gateway-owned columns, plus the plan of the reported price on the retriever path;Service.SyncPlanpushes a plan to the stripe gateway (a free plan answers an empty map without a call) and saves the returned ids even when a price step failed after the product was created; on the request path (nil transaction) it runs under the plan'sPlanLockKeyand re-reads the plan first, so two syncs of one plan never create two products. -
Built-in
usersubscriber.classes.UserSubscribable()resolves aliasuserover the user plugin'suserstable: e-mail, name (name and surname trimmed, the e-mail when both are empty), soft-deleted users included. Its customer id lives inusers.stripe_customer_id, written with a targetedUPDATEof that column only and only when none is stored: the first stored customer id is kept, and a concurrent checkout adopts it instead of overwriting it. An application opts in by returning it from its own plugin'sSubscribables().
Usage
Register the built-in user subscriber from an application plugin (and, in a gateway plugin, the gateway):
func (p *Plugin) Subscribables() []contracts.SubscriberResolver {
return []contracts.SubscriberResolver{classes.UserSubscribable()}
}
func (p *Plugin) SubscriptionGateways() []contracts.Gateway {
return []contracts.Gateway{p.gateway} // a contracts.Gateway implementation
}
The service is published once the database is: Boot builds it through lagoon.OnDatabase, so plugins activate before a command opens the database, as in the main.go summer build generates. Look it up at request time, not in another plugin's Boot.
Checkout is three calls: resolve the subscriber, find the plan, check out. A customer-facing checkout calls CheckoutGuarded, which refuses a second subscription and serialises parallel requests of one subscriber; Checkout is the unguarded call for a route that does its own check.
svc, _ := app.Lookup[*classes.Service]()
subscriber, err := svc.Subscriber(ctx, "user", userID)
plan, err := svc.ActivePlanByCode(ctx, "premium-monthly")
session, err := svc.CheckoutGuarded(ctx, subscriber, plan, successURL, cancelURL, contracts.CheckoutOptions{Currency: "pln"})
if errors.Is(err, classes.ErrAlreadySubscribed) {
// send the customer to the billing portal instead
}
// redirect the customer to session.URL
Check access and show the current subscription:
sub, err := svc.Latest(ctx, "user", userID) // with sub.Plan loaded; nil when none
if svc.HasAccess(sub) {
days := sub.DaysUntilRenewal(time.Now())
_ = days
}
Listen to the subscription events (they fire inside the transaction; put mail and other side effects in lagoon.AfterCommit, and keep listeners idempotent because an error retries the gateway's event):
app.Events.Listen[*events.SubscriptionActivated]("acme.shop", func(ctx context.Context, e *events.SubscriptionActivated) error {
if e.Subscription.SubscriberType == nil || *e.Subscription.SubscriberType != "user" {
return nil
}
lagoon.AfterCommit(ctx, e.Tx, func(ctx context.Context, db *gorm.DB) { /* send the welcome mail */ })
return nil
})
SubscriptionCanceled, SubscriptionPastDue and SubscriptionReactivated carry the same SubscriptionEvent; InvoicePaid and InvoicePaymentFailed carry InvoiceEvent with the contracts.Invoice.
A gateway reports a state change inside its own transaction, claiming the event first:
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
claimed, err := svc.ClaimEvent(ctx, tx, eventID, eventType)
if err != nil || !claimed {
return err
}
_, err = svc.Apply(ctx, tx, contracts.Update{
Gateway: models.GatewayStripe, SubscriptionID: "sub_...", Status: models.StatusActive,
PriceID: "price_...", SubscriberType: "user", SubscriberID: userID,
})
return err
})
Admin
Navigation: the top-level item Subscriptions (subscriptions, icon refresh-cw, order 510, any golem15.paymentgatewaysubscriptions.* permission) with the side items Subscriptions and Subscription Plans. Only registered screens are listed; the PHP featured placements item is not ported.
Permissions, the PHP codes verbatim:
| Code | Guards |
|---|---|
golem15.paymentgatewaysubscriptions.manage_subscriptions |
the Subscriptions screen |
golem15.paymentgatewaysubscriptions.manage_plans |
the Subscription Plans screen, its reorder page and both sync actions |
golem15.paymentgatewaysubscriptions.manage_placements |
no screen here; registered so roles exported from PHP import without unknown codes |
Subscription Plans (controllers.SubscriptionPlansControllerID, admin path golem15/paymentgatewaysubscriptions/subscriptionplans):
- The list is sorted by
sort_order, with checkboxes and search on code and name. - The create and update form ports the PHP form field by field: code, name, description,
stripe_price_id,price_cents(cents), currency (default EUR), billing interval (month or year), features,max_quotes_per_month, lead fee, active (default on) and sort order (default 0). The features field is a coretaglistfield inmode: array: tags are trimmed and de-duplicated and stored as the JSON list. - The reorder page is the flat (Sortable) reorder from
config_reorder.yaml(title,modelClass,nameFromonly). It writessort_order. - The bulk action
sync_to_stripe(Sync Selected to Stripe, with a confirm) and the toolbar actionsync_all_to_stripe(Sync All to Stripe, every active plan) push plans throughclasses.Service.SyncPlanand the gateway registry; the plugin imports no gateway code.- Free plans (
price_cents0) are skipped and counted. - A failing plan adds a
code: messageline to the result message; a failed save of a plan's ids is a failure too, never a synced count. The action never fails, so the provider ids already saved survive. - Both actions run outside any transaction:
sync_to_stripeis a detached bulk action (pact.AdminBulkAction.Detached, the plans are loaded without row locks), andsync_all_to_stripeopens none. Each plan's ids are saved right after its Stripe calls, in a short write that ignores the request's cancellation, so an id Stripe created is never lost and the next sync never creates a duplicate product. - Without an installed subscription gateway both actions answer 403 with the localized
errors.gateway_not_installed.
- Free plans (
- Not edited on the form, as on PHP:
currency_prices,stripe_pricesandstripe_product_id(the sync writes the provider ids).
Subscriptions (controllers.SubscriptionsControllerID, admin path golem15/paymentgatewaysubscriptions/subscriptions):
- The list shows, newest first: the subscriber, plan name, the status as its localized label (list field type
subscriptionstatus) and the current period end. The subscriber column is the subscriber's e-mail (its name when it has none), filled once per page throughpact.ListExtendRecords: one query per alias when the resolver implementscontracts.SubscriberBatchResolver(the built-in user subscriber does), else oneResolveper subscriber. A subscriber whose row is gone, or whose alias no plugin registers, shows as<alias> #<id>. The column is not stored, so it is neither sortable nor searchable; the subscriber type and id are hidden columns that the search still covers, as are the cancel flag and the creation date. - Filters by status (active, trialing, past_due, canceled, unpaid) and by plan.
- The preview is read-only and headed "Subscription # ()" (
pact.FormRecordTitle, langsubscriptions.record_title_plan, orsubscriptions.record_titlewhen the plan is gone). Its header partialsubscription_subscriberresolves the subscriber through the subscriber registry and shows the name and e-mail, soft-deleted users included. An alias no installed plugin registers is shown as a danger notice naming the alias and logged at Error; it is never a failed request. A subscriber whose row is gone gets a muted note. - There is no create button. Saving or deleting a subscription through the admin is refused (403): subscriptions change only through the gateway.
The field types subscriptionstatus and subscriptiongateway (FieldTypeSubscriptionStatus, FieldTypeSubscriptionGateway) show the localized label of a stored status or gateway code (an unknown code as stored) and accept no input. Their read-only element is golem15-paymentgatewaysubscriptions-label from assets/js/fields.js; it shows the value the admin hands it through its value property (a value attribute works too).
Differences from the PHP lists: cabana has no accessor columns and no valueFrom/default column keys. So the plans list shows price_cents and currency instead of formatted_price, and an empty max_quotes_per_month cell (unlimited) without the "Unlimited" text. The subscriptions list shows the subscriber's e-mail instead of subscriber_display_name's name. cabana lists have no number column type, so the PHP number columns are text columns. sync_all_to_stripe has no confirm dialog (pact.AdminAction carries none).
Customer API
A JSON API under /_paymentgatewaysubscriptions/api/v1 (APIPrefix) for the logged-in user, the headless successor of the Winter SubscriptionManager component. All routes share the throttle bucket paymentgatewaysubscriptions-api (APIBucket): 120 requests per minute per frontend user, else per client IP. The subscription routes need the user plugin's jwt guard through Authorization: Bearer only (the payment gateway's api.RequireJWT); cookies are never read, so a cross-site form cannot act. The subscriber is always the built-in user subscriber with the token's user id. No route takes a subscriber id, a subscription id or a redirect URL.
| Method and path | Auth | Answer |
|---|---|---|
GET /plans |
public | {"data": [PlanJSON]}: the active plans by sort_order |
GET /subscription |
Bearer | the user's latest subscription as SubscriptionJSON; 404 {"error": "Subscription not found"} when there is none |
POST /subscription/checkout {plan_code, currency?} |
Bearer | {checkout_url, session_id}; 409 Already subscribed while the user has any subscription that is not canceled, incomplete_expired or incomplete (active, trialing, past_due, unpaid, paused; a past_due or unpaid user manages it in the billing portal; an incomplete one is canceled by the checkout), checked again under the subscriber's lock by CheckoutGuarded; 404 Plan not found for an unknown or inactive plan; 422 for a missing plan_code, a free plan, or a currency the gateway does not support, the plan has no price for, or the plan has no gateway price of its own in (SubscriptionPlan.CheckoutPriceID is empty; no currency is billed at another currency's price), or whose gateway price the gateway refuses (contracts.ErrPriceUnavailable, for example a price edited but not synced) |
POST /subscription/portal |
Bearer | {portal_url}, the gateway's billing portal; 404 No billing account when the user never checked out |
POST /subscription/cancel |
Bearer | cancels at the period end and answers SubscriptionJSON with cancel_at_period_end: true; 404 Subscription not found without an active subscription |
Shapes:
-
PlanJSON:code,name,description,billing_interval,pricesandfeatures(a list of strings).pricesholds one money object per currency ofcurrency_prices, sorted by currency. A plan withoutcurrency_pricesgets one money object fromprice_centsandcurrency.- A money object is the order API's
{"amount": "29.0000", "amount_minor": 2900, "currency": "PLN"}(currency upper-cased).
-
SubscriptionJSON:status;plan(code,name,billing_interval);current_period_start,current_period_end,canceled_at,ended_atandtrial_ends_at(RFC 3339 or null);cancel_at_period_endanddays_until_renewal;has_accessandin_grace_period, from the service withgrace_period_days.
It carries no gateway id and no e-mail.
-
Errors are
{"error": message}, or the 422{"error": "Validation failed", "errors": {field: [message]}}:- 401 without a token or with an invalid one;
- 502
Payment provider unavailableon a gateway error, logged with the user id and plan code only; - 503
Subscription gateway not installed; - 429 from the throttle.
The checkout's success and cancel URLs and the portal's return URL come only from configuration (see Configuration). A redirect URL in the request body is ignored.
A frontend flow:
const api = '/_paymentgatewaysubscriptions/api/v1'
const auth = { Authorization: `Bearer ${token}` }
const { data: plans } = await (await fetch(`${api}/plans`)).json()
const current = await fetch(`${api}/subscription`, { headers: auth }) // 404: no subscription yet
const checkout = await fetch(`${api}/subscription/checkout`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify({ plan_code: plans[0].code, currency: 'pln' }),
})
if (checkout.ok) location.href = (await checkout.json()).checkout_url
// later: POST /subscription/portal -> portal_url, POST /subscription/cancel
API reference
Package pgsub (plugin root):
PluginID,ConfigGracePeriodDays,Plugin(Service,Subscribers,Gatewaysonce booted).- Admin:
PermissionManageSubscriptions,PermissionManagePlans,PermissionManagePlacements;FieldTypeSubscriptionStatus,FieldTypeSubscriptionGateway. - Customer API:
APIPrefix,APIBucket,ConfigAPISuccessURL,ConfigAPICancelURL,ConfigAPIPortalReturnURL.
Package controllers:
AdminControllers,SubscriptionsControllerID,SubscriptionPlansControllerID,PermissionManageSubscriptions,PermissionManagePlans,PermissionManagePlacements,ActionSyncToStripe,ActionSyncAllToStripe,Lang.
Package api:
- Handlers
Plans,Current,Checkout,Portal,Cancel;SubscriberAlias. PlanJSON,PlanSummaryJSON,SubscriptionJSON,CheckoutRequest,NewPlanJSON.RedirectURLs,ResolveRedirectURLs,ConfigSuccessURL,ConfigCancelURL,ConfigPortalReturnURL.
Package contracts:
Gateway(Identifier,GetOrCreateCustomer,CreateCheckoutSession,CreateManagementSession,CancelSubscription,SyncSubscription,SyncPlanToGateway,SupportsCurrency),CheckoutOptions(Gateway,Currency,Metadata),CheckoutSession(URL,SessionID).Subscriber(MorphAlias,Key,Email,Name,CustomerID,SetCustomerID; an implementation may keep an id that is already stored, the first write wins),SubscriberResolver(Alias,Resolve), the optionalSubscriberBatchResolver(ResolveMany, one query for many ids; the admin list uses it).SubscribersandGateways(NewSubscribers,NewGateways,Add,Resolver,Gateway,PluginID,Aliases,Identifiers,All),HasSubscribables,HasSubscriptionGateways.Update(ProductIDandPlanCodeare the plan fallbacks after the price id),InvoiceUpdate,Invoice.SubscriptionRetriever(RetrieveSubscription): optional; a gateway implementing it reports the provider's current state as anUpdate, whichService.SyncSubscriptionwrites, plan included.CheckoutSessionExpirer(ExpireOpenCheckoutSessions): optional;Service.CheckoutGuardedexpires a customer's open subscription checkout sessions through it before creating a new one.- Errors
ErrUnknownSubscriberType,ErrDuplicateAlias,ErrDuplicateGateway,ErrGatewayNotInstalled,ErrSubscriberNotFound,ErrPriceUnavailable(a gateway's price refusal wraps it; the customer API answers 422).
Package models:
Subscription(TableName,MorphName,Fillable,Rules,IsActive,InGracePeriod,HasAccess,HasFeature,WillCancelAtPeriodEnd,DaysUntilRenewal,OnTrial,IsFromGateway,IsStripeSubscription,IsGooglePlaySubscription),SubscriptionModelName.SubscriptionPlan(TableName,MorphName,Fillable,Rules,HasFeature,PriceCentsFor,StripePriceIDFor(PHP's lenient getStripePriceId),CheckoutPriceID(the strict per-currency price a checkout bills: a non-emptystripe_pricesmap decides alone, otherwisestripe_price_idserves only the plan's own currency),TierLevel),SubscriptionPlanModelName,BillingIntervalMonth,BillingIntervalYear.ProcessedWebhookEvent,ProcessedWebhookEventModelName;FeatureList(Scan,Value,Has).- Statuses
StatusIncomplete,StatusIncompleteExpired,StatusTrialing,StatusActive,StatusPastDue,StatusCanceled,StatusUnpaid,StatusPaused(Statuses); gatewaysGatewayStripe,GatewayGooglePlay(Gateways). TerminalStatuses(canceled, incomplete_expired); scopesForSubscriber,ScopeOpen(stripe_status not inTerminalStatuses),ScopeBlocksCheckout(open, but not incomplete),ScopeActive,ScopePastDue,ScopeCanceled,ScopeFromGateway,ScopeActivePlans,ScopeOrdered;Register,All.- Admin list filters:
FilterStatus,FilterPlan,FilterStatuses;Subscription.FilterScopes,Subscription.FilterScope.
Package events:
SubscriptionActivated,SubscriptionCanceled,SubscriptionPastDue,SubscriptionReactivated(embeddingSubscriptionEvent),InvoicePaid,InvoicePaymentFailed(embeddingInvoiceEvent).SubscriptionActivatedEventName,SubscriptionCanceledEventName,SubscriptionPastDueEventName,SubscriptionReactivatedEventName,InvoicePaidEventName,InvoicePaymentFailedEventName(the PHP names).
Package classes:
Service:New,Now,GracePeriodDays; lookupsActivePlans,ActivePlanByCode,Latest,Active,Open(the latest open subscription),CheckoutBlocker(the latest subscription that refuses a checkout),HasActiveSubscription,OnPlan,CurrentPlanCode,Subscriber,Gateway,Gateways; checksHasAccess,InGracePeriod,HasFeature; gateway callsCheckout,CheckoutGuarded(the customer-facing checkout: refuses withErrAlreadySubscribedwhile a blocking subscription exists, cancels incomplete ones and expires open sessions, underSubscriberLockKey),Portal,Cancel,SyncSubscription,SyncPlan; state changesApply,ApplyDeleted,ApplyInvoice,ClaimEvent,EventProcessed.Options,DefaultGracePeriodDays,ErrNoCustomer,ErrAlreadySubscribed,ErrSubscriptionNotStored,UserSubscribable,UserAlias.WithSessionLock(a session-level Postgres advisory lock on one pinned connection, taken outside any transaction so a gateway call may run under it) andSubscriptionLockKey(the key of one gateway subscription; the webhook job takes it, so two jobs about one subscription never interleave) andSubscriberLockKey(the key of one subscriber;CheckoutGuardedtakes it, so two checkouts of one subscriber never interleave) andPlanLockKey(the key of one plan;SyncPlantakes it on the request path).
Package updates: Register, All.
Configuration
config/config.yaml, merged at golem15.paymentgatewaysubscriptions.*:
| Key | Default | Environment | Meaning |
|---|---|---|---|
grace_period_days |
7 |
SUMMER_GOLEM15__PAYMENTGATEWAYSUBSCRIPTIONS__GRACE_PERIOD_DAYS |
days after the period end a past_due subscription keeps access (PHP SUBSCRIPTION_GRACE_PERIOD_DAYS); a negative or non-numeric value fails boot |
api.success_url |
"" |
SUMMER_GOLEM15__PAYMENTGATEWAYSUBSCRIPTIONS__API__SUCCESS_URL |
where a customer API checkout returns after payment |
api.cancel_url |
"" |
SUMMER_GOLEM15__PAYMENTGATEWAYSUBSCRIPTIONS__API__CANCEL_URL |
where a customer API checkout returns when abandoned |
api.portal_return_url |
"" |
SUMMER_GOLEM15__PAYMENTGATEWAYSUBSCRIPTIONS__API__PORTAL_RETURN_URL |
where the billing portal returns |
The three api.* values are resolved at boot. Each takes one of three forms:
- an absolute
httporhttpsURL, used as is; - a path starting with
/, joined toapp.url; - empty, which means
app.urlitself.
Any other value fails boot naming the key. When app.url is not an absolute URL, a path or empty value stays unresolved, and checkout or portal answers a logged 500.
The PHP subscribables config is replaced by the build-time registry; the lead-fee keys and the webhook secret key belong elsewhere and are not ported.
The plugin logs through the component paymentgatewaysubscriptions (log.components.paymentgatewaysubscriptions in config/log.yaml); the boot record listing the collected subscriber types and gateways is at Debug.
Differences from PHP
- A gateway never writes the database:
GetOrCreateCustomerreturns the id and the service stores it on the subscriber;SyncPlanToGatewaychanges the passed plan in memory and the service saves it;RetrieveSubscription(orSyncSubscriptionon a copy) reports a subscription's state and the service writes it. - The service, not the gateway's webhook, writes
cancel_at_period_endafter a successful cancel at the period end (the next gateway update confirms the same value, so the event diff is unchanged). FeatureListalso reads the legacy map-of-truthy-keys shape and always writes a JSON array.- The plan lookup by price id is exact (PHP used
LIKE), and currencies are compared lower-case. - The invoice events carry a typed, PII-free
contracts.Invoiceinstead of the raw invoice array. - The built-in
usersubscriber falls back to the e-mail for an empty name (the users table has no username column). - The gateway contract leaves out the PHP
getWebhookSecretandverifyWebhookSignature: only the provider's own webhook uses them. - The JSON columns are JSONB, so the database rejects malformed JSON as PHP's MariaDB
json_validCHECK did. - Out-of-order gateway events no longer behave as on PHP (gap closure 18.1-07, the 2026-10-14 decision superseding D-21 for ordering): the gateway's job applies the provider's current state, serialised per subscription (
WithSessionLockonSubscriptionLockKey), and a deletion that arrives before its subscription is stored is retried (ErrSubscriptionNotStored). SyncSubscriptionwrites only the gateway-owned columns of the re-read, locked row (stripe_status,cancel_at_period_end, the period bounds,canceled_at,ended_at,trial_ends_at,stripe_customer_idand, with aSubscriptionRetriever,subscription_plan_id), never the caller's whole row (PHP saved the full model), so a plan switch or subscriber written in between is kept and a plan change made at the provider is picked up.
Dependencies
git.golem15.com/golem15/summercms(lagoon,festival,party,pact,backpack,cabana,surf,bouncer,wire,phrasebook,compass);git.golem15.com/golem15/sm-paymentgateway-pluginpackagesapi(RequireJWT,MoneyJSON,NewMoneyJSON) andmoney;- the
golem15.paymentgatewayandgolem15.userplugins (activated before this one; the user plugin'suserstable backs the built-in subscriber).
Testing
go vet ./...
go test -short ./... # Docker-free
go test ./... # the Postgres tests (testcontainers)
The proof host boots the user plugin, the payment gateway, this plugin and the test-only acme.members fixture (the built-in user subscriber and a fake stripe gateway recording its calls) on Postgres. TestSubscriptionsTracer applies one active subscription; TestSubscriptionsCheckout checks a user out through the fake gateway; TestSubscriptionsCoreSmoke covers the idempotent migrations, the registries, the event diff, invoices, the claim, grace and the service API; TestPlanJSONBColumns round-trips the JSONB columns.
The admin and API tests assemble the routes on the same host:
TestAdminPlansSmokecovers the taglist form, the flat reorder, both sync actions (skip, partial failure, permissions, no gateway) andmanage_plans.TestAdminSubscriptionsSmokecovers the list order and labels, the subscriber column (e-mail,<alias> #<id>for an unregistered alias, not sortable), the record title in English and Polish, the filters, the subscriber partial (including an unregistered alias and a soft-deleted user), the read-only refusals andmanage_subscriptions.TestCustomerAPISmokecovers every customer API status code, the configured redirect targets, cross-user isolation and the absence of private keys.
The Docker-free tests are:
TestAdminCatalog(permissions and navigation);TestAdminLangParity(every phrase key the YAML, partials and Go sources name exists in EN and PL);TestRedirectURLs(URL resolution).
The unit tests of the last plan of the port (18.1-06):
| Test | Package | Needs Docker | What it pins |
|---|---|---|---|
TestSubscriptionChecks |
models |
no | IsActive, the exclusive grace boundary at period end plus grace days, HasAccess, DaysUntilRenewal (whole days, floored at 0, nil without a period end), OnTrial, the gateway checks (an empty gateway is stripe) |
TestPlanPrices |
models |
no | PriceCentsFor and StripePriceIDFor with the currency lower-cased and their fallbacks, TierLevel, the plan rules |
TestFeatureList |
models |
no | the list, the legacy map of truthy keys, NULL and empty values, malformed JSON as an error, Value always a JSON array |
TestRegistry |
contracts |
no | duplicate aliases and gateways naming both plugins, unknown alias and gateway errors, registration order, nil registries |
TestLangParity |
root | no | EN and PL define the same keys with the same :placeholders and no empty text, and every key the sources name exists |
TestApplyEvents |
root | yes | the events of every previous-to-current status pair with every cancel flag pair, deleted always canceled, invoices with no row change, refused updates storing nothing |
TestClaimEventConcurrent |
root | yes | two overlapping claims of one event id, exactly one wins; a rolled-back claim leaves no marker |
TestUserSubscribable |
root | yes | the name fallback, soft-deleted users, a missing user, ResolveMany (soft-deleted and missing ids), SetCustomerID writing one column only |
TestLabelElementValueProperty |
root | no (needs node) | the label element shows the value property and the value attribute, as text |
TestBaselineSchema |
root | yes | the table, column, index and constraint names of the PHP v2.4.0 dump, jsonb columns, RESTRICT, no dormant tables, idempotent re-runs, the users column added only when missing |
TestServiceAPI |
root | yes | checkout commits the customer id before the session and never holds a transaction across a gateway call; cancel, plan sync, ordering, portal, sync and access rules |
TestAdminSyncActions |
root | yes | the bulk and toolbar sync messages in EN and PL, kept provider ids, active plans only, 403 without manage_plans or a gateway |
TestCustomerAPIAuthz |
root | yes | every route against anonymous, malformed and admin tokens, the owner and another user; ignored redirect and subscriber fields; no private keys |
The gap-closure tests (18.1-09) pin the review fixes of plans 18.1-07 and 18.1-08:
| Test | Package | Needs Docker | What it pins |
|---|---|---|---|
TestCheckoutPriceID |
models |
no | CR-02: a synced stripe_prices map decides alone (no fallback to stripe_price_id), an unsynced plan bills stripe_price_id only in its own currency, case and spaces ignored, an empty map as no map |
TestTerminalStatuses |
models |
no | WR-03: exactly canceled and incomplete_expired are terminal, the other six statuses are open |
TestPlanResolution |
root | yes | WR-04: the plan by price id, stripe_prices value, the price's product, then the plan code (an inactive plan included), the price first; an unresolved new row is an error naming the price, product and code; an existing row keeps its plan |
TestApplyDeletedNotStored |
root | yes | CR-01: a deletion of an unstored subscription wraps ErrSubscriptionNotStored with no row and no event |
TestSyncSubscriptionFresh |
root | yes | WR-06: the retriever path refreshes the plan from the price; a plan switch, subscriber and customer id written after the caller's load survive; the legacy path changes the status only; no events; a sync waits for a held SubscriptionLockKey |
TestCheckoutGuarded |
root | yes | WR-03: each blocking status refused without a gateway call, canceled and incomplete_expired allowed, two checkouts of one subscriber never in flight together and sharing one customer, two subscribers in parallel |
TestCustomerIDFirstWriteWins |
root | yes | WR-02: the first stored customer id wins and a later writer adopts it, a missing user is ErrSubscriberNotFound, no other users column changes |
TestCheckoutIncompleteAndOpenSessions |
root | yes | 18.1 re-review WR-07/WR-04: incomplete canceled at the gateway before the session, open sessions expired before the next session, a blocking status refused without a call |
TestCancelTakesSubscriptionLock |
root | yes | WR-01: Cancel waits for a held subscription lock before calling the gateway |
TestSyncPlanSerialised |
root | yes | WR-03: two request-path syncs of one plan run one after the other and create one product |
TestCheckoutPriceUnavailable |
root | yes | WR-06: a gateway price refusal is 422 on currency |
TestCustomerAPIGuards |
root | yes | 409 for past_due, unpaid and paused, the open check before the plan lookup, 422 for a currency without its own gateway price, no gateway call on refusal |
TestAdminSyncDetached |
root | yes | WR-01: neither sync action calls the gateway while a session is idle in transaction, a failed save is a failure line, ids are saved although the request was cancelled |
Run one Docker suite with, for example, go test -count=1 -run '^TestApplyEvents$' .. The framework repository's scripts/check-phase18.1.sh runs all of them by name (plugins stage without Docker, postgres stage with it).