Customer Creation During Payment β Reference
Flow decisions, component behavior, state transitions, events, validation, and test coverage for the V2 customer creation path. See the overview for the lifecycle.
Flow Type Decision Matrixβ
PaymentFlowType | Customer not found | Customer service rejects request (4xx/5xx) | Customer found |
|---|---|---|---|
USER_INITIATED_PAYMENT | Park β PENDING_FOR_CUSTOMER_CREATION | FAILED (async, event published) | Enrich transaction and continue |
MERCHANT_INITIATED_PAYMENT | Synchronous find-or-create via CustomerClient.createCustomer(). If create also fails β FAILED (async) | FAILED (async, event published) | Enrich and continue |
GUEST_PAYMENT | Customer lookup skipped entirely | N/A | N/A |
Pre-validation failures (missing required fields already in the transaction) are also FAILED with UNPROCESSABLE_ENTITY:
| Scenario | PaymentFlowType | Missing field | Result |
|---|---|---|---|
customerId null | USER_INITIATED_PAYMENT | transaction.customerId | FAILED, UNPROCESSABLE_ENTITY 422 via polling |
customer object null | MERCHANT_INITIATED_PAYMENT | txn_details.customer | FAILED, UNPROCESSABLE_ENTITY 422 via polling |
Component Breakdownβ
1. CustomerCheckCommand β Post-Processing Commandβ
CustomerCheckCommand is a post-processing command (isPreProcessingCommand() = false). This is the central design principle: the transaction is persisted and 202 Accepted is returned to the caller before the customer check runs. All customer-related failures are surfaced asynchronously.
Making this post-processing ensures the V2 contract is preserved: POST /v2/payments is always 202 Accepted, and errors are discovered through GET /v2/payments polling or the PAYMENT_UPDATED webhook. A pre-processing command would surface customer failures synchronously (HTTP 422), which violates this contract.
This was the root cause of CC-12883: isPreProcessingCommand() was incorrectly returning true, causing customer-service 422s (e.g. invalid metadata keys) to be returned synchronously.
@Override
public boolean isPreProcessingCommand() {
return false; // Post-processing: runs after 202 is returned to the caller
}
@Override
public Mono<Map<String, Object>> execute(Map<String, Object> context, Transaction transaction) {
PaymentFlowType flowType = transaction.getTxn_details().getPaymentFlowType();
// Guest payments skip customer lookup entirely
if (PaymentFlowType.GUEST_PAYMENT.equals(flowType)) {
context.put(CUSTOMER_EXISTS_KEY, false);
return Mono.just(context);
}
// Non-guest flows require a customer object in the request
if (transaction.getTxn_details().getCustomer() == null) {
return Mono.error(new TransactionCommandException(CUSTOMER_COMMAND_NAME,
"Customer object is required for non-guest payment flows"));
}
return findCustomerBasedOnPaymentFlow(transaction)
.map(customerResponse -> {
transaction.enrichWithCustomerDetails(customerResponse);
context.put(CUSTOMER_RESPONSE_KEY, customerResponse);
context.put(CUSTOMER_EXISTS_KEY, true);
return context;
})
.onErrorResume(throwable -> handleError(throwable, transaction, context));
}
handleError() β Error Handling Decision Treeβ
All failures in execute() flow through handleError(). The branch order is critical:
private Mono<Map<String, Object>> handleError(Throwable throwable, Transaction transaction,
Map<String, Object> context) {
// 1. USER_INITIATED + CustomerNotFoundException β park in PENDING_FOR_CUSTOMER_CREATION
if (throwable instanceof CustomerNotFoundException
&& PaymentFlowType.USER_INITIATED_PAYMENT.equals(
transaction.getTxn_details().getPaymentFlowType())) {
transaction.setStatus(PaymentStatus.PENDING_FOR_CUSTOMER_CREATION);
return transactionRepository.save(transaction)
.doOnSuccess(this::publishPendingEvent)
.map(saved -> {
context.put(CUSTOMER_EXISTS_KEY, false);
context.put(CUSTOMER_PENDING_CREATION_KEY, true);
return context;
});
}
// 2. Network failure β errorGroup=INTERNAL_ERROR, httpStatus=GATEWAY_TIMEOUT
// Note: httpStatus=504 β PUBLISHABLE_FAILED_HTTP_STATUSES β no event published
// INTERNAL_ERROR β BUSINESS_RULE_VIOLATION_ERROR_GROUPS β GET returns 200 (FAILED, no 422)
if (throwable instanceof WebClientRequestException webClientRequestException) {
ErrorResponse error = ErrorResponse.builder()
.errorGroup(ErrorGroup.INTERNAL_ERROR)
.httpStatus(HttpStatus.GATEWAY_TIMEOUT)
.message(String.format("'%s' failed", CUSTOMER_COMMAND_NAME))
.build();
return Mono.error(new TransactionCommandException(CUSTOMER_COMMAND_NAME,
"Customer validation failed: " + webClientRequestException.getMessage(), error, throwable));
}
// 3. PaymentException with ErrorResponse β preserve the downstream error (e.g. 422 from customer service)
// PaymentException(ErrorResponse) constructor sets NO string message, so throwable.getMessage() == null.
// Use Optional to safely fall back.
if (throwable instanceof PaymentException paymentException
&& paymentException.getErrorResponse() != null) {
String customerServiceMessage = Optional.ofNullable(paymentException.getErrorResponse().getMessage())
.orElseGet(throwable::getMessage);
return Mono.error(new TransactionCommandException(CUSTOMER_COMMAND_NAME,
"Customer validation failed: " + customerServiceMessage,
paymentException.getErrorResponse(), throwable));
}
// 4. TransactionCommandException with no ErrorResponse β wrap as UNPROCESSABLE_ENTITY/422
// This catches pre-validation failures (null customerId, null customer object)
if (throwable instanceof TransactionCommandException tce && tce.getErrorResponse() == null) {
ErrorResponse error = ErrorResponse.builder()
.errorGroup(ErrorGroup.UNPROCESSABLE_ENTITY)
.httpStatus(HttpStatus.UNPROCESSABLE_ENTITY)
.message(tce.getErrorMessage())
.build();
return Mono.error(new TransactionCommandException(CUSTOMER_COMMAND_NAME,
"Customer validation failed: " + tce.getErrorMessage(), error, throwable));
}
// 5. Generic fallback β no ErrorResponse; TransactionAttemptOrchestrator treats this as INTERNAL_ERROR/500
return Mono.error(new TransactionCommandException(CUSTOMER_COMMAND_NAME,
throwable.getMessage(), throwable));
}
Why branch 3 must come before branch 5:
CustomerClientImpl.parseErrorResponse() always throws new PaymentException(ErrorResponse) β using the constructor that takes only an ErrorResponse and sets no string message. If the generic TransactionCommandException fallback (branch 5) caught this first, the error response would be lost, the transaction would end up with no ErrorResponse, and shouldPublishFailedEvent() would return false β making the failure invisible to the caller via polling.
What happens after handleError() throws:
handlePostProcessingCommandFailure() in TransactionService:
- Fetches the transaction from DB (falls back to the in-memory object if not found)
- Sets
status=FAILED,error=TransactionErrorMapper.toErrorResponse(exception)β which preserves theErrorResponsefrom the exception if present, or builds a genericINTERNAL_ERROR/500 fallback - Calls
TransactionUtil.normalizeBusinessRuleViolationError()β normalizes anyPAYMENT_METHOD_ERRORorINVALID_REQUESTerrorGroup toUNPROCESSABLE_ENTITY/422 before checking publishability - Saves and calls
publishFailedTransactionEvent()βshouldPublishFailedEvent()
Error classification after handleError():
| Branch | ErrorResponse.errorGroup | ErrorResponse.httpStatus | PUBLISHABLE_FAILED_HTTP_STATUSES? | GET returns |
|---|---|---|---|---|
| CustomerNotFoundException + USER_INITIATED | β (parked, not failed) | β | N/A | Via PENDING_FOR_CUSTOMER_CREATION state |
| WebClientRequestException | INTERNAL_ERROR | 504 GATEWAY_TIMEOUT | No (504 β set) | 200 OK (status=FAILED, no 422) |
| PaymentException (e.g. 422 from customer service) | Preserved (e.g. UNPROCESSABLE_ENTITY) | 422 | Yes | 422 with detail |
| TransactionCommandException (null ErrorResponse) wrapped to 422 | UNPROCESSABLE_ENTITY | 422 | Yes | 422 with detail |
| Generic fallback | INTERNAL_ERROR (via buildGenericErrorResponse()) | 500 | No | 200 OK (status=FAILED, no detail) |
PUBLISHABLE_FAILED_HTTP_STATUSES = Set.of(HttpStatus.NOT_FOUND, HttpStatus.UNPROCESSABLE_ENTITY)
2. Context Flag β CUSTOMER_PENDING_CREATION_KEYβ
The constant CommonConstants.CUSTOMER_PENDING_CREATION_KEY = "customerPendingCreation" is placed in the shared execution context by CustomerCheckCommand when the transaction is parked.
TransactionService reads this flag after pre-processing commands complete to decide whether to trigger TransactionAttemptOrchestrator:
// TransactionService β orchestration guard
private boolean isCustomerPendingCreation(Map<String, Object> context) {
return Boolean.TRUE.equals(context.get(CUSTOMER_PENDING_CREATION_KEY));
}
When true, orchestration (attempt creation β vendor calls) is skipped entirely for the current request. Resumption is exclusively triggered by the CustomerConsumer.
Orchestration is actually gated by two checks, which serve different scenarios:
if (transaction.isPendingForCustomerCreation()
|| Boolean.TRUE.equals(context.get(CUSTOMER_PENDING_CREATION_KEY))) {
// skip orchestration β no child payments created yet
return Mono.just(transaction);
}
isPendingForCustomerCreation()β catches idempotent retries, where the existing DB record is already in the pending state.CUSTOMER_PENDING_CREATION_KEYβ catches the initial request, where the in-flight transaction was just transitioned toPENDING_FOR_CUSTOMER_CREATIONin the same request lifecycle (before a fresh DB read would reflect it).
3. Transaction Domain Model β Lifecycle Methodsβ
Three methods added to the Transaction aggregate manage the pending/resumption lifecycle:
// Predicate
public boolean isPendingForCustomerCreation() {
return PaymentStatus.PENDING_FOR_CUSTOMER_CREATION.equals(status);
}
// Called by CustomerConsumer when customer CREATED event arrives
public Transaction resumeOnCustomerFound(CustomerEvent customerEvent) {
if (CustomerStatus.FAILED.equals(customerEvent.getStatus())) {
return failOnCustomerCreationFailure();
}
this.customerId = customerEvent.getCustomerId();
if (this.txn_details != null) {
this.txn_details.setCustomerId(customerEvent.getCustomerId());
this.txn_details.setVendorMerchantId(customerEvent.getVendorMerchantId());
}
this.status = PaymentStatus.PROCESSING;
return this;
}
// Terminal failure path
public Transaction failOnCustomerCreationFailure() {
this.status = PaymentStatus.FAILED;
this.error = ErrorResponse.builder()
.message("Customer creation failed β payment cannot proceed")
.build();
return this;
}
4. CustomerConsumer β V2 Resumption Pathβ
CustomerConsumer.handle() now runs three sequential flows using Flux.concat, ensuring V1 payments, V2 transactions, and refunds are all processed from a single customer event, with independent onErrorResume guards on each:
private Mono<Void> handle(CustomerPayload customerPayload) {
return Flux.concat(
handleV1Payments(customerPayload), // resumes cc_payment rows (V1)
handleV2Transactions(customerPayload), // resumes cc_transaction rows (V2)
handleRefunds(customerPayload) // resumes refunds (V1/shared)
).then();
}
V2 path:
private Flux<Transaction> handleV2Transactions(CustomerPayload customerPayload) {
return transactionRepository
.findByCustomerIdAndStatus(
customerPayload.getCustomerId(),
PaymentStatus.PENDING_FOR_CUSTOMER_CREATION)
.flatMap(transaction -> resumeTransactionOnCustomerFound(transaction, customerPayload))
.onErrorResume(throwable -> {
log.error("Unable to process V2 transaction on customer creation", throwable);
return Mono.empty(); // independent failure β does not affect V1 or refund paths
});
}
private Mono<Transaction> resumeTransactionOnCustomerFound(Transaction transaction,
CustomerPayload payload) {
CustomerEvent customerEvent = payload.toCustomerEvent();
if (CustomerStatus.FAILED.equals(customerEvent.getStatus())) {
transaction.failOnCustomerCreationFailure();
return transactionRepository.save(transaction)
.doOnSuccess(this::publishFailedTransactionEvent);
}
transaction.resumeOnCustomerFound(customerEvent);
return transactionRepository.save(transaction)
.flatMap(this::triggerTransactionAttemptCreation);
}
Failure resilience in attempt creation:
private Mono<Transaction> triggerTransactionAttemptCreation(Transaction transaction) {
TransactionAttemptCommandRequest attemptRequest =
transactionAttemptMapper.toTransactionAttemptCommandRequestWithLinkedPayments(transaction);
return transactionAttemptOrchestrator
.createTransactionAttempt(attemptRequest, new HashMap<>())
.collectList()
.thenReturn(transaction)
.onErrorResume(throwable -> {
// If attempt creation fails, transition to FAILED and publish event
transaction.failOnCustomerCreationFailure();
return transactionRepository.save(transaction)
.doOnSuccess(this::publishFailedTransactionEvent);
});
}
5. Database β Repository and Indexβ
TransactionRepository.findByCustomerIdAndStatus() queries CC_TRANSACTION rows in PENDING_FOR_CUSTOMER_CREATION during event resumption.
// JpaTransactionRepository
List<Transaction> findAllByCustomerIdAndStatus(UUID customerId, PaymentStatus status);
// TransactionRepositoryImpl (reactive wrapper)
public Flux<Transaction> findByCustomerIdAndStatus(UUID customerId, PaymentStatus status) {
return Mono.fromCallable(() ->
jpaTransactionRepository.findAllByCustomerIdAndStatus(customerId, status))
.flatMapMany(Flux::fromIterable)
.subscribeOn(Schedulers.boundedElastic());
}
A Flyway migration (V1_1_62) adds a composite index on (customer_id, status) to ensure this query remains performant as the table grows:
-- V1_1_62__add_customer_id_status_index.sql
CREATE INDEX IF NOT EXISTS idx_cc_transaction_customer_id_status
ON cc_transaction (customer_id, status);
State Transition: PENDING_FOR_CUSTOMER_CREATIONβ
| Trigger | From | To | Action |
|---|---|---|---|
CustomerCheckCommand β CustomerNotFoundException on USER_INITIATED_PAYMENT | INITIATED | PENDING_FOR_CUSTOMER_CREATION | Persist transaction, publish event, set context flag |
CustomerConsumer β Customer CREATED event received | PENDING_FOR_CUSTOMER_CREATION | PROCESSING | Enrich customer data, trigger attempt creation |
CustomerConsumer β Customer FAILED event received | PENDING_FOR_CUSTOMER_CREATION | FAILED | Set error message, publish failed event |
CustomerConsumer β Attempt creation throws | PROCESSING | FAILED | failOnCustomerCreationFailure() + publish failed event |
Event Publishingβ
Two events are published during this lifecycle:
| Event | When | Status in Payload |
|---|---|---|
PAYMENT_UPDATED | Transaction parked in PENDING_FOR_CUSTOMER_CREATION | PENDING_FOR_CUSTOMER_CREATION |
PAYMENT_UPDATED | Transaction resumes to PROCESSING (via CustomerConsumer) | PROCESSING β subsequent status changes follow normal flow |
PAYMENT_UPDATED | Customer creation failed | FAILED |
The event ID format is consistent across all publishing points:
String eventId = String.format("%s|%s|%s",
transaction.getId(),
transactionUpdateEvent, // e.g. "wallet.payment.updated"
transaction.getStatus());
PaymentRequestValidator β Null Customer Allowedβ
Prior to this feature, PaymentRequestValidator rejected a null customer object at the DTO layer. This was intentionally relaxed to allow GUEST_PAYMENT flows, where X-Customer-Id is not provided and no customer object is needed.
The null-customer guard was moved into CustomerCheckCommand, where the PaymentFlowType is already resolved:
// PaymentRequestValidator β customer is no longer @NotNull at DTO level
// Enforcement for non-guest flows is delegated to CustomerCheckCommand
// CustomerCheckCommand β enforces customer presence for non-guest flows
if (transaction.getTxn_details().getCustomer() == null) {
return Mono.error(new TransactionCommandException(CUSTOMER_COMMAND_NAME,
"Customer object is required for non-guest payment flows"));
}
Why this matters: Bean Validation (@Valid) runs before the payment flow type can be determined from the HTTP header. Deferring the check to CustomerCheckCommand allows the same validation logic to be applied correctly for all flow types.
Test Coverageβ
CustomerCheckCommand Tests (37 tests)β
| Test | What it verifies |
|---|---|
isPreProcessingCommand_shouldReturnFalse | Command is post-processing β runs after 202 is returned |
execute_guestPaymentFlow_skipsCustomerLookupAndReturnsContext | Guest flows short-circuit before any customer call |
execute_userInitiated_customerNotFound_transitionsToPendingForCustomerCreation | PENDING_FOR_CUSTOMER_CREATION status set, event published, context flags set |
execute_userInitiated_customerNotFound_preservesExistingContextEntries | CUSTOMER_EXISTS_KEY=false, CUSTOMER_PENDING_CREATION_KEY=true in context |
execute_ShouldFindOrCreateCustomer_WhenMerchantInitiatedPaymentAndCustomerNotFound | MERCHANT_INITIATED_PAYMENT triggers find-or-create |
execute_merchantInitiated_missingCustomerObject_wrapsAs422UnprocessableEntity | Null customer object β TransactionCommandException with UNPROCESSABLE_ENTITY/422 |
execute_userInitiated_nullCustomerId_wrapsAs422UnprocessableEntity | Null customerId β TransactionCommandException with UNPROCESSABLE_ENTITY/422 |
execute_merchantInitiated_customerCreationFailsWithUnprocessableEntity_throwsTransactionCommandExceptionWith422 | Customer service 422 β TransactionCommandException with preserved 422 ErrorResponse |
execute_merchantInitiated_customerCreationFailsWithPaymentException_preservesHttpStatusFromDownstream | PaymentException β ErrorResponse httpStatus preserved (not lost) |
execute_merchantInitiated_searchFailsWithPaymentException_preservesHttpStatus | Search 422 β preserved through handleError() |
execute_merchantInitiated_paymentException_errorMessageUsesErrorResponseMessage_notNull | throwable.getMessage()=null β uses errorResponse.getMessage() as fallback |
execute_userInitiated_paymentExceptionOnSearch_preservesHttpStatusAndMessage | USER_INITIATED non-404 failure from search β FAILED with correct status |
execute_merchantInitiated_createCustomerFailsWithWebClientRequestException_returnsGatewayTimeout | Network timeout β TransactionCommandException with errorGroup=INTERNAL_ERROR, httpStatus=504 GATEWAY_TIMEOUT |
execute_merchantInitiated_searchFailsWithWebClientRequestException_returnsGatewayTimeout | Network timeout on search β same: INTERNAL_ERROR errorGroup, 504 httpStatus |
execute_merchantInitiated_createCustomerFailsWithGenericException_wrapsAsTransactionCommandException | Unknown error β generic fallback |
execute_paymentExceptionWithNullErrorResponse_fallsToGenericHandler | PaymentException with null errorResponse β falls through to generic fallback |
execute_userInitiated_customerNotFound_saveFailure_propagatesDbError | DB save fails during park β error propagated upstream |
CustomerConsumer Testsβ
| Test | What it verifies |
|---|---|
handleV2Transactions_customerCreated_resumesTransaction | resumeOnCustomerFound() called, PROCESSING state saved, attempt creation triggered |
handleV2Transactions_customerFailed_transitionsToFailed | failOnCustomerCreationFailure() called, FAILED event published |
handleV2Transactions_attemptCreationFails_transitionToFailedAndPublishesEvent | Attempt creation error β transaction transitions to FAILED, event published |
TransactionService Testsβ
| Test | What it verifies |
|---|---|
testProcessTransaction_PendingForCustomerCreationStatus | Orchestrator is never invoked when CUSTOMER_PENDING_CREATION_KEY=true |
processTransaction_cc12883_customerCheckPostProcessing_invalidMetadata_returns202AndEventuallyFails | CC-12883 regression test β invalid metadata POST returns 202; async post-processing transitions transaction to FAILED with 422 |
Transaction Domain Testsβ
| Test | What it verifies |
|---|---|
resumeOnCustomerFound_customerCreated_transitionsToProcessing | customerId, vendorMerchantId enriched, status = PROCESSING |
resumeOnCustomerFound_customerFailed_transitionsToFailed | Delegates to failOnCustomerCreationFailure() |
failOnCustomerCreationFailure_setsFailedStatus | Status = FAILED, error message set |
Validation Rulesβ
| Rule | HTTP Status | Error |
|---|---|---|
customer object is required for non-guest flows | 400 | INVALID_REQUEST |
customer must include at least one of hsid, enterpriseIdentifier, or metadata | 400 | INVALID_REQUEST β customer object must include at least one of... |
customer.email must be a valid email address format | 400 | INVALID_REQUEST |
customer.dateOfBirth must be in YYYY-MM-DD format | 400 | INVALID_REQUEST |
customer.ssnLastFour must be exactly 4 digits | 400 | INVALID_REQUEST |
customer.zip5 must be exactly 5 digits | 400 | INVALID_REQUEST |
Guest payments (GUEST_PAYMENT) do not require a customer object | β | Validation skipped |
Webhook Eventsβ
| Event | When Emitted | Notes |
|---|---|---|
PAYMENT_UPDATED (status: PENDING_FOR_CUSTOMER_CREATION) | Transaction enters pending state | Emitted by wallet-payment-service after saving; dataVersion: "2.0.0" |
PAYMENT_UPDATED (status: PROCESSING) | Customer created; processing resumes | Emitted when customer event is consumed and transaction re-enters processing |
PAYMENT_SUCCEEDED | All allocations complete | Standard completion event |
PAYMENT_FAILED | Customer creation failed or payment processing failed | Terminal state |
Edge Casesβ
| Scenario | Behavior | Notes |
|---|---|---|
Retry with same merchantTransactionId while pending | handleDuplicateTransactionScenario detects the existing record, reuses its transactionId, and re-runs post-processing against it; isPendingForCustomerCreation() returns true again, so orchestration is skipped β returns the existing transaction in PENDING_FOR_CUSTOMER_CREATION | Idempotent β no duplicate customer or payment created |
| Customer creation fails in vendor system | Transaction transitions to FAILED | Terminal; no automatic retry; merchant must submit new request |
| Customer already exists at time of event | CustomerCheckCommand finds customer on first pass; normal flow proceeds without pausing | Common when customer is created by a concurrent request |
| Split-tender with new customer | Both allocations created only after customer is provisioned | Same pausing behavior as single payment; all allocations start after resume |
| Customer event arrives before transaction is persisted | Transaction not found in PENDING_FOR_CUSTOMER_CREATION query; event is effectively no-op | Rare race condition; merchant may need to retry the original request |
Constraints and Out-of-Scope Itemsβ
- This behavior applies to both single-payment and split-tender transactions. Guest payments do not create customers and are not in scope β they bypass customer resolution entirely.
- Customer updates or profile management beyond what is needed to resolve the payment are not handled here β see Customer Creation in wallet-customer-service for end-to-end provisioning.
- Manual retries are not supported for a parked transaction β resumption is fully automatic on
WALLET_CUSTOMER_UPDATED. - V1 payments (
cc_paymentrows) are handled by a separate path inCustomerConsumer.handleV1Paymentsand are not affected by this flow. - No wallet, payment method, or
PaymentMethodCreatedevents are emitted while a transaction is inPENDING_FOR_CUSTOMER_CREATION. - All V2 events in this flow carry
dataVersion: "2.0.0".
Related Documentationβ
- Payment Lifecycle States
- Single Payment Flow
- Split-Tender Payment Flow
- Pay with Wallet β the standard V2 payment flow without new-customer creation
- Error Strategy
- V2 Payment Request Lifecycle
- Commons Library
- Error Codes
- Customer Creation During Payment
- How to Submit a Payment with Customer Creation
- Troubleshoot Customer Creation During Payment