Troque o provedor de pagamento falso do lab 9 por um real, em sandbox: o modo de teste da Stripe, em que nenhum dinheiro se move.
Mantenha o contrato que o order enxerga: o payment continua respondendo AUTHORIZED ou DECLINED, atrás de uma interface Psp com duas implementações — a falsa (ainda o padrão) e a Stripe.
Receba os webhooks da Stripe, confira a assinatura deles, processe cada evento uma vez e deixe um webhook registrar a cobrança cuja resposta se perdeu.
Reconcilie os seus pagamentos com o provedor, a fonte da verdade.
Veja como o mesmo design recebe o Pix com o Mercado Pago.
O lab 9 ensinou o payment a sobreviver a um provedor lento ou fora do ar — contra um WireMock que responde o que roteirizamos. Um provedor de serviços de pagamento (PSP, payment service provider) de verdade acrescenta o que um falso não tem: uma conta e chaves, valores em centavos, cartões recusados que são respostas e não falhas, e um segundo canal — o provedor chama você de volta, depois, talvez duas vezes, para dizer o que realmente aconteceu. Este lab liga o BoxOffice ao sandbox da Stripe e trata tudo isso, sem gastar um centavo.
A história até aqui
Capítulo 10 da história da disciplina, o seu segundo lab, que amarra três fios. A aula 3 avisou que, entre máquinas, uma mensagem pode se perder ou se duplicar: um "comprar" repetido pode cobrar duas vezes. O lab 9 respondeu com uma chave de idempotência por pedido (order-<orderId>) contra um provedor falso e mostrou a outra face de um timeout: quando o cliente do lab 9 desiste depois de 1 s e 3 tentativas, a cobrança pode ter acontecido mesmo assim — num dia de provedor lento, o simulador abaixo deixa 133 de 1.000 checkouts em UNKNOWN. A aula 12 acrescenta que todo endpoint que a internet alcança precisa provar quem está chamando. Este lab liga o payment ao sandbox de um provedor real, transforma o UNKNOWN numa resposta conhecida com webhooks assinados e uma reconciliação e mede isso: cada checkout cobrado exatamente uma vez e zero divergências com o provedor.
Antes de começar
Tempo
3–4 horas
Você precisa de
as ferramentas do lab 0; uma conta Stripe gratuita (um e-mail basta para o sandbox); jq e openssl (os dois vêm com o macOS e a maioria das distribuições Linux)
Diretório
todo comando roda a partir da raiz do seu repositório boxoffice/
Custos
zero: o sandbox (modo de teste) não move dinheiro e o serviço se recusa a subir com uma chave de produção
dockercomposeversion# v2.xjq--version# jq-1.6+opensslversion# any
Estado inicial — o fim do lab 13 (o lab 9 é a base deste: payment, order, Toxiproxy e o provedor falso psp):
Pulou ou quebrou um lab? Baixe boxoffice-after-lab-13.zip, descompacte e entre em boxoffice. Este lab acrescentaPsp.java, StripePsp.java, StripeSignature.java, StripeWebhookController.java, Reconciliation.java, V2__stripe_events.sql, um teste de unidade e scripts/send-webhook.sh e substitui o compose.yaml e, em services/payment/, pom.xml, application.yaml, ChargeRequest.java, PaymentService.java e PspClient.java. Todos estão completos nesta página e em boxoffice-after-lab-14.zip.
Slides
Clique nos slides e use ← → para navegar; F abre em tela cheia e P abre a visão do apresentador, com as notas. Abrir os slides em uma nova aba
O que você vai construir
flowchart LR
order["order<br/>chave order-<id>"]:::comp -->|"POST /payments<br/>(via Toxiproxy)"| payment["payment<br/>Psp: fake | stripe"]:::comp
payment -->|"POST /v1/payment_intents<br/>Idempotency-Key, confirm=true"| stripe["sandbox da Stripe"]:::tech
stripe -->|"payment_intent.succeeded<br/>(depois, talvez duas vezes)"| cli["stripe-cli<br/>listen --forward-to"]:::tech
cli -->|"POST /webhooks/stripe<br/>Stripe-Signature"| payment
payment -->|"GET /payments/reconcile<br/>consulta cada PaymentIntent"| stripe
Passo
O que muda
Você deve ver
1. Um sandbox
uma conta Stripe, uma chave de teste no .env
GET /v1/balance responde com "livemode": false
2. O adaptador
Psp + StripePsp, o falso ainda é o padrão
o payment compila; 5 testes passam
3. Cobrar
PSP_PROVIDER=stripe
AUTHORIZED com uma referência pi_…; a mesma chave, o mesmo pagamento; um cartão recusado é DECLINED
4. Webhooks
assinatura, um evento uma vez, stripe-cli
webhook evt_… → AUTHORIZED; uma repetição é duplicate; uma falsificação é 400
5. A resposta perdida
uma cobrança que o payment nunca gravou
o webhook a grava; pagar de novo confirma o pedido sem segunda cobrança
6. Reconciliar
o nosso contra o da Stripe
{"checked": N, "mismatches": []} — depois uma divergência, encontrada
1. Um sandbox da Stripe
Crie uma conta em dashboard.stripe.com/register. Você não precisa ativar pagamentos: um sandbox (o ambiente de teste da Stripe) fica disponível na hora.
No Dashboard, abra Developers → API keys do seu sandbox e copie a secret key: ela começa com sk_test_.
Coloque-a no .env, na raiz do repositório — o Compose o lê e o .gitignore do lab 0 o mantém fora do Git:
.env
PSP_PROVIDER=stripe
STRIPE_SECRET_KEY=sk_test_...
gitcheck-ignore.env# prints ".env": it will never be committedcurl-shttps://api.stripe.com/v1/balance-u"$(grep'^STRIPE_SECRET_KEY='.env|cut-d=-f2-):"|jq'{object, livemode}'
Você deve ver {"object": "balance", "livemode": false}. livemode: false é o sandbox: nada que você fizer aqui cobra um cartão de verdade.
Uma secret key é uma senha para o seu dinheiro
Nunca a cole em código, num commit, num print de tela ou num chat. Se ela vazar, troque-a no Dashboard (Developers → API keys → Roll key). O StripePsp recusa qualquer chave que não comece com sk_test_: nesta disciplina, uma chave de produção é um bug.
2. O adaptador: uma interface, dois provedores
O order não pode saber qual provedor está atrás do payment — esse é o ponto do adaptador do lab 9. A nova interface Psp tem duas implementações, escolhidas por boxoffice.psp.provider: o PspClient do lab 9 (ainda o padrão, para que os experimentos de caos e o CI continuem funcionando sem chaves) e o StripePsp.
packageboxoffice.payment;importjava.math.BigDecimal;importjava.util.UUID;/** A payment service provider: the fake of lab 9 or the Stripe sandbox. */publicinterfacePsp{/** id: the provider's reference; approved: false when the card was declined. */recordCharge(Stringid,booleanapproved){}/** Charges once per idempotency key, however many times it is called. */Chargecharge(StringidempotencyKey,BigDecimalamount,UUIDorderId,StringpaymentMethod);}
packageboxoffice.payment;importjava.math.BigDecimal;importjava.net.http.HttpClient;importjava.time.Duration;importjava.util.UUID;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;importorg.springframework.http.MediaType;importorg.springframework.http.client.JdkClientHttpRequestFactory;importorg.springframework.stereotype.Component;importorg.springframework.util.LinkedMultiValueMap;importorg.springframework.util.MultiValueMap;importorg.springframework.web.client.RestClient;/** The Stripe sandbox: one PaymentIntent per order, created and confirmed on the server. */@Component@ConditionalOnProperty(name="boxoffice.psp.provider",havingValue="stripe")publicclassStripePspimplementsPsp{/** The fields of a PaymentIntent this service reads. */recordIntent(Stringid,Stringstatus){}/** Stripe's error body: a declined card comes back as HTTP 402 with type card_error. */recordErrorBody(Errorerror){recordError(Stringtype,Stringcode,Stringdecline_code,Stringmessage,Intentpayment_intent){}}privatefinalRestClienthttp;privatefinalStringcurrency;privatefinalStringdefaultMethod;publicStripePsp(RestClient.Builderbuilder,@Value("${boxoffice.stripe.url}")Stringurl,@Value("${boxoffice.stripe.secret-key}")StringsecretKey,@Value("${boxoffice.stripe.currency}")Stringcurrency,@Value("${boxoffice.stripe.payment-method}")StringdefaultMethod,@Value("${boxoffice.psp.connect-timeout}")DurationconnectTimeout,@Value("${boxoffice.psp.read-timeout}")DurationreadTimeout){if(!secretKey.startsWith("sk_test_")){// a live key (sk_live_…) moves real money: this lab refuses to start with onethrownewIllegalStateException("STRIPE_SECRET_KEY must be a test key (sk_test_…)");}// the JDK HttpClient keeps the body of an error answer (HttpURLConnection may drop it)JdkClientHttpRequestFactoryfactory=newJdkClientHttpRequestFactory(HttpClient.newBuilder().connectTimeout(connectTimeout).build());factory.setReadTimeout(readTimeout);this.http=builder.baseUrl(url).defaultHeader("Authorization","Bearer "+secretKey).requestFactory(factory).build();this.currency=currency;this.defaultMethod=defaultMethod;}@OverridepublicChargecharge(StringidempotencyKey,BigDecimalamount,UUIDorderId,StringpaymentMethod){MultiValueMap<String,String>form=newLinkedMultiValueMap<>();form.add("amount",String.valueOf(amount.movePointRight(2).longValueExact()));// centavosform.add("currency",currency);form.add("payment_method",paymentMethod!=null?paymentMethod:defaultMethod);form.add("confirm","true");// charge now, on the serverform.add("automatic_payment_methods[enabled]","true");form.add("automatic_payment_methods[allow_redirects]","never");// no browser to redirectform.add("metadata[order_id]",orderId.toString());form.add("metadata[idempotency_key]",idempotencyKey);// lets a webhook find the paymentreturnhttp.post().uri("/v1/payment_intents").header("Idempotency-Key",idempotencyKey)// Stripe charges once per key.contentType(MediaType.APPLICATION_FORM_URLENCODED).body(form).exchange((request,response)->{if(response.getStatusCode().is2xxSuccessful()){Intentintent=response.bodyTo(Intent.class);returnnewCharge(intent.id(),"succeeded".equals(intent.status()));}ErrorBodybody=response.bodyTo(ErrorBody.class);if(response.getStatusCode().value()==402&&body!=null&&body.error().payment_intent()!=null){returnnewCharge(body.error().payment_intent().id(),false);// declined: an answer, not a failure}Stringmessage=body!=null?body.error().message():response.getStatusText();thrownewIllegalStateException("Stripe answered "+response.getStatusCode().value()+": "+message);});}/** The provider's view of one PaymentIntent: the source of truth for reconciliation. */publicIntentretrieve(StringintentId){returnhttp.get().uri("/v1/payment_intents/{id}",intentId).retrieve().body(Intent.class);}}
packageboxoffice.payment;importjava.math.BigDecimal;importjava.time.Duration;importjava.util.UUID;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;importorg.springframework.http.client.SimpleClientHttpRequestFactory;importorg.springframework.stereotype.Component;importorg.springframework.web.client.RestClient;/** Lab 9's fake provider (WireMock behind Toxiproxy): still the default, so the chaos experiments keep working. */@Component@ConditionalOnProperty(name="boxoffice.psp.provider",havingValue="fake",matchIfMissing=true)publicclassPspClientimplementsPsp{recordChargeBody(BigDecimalamount,Stringcurrency,Stringreference){}recordChargeOut(Stringid,Stringstatus){}privatefinalRestClienthttp;publicPspClient(RestClient.Builderbuilder,@Value("${boxoffice.psp.url}")Stringurl,@Value("${boxoffice.psp.connect-timeout}")DurationconnectTimeout,@Value("${boxoffice.psp.read-timeout}")DurationreadTimeout){SimpleClientHttpRequestFactoryfactory=newSimpleClientHttpRequestFactory();factory.setConnectTimeout(connectTimeout);// time to open the TCP connectionfactory.setReadTimeout(readTimeout);// max silence while waiting for the responsethis.http=builder.baseUrl(url).requestFactory(factory).build();}/** The provider deduplicates by Idempotency-Key, like real PSPs do. */@OverridepublicChargecharge(StringidempotencyKey,BigDecimalamount,UUIDorderId,StringpaymentMethod){ChargeOutout=http.post().uri("/v1/charges").header("Idempotency-Key",idempotencyKey).body(newChargeBody(amount,"BRL","order-"+orderId)).retrieve().body(ChargeOut.class);returnnewCharge(out.id(),"approved".equals(out.status()));}}
server:port:8085spring:application:name:paymentmvc:problemdetails:enabled:truedatasource:url:jdbc:postgresql://${DB_HOST:db}:${DB_PORT:5432}/${DB_NAME:boxoffice}?currentSchema=paymentusername:${DB_USER:boxoffice}password:${DB_PASSWORD:boxoffice}flyway:schemas:paymentboxoffice:psp:provider:${PSP_PROVIDER:fake}# fake (lab 9's WireMock) | stripe (the sandbox, lab 14)url:${PSP_URL:http://psp:8080}connect-timeout:500msread-timeout:${PSP_READ_TIMEOUT:2s}stripe:url:https://api.stripe.comsecret-key:${STRIPE_SECRET_KEY:}# sk_test_…: from the environment, never from Gitwebhook-secret:${STRIPE_WEBHOOK_SECRET:}# whsec_…: printed by stripe listencurrency:${STRIPE_CURRENCY:brl}payment-method:${STRIPE_PAYMENT_METHOD:pm_card_visa}# a test card when the request names nonetolerance:300s# max age of a webhook signaturemanagement:endpoints:web:exposure:include:health,info,metricsendpoint:health:probes:enabled:true
Um PaymentIntent por pedido, confirmado no servidor.confirm=true cobra na hora com o meio de pagamento de teste (pm_card_visa por padrão — num checkout real, o Stripe.js no navegador transforma o cartão num id desses, de modo que números de cartão nunca tocam o BoxOffice). allow_redirects=never: não há navegador para mandar a uma página do banco.
Valores em centavos. R$ 350,00 é amount=35000; movePointRight(2).longValueExact() falha alto diante de uma fração de centavo em vez de arredondar dinheiro.
A mesma Idempotency-Key da tabela do próprio payment (order-<orderId>, vinda do order). A Stripe guarda o resultado do primeiro pedido com uma chave e o repete para todo retry com a mesma chave; um retry depois de uma queda entre "a Stripe cobrou" e "nós gravamos" não consegue cobrar duas vezes.
Um cartão recusado é uma resposta. A Stripe devolve HTTP 402 com type: card_error e o PaymentIntent; o payment registra DECLINED. Todo o resto (401, 5xx, um timeout) é uma exceção: o retry, o breaker e o fallback do lab 9 no order tratam dela.
Metadadosorder_id e idempotency_key viajam com o PaymentIntent: o webhook do passo 4 os usa para encontrar — ou criar — o pagamento.
O PaymentService agora pergunta à interface Psp em vez do PspClient; o código completo dele está no passo 4. Reconstrua o payment e rode os testes dele:
dockercomposebuildpayment# the Dockerfile runs mvn package -DskipTestsdockerrun--rm-v"$PWD/services/payment":/src-w/srcmaven:3.9-eclipse-temurin-21mvn-B-qtest
Você deve ver Tests run: 5, Failures: 0 para o StripeSignatureTest (passo 4).
3. Cobre no sandbox
O compose.yaml passa as novas variáveis ao payment (e acrescenta o stripe-cli, usado no passo 4):
name:boxoffice# lab 8: OpenTelemetry settings shared by every Java service (merged into each "environment")x-otel:&otelJAVA_TOOL_OPTIONS:-javaagent:/otel/opentelemetry-javaagent.jarOTEL_JAVAAGENT_ENABLED:${OTEL_ON:-true}# false = same image, agent offOTEL_EXPORTER_OTLP_ENDPOINT:http://otel-lgtm:4318OTEL_METRIC_EXPORT_INTERVAL:"10000"# 10 s instead of 60 sOTEL_RESOURCE_ATTRIBUTES:service.namespace=boxoffice,deployment.environment.name=localOTEL_TRACES_SAMPLER:${OTEL_TRACES_SAMPLER:-parentbased_always_on}OTEL_TRACES_SAMPLER_ARG:${OTEL_TRACES_SAMPLER_ARG:-1.0}LOGGING_PATTERN_CORRELATION:"[%X{trace_id:-},%X{span_id:-}]"# trace id in console logs# settings shared by the three catalog replicas (a YAML anchor)x-catalog:&catalogbuild:./services/catalogimage:boxoffice-catalogvolumes:-./infra/otel:/otel:ro# lab 8: the Java agentenvironment:<<:*otelOTEL_SERVICE_NAME:catalog# three replicas, ONE serviceDB_HOST:dbDB_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}DB_POOL_SIZE:${DB_POOL_SIZE:-10}REDIS_HOST:redisREDIS_PORT:6379CACHE_ENABLED:${CACHE_ENABLED:-true}CACHE_TTL_EVENT:${CACHE_TTL_EVENT:-60s}CACHE_TTL_LIST:${CACHE_TTL_LIST:-10s}CACHE_STAMPEDE_PROTECTION:${CACHE_STAMPEDE_PROTECTION:-false}depends_on:db:condition:service_healthyredis:condition:service_healthydeploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8082/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120s# lab 8: with the agent, JVMs starting together need up to ~90 sretries:3services:db:image:pgvector/pgvector:0.8.7-pg17-trixie# lab 12: PostgreSQL 17 + the pgvector extensioncommand:["postgres","-c","max_connections=${DB_MAX_CONNECTIONS:-100}"]environment:POSTGRES_DB:${DB_NAME:-boxoffice}POSTGRES_USER:${DB_USER:-boxoffice}POSTGRES_PASSWORD:${DB_PASSWORD:-boxoffice}REPLICATION_PASSWORD:${REPLICATION_PASSWORD:-replicator}ports:-"5432:5432"volumes:-db-data:/var/lib/postgresql/data# runs only when the volume is new: creates the "replicator" user-./infra/postgres/10-replication.sh:/docker-entrypoint-initdb.d/10-replication.sh:rohealthcheck:test:["CMD-SHELL","pg_isready-U$${POSTGRES_USER}-d$${POSTGRES_DB}"]interval:5stimeout:3sretries:10# read-only streaming replica of db (hot standby)db-replica:image:pgvector/pgvector:0.8.7-pg17-trixie# lab 12: PostgreSQL 17 + the pgvector extensionuser:postgresentrypoint:["/usr/local/bin/replica-entrypoint.sh"]environment:PGPASSWORD:${REPLICATION_PASSWORD:-replicator}# used by pg_basebackupREPLICA_DELAY:${REPLICA_DELAY:-0}# e.g. 2s: artificial lagports:-"5433:5432"volumes:-replica-data:/var/lib/postgresql/data-./infra/postgres/replica-entrypoint.sh:/usr/local/bin/replica-entrypoint.sh:rodepends_on:db:condition:service_healthyhealthcheck:test:["CMD-SHELL","pg_isready-Uboxoffice-dboxoffice"]interval:5stimeout:3sretries:20pgbouncer:image:edoburu/pgbouncer:v1.26.0-p0ports:-"6432:6432"volumes:-./infra/pgbouncer/pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini:ro-./infra/pgbouncer/userlist.txt:/etc/pgbouncer/userlist.txt:rodepends_on:db:condition:service_healthyredis:image:redis:8-alpine# a pure cache: bounded memory, evict least-recently-used keys, no persistencecommand:["redis-server","--maxmemory","256mb","--maxmemory-policy","allkeys-lru","--save","","--appendonly","no"]ports:-"6379:6379"healthcheck:test:["CMD","redis-cli","ping"]interval:5stimeout:3sretries:10# three identical replicas; no "ports:" — only the edge is reachable from outsidecatalog-1:<<:*cataloghostname:catalog-1catalog-2:<<:*cataloghostname:catalog-2catalog-3:<<:*cataloghostname:catalog-3inventory:build:./services/inventoryvolumes:-./infra/otel:/otel:roenvironment:<<:*otelOTEL_SERVICE_NAME:inventoryDB_HOST:${INVENTORY_DB_HOST:-pgbouncer}# writes go through PgBouncer...DB_PORT:${INVENTORY_DB_PORT:-6432}DB_MIGRATION_HOST:db# ...migrations straight to the primaryDB_REPLICA_HOST:${DB_REPLICA_HOST:-db-replica}DB_REPLICA_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}DB_POOL_SIZE:${INVENTORY_POOL_SIZE:-20}INVENTORY_LOCKING:${INVENTORY_LOCKING:-pessimistic}INVENTORY_HOLD_TTL:${INVENTORY_HOLD_TTL:-PT10M}ports:-"8083:8083"# published for experiments; clients go through the edgedepends_on:db:condition:service_healthydb-replica:condition:service_healthypgbouncer:condition:service_starteddeploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8083/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120sretries:3auth:build:./services/authvolumes:-./infra/otel:/otel:roenvironment:<<:*otelOTEL_SERVICE_NAME:authDB_HOST:dbDB_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}JWT_ISSUER:${JWT_ISSUER:-boxoffice-auth}JWT_TTL:${JWT_TTL:-PT1H}ADMIN_EMAIL:${ADMIN_EMAIL:-admin@boxoffice.dev}ADMIN_PASSWORD:${ADMIN_PASSWORD:-boxoffice-admin}depends_on:db:condition:service_healthydeploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8081/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120sretries:3gateway:build:./services/gatewayvolumes:-./infra/otel:/otel:roenvironment:<<:*otelOTEL_SERVICE_NAME:gatewayAUTH_URL:http://auth:8081INVENTORY_URL:http://inventory:8083AUTH_JWKS_URI:http://auth:8081/auth/.well-known/jwks.jsonJWT_ISSUER:${JWT_ISSUER:-boxoffice-auth}ports:-"8080:8080"# published for experiments; clients use the edge (port 80)depends_on:-auth-inventory-catalog-1-catalog-2-catalog-3deploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8080/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120sretries:3edge:image:nginx:1.30-alpineports:-"80:80"volumes:-./infra/nginx/nginx.conf:/etc/nginx/nginx.conf:rodepends_on:-gateway# ---- lab 7: Kafka (KRaft), Kafka UI, Mailpit, order and notification ----kafka:image:apache/kafka:4.3.1hostname:kafkaports:-"9094:9094"environment:KAFKA_NODE_ID:1KAFKA_PROCESS_ROLES:broker,controllerKAFKA_CONTROLLER_QUORUM_VOTERS:1@kafka:9093KAFKA_LISTENERS:PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094KAFKA_ADVERTISED_LISTENERS:PLAINTEXT://kafka:9092,EXTERNAL://localhost:9094KAFKA_LISTENER_SECURITY_PROTOCOL_MAP:PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXTKAFKA_CONTROLLER_LISTENER_NAMES:CONTROLLERKAFKA_INTER_BROKER_LISTENER_NAME:PLAINTEXTKAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR:1KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR:1KAFKA_TRANSACTION_STATE_LOG_MIN_ISR:1KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS:0KAFKA_AUTO_CREATE_TOPICS_ENABLE:"false"healthcheck:test:["CMD-SHELL","/opt/kafka/bin/kafka-broker-api-versions.sh--bootstrap-serverlocalhost:9092>/dev/null2>&1"]interval:10stimeout:10sstart_period:60s# a busy laptop can take a minute to start the brokerretries:20kafka-init:image:apache/kafka:4.3.1depends_on:kafka:condition:service_healthyentrypoint:["/bin/sh","-c"]command:-|/opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka:9092 --create --if-not-exists \--topic order-events --partitions 6 --replication-factor 1 &&/opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka:9092 --create --if-not-exists \--topic order-events-dlt --partitions 6 --replication-factor 1restart:"no"kafka-ui:image:kafbat/kafka-ui:v1.5.0depends_on:kafka:condition:service_healthyports:-"8089:8080"environment:KAFKA_CLUSTERS_0_NAME:boxofficeKAFKA_CLUSTERS_0_BOOTSTRAPSERVERS:kafka:9092mailpit:image:axllent/mailpit:v1.31ports:-"8025:8025"-"1025:1025"order:build:./services/ordervolumes:-./infra/otel:/otel:roenvironment:<<:*otelOTEL_SERVICE_NAME:orderDB_HOST:dbDB_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}REDIS_HOST:redisKAFKA_BOOTSTRAP_SERVERS:kafka:9092NOTIFICATION_URL:http://notification:8086PAYMENT_URL:http://toxiproxy:18085# lab 9: through Toxiproxy, not payment:8085PAYMENT_RESILIENCE:${PAYMENT_RESILIENCE:-true}PAYMENT_READ_TIMEOUT:${PAYMENT_READ_TIMEOUT:-1s}PAYMENT_RETRY_ATTEMPTS:${PAYMENT_RETRY_ATTEMPTS:-3}PAYMENT_BULKHEAD:${PAYMENT_BULKHEAD:-10}NOTIFY_MODE:${NOTIFY_MODE:-outbox}# outbox (after) | sync (before)ADMIT_PER_SECOND:${ADMIT_PER_SECOND:-20}# waiting-room admission rateports:-"8084:8084"depends_on:db:condition:service_healthyredis:condition:service_healthykafka-init:condition:service_completed_successfullydeploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8084/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120sretries:3notification:build:./services/notificationvolumes:-./infra/otel:/otel:roenvironment:<<:*otelOTEL_SERVICE_NAME:notificationDB_HOST:dbDB_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}KAFKA_BOOTSTRAP_SERVERS:kafka:9092MAIL_HOST:mailpitNOTIFY_CONCURRENCY:${NOTIFY_CONCURRENCY:-3}# consumer threads (max useful: 6 partitions)EMAIL_LATENCY:${EMAIL_LATENCY:-50ms}# simulated e-mail provider latencyNOTIFY_IDEMPOTENT:${NOTIFY_IDEMPOTENT:-true}# false = no dedupe (to see duplicates)ports:-"8086:8086"depends_on:db:condition:service_healthymailpit:condition:service_startedkafka-init:condition:service_completed_successfullydeploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8086/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120sretries:3# ---- lab 8: observability backend (Grafana, Prometheus, Tempo, Loki, OTel Collector) ----otel-lgtm:image:grafana/otel-lgtm:0.37.0ports:-"3000:3000"# Grafana (no login)-"4317:4317"# OTLP gRPC-"4318:4318"# OTLP HTTPvolumes:-./infra/grafana/dashboards.yaml:/otel-lgtm/grafana/conf/provisioning/dashboards/boxoffice.yaml:ro-./infra/grafana/dashboards:/otel-lgtm/boxoffice-dashboards:ro-./infra/grafana/alerting:/otel-lgtm/grafana/conf/provisioning/alerting:ro# ---- lab 9: payment adapter, fake provider and fault injection ----psp:image:wiremock/wiremock:3.13.2volumes:-./infra/psp:/home/wiremock:rotoxiproxy:image:ghcr.io/shopify/toxiproxy:2.13.0command:["-host=0.0.0.0","-config=/config/toxiproxy.json"]volumes:-./infra/toxiproxy/toxiproxy.json:/config/toxiproxy.json:roports:-"8474:8474"payment:build:./services/paymentvolumes:-./infra/otel:/otel:roenvironment:<<:*otelOTEL_SERVICE_NAME:paymentDB_HOST:dbDB_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}PSP_URL:http://toxiproxy:18095# the provider, through ToxiproxyPSP_PROVIDER:${PSP_PROVIDER:-fake}# lab 14: fake (lab 9) | stripe (the sandbox)STRIPE_SECRET_KEY:${STRIPE_SECRET_KEY:-}# sk_test_…: from your shell or .env, never committedSTRIPE_WEBHOOK_SECRET:${STRIPE_WEBHOOK_SECRET:-}STRIPE_CURRENCY:${STRIPE_CURRENCY:-brl}ports:-"8085:8085"depends_on:db:condition:service_healthytoxiproxy:condition:service_startedpsp:condition:service_starteddeploy:resources:limits:cpus:"1.0"memory:768Mhealthcheck:test:["CMD-SHELL","wget-qO-http://localhost:8085/actuator/health/readiness||exit1"]interval:10stimeout:3sstart_period:120sretries:3# ---- lab 12: AI assistant (FastAPI + LiteLLM + pgvector) and a local LLM ----stripe-cli:# lab 14: forwards the sandbox's webhooks to paymentimage:stripe/stripe-cli:v1.55.11profiles:["stripe"]# only with --profile stripeenvironment:STRIPE_API_KEY:${STRIPE_SECRET_KEY:-}# the CLI reads its key from STRIPE_API_KEYcommand:["listen","--events","payment_intent.succeeded,payment_intent.payment_failed","--forward-to","http://payment:8085/webhooks/stripe"]depends_on:payment:condition:service_healthyollama:image:ollama/ollama:0.40.6ports:-"11434:11434"volumes:-ollama-models:/root/.ollama# models survive restarts (about 1.3 GB)healthcheck:# ollama-init must wait for the server, not just the containertest:["CMD","ollama","list"]interval:5stimeout:5sretries:12# one-shot: download the chat model and the embedding model, then exitollama-init:image:ollama/ollama:0.40.6environment:OLLAMA_HOST:ollama:11434entrypoint:["/bin/sh","-c"]command:-|ollama pull ${LOCAL_MODEL_TAG:-qwen2.5:1.5b} && ollama pull nomic-embed-textdepends_on:ollama:condition:service_healthyrestart:"no"assistant:build:./services/assistantenvironment:DB_HOST:dbDB_PORT:5432DB_NAME:${DB_NAME:-boxoffice}DB_USER:${DB_USER:-boxoffice}DB_PASSWORD:${DB_PASSWORD:-boxoffice}OLLAMA_URL:${OLLAMA_URL:-http://ollama:11434}# macOS: http://host.docker.internal:11434 (native Ollama)LOCAL_MODEL:ollama_chat/${LOCAL_MODEL_TAG:-qwen2.5:1.5b}CATALOG_URL:http://gateway:8080# GET /catalog/** is public at the gatewayORDER_URL:http://order:8084ANTHROPIC_API_KEY:${ANTHROPIC_API_KEY:-}# optional: empty = local model onlyOTEL_SERVICE_NAME:assistantOTEL_EXPORTER_OTLP_ENDPOINT:http://otel-lgtm:4318OTEL_METRIC_EXPORT_INTERVAL:"10000"OTEL_RESOURCE_ATTRIBUTES:service.namespace=boxoffice,deployment.environment.name=localports:-"8088:8088"extra_hosts:-"host.docker.internal:host-gateway"# reach a native Ollama on the hostdepends_on:db:condition:service_healthydeploy:resources:limits:cpus:"1.0"memory:1Ghealthcheck:test:["CMD","python","-c","importurllib.request;urllib.request.urlopen('http://localhost:8088/assistant/health')"]interval:10stimeout:5sstart_period:30sretries:3volumes:db-data:replica-data:ollama-models:
Suba o payment com o provedor Stripe (o .env define PSP_PROVIDER=stripe) e cobre direto nele, como no lab 9:
Você deve ver 201 e "status":"AUTHORIZED","providerRef":"pi_…". No Dashboard (Payments), um pagamento de R$ 350,00 mostra os metadados order_id e idempotency_key. Depois:
O mesmo pedido de novo: 200, o mesmo id e o mesmo providerRef — e ainda um único pagamento no Dashboard.
Um cartão recusado, com uma chave nova: acrescente "paymentMethod":"pm_card_visa_chargeDeclined" ao corpo e use Idempotency-Key: sandbox-2. Você deve ver 201 com "status":"DECLINED"; pm_card_visa_chargeDeclinedInsufficientFunds também recusa, por outro motivo (os dois são meios de pagamento de teste da Stripe).
De ponta a ponta, pelo order e pelo Toxiproxy, como no lab 9:
Você deve ver "status":"CONFIRMED". Se o primeiro pay responder 503, a Stripe demorou mais que o read timeout de 1 s do order: o payment terminou mesmo assim e gravou a cobrança, então chamar pay de novo confirma o pedido com o mesmo PaymentIntent — a resposta perdida do passo 5, por acidente.
4. Webhooks: o provedor conta depois
Uma resposta síncrona pode se perder; a Stripe também chama você de volta com um evento a cada mudança de um PaymentIntent. No sandbox, os eventos são reenviados três vezes em poucas horas se o seu endpoint não responder 2xx; o mesmo evento pode chegar mais de uma vez e os eventos podem chegar fora de ordem. Por isso o endpoint precisa: provar que a chamada vem da Stripe, processar cada evento uma vez e responder rápido.
packageboxoffice.payment;importjava.time.Clock;importjava.time.Duration;importjava.util.Map;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;importorg.springframework.http.ResponseEntity;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestHeader;importorg.springframework.web.bind.annotation.RestController;importtools.jackson.databind.ObjectMapper;/** Stripe tells us what happened, later and maybe twice: the webhook is the source of truth. */@RestController@ConditionalOnProperty(name="boxoffice.psp.provider",havingValue="stripe")publicclassStripeWebhookController{privatestaticfinalLoggerlog=LoggerFactory.getLogger(StripeWebhookController.class);recordEvent(Stringid,Stringtype,Datadata){recordData(Intentobject){}recordIntent(Stringid,Stringstatus,longamount,Map<String,String>metadata){}}privatefinalPaymentServicepayments;privatefinalObjectMapperjson;privatefinalStringsecret;privatefinalDurationtolerance;privatefinalClockclock=Clock.systemUTC();publicStripeWebhookController(PaymentServicepayments,ObjectMapperjson,@Value("${boxoffice.stripe.webhook-secret}")Stringsecret,@Value("${boxoffice.stripe.tolerance}")Durationtolerance){this.payments=payments;this.json=json;this.secret=secret;this.tolerance=tolerance;}/** The raw body, as a String: the signature is computed over the exact bytes Stripe sent. */@PostMapping("/webhooks/stripe")publicResponseEntity<String>receive(@RequestBodyStringbody,@RequestHeader(value="Stripe-Signature",required=false)Stringsignature){if(!StripeSignature.valid(body,signature,secret,tolerance,clock)){log.warn("webhook rejected: bad or missing Stripe-Signature");returnResponseEntity.badRequest().body("bad signature");}Eventevent=json.readValue(body,Event.class);Stringstatus=switch(event.type()){case"payment_intent.succeeded"->"AUTHORIZED";case"payment_intent.payment_failed"->"DECLINED";default->null;// other events: acknowledged, ignored};if(status==null){returnResponseEntity.ok("ignored");}Event.Intentintent=event.data().object();booleanapplied=payments.applyWebhook(event.id(),event.type(),intent.id(),status,intent.amount(),intent.metadata());log.info("webhook {} {} {} → {}",event.id(),event.type(),intent.id(),applied?status:"duplicate, skipped");returnResponseEntity.ok(applied?"applied":"duplicate");// 2xx quickly, or Stripe retries}}
packageboxoffice.payment;importjava.nio.charset.StandardCharsets;importjava.security.MessageDigest;importjava.time.Clock;importjava.time.Duration;importjava.util.HexFormat;importjavax.crypto.Mac;importjavax.crypto.spec.SecretKeySpec;/** * Checks the Stripe-Signature header of a webhook: t=<unix time>,v1=<hex HMAC-SHA256 of "t.body">. * Without it, anyone who finds the URL can post "payment succeeded". */publicfinalclassStripeSignature{privateStripeSignature(){}publicstaticbooleanvalid(Stringbody,Stringheader,Stringsecret,Durationtolerance,Clockclock){if(header==null||secret==null||secret.isBlank()){returnfalse;}Stringtimestamp=null;Stringexpected=null;for(Stringpart:header.split(",")){String[]kv=part.split("=",2);if(kv.length==2&&kv[0].equals("t")){timestamp=kv[1];}elseif(kv.length==2&&kv[0].equals("v1")&&expected==null){expected=kv[1];}}if(timestamp==null||expected==null){returnfalse;}longage=clock.instant().getEpochSecond()-Long.parseLong(timestamp);if(Math.abs(age)>tolerance.toSeconds()){returnfalse;// an old, replayed request: even with a correct signature}Stringcomputed=hmacSha256Hex(secret,timestamp+"."+body);// constant-time comparison: do not leak, byte by byte, how much of the signature matchedreturnMessageDigest.isEqual(computed.getBytes(StandardCharsets.UTF_8),expected.getBytes(StandardCharsets.UTF_8));}staticStringhmacSha256Hex(Stringsecret,Stringpayload){try{Macmac=Mac.getInstance("HmacSHA256");mac.init(newSecretKeySpec(secret.getBytes(StandardCharsets.UTF_8),"HmacSHA256"));returnHexFormat.of().formatHex(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));}catch(Exceptione){thrownewIllegalStateException(e);}}}
packageboxoffice.payment;importjava.math.BigDecimal;importjava.util.List;importjava.util.Map;importjava.util.Optional;importjava.util.UUID;importorg.springframework.jdbc.core.simple.JdbcClient;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;@ServicepublicclassPaymentService{publicrecordResult(PaymentOutpayment,booleancreated){}privatefinalJdbcClientjdbc;privatefinalPsppsp;publicPaymentService(JdbcClientjdbc,Psppsp){this.jdbc=jdbc;this.psp=psp;}publicResultcharge(StringidempotencyKey,ChargeRequestreq){Optional<PaymentOut>done=find(idempotencyKey);if(done.isPresent()){returnnewResult(done.get(),false);// a retry: answer, do not charge again}// remote call OUTSIDE any database transaction: never hold a connection while waitingPsp.Chargecharge=psp.charge(idempotencyKey,req.amount(),req.orderId(),req.paymentMethod());Stringstatus=charge.approved()?"AUTHORIZED":"DECLINED";jdbc.sql(""" INSERT INTO payments (id, idempotency_key, order_id, amount, status, provider_ref) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING """).params(UUID.randomUUID(),idempotencyKey,req.orderId(),req.amount(),status,charge.id()).update();returnnewResult(find(idempotencyKey).orElseThrow(),true);}/** * Applies a webhook once per event id. Updates the payment of that PaymentIntent, or creates it when * the charge went through but its answer never arrived (the caller timed out): the gap the webhook heals. * Returns false for a duplicate delivery. */@TransactionalpublicbooleanapplyWebhook(StringeventId,Stringtype,StringintentId,Stringstatus,longamountInCents,Map<String,String>metadata){intfresh=jdbc.sql("INSERT INTO stripe_events (id, type) VALUES (?, ?) ON CONFLICT DO NOTHING").params(eventId,type).update();if(fresh==0){returnfalse;// already processed: Stripe delivers at least once}intupdated=jdbc.sql("UPDATE payments SET status = ? WHERE provider_ref = ?").params(status,intentId).update();if(updated==0&&metadata!=null&&metadata.containsKey("idempotency_key")){jdbc.sql(""" INSERT INTO payments (id, idempotency_key, order_id, amount, status, provider_ref) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING """).params(UUID.randomUUID(),metadata.get("idempotency_key"),UUID.fromString(metadata.get("order_id")),BigDecimal.valueOf(amountInCents).movePointLeft(2),status,intentId).update();}returntrue;}/** The payments of the last hours, with their provider reference: what reconciliation checks. */publicList<PaymentOut>since(java.time.Durationwindow){returnjdbc.sql(""" SELECT id, order_id, amount, status, provider_ref, created_at FROM payments WHERE created_at > now() - make_interval(secs => ?) ORDER BY created_at """).param(window.toSeconds()).query(PaymentOut.class).list();}privateOptional<PaymentOut>find(StringidempotencyKey){returnjdbc.sql(""" SELECT id, order_id, amount, status, provider_ref, created_at FROM payments WHERE idempotency_key = ? """).param(idempotencyKey).query(PaymentOut.class).optional();}}
-- every webhook event processed once: Stripe may deliver the same event more than onceCREATETABLEstripe_events(idVARCHAR(100)PRIMARYKEY,-- evt_…typeVARCHAR(100)NOTNULL,received_atTIMESTAMPTZNOTNULLDEFAULTnow());-- the provider's PaymentIntent id is how a webhook finds its paymentCREATEUNIQUEINDEXpayments_provider_refONpayments(provider_ref);
packageboxoffice.payment;import staticorg.junit.jupiter.api.Assertions.assertFalse;import staticorg.junit.jupiter.api.Assertions.assertTrue;importjava.time.Clock;importjava.time.Duration;importjava.time.Instant;importjava.time.ZoneOffset;importorg.junit.jupiter.api.Test;classStripeSignatureTest{staticfinalStringSECRET="whsec_test_secret";staticfinalStringBODY="{\"id\":\"evt_1\",\"type\":\"payment_intent.succeeded\"}";staticfinallongT=1_800_000_000L;staticfinalClockNOW=Clock.fixed(Instant.ofEpochSecond(T+10),ZoneOffset.UTC);staticfinalDurationTOLERANCE=Duration.ofSeconds(300);staticStringheader(longt,Stringbody,Stringsecret){return"t="+t+",v1="+StripeSignature.hmacSha256Hex(secret,t+"."+body);}@TestvoidacceptsTheSignatureStripeComputes(){assertTrue(StripeSignature.valid(BODY,header(T,BODY,SECRET),SECRET,TOLERANCE,NOW));}@TestvoidrejectsAnEditedBody(){assertFalse(StripeSignature.valid(BODY.replace("succeeded","failed"),header(T,BODY,SECRET),SECRET,TOLERANCE,NOW));}@TestvoidrejectsAnotherSecret(){assertFalse(StripeSignature.valid(BODY,header(T,BODY,"whsec_other"),SECRET,TOLERANCE,NOW));}@TestvoidrejectsAnOldSignature(){longold=T-600;// ten minutes before NOW: a replayed requestassertFalse(StripeSignature.valid(BODY,header(old,BODY,SECRET),SECRET,TOLERANCE,NOW));}@TestvoidrejectsAMissingHeader(){assertFalse(StripeSignature.valid(BODY,null,SECRET,TOLERANCE,NOW));}}
A assinatura.Stripe-Signature: t=<unix time>,v1=<hex>, em que v1 é o HMAC-SHA256 (um código de autenticação de mensagem baseado em hash, HMAC, hash-based message authentication code: um hash SHA-256 com a chave secreta do endpoint) de <t>.<corpo bruto>. O controller lê o corpo como String — interpretar primeiro e serializar de novo mudaria os bytes —, compara em tempo constante e recusa um timestamp com mais de 5 minutos, para que uma requisição capturada não possa ser repetida depois.
Uma vez por evento. A tabela stripe_events tem o id do evento como chave primária; INSERT … ON CONFLICT DO NOTHING devolve 0 para uma repetição, que é confirmada e pulada.
O webhook cura. Se nenhum pagamento tem aquele PaymentIntent — a cobrança passou, mas a resposta nunca chegou ao banco —, os metadados o recriam, com a mesma chave de idempotência. O próximo pay daquele pedido o encontra.
Encaminhe os eventos do sandbox ao payment. A interface de linha de comando (CLI, command-line interface) da Stripe abre uma conexão com a Stripe e encaminha os eventos a uma URL local — sem endereço público. Pegue o segredo de assinatura dela (ele não muda entre execuções), coloque-o no .env, reinicie o payment e suba o encaminhador:
dockercomposerun--rm--no-depsstripe-clilisten--print-secret# prints whsec_…echo"STRIPE_WEBHOOK_SECRET=whsec_...">>.env# paste the value it printeddockercomposeup-d--waitpayment
dockercompose--profilestripeup-dstripe-cli
dockercomposelogsstripe-cli|grep-iready
Você deve ver Ready! … Your webhook signing secret is whsec_… (o mesmo valor). Pague outro pedido (passo 3) e acompanhe os logs:
dockercomposelogs-fpayment|grepwebhook
Você deve ver webhook evt_… payment_intent.succeeded pi_… → AUTHORIZED, um instante depois de o pay responder: o evento confirma o que a resposta síncrona disse.
Uma repetição e uma falsificação. O scripts/send-webhook.sh assina um evento do jeito que a Stripe assina, com o segredo do .env:
#!/usr/bin/env bash# Sends a webhook event to payment, signed the way Stripe signs it (lab 14, section 4):# Stripe-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>" with the webhook secret>.# scripts/send-webhook.sh event.json # secret: STRIPE_WEBHOOK_SECRET from .env# scripts/send-webhook.sh event.json whsec_x # another secret: payment must answer 400set-euopipefail
body=$(cat"$1")secret=${2:-$(grep'^STRIPE_WEBHOOK_SECRET='.env|cut-d=-f2-)}t=$(date+%s)sig=$(printf'%s.%s'"$t""$body"|openssldgst-sha256-hmac"$secret"-hex|sed's/^.* //')curl-s-w' %{http_code}\n'-XPOSTlocalhost:8085/webhooks/stripe\-H'Content-Type: application/json'-H"Stripe-Signature: t=$t,v1=$sig"--data-binary"$body"
cat>/tmp/evt.json<<EOF{"id":"evt_sandbox_1","type":"payment_intent.succeeded","data":{"object":{"id":"pi_sandbox_1","status":"succeeded","amount":35000,"metadata":{"order_id":"5b0c2f9e-7d0a-4f43-9a55-1c1c2c8f8e11","idempotency_key":"sandbox-replay"}}}}EOFbashscripts/send-webhook.sh/tmp/evt.json# applied 200bashscripts/send-webhook.sh/tmp/evt.json# duplicate 200bashscripts/send-webhook.sh/tmp/evt.jsonwhsec_wrong# bad signature 400
A primeira chamada grava um pagamento que o payment nunca cobrou — exatamente o que o passo 5 precisa de um evento real. A segunda é pulada, a terceira recusada (e registrada como webhook rejected).
5. A resposta perdida: cobrado, mas ninguém sabe
O pior caso do lab 9: a Stripe cobrou e o payment caiu antes de gravar — ou o order estourou o timeout em todas as tentativas. Para o fã, o checkout é UNKNOWN; para o provedor, o dinheiro se moveu. Reproduza: crie um pedido e mande à Stripe exatamente o pedido que o payment manda, à mão, como se o payment tivesse morrido logo depois:
Você deve ver "status": "succeeded": o fã foi cobrado e o BoxOffice não tem registro. Depois:
docker compose logs payment | grep webhook | tail -1 — o evento chegou e o paymentcriou o pagamento a partir dos metadados.
curl -s -X POST localhost:8084/orders/$ID/pay | jq '{id, status}' — o fã (ou um retry) paga de novo: CONFIRMED. O payment achou o pagamento pela chave order-<id> e não chamou a Stripe; se tivesse chamado, a Stripe repetiria o mesmo PaymentIntent para aquela chave.
No Dashboard, procure o id do pedido nos metadados: um pagamento.
O simulador mostra o tamanho do problema com o cliente do lab 9 e um provedor lento:
Experimente
Com o cliente do lab 9 (read timeout de 1 s, 3 tentativas) contra um provedor lento, 40,2% das chamadas estouram o timeout. Uma chave por pedido (a order-<orderId> do lab 9) mantém 1.000 cobranças para 1.000 fãs — 0 duplicadas —, mas 133 checkouts terminam UNKNOWN, cada um cobrado uma vez: é isso que o webhook e a reconciliação deste lab resolvem. Troque a chave para "nenhuma": 392 fãs pagam duas vezes ou mais.
6. Reconcilie: o provedor é a fonte da verdade
Webhooks podem se perder (um endpoint fora do ar por mais de algumas horas, um bug que respondeu 200 e não fez nada). Uma reconciliação periódica compara cada pagamento recente com o PaymentIntent do provedor:
packageboxoffice.payment;importjava.time.Duration;importjava.util.ArrayList;importjava.util.List;importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;importorg.springframework.web.client.HttpClientErrorException;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;/** Compares our payments with Stripe's PaymentIntents: what the provider says wins. */@RestController@ConditionalOnProperty(name="boxoffice.psp.provider",havingValue="stripe")publicclassReconciliation{recordMismatch(StringproviderRef,Stringours,Stringstripe){}recordReport(intchecked,List<Mismatch>mismatches){}privatefinalPaymentServicepayments;privatefinalStripePspstripe;publicReconciliation(PaymentServicepayments,StripePspstripe){this.payments=payments;this.stripe=stripe;}@GetMapping("/payments/reconcile")publicReportreconcile(@RequestParam(defaultValue="PT1H")Durationwindow){List<PaymentOut>ours=payments.since(window);List<Mismatch>mismatches=newArrayList<>();for(PaymentOutp:ours){if(p.providerRef()==null||!p.providerRef().startsWith("pi_")){continue;// not a Stripe payment (lab 9's fake provider)}Stringtheirs;try{theirs=stripe.retrieve(p.providerRef()).status();}catch(HttpClientErrorException.NotFounde){theirs="missing";// a payment Stripe never made: the worst mismatch}Stringexpected=switch(theirs){case"succeeded"->"AUTHORIZED";case"requires_payment_method","canceled"->"DECLINED";default->null;// processing, requires_action, missing…: always worth a look};if(!p.status().equals(expected)){mismatches.add(newMismatch(p.providerRef(),p.status(),theirs));}}returnnewReport(ours.size(),mismatches);}}
Você deve ver checked contando os seus pagamentos Stripe das últimas duas horas (as referências falsas ch_… do lab 9 são puladas) e uma divergência: {"providerRef": "pi_sandbox_1", "ours": "AUTHORIZED", "stripe": "missing"} — o evento que você mesmo assinou no passo 4 registrou um pagamento que a Stripe nunca fez. É o pior tipo de divergência (um ingresso vendido por nada) e o motivo de a reconciliação existir. Remova-o, depois quebre um de verdade, de propósito, e encontre-o:
dockercomposeexecdbpsql-Uboxoffice-dboxoffice-c"DELETE FROM payment.payments WHERE provider_ref = 'pi_sandbox_1'"curl-s'localhost:8085/payments/reconcile?window=PT2H'|jq'.mismatches'# []dockercomposeexecdbpsql-Uboxoffice-dboxoffice-c\"UPDATE payment.payments SET status = 'DECLINED' WHERE id = (SELECT id FROM payment.payments WHERE status = 'AUTHORIZED' AND provider_ref LIKE 'pi_%' LIMIT 1)"curl-s'localhost:8085/payments/reconcile?window=PT2H'|jq'.mismatches'
Você deve ver uma divergência: "ours": "DECLINED", "stripe": "succeeded" — um fã que pagou e cujo pedido o BoxOffice teria cancelado. Em produção, esse relatório roda num agendamento e cada divergência vira um alerta ou uma correção automática (confirmar o pedido ou estornar).
Custos e limites do sandbox
O sandbox tem limites de taxa menores que o modo de produção e guarda os dados de teste até você apagá-los (Developers → … → Delete all test data). O GET /payments/reconcile faz uma chamada à Stripe por pagamento: tudo bem para um lab; para volumes reais, um job com paginação (GET /v1/payment_intents?created[gte]=…).
7. Pix com o Mercado Pago
A interface Psp é a junta para qualquer provedor. O Mercado Pago é a escolha comum no Brasil para o Pix e o Pix muda uma coisa no fluxo: a resposta a "cobrar" não é "pago" — é um QR code. O fã paga depois, no app do banco, e só o webhook diz que o dinheiro chegou. O que é uma rede de segurança com os cartões da Stripe vira o caminho principal.
Stripe (este lab)
Mercado Pago, Pix
Sandbox
chaves de modo de teste sk_test_…
credenciais de teste (access token de teste) do painel de desenvolvedor
Criar
POST /v1/payment_intents, confirm=true
POST /v1/orders (Orders API), o meio de pagamento Pix em transactions.payments
Idempotência
header Idempotency-Key
header X-Idempotency-Key (obrigatório)
Primeira resposta
succeeded ou uma recusa 402
pendente, com um QR code (qr_code, qr_code_base64) para mostrar ao fã
notificação com um header x-signature (ts=…,v1=…), verificada com o segredo da Configuração de Webhooks (o kit de desenvolvimento oficial, SDK, software development kit, implementa a checagem HMAC)
Resultados de teste
meios de pagamento de teste (pm_card_visa…)
cartões de teste cujo nome do titular escolhe o resultado (APRO aprovado, OTHE erro, CONT pendente, FUND saldo insuficiente), Cadastro de Pessoa Física (CPF) 12345678909
Um MercadoPagoPsp devolveria Charge(id, false) com um estado novo — "pendente" — que o order precisa mostrar como "aguardando pagamento" e o webhook levaria o pagamento a AUTHORIZED. Confira a documentação de desenvolvedores do Mercado Pago atual antes de escrevê-lo: os nomes dos campos da Orders API diferem dos da Payments API, mais antiga.
Boas práticas neste lab
Mantenha o provedor atrás de uma interface — Psp com PspClient e StripePsp; o order nunca sabe qual deles cobrou (Compute — integrações externas).
Uma chave de idempotência por pedido, de ponta a ponta — order-<orderId> do order, a coluna única de payments e a Idempotency-Key da Stripe são o mesmo valor, então nenhum retry, em lugar nenhum, cobra duas vezes (Sistemas Distribuídos).
Trate uma recusa como resposta, não como falha — o StripePsp mapeia o 402 para DECLINED; só as falhas reais chegam ao retry e ao breaker do lab 9 (Padrões de confiabilidade).
Verifique todo webhook, processe cada evento uma vez — StripeSignature (HMAC, tempo constante, tolerância de 5 minutos) e a tabela stripe_events (Rede e Segurança).
Reconcilie com a fonte da verdade — a Reconciliation encontra o que os webhooks perderam; dinheiro precisa de uma segunda conferência, não de confiança (Observabilidade).
Segredos vindos do ambiente, só chaves de teste — .env ignorado pelo Git, sk_test_ exigido na subida.
Solução de problemas
Sintoma
Causa
Correção
o payment sai: STRIPE_SECRET_KEY must be a test key (sk_test_…)
PSP_PROVIDER=stripe com uma chave vazia ou de produção
coloque a chave sk_test_… no .env ou remova PSP_PROVIDER para voltar ao falso
500 e Stripe answered 401: Invalid API Key provided nos logs
a chave foi copiada errada ou trocada
copie-a de novo em Developers → API keys
Stripe answered 400 falando da moeda
o país da sua conta não aceita cobranças em BRL
acrescente STRIPE_CURRENCY=usd ao .env e reinicie o payment
Stripe answered 400 sobre idempotência
a mesma Idempotency-Key enviada com outros parâmetros (outro valor ou cartão)
use uma chave nova para um pedido novo; uma chave significa "este pedido exato"
os webhooks respondem 400 bad signature
o STRIPE_WEBHOOK_SECRET difere do que listen --print-secret imprime ou o payment não foi reiniciado depois de editar o .env
corrija o .env e rode docker compose up -d --wait payment
nenhuma linha webhook nos logs
o stripe-cli não está rodando (ele tem um profile)
Todo checkout agora é cobrado uma vez e toda cobrança é conhecida — mas saber não é consertar. A divergência da reconciliação é um fã que pagou por um pedido que o BoxOffice cancelou: isso pede um estorno (POST /v1/refunds) ou uma confirmação tardia, decididos por um job, não à mão. Cartões que pedem 3-D Secure precisam do navegador do fã (Stripe.js), o que significa um front end e um estado requires_action que o servidor sozinho não termina. O Pix torna "pendente" o caso normal, então o order precisa aprender um terceiro estado. E dinheiro de verdade significa chaves de produção, uma empresa verificada e as regras de dados de cartão do Padrão de Segurança de Dados da Indústria de Cartões de Pagamento (PCI DSS, Payment Card Industry Data Security Standard) — mantidas pequenas justamente porque números de cartão nunca tocam o BoxOffice. Se tudo isso ainda se sustenta às 10:00, com 2 milhões de fãs, é a pergunta da aula 15 — Engenharia de Desempenho e do seu projeto.