Files
commerce/api/billing/square_customer_test.go
b9abb94aa2 Tell the processors who is paying (#50)
* billing: processors are told who is paying, so their card checks stop declining a stranger

A live Stripe account was declining first-period charges (card_velocity_exceeded,
do_not_honor, insufficient_funds on a normal-risk buyer). The customer Stripe held
was named for the org slug ("github"), with no email, phone or address; the card
carried only a postal code; the PaymentIntent had no receipt email, no statement
suffix and metadata of only hanzo_subject.

vaultCustomer no longer passes the billing subject as the customer name. A Payer
(name, email, phone, billing address, org, user) is carried from the host to the
processors: Stripe and Square create ONE customer per payer with everything known
and bring an existing customer up to date at its next checkout (processor.PayerProfiles:
CreateCustomerFor, ProfileCustomer; writes nothing when it already agrees). The name
and email are the host's verified identity and no request body can set them
(CreateMethodIn.BillingName is json:"-"); phone and address are the buyer's.
After a SetupIntent saves a card, its billing_details are completed from the customer.
Every Stripe card PaymentIntent now carries receipt_email, statement_descriptor_suffix
"HANZO AI", a description naming plan, seats and date, and metadata org/user/subject;
saved cards remember their payer's email/name/org/user so renewals and reloads carry
them too. The Payment Element intent is made for the payer's customer with the same.

BackfillPayers reads (dry run by default) the customers commerce made whose name is a
billing key and proposes the person's name and email from the host's identity lookup;
writing is a separate explicit argument, and a repeat writes nothing. It was not run.

There is no automatic re-attempt with a new amount: a first-period charge is made only
by the buyer's own request, and a renewal charges the invoice's amount; nothing here
adds a retry.

Testing: Stripe test mode, TestLiveStripe_TheCustomerAndTheCardNameThePayer (customer name/
email/phone/address/metadata, card billing_details, PaymentIntent receipt_email/suffix/
description/metadata) and TestLiveStripe_ACustomerMadeNamelessIsNamedAtItsNextCheckout fail
with the old behaviour (customer "hanzo", no phone, no address) and pass; TestTheBackfill...;
Square TestAPayerIsSplit...; full api/billing, payment/..., thirdparty/square, api/checkout pass.
Risk: medium (billing). Customers already at Stripe are updated in place at their next
checkout; a profile that cannot be written is logged and does not stop the checkout.
How to revert: git revert this commit; customers are named for the billing subject again.

Co-authored-by: Hanzo Dev <[email protected]>

* square: a payer the host could not name is still a customer, under its org's company name

Square refuses a customer with no name, email, phone or company. Before, the billing
subject stood in as the given name; with the subject gone from the name, a sale whose
host passed no name and no email failed at the customer ("Card declined"). The org the
payer buys for is now the customer's company_name, which is what it is.

Testing: cloud apps/commerce TestASquareSaleOfEveryRungIsTheLimitersPlan (Square sandbox)
failed without this ("Card declined — invalid card number") and passes with it.
Risk: low; one more field on a new Square customer.
How to revert: git revert this commit.

Co-authored-by: Hanzo Dev <[email protected]>

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-11-13 16:43:36 -08:00

128 lines
4.3 KiB
Go

package billing
// A billing subject has one Square customer, found or made once:
//
// a declined card and a retry make one customer, not two
// saves at once for one subject make one customer
// a subject with a saved card reuses its customer and asks Square nothing
// a failed search still makes the customer, under its key
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/hanzoai/commerce/datastore"
"github.com/hanzoai/commerce/payment/processor"
"github.com/hanzoai/commerce/util/test/ae"
)
// slowCreate holds each customer create open for a moment, as Square's round
// trip does, so saves that nothing orders all search before any create lands.
type slowCreate struct{ *MockSquareProcessor }
func (s slowCreate) CreateCustomer(ctx context.Context, email, name string, meta map[string]interface{}) (string, error) {
time.Sleep(20 * time.Millisecond)
return s.MockSquareProcessor.CreateCustomer(ctx, email, name, meta)
}
func TestSaveCard_ADeclineAndARetryMakeOneCustomer(t *testing.T) {
ctx := ae.NewContext()
defer ctx.Close()
org := moneyOrg("custretry")
db := datastore.New(org.Namespaced(ctx))
m := squareMock("cust_once", "ccof_once", "ref")
m.addCardErr = errors.New("CARD_DECLINED")
if _, _, err := saveCard(context.Background(), db, m, "custretry", processor.Payer{Email: "[email protected]"}, "cnon:bad"); err == nil {
t.Fatal("a declined card must fail the save")
}
if m.createCustomerCalls != 1 || m.customers["custretry/custretry"] != "cust_once" {
t.Fatalf("first save: creates=%d customers=%v, want one customer under custretry/custretry",
m.createCustomerCalls, m.customers)
}
m.addCardErr = nil
pm, created, err := saveCard(context.Background(), db, m, "custretry", processor.Payer{Email: "[email protected]"}, "cnon:good")
if err != nil || !created {
t.Fatalf("retry: created=%v err=%v", created, err)
}
if m.createCustomerCalls != 1 {
t.Fatalf("CreateCustomer calls=%d after a decline and a retry, want 1", m.createCustomerCalls)
}
if got := customerIDOf(pm); got != "cust_once" {
t.Fatalf("saved card names customer %q, want cust_once", got)
}
}
func TestSaveCard_SavesAtOnceMakeOneCustomer(t *testing.T) {
ctx := ae.NewContext()
defer ctx.Close()
org := moneyOrg("custrace")
m := squareMock("cust_race", "ccof_race", "ref")
m.addCardErr = errors.New("CARD_DECLINED")
cp := slowCreate{m}
const n = 8
var wg sync.WaitGroup
declined := make(chan error, n)
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
own := datastore.New(org.Namespaced(ctx))
_, _, err := saveCard(context.Background(), own, cp, "custrace", processor.Payer{Email: "[email protected]"}, "cnon:bad")
declined <- err
}()
}
wg.Wait()
close(declined)
for err := range declined {
if err == nil {
t.Fatal("a declined card must fail every save")
}
}
if m.createCustomerCalls != 1 {
t.Fatalf("CreateCustomer calls=%d for %d saves at once, want 1", m.createCustomerCalls, n)
}
}
func TestSaveCard_ASavedCardsCustomerIsReused(t *testing.T) {
ctx := ae.NewContext()
defer ctx.Close()
org := moneyOrg("custsaved")
db := datastore.New(org.Namespaced(ctx))
seedSavedCard(t, db, "custsaved", "ccof_old", "cust_saved")
m := squareMock("cust_never", "ccof_new", "ref")
if _, _, err := saveCard(context.Background(), db, m, "custsaved", processor.Payer{Email: "[email protected]"}, "cnon:new"); err != nil {
t.Fatalf("saveCard: %v", err)
}
if m.findCalls != 0 || m.createCustomerCalls != 0 {
t.Fatalf("searches=%d creates=%d, want neither for a subject with a saved card", m.findCalls, m.createCustomerCalls)
}
if m.addCardCustomerID != "cust_saved" {
t.Fatalf("vaulted under %q, want the saved card's customer cust_saved", m.addCardCustomerID)
}
}
func TestSaveCard_AFailedSearchStillMakesTheCustomer(t *testing.T) {
ctx := ae.NewContext()
defer ctx.Close()
org := moneyOrg("custsearch")
db := datastore.New(org.Namespaced(ctx))
m := squareMock("cust_s", "ccof_s", "ref")
m.findErr = errors.New("503 Service Unavailable")
pm, _, err := saveCard(context.Background(), db, m, "custsearch", processor.Payer{Email: "[email protected]"}, "cnon:ok")
if err != nil {
t.Fatalf("saveCard: %v", err)
}
if m.createCustomerCalls != 1 || customerIDOf(pm) != "cust_s" {
t.Fatalf("creates=%d customer=%q, want the customer made once", m.createCustomerCalls, customerIDOf(pm))
}
}