Files
commerce/payment/orgsetup.go
df11077bdc Every processor is configured from its account in the policy, not the environment (#60)
Testing: go test ./payment/... ./api/... ./billing/... ./checkout/... ./thirdparty/...; full TestLiveStripe_ suite; source test that no processor reads the environment.
Risk: boot configuration of Stripe/Square/PayPal moves to the policy; the seed names each secret at the KMS path that resolves on the deployment.
How to revert: revert this commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 02:58:45 -08:00

196 lines
7.7 KiB
Go

// Package payment provides per-org payment processor configuration.
//
// The payment/processor registry holds global singleton processors registered at
// init() time. These singletons are NOT safe for multi-tenant use because
// credentials would be shared across orgs.
//
// ProcessorsForOrg creates a FRESH registry with per-org processor instances,
// each configured with the credentials on the Organization: the org's own when
// a merchant path loaded them (Hydrate), else the deployment's environment.
package payment
import (
"strings"
"github.com/hanzoai/commerce/models/organization"
"github.com/hanzoai/commerce/payment/processor"
"github.com/hanzoai/commerce/payment/providers/adyen"
"github.com/hanzoai/commerce/payment/providers/braintree"
"github.com/hanzoai/commerce/payment/providers/lemonsqueezy"
"github.com/hanzoai/commerce/payment/providers/paypal"
"github.com/hanzoai/commerce/payment/providers/recurly"
"github.com/hanzoai/commerce/payment/providers/square"
"github.com/hanzoai/commerce/payment/providers/stripe"
sqenv "github.com/hanzoai/commerce/thirdparty/square"
)
// defaultSquareWebhookURL is the canonical commerce API ingress URL that
// Square callbacks are delivered to. Square signs each delivery over this URL
// plus the raw body, so it must match the URL registered in the Square
// dashboard byte-for-byte. pay.hanzo.ai is the customer-facing payment host
// (the commerce API ingress); commerce.hanzo.ai serves the marketing SPA, not
// the API. Overridable per-org (org.Square.WebhookURL) or per-deployment
// (SQUARE_WEBHOOK_URL) for non-production hosts.
//
// It answers under COMMERCE's root because that is the capability that verifies
// it. /v1/billing is the billing capability's address and billing holds no
// signature key; this callback is commerce's own, and a processor posts it to
// the app that can check it.
//
// THIS VALUE IS PART OF THE SIGNATURE, not merely where the request lands, so
// changing it is a coordinated change and never a redirect: the Square
// dashboard's notification URL and any SQUARE_WEBHOOK_URL override must move
// with it, or every delivery fails verification with a valid signature.
const defaultSquareWebhookURL = "https://pay.hanzo.ai/v1/commerce/webhooks/square"
// ProcessorsForOrg returns a processor registry configured with the given
// organization's payment credentials. Each processor is a fresh instance —
// no shared state with other orgs or the global singleton registry.
//
// Processors without credentials in the org are still registered but marked
// as unavailable (IsAvailable returns false).
func ProcessorsForOrg(org *organization.Organization) *processor.Registry {
reg := processor.NewRegistry(processor.DefaultConfig())
// Stripe — the org's own keys, else the deployment's of the org's kind
// (StripeKeys), exactly as Square and PayPal fall back below. The webhook
// secret is the deployment's and lives on the global provider.
if keys := StripeKeys(org); keys.SecretKey != "" {
reg.Register(stripe.NewProvider(stripe.Config{
SecretKey: keys.SecretKey,
PublishableKey: keys.PublishableKey,
}))
}
// Square. The ORG is the single authority for sandbox-vs-production (see
// org.TestMode): it selects BOTH which credential set to use AND
// the Environment passed to the provider (which drives the Square API base
// URL). This used to be the deployment's SQUARE_ENVIRONMENT, which forced every
// tenant in the process into one mode; per-org resolution is what lets one
// replica serve a sandbox merchant and a live merchant. Falls back to process
// env vars when KMS is disabled or the org has no stored Square credentials —
// that fallback still reads the env and is the next thing to retire, since it
// lets a tenant transact on the deployment's own payment account.
{
useSandbox := org.TestMode()
env := org.SquareEnvironment()
sqCfg := org.SquareConfig(useSandbox)
token := sqCfg.AccessToken
locationID := sqCfg.LocationId
appID := sqCfg.ApplicationId
webhookKey := org.Square.WebhookSignatureKey
// Notification URL that Square signs deliveries against. Prefer the
// org's configured value, then the deployment's square account, then the canonical
// commerce ingress URL. Must match the URL registered in the Square
// dashboard byte-for-byte or HMAC verification fails.
webhookURL := org.Square.WebhookURL
if webhookURL == "" {
webhookURL = strings.TrimSpace(sqenv.Active().Setting("webhookUrl"))
}
if webhookURL == "" {
webhookURL = defaultSquareWebhookURL
}
// Env-var credential fallback (KMS disabled or no stored Square creds).
// The SAME useSandbox authority picks the sandbox vs production env vars,
// so the credential set always matches `env`, and a sandbox org reads
// the sandbox names only (sqenv.Deployment).
if token == "" {
creds := sqenv.Deployment(useSandbox)
token, locationID, appID = creds.AccessToken, creds.LocationID, creds.ApplicationID
if webhookKey == "" {
webhookKey = strings.TrimSpace(sqenv.Active().Secret("webhookSignature"))
}
}
if token != "" && locationID != "" {
reg.Register(square.NewProvider(square.Config{
ApplicationID: appID,
AccessToken: token,
LocationID: locationID,
WebhookSignatureKey: webhookKey,
WebhookURL: webhookURL,
Environment: env,
Org: org.Name,
}))
}
}
// Adyen
if org.Adyen.APIKey != "" {
reg.Register(adyen.NewProvider(adyen.Config{
APIKey: org.Adyen.APIKey,
MerchantAccount: org.Adyen.MerchantAccount,
HMACKey: org.Adyen.HMACKey,
Environment: adyen.Environment(org.Adyen.Environment),
LiveURLPrefix: org.Adyen.LiveURLPrefix,
}))
}
// Braintree
if org.Braintree.PublicKey != "" {
reg.Register(braintree.NewProvider(braintree.Config{
MerchantID: org.Braintree.MerchantID,
PublicKey: org.Braintree.PublicKey,
PrivateKey: org.Braintree.PrivateKey,
Environment: org.Braintree.Environment,
}))
}
// PayPal — REST API v2 OAuth2 client credentials, resolved through the same
// single org.TestMode() authority as Square: per-org REST v2 ClientId/ClientSecret
// first, then legacy SecurityUserId/SecurityPassword when both are present,
// then the deployment's env fallback (paypal.Deployment) matching useSandbox.
{
useSandbox := org.TestMode()
ppCfg := org.PayPalConfig(useSandbox)
clientID := strings.TrimSpace(ppCfg.ClientId)
clientSecret := strings.TrimSpace(ppCfg.ClientSecret)
webhookID := strings.TrimSpace(ppCfg.WebhookId)
if webhookID == "" && !useSandbox {
webhookID = strings.TrimSpace(org.Paypal.WebhookId)
}
if clientID == "" && ppCfg.SecurityUserId != "" && ppCfg.SecurityPassword != "" {
clientID = strings.TrimSpace(ppCfg.SecurityUserId)
clientSecret = strings.TrimSpace(ppCfg.SecurityPassword)
}
if clientID == "" || clientSecret == "" {
creds := paypal.Deployment(useSandbox)
clientID, clientSecret = creds.ClientID, creds.ClientSecret
if webhookID == "" {
webhookID = creds.WebhookID
}
}
if clientID != "" && clientSecret != "" {
reg.Register(paypal.NewProvider(paypal.Config{
ClientID: clientID,
ClientSecret: clientSecret,
WebhookID: webhookID,
Sandbox: useSandbox,
Org: org.Name,
}))
}
}
// Recurly
if org.Recurly.APIKey != "" {
reg.Register(recurly.NewProvider(recurly.Config{
APIKey: org.Recurly.APIKey,
Subdomain: org.Recurly.Subdomain,
}))
}
// LemonSqueezy
if org.LemonSqueezy.APIKey != "" {
reg.Register(lemonsqueezy.NewProvider(lemonsqueezy.Config{
APIKey: org.LemonSqueezy.APIKey,
StoreID: org.LemonSqueezy.StoreID,
WebhookSecret: org.LemonSqueezy.WebhookSecret,
DefaultVariantID: org.LemonSqueezy.DefaultVariantID,
}))
}
return reg
}