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:

go
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) error

Acceptance criteria

  • Sign returns the lowercase hexadecimal HMAC-SHA256 signature of the exact body bytes. Verify accepts the matching signature and rejects a tampered body, a different secret, non-hexadecimal input, truncated input, and an empty signature.
  • CreateIntent creates and persists a payment with a non-empty ID, the supplied order ID and amount, PENDING status, the provider reference, and the injected clock's current time. For the test order o-1, the expected amount is 49900 and the provider reference is pi_o-1. The stored payment must equal the returned payment.
  • A valid payment.captured webhook returns HTTP 200, transitions the payment from PENDING to CAPTURED, and marks its order placed. A valid payment.failed webhook returns HTTP 200, transitions the payment from PENDING to FAILED, and marks its order cancelled.
  • An invalid or missing X-Signature returns 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 FAILED and the order unplaced. Repeated delivery of that capture must issue exactly one refund for provider reference pi_o-1.
  • Reconciliation must settle old pending payments according to provider status: CAPTURED places the order, FAILED cancels it, and PENDING leaves 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 Payment comparable 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:

bash
cd backend
make test W=8B2

The 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.

Finished Exercise 8.4?

Payment workflow

2 items

  • 8.3HMAC webhooks and payment sagasnot completed
  • 8.4Payment processing servicenot completed

App integration and capacity

Up next · Module 3 · 3 items · about 2 h 30 min

Start module 3

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. HMAC signatures are generated and verified against the raw body.
  2. Payment intents are created and persisted with the injected time.
  3. Signed webhooks settle payments without duplicate order updates.
  4. Out-of-order captures trigger the required refund.
  5. Reconciliation settles old payments without repeating settlement.

Commands

terminal
cd backend && make test W=8B2

Tests

  • TestW8B2_SignIsHexHMACSHA256OfTheBody in backend/internal/payments/payments_test.go
  • TestW8B2_VerifyAcceptsTheRightSignatureAndRejectsEverythingElse in backend/internal/payments/payments_test.go
  • TestW8B2_CreateIntentStoresAPendingPaymentWithTheProviderRef in backend/internal/payments/payments_test.go
  • TestW8B2_ACapturedWebhookMarksThePaymentCapturedAndPlacesTheOrder in backend/internal/payments/payments_test.go
  • TestW8B2_AFailedWebhookMarksThePaymentFailedAndCancelsTheOrder in backend/internal/payments/payments_test.go
  • TestW8B2_ABadSignatureIs401AndChangesNothing in backend/internal/payments/payments_test.go
  • TestW8B2_TheSignatureIsCheckedBeforeTheBodyIsParsed in backend/internal/payments/payments_test.go
  • TestW8B2_AMissingSignatureHeaderIs401 in backend/internal/payments/payments_test.go
  • TestW8B2_AnUnknownPaymentIs404AndTheEventIsNotConsumed in backend/internal/payments/payments_test.go
  • TestW8B2_TheSameWebhookThreeTimesPlacesTheOrderOnce in backend/internal/payments/payments_test.go
  • TestW8B2_ConcurrentDuplicateDeliveriesPlaceTheOrderOnce in backend/internal/payments/payments_test.go
  • TestW8B2_ASecondCaptureWithAnotherEventIDChangesNothing in backend/internal/payments/payments_test.go
  • TestW8B2_AFailureArrivingAfterACaptureIsIgnored in backend/internal/payments/payments_test.go
  • TestW8B2_ACaptureArrivingAfterAFailureIsRefundedOnce in backend/internal/payments/payments_test.go
  • TestW8B2_ReconcileSettlesOldPendingPaymentsFromTheProvider in backend/internal/payments/payments_test.go
  • TestW8B2_ReconcileLeavesRecentPaymentsAlone in backend/internal/payments/payments_test.go
  • TestW8B2_ReconcileKeepsPaymentsTheProviderStillCallsPending in backend/internal/payments/payments_test.go
  • TestW8B2_ReconcileAfterAWebhookDoesNotPlaceTheOrderTwice in backend/internal/payments/payments_test.go