golem15.pgstripe
The compiled Stripe payment operator for the SummerCMS payment gateway: hosted Checkout Sessions and PaymentIntents on the official Stripe SDK, signed webhook events, refunds, a safe browser return and a Stripe settings page with encrypted write-only secrets.
import _ "git.golem15.com/golem15/sm-pgstripe-plugin"
Module git.golem15.com/golem15/sm-pgstripe-plugin, package pgstripe, plugin ID golem15.pgstripe, requires golem15.paymentgateway.
Overview
The plugin ports the WinterCMS Golem15.PGStripe plugin. Its subscription gateway lives in the subscriptions package of this repository, a plugin of its own (see Subscriptions), so an application that lists only golem15.pgstripe links no subscription code. The root plugin publishes one payment operator through the gateway's operators.HasOperators:
- operator code
golem15.pgstripe::lang.operators.stripe(pgstripe.OperatorCode, the PHP code stored inpayments.operator), modeapi, any currency; - notification route
/_paymentgateway/Z29sZW0xNS5wZ3N0cmlwZTo6bGFuZy5vcGVyYXRvcnMuc3RyaXBl(the gateway's route with the base64 operator code), which receives both the signed Stripe webhook events and the customer's browser return.
A consuming shop plugin builds its cart and details for pgstripe.OperatorCode and calls Orders.Make, Payments.Create and Payments.Purchase (see the gateway README). The operator talks to Stripe with a client built per call from the active mode's secret key; no key lives in a package variable.
Features
-
Two checkout modes (D-16). The
checkout_modesetting picks the default (checkout, the Stripe-hosted page, orpayment_intent, a card form on the site); the Details parameterstripe_checkout_mode(pgstripe.CheckoutModeParam) overrides it for one order. -
Checkout mode.
Purchasecreates a Checkout Session (modepayment, one line item at the order's gross total from the stored cart, in the lower-case ISO currency;success_urlis the browser return below,cancel_urlthe order's return URL; the payment uuid is theclient_reference_idand thepayment_uuidmetadata of the session and of its PaymentIntent). It storesstripe_checkout_session_id(andpayment_intent_idwhen Stripe reports one) inpayments.dataand answers pending; the payment is Sent. -
PaymentIntent mode.
Purchasecreates a PaymentIntent for the same server-side amount with thepayment_uuidandemailmetadata and storespayment_intent_id. With the Details parameterpayment_method_id(pgstripe.PaymentMethodParam) it confirms at once, with the browser return asreturn_url. Status map:requires_action(orrequires_payment_methodwhen no payment method was sent) asks for the customer's step;succeededcompletes the payment (Sent and Accepted,is_paid_in_stripeandcharge_idstored);processingis pending;requires_payment_methodafter a confirmed payment method (a decline) andcanceledfail it (Sent and Rejected, with Stripe's message). That is the server-confirmed decline atPurchase(payment_method_id): the response carries no client secret, so the customer retries with a new payment. A decline reported later by a webhook never rejects (see Webhook events). -
Process response bundles (D-17), the
operators.Responsethe payment service returns:- Checkout:
{"status":"pending","redirect_url":"https://checkout.stripe.com/..."}; - PaymentIntent step:
{"status":"requires_action","client_secret":"pi_..._secret_...","payment_intent_id":"pi_...","publishable_key":"pk_test_...","data":{"payment_uuid":"..."}}, with the active mode's publishable key; the client secret is never stored; - PaymentIntent completed:
{"status":"complete"}; declined:{"status":"error","message":"Your card was declined."}.
- Checkout:
-
Amounts. The amount is always computed on the server from the stored cart: the scale-4 gross total converted with
Minor()to cents (whole units for Stripe's zero-decimal currencies such as JPY, thousandths for the three-decimal ones). The client never supplies an amount. -
Webhook events (D-14). A POST is verified with
webhook.ValidatePayloadagainst the active mode's signing secret on the raw body before any lookup; a missingStripe-Signatureheader, a missing secret or a bad signature is refused with 403 and a log line. The event is decoded into a minimal local struct (pgstripe.MinimalEvent), so the endpoint's API version does not matter. Events applied:checkout.session.completedwithpayment_statuspaid: Accept (unpaid: nothing, an asynchronous method is still running);checkout.session.async_payment_succeeded: Accept;checkout.session.async_payment_failed: Reject. It is terminal: the asynchronous payment of a completed session failed;payment_intent.succeeded: Accept, recording the charge;payment_intent.payment_failed: no change; one Warn log line with the payment id, uuid, event id, PaymentIntent id and Stripe's decline codes. Stripe sends it on every declined attempt, and the customer may retry on the same Checkout page or card form;checkout.session.expiredandpayment_intent.canceled: no change. The gateway'spg:cancel-sent-paymentscancels the abandoned payment afterpayment_sent_to_canceled_timeout, as on PHP;- any other type: 200 without a change. An authentic event that names no Stripe payment of this application (another integration or site on the same Stripe account) answers 200
{"status":"ignored"}.
A paid signal (an event or the browser return) for a payment that can no longer be accepted (Rejected or Canceled) changes nothing and writes one Error log line containing
refuses Accept, with the payment id, uuid, state, event id orbrowser_return, PaymentIntent id and session id. The customer was charged, so refund at Stripe or settle the order by hand. A paid signal for an Accepted or Refunded payment is a silent no-op.Accept and Reject apply only when the payment machine allows them inside the transaction holding the payment row lock, so a replayed or concurrent delivery is a 200 no-op.
-
Browser return (
GET ...?pgUuid=<base64 uuid>, no signature). It never changes state from its input: the operator retrieves the stored Checkout Session or PaymentIntent from Stripe and accepts only when Stripe reports it paid, then always redirects (303) to the order's stored return URL. An unknownpgUuidis 404. -
Refunds.
Payments.Refundrefunds by the stored PaymentIntent (read from the stored Checkout Session when only that is known), else by the charge. -
Keys and modes (D-13).
test_modeselects the test or live triple (secret key, publishable key, webhook signing secret) for every call: purchase, refund, the browser return and the signature check. Each secret is the encrypted settings column, or, while it is empty, the config keygolem15.pgstripe.<column>(environmentSUMMER_GOLEM15__PGSTRIPE__SECRET_KEY,SUMMER_GOLEM15__PGSTRIPE__TEST_SECRET_KEY,SUMMER_GOLEM15__PGSTRIPE__WEBHOOK_SECRET,SUMMER_GOLEM15__PGSTRIPE__TEST_WEBHOOK_SECRET). An empty secret key makesPurchasefail withpgstripe.ErrNoSecretKey, never a panic. -
Settings page. "Stripe" in the Payments settings category (permission
golem15.paymentgateway.access_settings): the operator switch, test mode and the checkout mode on the default tab, then Live keys and Test keys tabs with the publishable key (plain) and the secret key, the webhook signing secret and the subscriptions webhook signing secret (write-only password fields: the page shows whether a value is stored, comes from the server configuration or is empty, never the value). -
Subscription webhook signing secrets.
subscription_webhook_secretandtest_subscription_webhook_secretare the signing secrets of the subscriptions endpoint (/webhook/stripe/subscriptions), read bypgstripe.SubscriptionWebhookSecretfor the active mode with the config fallbacksgolem15.pgstripe.subscription_webhook_secretandgolem15.pgstripe.test_subscription_webhook_secret. They never fall back to the payment webhook secret: Stripe issues one secret per endpoint.ModeKeysis unchanged.
Usage
Taking a payment
d := cart.NewDetails(pgstripe.OperatorCode, "Book order", "https://shop.example.com/orders/return", user.Email)
d.Set(pgstripe.CheckoutModeParam, "checkout") // optional; the setting decides otherwise
order, err := ordersSvc.Make(ctx, tx, c, d, user)
p, err := paymentsSvc.Create(ctx, tx, c, d, user, payments.ForOrder(order))
resp, err := paymentsSvc.Purchase(ctx, tx, p)
// resp.RedirectURL: send the customer to Stripe (Checkout)
// resp.ClientSecret, resp.PublishableKey: confirm with Stripe.js (PaymentIntent)
The order becomes Paid when the signed webhook event (or the browser return, after Stripe confirms) accepts the payment; listen to events.OrderPaid to fulfil it.
Stripe Dashboard
The PHP settings partial (_stripe_info.htm) moved here:
- Sign in to the Stripe Dashboard and copy the publishable and secret keys from Developers > API keys into the Live keys tab (turn on Test mode in the Dashboard for the test keys and the Test keys tab).
- Under Developers > Webhooks, add an endpoint for
https://<site>/_paymentgateway/Z29sZW0xNS5wZ3N0cmlwZTo6bGFuZy5vcGVyYXRvcnMuc3RyaXBlwith the eventscheckout.session.completed,checkout.session.async_payment_succeeded,checkout.session.async_payment_failedandpayment_intent.succeeded.payment_intent.payment_failedis optional: it is only logged. Paste its signing secret (whsec_...) into the webhook signing secret field of the same mode. Create one endpoint per mode; each has its own secret. - The endpoint's API version does not matter: verification checks the signature only and the operator reads a few stable fields.
Test cards (test mode, CVC 123, any future expiry date):
4242424242424242: succeeds without authentication;4000000000003055: 3D Secure supported, not required;4000000000003063: 3D Secure required;4000000000000002: declined;378282246310005: American Express, 3D Secure not supported.
Subscriptions
The Stripe implementation of golem15.paymentgatewaysubscriptions is the plugin golem15.pgstripesubscriptions in the subscriptions package (git.golem15.com/golem15/sm-pgstripe-plugin/subscriptions). An application that sells subscriptions adds it to summer.yaml next to golem15.pgstripe and golem15.paymentgatewaysubscriptions:
plugins:
- id: golem15.pgstripesubscriptions
module: git.golem15.com/golem15/sm-pgstripe-plugin/subscriptions
It brings the subscription gateway (customer, subscription Checkout, billing portal, cancel, sync and the plan sync to Stripe products and prices), the subscription webhook on /webhook/stripe/subscriptions and the legacy alias /api/subscriptions/webhook, and the River job that applies the five subscription event types. Its webhook is verified with the subscription signing secrets of this plugin's settings page. The root package never imports it: go list -deps of golem15.pgstripe names no sm-paymentgatewaysubscriptions-plugin package.
API reference
- Plugin:
Plugin,PluginID,SettingsCode,PermissionAccessSettings. - Operator:
Operator,NewOperator,OperatorCode,LogoPath,CheckoutModeParam,CheckoutModeSetting,PaymentMethodParam,BrowserReturnParam,MetadataPaymentUUID, thepayments.datakeysDataCheckoutSessionID(stripe_checkout_session_id),DataPaymentIntentID(payment_intent_id),DataChargeID(charge_id),DataIsPaidInStripe(is_paid_in_stripe). - Client:
ModeKeys,SubscriptionWebhookSecret,KeyModeLive,KeyModeTest,ClientFactory,BackendOverride,NewClient,RequestTimeout,MaxNetworkRetries,ErrNoSecretKey,ErrNoWebhookSecret. - Webhook:
VerifySignature,DecodeEvent,MinimalEvent,EventObject,PaymentError,ExpandableID,PaymentStatusPaid,EventCheckoutSessionCompleted,EventCheckoutSessionAsyncPaymentSucceeded,EventCheckoutSessionAsyncPaymentFailed,EventPaymentIntentSucceeded,EventPaymentIntentPaymentFailed,ErrMissingSignature,ErrEventMalformed,ErrBadReturnUUID. models:Settings(withSecretFallbacks,DropdownOptions,GetCheckoutModeOptions,Mode),LoadSettings,ValidCheckoutMode,Text,LangPrefix,CheckoutModeCheckout,CheckoutModePaymentIntent,ConfigSecretKey,ConfigTestSecretKey,ConfigWebhookSecret,ConfigTestWebhookSecret,ConfigSubscriptionWebhookSecret,ConfigTestSubscriptionWebhookSecret,Register,All.console:ImportWinter,ImportWinterFile,ReadWinterSettings,ReadWinterSettingsFor,WebhookSecretTargetPayments,WebhookSecretTargetSubscriptions,WebhookSecretTargetBoth,WinterOptions,WinterReport,WinterSettingsItem,IsLaravelPayload,ParseAppKey, theWinter*key constants.updates:All,Register.
Tests point the SDK at an httptest server by publishing a BackendOverride on the app before activation (app.Publish(&pgstripe.BackendOverride{URL: srv.URL, HTTPClient: srv.Client()})); production publishes none.
Configuration
Settings table golem15_pgstripe_settings (singleton row 1, migrations 202610130001_create_golem15_pgstripe_settings and 202610150001_add_subscription_webhook_secrets, the latter adding the two subscription columns only when missing):
| Column | Type | PHP key |
|---|---|---|
enabled |
boolean, default false | golem15.pgstripe::lang.operators.stripe |
test_mode |
boolean, default false | stripe.testMode |
checkout_mode |
checkout (default) or payment_intent |
new |
publishable_key |
text | stripe.apiKey |
test_publishable_key |
text | stripe.testApiKey |
secret_key |
encrypted, write-only | stripe.sapiKey |
test_secret_key |
encrypted, write-only | stripe.stestApiKey |
webhook_secret |
encrypted, write-only | stripe.webhookSecret |
test_webhook_secret |
encrypted, write-only | stripe.testWebhookSecret |
subscription_webhook_secret |
encrypted, write-only | stripe.webhookSecret with --webhook-secret-target subscriptions or both |
test_subscription_webhook_secret |
encrypted, write-only | stripe.testWebhookSecret with --webhook-secret-target subscriptions or both |
Config keys (config/config.yaml, merged at golem15.pgstripe.*), the fallbacks of the six secrets while their column is empty:
| Key | Environment |
|---|---|
golem15.pgstripe.secret_key |
SUMMER_GOLEM15__PGSTRIPE__SECRET_KEY |
golem15.pgstripe.test_secret_key |
SUMMER_GOLEM15__PGSTRIPE__TEST_SECRET_KEY |
golem15.pgstripe.webhook_secret |
SUMMER_GOLEM15__PGSTRIPE__WEBHOOK_SECRET |
golem15.pgstripe.test_webhook_secret |
SUMMER_GOLEM15__PGSTRIPE__TEST_WEBHOOK_SECRET |
golem15.pgstripe.subscription_webhook_secret |
SUMMER_GOLEM15__PGSTRIPE__SUBSCRIPTION_WEBHOOK_SECRET |
golem15.pgstripe.test_subscription_webhook_secret |
SUMMER_GOLEM15__PGSTRIPE__TEST_SUBSCRIPTION_WEBHOOK_SECRET |
The encrypted columns need SUMMER_APP__KEY (the application's 32-byte column key). app.url must be set: the Checkout success_url and the PaymentIntent return_url are built from it.
CLI commands
pgstripe:import-winter --settings <file> [--app-key <base64:...>] [--dry-run] [--force] [--webhook-secret-target payments|subscriptions|both]: copies thestripe.*keys of a WinterCMS settings export (scripts/winter-export-settings.sql, the same exportpaymentgateway:import-winterreads) onto the settings row. Laravel-encrypted secrets are decrypted with the PHPAPP_KEYgiven as--app-key(a missing key with such a value is an error naming the setting); plaintext values pass through, as the PHP lazy decrypt allowed.stripe.3dsecureandstripe.stestPublishableKeyare ignored with a notice. A secret already stored is kept unless--force.--dry-runprints the mapping with every secret masked and writes nothing.--webhook-secret-targetplacesstripe.webhookSecretandstripe.testWebhookSecret:payments(the default) writeswebhook_secretandtest_webhook_secret,subscriptionswritessubscription_webhook_secretandtest_subscription_webhook_secretinstead,bothwrites the same value to both pairs. Any other value is an error naming the flag and its three values, before anything is written.
Example: bin/<app> pgstripe:import-winter --settings stripe-settings.json --app-key "$PHP_APP_KEY" --dry-run. bin/<app> help pgstripe:import-winter shows the long help and more examples. The plugin logs through the component pgstripe and the subscriptions plugin through pgstripesubscriptions (log.components in config/log.yaml).
Cutover
What an application moving from the PHP plugin does (no application cuts over in this phase):
- Gateway first. Run the payment gateway's cutover (rows,
paymentgateway:import-winter, salt and key). - Settings. With the same export, run
pgstripe:import-winter --settings paymentgateway-settings.json --app-key "$PHP_APP_KEY" --dry-run, check the mapping, then run it without--dry-run. Delete the export afterwards: it holds live secrets. The PHP plugin read onlySTRIPE_WEBHOOK_SECRETfrom the environment; setSUMMER_GOLEM15__PGSTRIPE__WEBHOOK_SECRET(or the test key) instead when the secret lives in the environment. - Dashboard. Add (or repoint) a webhook endpoint per mode at
https://<site>/_paymentgateway/Z29sZW0xNS5wZ3N0cmlwZTo6bGFuZy5vcGVyYXRvcnMuc3RyaXBlwith the events listed in Stripe Dashboard and store its signing secret. Existing endpoints created under older API versions (for example2025-02-24.acacia) keep working; verification ignores the version. The PHP plugin had no working webhook on this route (its notification was a browser redirect), so an application that handled Stripe with its own webhook keeps that endpoint until it moves to the operator path; events of its own sessions reaching this route are answered 200 and ignored. - Checkout mode. PHP had only the on-site card form (PaymentIntents); choose
checkout_modeon the settings page. Checkout (the default) needs no Stripe.js on the site. - Subscriptions. On PHP one secret (
stripe.webhookSecret, orSTRIPE_WEBHOOK_SECRET) served both the payment notifications and the subscriptions endpoint/webhook/stripe/subscriptions. Here each endpoint has its own secret, because Stripe issues one per endpoint. Choose--webhook-secret-targetby the endpoint the PHP secret belonged to:subscriptionswhen the Stripe dashboard endpoint with that secret points at/webhook/stripe/subscriptions(or/api/subscriptions/webhook),paymentswhen it points at the payment notification route,bothonly when one dashboard endpoint really served both. A secret held in the environment moves toSUMMER_GOLEM15__PGSTRIPE__SUBSCRIPTION_WEBHOOK_SECRET(or the test key). The subscription endpoints, the job and themetadata_apptag are described in the subscriptions README.
Not ported
- The
StripeKeyscomponent (D-17): the publishable key reaches the client in the PaymentIntent process response. - The
stripe.3dsecureswitch: 3D Secure is automatic with PaymentIntents. - The PHP
secure_redirectandpayment_intent_idre-entry intosendPurchaseRequest: the browser return re-checks the intent at Stripe instead.
Dependencies
git.golem15.com/golem15/sm-paymentgateway-plugin(operators, payments, orders, cart, money, models).git.golem15.com/golem15/sm-paymentgatewaysubscriptions-plugin(contracts, classes, models, events), imported by thesubscriptionspackage only.git.golem15.com/golem15/summercmsv0.4.0 (backpack, party, pact, lagoon, cabana, bonfire, diary, wire).github.com/stripe/stripe-go/v87v87.0.0, the official SDK, pinned to the API version2026-09-30.endive(decision D-12). Its dependencygithub.com/shopspring/decimalis transitive and unused by this plugin (money stays the gateway's exact scale-4 type).gorm.io/gorm,github.com/go-gormigrate/gormigrate/v2; tests usegit.golem15.com/golem15/sm-user-plugin,github.com/jackc/pgx/v5andgithub.com/testcontainers/testcontainers-go.
During development go.work replaces the framework with ../summercms.go, the gateway with ../sm-paymentgateway-plugin, the subscriptions core with ../sm-paymentgatewaysubscriptions-plugin and the user plugin with ../sm-summercmsio-app/plugins/golem15/user.
Testing
go vet ./...
go test -short ./... # the unit suites below: no Docker, no network
go test ./... # also the proof host and the settings and import smokes (testcontainers Postgres, needs Docker)
The framework repository's scripts/check-phase18.sh runs every suite below by name and fails on a skip, a miss or an empty run.
Unit suites (-short):
TestStripeWebhookverifies signatures and decodes the minimal event, including thelast_payment_errorcodes of a declined attempt.TestStripeAuthentication(STRIPE-002) refuses a missing header, an internal flag or a query value in place of the signature, and an invalid signature. It accepts a valid one, also during a secret rotation.TestStripeOperatorchecks the Checkout Session and PaymentIntent request bodies, every PaymentIntent status with and without a payment method, and Stripe errors. It also covers the minor-unit amount for zero- and three-decimal currencies, the per-order checkout mode, the browser return's shape, and the mode keys with the config fallback. Without a payment service it proves that a declined attempt is logged with Stripe's codes (never the decline text) and reaches no transition, and that an expired session or a canceled intent changes nothing.TestStripeDataHandling(STRIPE-001) proves the secrets are encrypted columns that never serialize, are ciphertext at rest and survive a round trip. It also checks that the import decrypts Laravel payloads and passes plaintext values.TestSDKPin(STRIPE-003) assertsgithub.com/stripe/stripe-go/v87 v87.0.0and its go.sum lines.TestFixtureAbsentFromProductionguards that the shop fixture stays out of the production source.TestCommandsDocumentedlogs (never fails) each command whose help lacks a description, long help, examples or an option description (bonfire.CheckDocs).
Postgres suites: TestHostStripeFlow, TestStripeSettingsSmoke (with the subscription secret subtests), TestStripeImportWinterSmoke (with the --webhook-secret-target subtests) and TestStripeSubscriptionSecrets (the STRIPE-001 and PAY-10 cases for the two subscription webhook secrets: never readable, fresh ciphertext at rest, round trip, and the import of a plaintext and a Laravel-encrypted PHP value into them). The subscriptions package has its own suites, TestHostSubscriptionFlow and TestSubscriptionWebhookSmoke (see its README).
No test reaches the network: the tests point every Stripe client at an httptest fake of the API, through a published BackendOverride or a client built with NewClient. TestHostStripeFlow mounts golem15.user, golem15.paymentgateway, golem15.pgstripe and a fake shop plugin (registered from a test file only) on Postgres, and it proves both pay paths:
- the operator path: Make, Purchase to a Checkout Session or PaymentIntent, a signed event, Accepted, Paid, one
OrderPaid, the paid mail, and a replay that changes nothing; - the consumer-driven path: the shop's own Checkout Session and webhook record the payment through
Payments.RecordExternal,SendandAccept.
It also covers a wrong secret, a missing header, a missing secret with the env fallback, an older API version, eight concurrent deliveries, the browser return, a refund, the event table, a declined attempt followed by a successful retry in both modes and a paid signal for a Canceled or Rejected payment.
PHP test map (D-02). Each of the 9 PHP security tests of the Winter plugin has a Go counterpart that names it in a // PHP: tests/<file> <method> comment:
AuthenticationTest(4) maps toTestStripeAuthentication.DataHandlingTest(5) maps toTestStripeDataHandlingandTestSDKPin.
The 2 ReliabilityTest cases cover the subscription job's idempotency marker; their Go cases are subscriptions.TestStripeSubscriptionReliability (stripe_006_marker_after_job_success, stripe_006_double_processing_prevented). The idempotency evidence for payment events is TestHostStripeFlow/replay_and_race.
The Phase 18.1 rows of the map (the subscription webhook and its secrets) are listed in the subscriptions README: STRIPE-006 in subscriptions.TestStripeSubscriptionReliability, STRIPE-001 and PAY-10 for the subscription secrets in TestStripeSubscriptionSecrets, STRIPE-003 in TestSDKPin, and PAY-09 on both subscription URLs in subscriptions.TestSubscriptionAuthentication. The two STRIPE-002 cases test the payment notification and stay with TestStripeAuthentication (Phase 18).