Payment processing service
You build a payment processing service that creates payment intents and settles them from signed provider webhooks. A reconciliation pass resolves old pending payments, while late captures after failure trigger refunds.
Ticket
Build a payment processing service in backend/internal/payments. It creates payment intents through the provider, verifies webhook signatures, applies payment state transitions, and reconciles payments that remain pending.
Provider callbacks can be delivered more than once or arrive out of order. A capture can also arrive after an order has been cancelled. The service must prevent duplicate order updates and refund a payment that was captured after failure. The next module integrates the stretch feature into the app and runs final testing, so it depends on these payment operations behaving correctly.
The tests call these exported declarations:
import (
"context"
"net/http"
"time"
)
type Status string
const (
StatusPending Status = "PENDING"
StatusCaptured Status = "CAPTURED"
StatusFailed Status = "FAILED"
)
var ErrNotFound error
type Payment struct {
ID string
OrderID string
Status Status
ProviderRef string
AmountPaise int64
CreatedAt time.Time
}
type Store interface {
Create(context.Context, Payment) error
Get(context.Context, string) (Payment, error)
Transition(context.Context, string, Status, Status) (bool, error)
SeenEvent(context.Context, string) (bool, error)
Pending(context.Context, time.Time) ([]Payment, error)
}
type Orders interface {
MarkPlaced(context.Context, string) error
MarkCancelled(context.Context, string) error
}
type Provider interface {
CreateIntent(context.Context, string, int64) (string, error)
Status(context.Context, string) (Status, error)
Refund(context.Context, string) error
}
type Service struct {
// unexported implementation fields
}
func Sign(secret, body []byte) string
func Verify(secret, body []byte, signature string) bool
func NewService(store Store, orders Orders, provider Provider, secret []byte, now func() time.Time) *Service
func (s *Service) CreateIntent(ctx context.Context, orderID string, amountPaise int64) (Payment, error)
func (s *Service) Webhook() http.Handler
func (s *Service) Reconcile(ctx context.Context) errorAcceptance criteria
Signreturns the lowercase hexadecimal HMAC-SHA256 signature of the exact body bytes.Verifyaccepts the matching signature and rejects a tampered body, a different secret, non-hexadecimal input, truncated input, and an empty signature.CreateIntentcreates and persists a payment with a non-empty ID, the supplied order ID and amount,PENDINGstatus, the provider reference, and the injected clock's current time. For the test ordero-1, the expected amount is49900and the provider reference ispi_o-1. The stored payment must equal the returned payment.- A valid
payment.capturedwebhook returns HTTP 200, transitions the payment fromPENDINGtoCAPTURED, and marks its order placed. A validpayment.failedwebhook returns HTTP 200, transitions the payment fromPENDINGtoFAILED, and marks its order cancelled. - An invalid or missing
X-Signaturereturns HTTP 401 without changing payment or order state. Signature verification must happen before JSON parsing. - A webhook for an unknown payment returns HTTP 404 without consuming its event ID. After that payment exists, retrying the same event ID must return HTTP 200 and process the capture.
- Delivering the same capture webhook three times returns HTTP 200 for each delivery and places the order exactly once, without issuing a refund. Sending 20 concurrent copies of the same signed event must also result in exactly one order placement.
- A second capture with a different event ID must not place the order again or issue a refund. A failure arriving after a capture returns HTTP 200 and leaves the payment
CAPTURED, without cancelling the order. - A capture arriving after a failure must leave the payment
FAILEDand the order unplaced. Repeated delivery of that capture must issue exactly one refund for provider referencepi_o-1. - Reconciliation must settle old pending payments according to provider status:
CAPTUREDplaces the order,FAILEDcancels it, andPENDINGleaves the payment unchanged. It must not query a payment only four minutes old, and it must not place an order again when a webhook has already captured the payment.
Constraints
- Keep
Paymentcomparable using==. - Do not modify the provided tests.
Design direction
A straightforward starting point is internal/payments/payments.go. Keep signature generation and verification independent of payment state. Let the service coordinate the store, order service, and provider through the supplied interfaces.
Treat Store.Transition as the authority for payment state changes. It should act as an atomic compare-and-set operation, so only one caller can move a payment out of PENDING. Keep event-ID deduplication separate from payment transitions: an event can be redelivered, but a different event ID can also describe a payment that is already settled.
Use the same settlement logic for webhooks and reconciliation. This avoids giving the background path different rules from the callback path. Consider the boundary between a successful payment transition and the subsequent order update. They are separate operations, so a production system may need an outbox or retry mechanism if the order update fails after the transition.
Any package layout that meets the contract passes.
How to check your work
Run the payment tests from the repository root:
cd backend
make test W=8B2The command runs the matching tests with Go's race detector. Read the first failing assertion first: it identifies the observed status, payment state, or side effect that differs from the expected result.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Payment workflow
2 items
- 8.3HMAC webhooks and payment sagasnot completed
- 8.4Payment processing servicenot completed
Up next · Module 3 · 3 items · about 2 h 30 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- HMAC signatures are generated and verified against the raw body.
- Payment intents are created and persisted with the injected time.
- Signed webhooks settle payments without duplicate order updates.
- Out-of-order captures trigger the required refund.
- Reconciliation settles old payments without repeating settlement.
Commands
cd backend && make test W=8B2Tests
TestW8B2_SignIsHexHMACSHA256OfTheBodyinbackend/internal/payments/payments_test.goTestW8B2_VerifyAcceptsTheRightSignatureAndRejectsEverythingElseinbackend/internal/payments/payments_test.goTestW8B2_CreateIntentStoresAPendingPaymentWithTheProviderRefinbackend/internal/payments/payments_test.goTestW8B2_ACapturedWebhookMarksThePaymentCapturedAndPlacesTheOrderinbackend/internal/payments/payments_test.goTestW8B2_AFailedWebhookMarksThePaymentFailedAndCancelsTheOrderinbackend/internal/payments/payments_test.goTestW8B2_ABadSignatureIs401AndChangesNothinginbackend/internal/payments/payments_test.goTestW8B2_TheSignatureIsCheckedBeforeTheBodyIsParsedinbackend/internal/payments/payments_test.goTestW8B2_AMissingSignatureHeaderIs401inbackend/internal/payments/payments_test.goTestW8B2_AnUnknownPaymentIs404AndTheEventIsNotConsumedinbackend/internal/payments/payments_test.goTestW8B2_TheSameWebhookThreeTimesPlacesTheOrderOnceinbackend/internal/payments/payments_test.goTestW8B2_ConcurrentDuplicateDeliveriesPlaceTheOrderOnceinbackend/internal/payments/payments_test.goTestW8B2_ASecondCaptureWithAnotherEventIDChangesNothinginbackend/internal/payments/payments_test.goTestW8B2_AFailureArrivingAfterACaptureIsIgnoredinbackend/internal/payments/payments_test.goTestW8B2_ACaptureArrivingAfterAFailureIsRefundedOnceinbackend/internal/payments/payments_test.goTestW8B2_ReconcileSettlesOldPendingPaymentsFromTheProviderinbackend/internal/payments/payments_test.goTestW8B2_ReconcileLeavesRecentPaymentsAloneinbackend/internal/payments/payments_test.goTestW8B2_ReconcileKeepsPaymentsTheProviderStillCallsPendinginbackend/internal/payments/payments_test.goTestW8B2_ReconcileAfterAWebhookDoesNotPlaceTheOrderTwiceinbackend/internal/payments/payments_test.go