← All plugins
golem15.pgstripe

Stripe payments

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.

summer plugin:install golem15.pgstripe
Latest version
v0.1.4
Framework
v0.6.0
Requires
golem15.paymentgateway v0.1.0
Category
Commerce
Go module
git.golem15.com/golem15/sm-pgstripe-plugin

README

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 in payments.operator), mode api, 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_mode setting picks the default (checkout, the Stripe-hosted page, or payment_intent, a card form on the site); the Details parameter stripe_checkout_mode (pgstripe.CheckoutModeParam) overrides it for one order.

  • Checkout mode. Purchase creates a Checkout Session (mode payment, one line item at the order's gross total from the stored cart, in the lower-case ISO currency; success_url is the browser return below, cancel_url the order's return URL; the payment uuid is the client_reference_id and the payment_uuid metadata of the session and of its PaymentIntent). It stores stripe_checkout_session_id (and payment_intent_id when Stripe reports one) in payments.data and answers pending; the payment is Sent.

  • PaymentIntent mode. Purchase creates a PaymentIntent for the same server-side amount with the payment_uuid and email metadata and stores payment_intent_id. With the Details parameter payment_method_id (pgstripe.PaymentMethodParam) it confirms at once, with the browser return as return_url. Status map: requires_action (or requires_payment_method when no payment method was sent) asks for the customer's step; succeeded completes the payment (Sent and Accepted, is_paid_in_stripe and charge_id stored); processing is pending; requires_payment_method after a confirmed payment method (a decline) and canceled fail it (Sent and Rejected, with Stripe's message). That is the server-confirmed decline at Purchase (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.Response the 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."}.
  • 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.ValidatePayload against the active mode's signing secret on the raw body before any lookup; a missing Stripe-Signature header, 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.completed with payment_status paid: 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.expired and payment_intent.canceled: no change. The gateway's pg:cancel-sent-payments cancels the abandoned payment after payment_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 or browser_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 unknown pgUuid is 404.

  • Refunds. Payments.Refund refunds 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_mode selects 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 key golem15.pgstripe.<column> (environment SUMMER_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 makes Purchase fail with pgstripe.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_secret and test_subscription_webhook_secret are the signing secrets of the subscriptions endpoint (/webhook/stripe/subscriptions), read by pgstripe.SubscriptionWebhookSecret for the active mode with the config fallbacks golem15.pgstripe.subscription_webhook_secret and golem15.pgstripe.test_subscription_webhook_secret. They never fall back to the payment webhook secret: Stripe issues one secret per endpoint. ModeKeys is 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:

  1. 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).
  2. Under Developers > Webhooks, add an endpoint for https://<site>/_paymentgateway/Z29sZW0xNS5wZ3N0cmlwZTo6bGFuZy5vcGVyYXRvcnMuc3RyaXBl with the events checkout.session.completed, checkout.session.async_payment_succeeded, checkout.session.async_payment_failed and payment_intent.succeeded. payment_intent.payment_failed is 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.
  3. 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, the payments.data keys DataCheckoutSessionID (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 (with SecretFallbacks, 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, the Winter* 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 the stripe.* keys of a WinterCMS settings export (scripts/winter-export-settings.sql, the same export paymentgateway:import-winter reads) onto the settings row. Laravel-encrypted secrets are decrypted with the PHP APP_KEY given 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.3dsecure and stripe.stestPublishableKey are ignored with a notice. A secret already stored is kept unless --force. --dry-run prints the mapping with every secret masked and writes nothing. --webhook-secret-target places stripe.webhookSecret and stripe.testWebhookSecret: payments (the default) writes webhook_secret and test_webhook_secret, subscriptions writes subscription_webhook_secret and test_subscription_webhook_secret instead, both writes 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):

  1. Gateway first. Run the payment gateway's cutover (rows, paymentgateway:import-winter, salt and key).
  2. 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 only STRIPE_WEBHOOK_SECRET from the environment; set SUMMER_GOLEM15__PGSTRIPE__WEBHOOK_SECRET (or the test key) instead when the secret lives in the environment.
  3. Dashboard. Add (or repoint) a webhook endpoint per mode at https://<site>/_paymentgateway/Z29sZW0xNS5wZ3N0cmlwZTo6bGFuZy5vcGVyYXRvcnMuc3RyaXBl with the events listed in Stripe Dashboard and store its signing secret. Existing endpoints created under older API versions (for example 2025-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.
  4. Checkout mode. PHP had only the on-site card form (PaymentIntents); choose checkout_mode on the settings page. Checkout (the default) needs no Stripe.js on the site.
  5. Subscriptions. On PHP one secret (stripe.webhookSecret, or STRIPE_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-target by the endpoint the PHP secret belonged to: subscriptions when the Stripe dashboard endpoint with that secret points at /webhook/stripe/subscriptions (or /api/subscriptions/webhook), payments when it points at the payment notification route, both only when one dashboard endpoint really served both. A secret held in the environment moves to SUMMER_GOLEM15__PGSTRIPE__SUBSCRIPTION_WEBHOOK_SECRET (or the test key). The subscription endpoints, the job and the metadata_app tag are described in the subscriptions README.

Not ported

  • The StripeKeys component (D-17): the publishable key reaches the client in the PaymentIntent process response.
  • The stripe.3dsecure switch: 3D Secure is automatic with PaymentIntents.
  • The PHP secure_redirect and payment_intent_id re-entry into sendPurchaseRequest: 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 the subscriptions package only.
  • git.golem15.com/golem15/summercms v0.4.0 (backpack, party, pact, lagoon, cabana, bonfire, diary, wire).
  • github.com/stripe/stripe-go/v87 v87.0.0, the official SDK, pinned to the API version 2026-09-30.endive (decision D-12). Its dependency github.com/shopspring/decimal is 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 use git.golem15.com/golem15/sm-user-plugin, github.com/jackc/pgx/v5 and github.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):

  • TestStripeWebhook verifies signatures and decodes the minimal event, including the last_payment_error codes 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.
  • TestStripeOperator checks 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) asserts github.com/stripe/stripe-go/v87 v87.0.0 and its go.sum lines.
  • TestFixtureAbsentFromProduction guards that the shop fixture stays out of the production source.
  • TestCommandsDocumented logs (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, Send and Accept.

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 to TestStripeAuthentication.
  • DataHandlingTest (5) maps to TestStripeDataHandling and TestSDKPin.

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).

Versions

VersionFrameworkRequiresReleased
v0.1.4v0.6.0golem15.paymentgateway v0.1.02026-10-30