golem15.pgstripesubscriptions
The Stripe subscription gateway for golem15.paymentgatewaysubscriptions: customer, subscription Checkout, billing portal, cancel, sync and plan sync on the official Stripe SDK, plus the signed subscription webhook and the River job that applies its events.
import _ "git.golem15.com/golem15/sm-pgstripe-plugin/subscriptions"
Module git.golem15.com/golem15/sm-pgstripe-plugin, package subscriptions, plugin ID golem15.pgstripesubscriptions, requires golem15.pgstripe and golem15.paymentgatewaysubscriptions.
Overview
The package ports the subscription parts of the WinterCMS Golem15.PGStripe plugin: StripeSubscriptionGateway (read at d00f850, which adds the plan sync), ProcessStripeSubscriptionWebhook and the /webhook/stripe/subscriptions route with StripeWebhookController (both at 8b47457). It is a plugin of its own, separate from golem15.pgstripe. The root package never imports it, so an application that sells no subscriptions links no subscription code.
The subscriptions core owns the rules: it stores rows, diffs the state and fires the six golem15.pgsub.* events. This plugin only talks to Stripe and maps Stripe objects onto the core's gateway-neutral contracts:
SubscriptionGatewayspublishes thestripegateway (Gateway), which the core collects at boot.classes.Service(Checkout, Portal, Cancel, SyncSubscription, SyncPlan) calls it.- The webhook handler verifies an event and queues one job per handled event.
- The job (kind
golem15_pgstripesubscriptions_webhook) claims the processed-event marker, then callsService.Apply,Service.ApplyDeletedorService.ApplyInvoicein one transaction. Forcustomer.subscription.createdand.updatedit first retrieves the subscription from Stripe, outside any transaction and under a per-subscription lock, and applies that state instead of the event's snapshot.
Features
-
Customer.
GetOrCreateCustomerreturns the subscriber's stored Stripe customer id. Otherwise it creates the customer with the e-mail, the name and the metadatasubscriber_typeandsubscriber_id; the core stores the id. The create carries a Stripe idempotency key built from the subscriber alias and id, a SHA-256 of the parameters (e-mail, name, metadata) and a 10-minute window, so concurrent or retried checkouts of one subscriber get one customer. Keys are never logged. A subscriber without an e-mail is refused. -
Checkout.
CreateCheckoutSessioncreates asubscription-mode Checkout Session:- one line item: the plan's own Stripe price in the checkout currency (
CheckoutOptions.Currency,usdwhen empty), fromSubscriptionPlan.CheckoutPriceID. A non-emptystripe_pricesmap decides alone, andstripe_price_idserves only the plan's own currency when the plan was never synced. There is no fallback across currencies: a currency without a price of its own isErrNoPriceForCurrency, without a Stripe call; - promotion codes allowed;
- the success URL gets
session_id={CHECKOUT_SESSION_ID}appended with?, or with&when the URL already has a query; - before the session the price is retrieved: a price missing at Stripe, inactive, in another currency or of another amount than the plan's price in the currency (an edit not yet synced) is
ErrNoPriceForCurrency(it wrapscontracts.ErrPriceUnavailable, so the customer API answers 422) and no session is created; - the create carries no idempotency key of its own: the core serialises a subscriber's checkouts and expires the customer's open sessions first (
ExpireOpenCheckoutSessions,contracts.CheckoutSessionExpirer), and a replayed response would hand back a session it just expired. stripe-go's retry key still covers network retries.
- one line item: the plan's own Stripe price in the checkout currency (
-
Open sessions.
ExpireOpenCheckoutSessionslists the customer's open Checkout Sessions and expires the subscription-mode ones; payment-mode sessions are left alone. -
Checkout metadata. The subscription metadata holds:
subscriber_type,subscriber_id,plan_code,user_email,currency(upper case) andgateway, as PHP wrote them;app, only whenmetadata_appis set;- the keys of
CheckoutOptions.Metadata. The subscriber and plan keys win over an option of the same name.
-
Portal.
CreateManagementSessioncreates a billing portal session for the subscriber's customer, returning to the given URL. A subscriber without a customer is refused. -
Cancel.
CancelSubscriptionat period end updates the subscription withcancel_at_period_end(the core then sets the local flag). Otherwise it cancels the subscription at once and leaves the row to Stripe'scustomer.subscription.deleted. A subscription without a Stripe id is refused. -
Sync. The gateway implements
contracts.SubscriptionRetriever, soService.SyncSubscriptioncallsRetrieveSubscription(outside any transaction, under the subscription's lock) and writes only the gateway-owned columns of the re-read row, including the plan of the retrieved price; a plan switch or customer id written after the caller loaded the row is kept. The contract methodSyncSubscription, built onRetrieveSubscription, still sets these fields in memory:- status and
cancel_at_period_end(true also for acancel_atdate while active or trialing, see Deviations from PHP); - the billing period from the first item, else the top-level fields;
canceled_at,ended_atandtrial_ends_atwhen Stripe reports them.
- status and
-
Plan sync.
SyncPlanToGatewayportssyncPlanToGateway,createOrUpdateStripeProductandcreateOrUpdateStripePrice:- A free plan (
price_cents0) makes no call. - The product is created, or updated when
stripe_product_idis set, with the metadataplan_codeandtier_level. The create carries an idempotency key over the plan id, code, name, description and tier in the 10-minute window, so two syncs that both found no product get one. Its id goes on the plan at once, so a later price error keeps it (the core saves it). - Prices are made in
usd,eurandpln(PHP's list) and in every other supported currency the plan prices (its own currency and thecurrency_priceskeys), under the lookup key<code>_<currency>. An active price with the same amount and interval is reused. Otherwise a recurring price is created withtransfer_lookup_keyand the old one is archived. - The plan gets
stripe_prices(currency to price id) andstripe_price_id(theusdprice).
- A free plan (
-
Currencies.
SupportsCurrencyaccepts PHP's list without the yen, in any case: usd, eur, pln, gbp, cad, aud, chf. -
Webhook.
POST /webhook/stripe/subscriptions(WebhookPath) and the legacyPOST /api/subscriptions/webhook(LegacyWebhookPath) reach one handler. They carry no CSRF and share the bucketpgstripesubscriptions-webhook(WebhookBucket): 60 requests per minute per client IP, PHP'sthrottle:60,1. The answers are PHP's plain-text bodies, in this order:Check Status Body no subscription signing secret for the active mode (Error log) 500 Webhook secret not configuredmissing or wrong Stripe-Signature(Warn log)400 Invalid signaturenot a Stripe event, or larger than 1 MiB 400 Invalid payloadthe event's processed marker exists 200 Already processedotherwise 200 Webhook receivedThe secret is resolved before the header is read, so a missing secret answers 500 even without a signature. The signature is checked on the raw body. Only
customer.subscription.created,customer.subscription.updated,customer.subscription.deleted,invoice.paidandinvoice.payment_failedqueue a job (HandledEventTypes). The handler never writes the marker, and log lines carry the event id and type at most. -
Job. One transaction per event:
- It claims the marker (
Service.ClaimEvent,ON CONFLICT DO NOTHING). An event already claimed commits nothing new; a concurrent duplicate waits on the marker's unique key. - An event whose
appmetadata is set and differs frommetadata_appis skipped. The marker is kept (STRIPE-007). customer.subscription.createdand.updatedgo toApply,.deletedtoApplyDeleted, andinvoice.paidandinvoice.payment_failedtoApplyInvoice(no row change).- Any error rolls the marker back and River retries the job (STRIPE-006).
- It claims the marker (
-
Fresh state. A
customer.subscription.createdor.updatedevent applies the subscription Stripe holds when the job runs, not the event'sdata.object, so an older or retried event cannot set an active row back toincompleteor withdraw a scheduled cancellation:- A processed event is answered from its marker without a Stripe call, and another application's event takes the claim-first path above (marker kept, no Stripe call).
- The job takes the session advisory lock of the subscription (
classes.WithSessionLockonclasses.SubscriptionLockKey), so two jobs about one subscription never interleave. No transaction is open while it holds the lock and calls Stripe. - It retrieves the subscription (
Gateway.RetrieveSubscription). A failed retrieval leaves no marker and River retries. When Stripe answers that the subscription does not exist (ErrSubscriptionMissing), the event's own snapshot is applied with a Warn log, as before. - On the same connection, one transaction claims the marker and calls
Apply; the lock is released afterwards.
-
Deletion retry. A
customer.subscription.deletedevent runs its claim-first transaction under the same per-subscription lock. When the subscription has no stored row yet (itscreatedjob is still retrying),ApplyDeletedanswersclasses.ErrSubscriptionNotStored: the marker is rolled back, the job's Error log names it and River retries. The retriedcreatedjob stores the state Stripe reports (canceled), so a deleted subscription never comes back active and never firesactivated. -
Plan fallback. The job passes the subscribed price's product (
product_id) and the checkout'splan_codemetadata toApply, which finds the plan by exact price id, then bystripe_product_id, then by plan code. A subscription on a price that a later plan sync archived, or on a plan whose code changed, is still stored.Job arguments hold ids, statuses, flags, timestamps, the price id, the price's product id (
product_id), amounts and the metadatasubscriber_type,subscriber_id,plan_codeandapp. They never hold a raw Stripe object, an e-mail or an address. -
Both payload shapes. Periods are read from the first subscription item (basil and later), else from the subscription's top-level fields (earlier API versions). An invoice's subscription is read from
parent.subscription_details.subscription, else from the top-levelsubscription.
Usage
Add the plugin to summer.yaml next to the plugins it requires:
plugins:
- id: golem15.pgstripe
module: git.golem15.com/golem15/sm-pgstripe-plugin
- id: golem15.paymentgatewaysubscriptions
module: git.golem15.com/golem15/sm-paymentgatewaysubscriptions-plugin
- id: golem15.pgstripesubscriptions
module: git.golem15.com/golem15/sm-pgstripe-plugin/subscriptions
Then:
- Keys. Store the Stripe keys on the Stripe settings page (the same secret key as payments).
- Webhook endpoint. In the Stripe Dashboard, under Developers > Webhooks, add an endpoint per mode for
https://<site>/webhook/stripe/subscriptionswith the eventscustomer.subscription.created,customer.subscription.updated,customer.subscription.deleted,invoice.paidandinvoice.payment_failed. - Signing secret. Paste the endpoint's signing secret into the subscriptions webhook signing secret field of the same mode. The fallback config keys are
golem15.pgstripe.subscription_webhook_secretandgolem15.pgstripe.test_subscription_webhook_secret, with the environment variablesSUMMER_GOLEM15__PGSTRIPE__SUBSCRIPTION_WEBHOOK_SECRETandSUMMER_GOLEM15__PGSTRIPE__TEST_SUBSCRIPTION_WEBHOOK_SECRET. - Worker. Run a job worker. The webhook only queues:
servewithqueue.work_in_serveon, or aqueue:workprocess. Without a worker, events wait inriver_job. - Plans. Create the plans and sync them to Stripe (
Service.SyncPlan) before the first checkout, so each plan has its Stripe prices.
A consuming plugin starts a checkout through the core's service; this plugin is not called directly:
sub, err := svc.Subscriber(ctx, classes.UserAlias, user.ID)
session, err := svc.Checkout(ctx, sub, plan, "https://example.com/billing/done", "https://example.com/billing",
contracts.CheckoutOptions{Currency: "pln", Metadata: map[string]string{"campaign": "spring"}})
// redirect the customer to session.URL
API reference
- Plugin:
Plugin,PluginID,WebhookPath,LegacyWebhookPath,WebhookBucket,WebhookBucketMax,ConfigMetadataApp. - Gateway:
Gateway(fieldNow, the clock of the idempotency key window,time.Nowwhen nil),NewGateway,DefaultCurrency,ErrNoPriceForCurrency,ExpireOpenCheckoutSessions(contracts.CheckoutSessionExpirer),ErrSubscriptionMissing,RetrieveSubscription(the subscription Stripe holds, mapped ontocontracts.Updateas the job maps an event); thecontracts.GatewaymethodsIdentifier,GetOrCreateCustomer,CreateCheckoutSession,CreateManagementSession,CancelSubscription,SyncSubscription,SyncPlanToGateway,SupportsCurrency;contracts.SubscriptionRetrieverthroughRetrieveSubscription. - Webhook:
MaxWebhookBytes, the bodiesBodySecretNotConfigured,BodyInvalidSignature,BodyInvalidPayload,BodyAlreadyProcessed,BodyWebhookReceived,ErrEventMalformed, the metadata keysMetadataSubscriberType,MetadataSubscriberID,MetadataPlanCode,MetadataApp. - Job:
JobKind(golem15_pgstripesubscriptions_webhook),WebhookJobArgs,SubscriptionArgs,InvoiceArgs,HandledEventTypes,EventSubscriptionCreated,EventSubscriptionUpdated,EventSubscriptionDeleted,EventInvoicePaid,EventInvoicePaymentFailed.
Configuration
config/config.yaml, merged at golem15.pgstripesubscriptions.*:
| Key | Default | Environment | Meaning |
|---|---|---|---|
golem15.pgstripesubscriptions.metadata_app |
"" |
SUMMER_GOLEM15__PGSTRIPESUBSCRIPTIONS__METADATA_APP |
The application tag on a Stripe account several applications share. When set, Checkout writes it as subscription_data.metadata.app, and the job skips (and marks processed) events whose subscription or invoice has a different app tag. Events without a tag are applied. Empty writes no tag and filters nothing. |
The signing secrets and the Stripe keys are settings of golem15.pgstripe (see its README).
Cutover
What an application moving from the PHP plugins does:
- URLs. Keep the Stripe dashboard endpoints: both PHP URLs exist here with the same answers.
- Secret. On PHP one secret (
stripe.webhookSecret, orSTRIPE_WEBHOOK_SECRET) served both this endpoint and the payment notifications. Import it withpgstripe:import-winter --webhook-secret-target subscriptions(orboth) when the dashboard endpoint holding that secret points at this route. - App tag. If the PHP gateway tagged subscriptions with an application name in
metadata.app, setmetadata_appto the same value. Otherwise the existing subscriptions' events would be skipped as another application's. - Worker. Run a job worker (see Usage).
Deviations from PHP
- Price lookup. Uses the Prices List call with
lookup_keysandactive=trueinstead of PHP's Prices Search. The outcome is the same, but List is not eventually consistent, so a quick re-sync cannot miss a just-created price and create a duplicate. - No owner metadata. The gateway writes no per-application owner key. An application passes such keys in
CheckoutOptions.Metadata. - App tag. It was hard-coded on PHP; here it is the
metadata_appconfig key, empty by default. - Payload shapes. Both are read: PHP read periods from the items only and an invoice's subscription from the top-level field only.
- Secret. The subscription signing secret is its own setting and never falls back to the payment notification secret.
- Plan lookup. The plan is found by exact price id, never
LIKE, in the subscriptions core, then by the price's product and the checkout'splan_code(PHP failed a subscription whose price a re-sync archived). - Content-Type. Webhook answers are
text/plain; charset=utf-8with the PHP bodies (Laravel's default type wastext/html). - No cross-currency price fallback. PHP getStripePriceId fell back to
stripe_price_idfor a currency missing fromstripe_prices, so such a checkout billed another currency's price. A checkout here bills only the plan's own price in its currency and is refused otherwise. - No yen. The zero-decimal yen (jpy) is not supported: the core's money display divides minor units by 100, so a yen price would show a hundredth of what Stripe bills.
- Currencies of the plan sync. The usd, eur and pln loop is kept (a plan without its own price in one of them gets its default
price_centsthere, andstripe_price_idis the usd price), and every other supported currency the plan prices is synced as well. PHP synced only the three, so a plan priced in gbp, cad, aud or chf could not be bought after a sync. - Checkout price check. PHP billed whatever the stored price id held at Stripe. A checkout here retrieves the price first and refuses one that no longer matches the plan.
- Out-of-order events. They no longer behave as on PHP. This is the D-21 amendment of gap closure 18.1-07, the user's 2026-10-14 decision; D-21's other defaults are unchanged. In detail:
- Created and updated events apply the subscription Stripe holds when the job runs, not the event's snapshot, serialised per subscription.
- When Stripe answers 404 for the subscription, the event's snapshot is applied.
- A deletion that arrives before its subscription is stored is retried instead of being marked processed.
- An invoice processed before its subscription exists is still marked processed and fires nothing.
- Sync. PHP saved the whole model after a sync. Here only the gateway-owned columns of the locked, re-read row are written, and the plan follows the retrieved price.
- Billing-portal cancellations. PHP read only
cancel_at_period_end. On API2026-09-30.endivea billing-portal cancellation reportscancel_at(the period end) withcancel_at_period_endfalse, so the row'scancel_at_period_endis true when Stripe reports that flag or acancel_atdate on an active or trialing subscription. Clearingcancel_at(an un-cancel) maps back to false and firesreactivated(D-21, amended 2026-10-16).
Dependencies
git.golem15.com/golem15/sm-pgstripe-plugin(the root package: client factory, mode keys, signature check, settings).git.golem15.com/golem15/sm-paymentgatewaysubscriptions-plugin(contracts, classes, models, events).git.golem15.com/golem15/summercms(backpack, party, pact, surf, conga, lagoon, wire).github.com/stripe/stripe-go/v87v87.0.0, pinned by the root module.
Testing
go test -short ./subscriptions # compiles the suites; the Postgres suites skip
go test ./subscriptions # testcontainers Postgres, needs Docker
No test reaches the network. The package has its own httptest Stripe fake (stripefake_test.go), reached through the published pgstripe.BackendOverride; Phase 18's root fake is unchanged. The proof host activates golem15.user, golem15.paymentgateway, golem15.pgstripe, golem15.paymentgatewaysubscriptions, this plugin and a test-only consumer plugin.
TestHostSubscriptionFlowcovers these subtests:checkout_activation: checkout, a signedcustomer.subscription.created, the job and exactly oneactivated;- invoices in the basil and pre-basil shapes;
past_duewith the grace period;- cancel at period end, then deletion;
- immediate cancel;
- reactivation;
- pre-basil periods;
- a duplicate event;
- the app tag;
- the plan sync (create, unchanged, one changed price archived, free plan);
- the portal;
- sync;
- one event worked by a real conga worker.
TestSubscriptionWebhookSmokecovers:- a missing secret and the env fallback;
- a wrong secret, and a live secret in test mode;
- a missing header;
- bad and oversize payloads;
- an unhandled type;
- the five handled types;
- the legacy alias;
- the shared bucket;
- that the handler writes no marker.
Unit tests of the package (plan 18.1-06):
| Test | Needs Docker | What it pins |
|---|---|---|
TestDecodeSubscription |
no | periods from the first item (basil) or the top level (pre-basil), each bound on its own; an expanded customer; the subscriber only for both metadata keys with a positive whole id; cancel_at alone, both fields, an un-cancel, and cancel_at in past_due or canceled for the pending-cancellation flag |
TestDecodeInvoice |
no | the subscription id from parent.subscription_details (basil) over the top level (pre-basil); the lower-cased currency; the invoice's own app tag |
TestJobArgsMinimal |
no | malformed bodies; the five handled types in PHP order; job arguments with a fixed key list (including product_id and plan_code for subscriptions) and no e-mail, name, address, phone or raw object even when the event carries them |
TestSubscriptionJob |
yes | STRIPE-006 (a failing apply rolls back the row and the marker and returns the error; a retry stores one of each), STRIPE-007 (another app's event and an unhandled type keep the marker and fire nothing), an unknown deletion fails with no marker so it is retried, a duplicate job and two concurrent jobs fire once, both payload shapes |
TestSyncPlan |
yes | free plan, product create then update, price reuse, a changed amount or interval archives and replaces with transfer_lookup_key, the usd/eur/pln loop, the stored map and stripe_price_id, the product id kept when a price fails |
TestSubscriptionGateway |
yes | the success URL separator, the session form and metadata (app tag only when configured, no owner key), the currency default and ErrNoPriceForCurrency (no fallback across currencies), the customer create's idempotency key (same key in a window, a new one for changed parameters or the next window) and no pgsub key on the session create, customer creation, portal, cancel at period end versus immediately, sync from the items and from the top level, SupportsCurrency |
TestFreshStateSmoke |
yes | smoke of the fresh-state job (plan 18.1-07): a stale updated event leaves an active row active, a stale update after a cancel at period end fires no reactivated, a subscription Stripe does not know stores the snapshot, a deletion before creation is retried, never activates and fires canceled once, the product and plan-code plan fallbacks, a sync with a stale copy keeps a plan switch and picks up a plan change at Stripe, a billing-portal cancel reporting cancel_at alone schedules the cancellation and its un-cancel fires reactivated once |
TestStripeSubscriptionReliability |
yes | the two STRIPE-006 PHP cases (below) |
TestSubscriptionAuthentication |
yes | the two PAY-09 PHP cases on both URLs (below) |
Gap-closure tests (plan 18.1-09), pinning the review fixes of plans 18.1-07 and 18.1-08:
| Test | Needs Docker | What it pins |
|---|---|---|
TestDecodeSubscription (extended) |
no | the price's product as an id or an expanded object and the plan_code metadata in the arguments and the update; no e-mail, name or address in the arguments |
TestEventOrdering |
yes | CR-01: the Checkout race with updated first and with two concurrent jobs (active, one activated), a deletion before the creation (retried, canceled once, no activated, no access), an older update after a local cancel fires no reactivated, a failed Stripe retrieval leaves no marker and is retried, a duplicate or another application's event makes no Stripe call |
TestGatewayStrictPrice |
yes | CR-02: a synced plan without the currency is ErrNoPriceForCurrency although stripe_price_id is set, an unsynced plan bills only its own currency, no Stripe call on refusal, the yen refused |
TestGatewayIdempotencyKeys |
yes | WR-02: the customer create's Idempotency-Key is equal within a window for equal parameters and differs across windows (Gateway.Now); the session create sends no pgsub key |
TestReviewFixesGateway |
yes | 18.1 re-review (quick 261016-myi): WR-05 sync of every supported plan currency and a gbp checkout after it, WR-03 product create idempotency key, WR-06 stale, inactive, foreign-currency or missing price refused before the session, WR-04 expiry of the customer's open subscription sessions only |
TestRetrieveSubscription |
yes | the status, both period shapes, cancel flag and dates, price, product (id or expanded), plan code and subscriber; a 404 wraps ErrSubscriptionMissing, a 500 is another error, an empty id makes no call, an answer naming another subscription is refused |
PHP test map (pgstripe 8b47457, the rows that concern subscriptions; each Go case names its PHP file, method and line in a comment):
| PHP test | Go case | Scope |
|---|---|---|
tests/reliability/ReliabilityTest.php test_stripe_006_idempotency_marker_after_job_success |
TestStripeSubscriptionReliability/stripe_006_marker_after_job_success |
18.1 |
tests/reliability/ReliabilityTest.php test_stripe_006_idempotency_marker_double_processing_prevented |
TestStripeSubscriptionReliability/stripe_006_double_processing_prevented |
18.1 |
tests/security/DataHandlingTest.php test_stripe_001_api_keys_stored_as_plaintext |
root TestStripeSubscriptionSecrets/stripe_001_not_plaintext |
18.1 (the two subscription secrets; the payment secrets are TestStripeDataHandling) |
tests/security/DataHandlingTest.php test_stripe_001_keys_encrypted_at_rest |
root TestStripeSubscriptionSecrets/stripe_001_encrypted_at_rest |
18.1 |
tests/security/DataHandlingTest.php test_stripe_001_secret_keys_round_trip_encrypted_to_db |
root TestStripeSubscriptionSecrets/stripe_001_round_trip |
18.1 |
tests/security/DataHandlingTest.php test_pay_10_lazy_decrypt_handles_plaintext |
root TestStripeSubscriptionSecrets/pay_10_import_plaintext_and_encrypted |
18.1 |
tests/security/DataHandlingTest.php test_stripe_003_sdk_constraint_pinned |
root TestSDKPin (one stripe-go major for the root and this package) |
18 and 18.1 |
tests/security/AuthenticationTest.php test_pay_09_stripe_verify_notification_accepts_valid_sig |
TestSubscriptionAuthentication/pay_09_accepts_valid |
18.1 |
tests/security/AuthenticationTest.php test_pay_09_stripe_verify_notification_rejects_invalid_sig |
TestSubscriptionAuthentication/pay_09_rejects_invalid |
18.1 |
tests/security/AuthenticationTest.php test_stripe_002_notification_no_signature_check |
root TestStripeAuthentication |
Phase 18 (STRIPE-002, payment notification), not this package |
tests/security/AuthenticationTest.php test_stripe_002_notification_relies_on_internal_flag_only |
root TestStripeAuthentication |
Phase 18 (STRIPE-002, payment notification), not this package |
Run one suite with, for example, go test -count=1 -run '^TestSubscriptionJob$' ./subscriptions. The framework repository's scripts/check-phase18.1.sh runs all of them by name.