Skip to main content
← Back to Blog

Credit Card Payments, PCI DSS, and Tokenization

The architect's visual guide to payments that won't get you fired.

You're building a checkout. The instinct is to treat it like any other API call—post JSON, get a response, store the result. That instinct will land you in PCI scope with 300+ compliance controls, potential fines, and legal exposure. Let's fix that.


The Mental Model: Think Like a Coat Check

Before diving into protocols and standards, anchor the entire payment flow to one analogy:

Tokenization is a coat check.

Loading diagram...

The ticket (token) is useless to a thief—it only works at that coat check. Similarly, a payment token only works with that gateway. You never carry the coat (card number) around the building (your infrastructure). You carry the ticket.

The rule: If someone breaks into your database and finds pm_1Axyz, they can't buy anything. That's the point.


Trust Zones: Where Data Lives Matters

Every payment architecture has three trust zones. Your goal is to stay out of the red one.

Loading diagram...
ZoneContainsWho Manages ItYour PCI Burden
Zone 1 — RedRaw card dataGateway (Stripe, Adyen, Braintree)None — it's their problem
Zone 2 — YellowTokens, charge IDs, metadataYour serverMinimal — SAQ A or A-EP
Zone 3 — GreenLast 4, brand, expiryYour frontendDisplay only — no PCI concern

Architect's rule: If raw card data ever enters Zone 2, you've just inherited Zone 1's compliance burden. Design to prevent that.


Decision Flowchart: Picking Your Payment Architecture

Loading diagram...

How a Card Payment Works

Loading diagram...
PhaseWhat HappensTiming
AuthorizationIssuing bank checks balance, fraud rules, 3DS challenges. Reserves funds.Real-time (~1-3s)
CaptureTells the acquirer to move the reserved amount. Can be immediate or delayed (e.g., ship-then-capture).Immediate or up to 7 days
SettlementFunds move from issuer → card network → acquirer → your merchant account, minus interchange + assessment fees.T+1 to T+3 business days
FundingAcquirer deposits net amount into your bank account.T+2 to T+7 depending on processor

Key insight: Your app never touches card data. The gateway collects it directly from the customer's browser via an iframe, then gives you a token. The full chain (acquirer → network → issuer) is invisible to you.


What You Can and Cannot Store

Loading diagram...

The CVV rule is absolute. Even encrypted, even for one millisecond, even in logs—CVV must never be stored post-authorization. PCI DSS Requirement 3.2 makes this non-negotiable.

Your Database FieldExampleWhy
payment_tokenpm_1AxyzCharge the card again
last44242"Visa ending in 4242"
brandvisaDisplay card icon
exp_month/year12/2027Notify before expiry
fingerprintgUi3...Detect duplicate cards across customers
charge_idch_3MxyzReference for refunds and disputes

PCI DSS Compliance: Pick Your Architecture Wisely

Your integration pattern determines how many compliance controls you face. PCI DSS v4.0 became mandatory March 2025 — all assessments now use v4.0.

Loading diagram...
PatternSAQ TypeControlsWhen to Use
Redirect (Stripe Checkout, PayPal)SAQ A~22Simple checkout, fastest compliance
Hosted Fields (iframe on your page)SAQ A-EP~140Custom branded checkout
Direct APISAQ D~300+Avoid unless you're a payment processor

Key PCI DSS v4.0 Changes Architects Must Know

RequirementWhat ChangedImpact
6.4.3All payment page scripts must be inventoried, authorized, and integrity-checkedYou need CSP headers + Subresource Integrity (SRI) on every <script> tag on checkout pages
11.6.1Tamper-detection mechanism for payment pagesMonitor your checkout page DOM for unauthorized changes (skimming attacks)
8.3.6Minimum 12-character passwords for system accountsUpdate all service account credentials
12.3.1Targeted risk analysis for flexible requirementsDocument why you chose specific control implementations

v4.0 headline: Client-side security is no longer optional. If you serve a checkout page, you must prove no unauthorized scripts can execute on it.


3D Secure 2 (3DS2) — Strong Customer Authentication

3DS2 shifts fraud liability from you to the issuing bank when the cardholder authenticates. It's required in the EU (PSD2/SCA) and increasingly expected elsewhere.

Loading diagram...
OutcomeLiabilityWhat Happened
Frictionless passBankIssuer approved silently — best UX
Challenge passBankCustomer completed OTP/biometric
Challenge failYouCustomer failed auth — don't proceed
3DS not attemptedYouNo liability shift — you eat the chargeback

Architect's tip: Always send 3DS data (device fingerprint, browser metadata) with the charge request. Even if 3DS isn't triggered, it improves authorization rates.


How Tokenization Works

Loading diagram...

Network Tokens vs. Gateway Tokens

TypeIssued BySurvives Card Re-issue?Portable?Auth Rate Impact
Network TokenVisa / MastercardYes — auto-rotates with new cardWorks across gateways+2-4% improvement
Gateway TokenStripe / Braintree / AdyenDepends on gateway's updater serviceLocked to one processorBaseline

Network tokens improve authorization rates because issuers trust them more — they're cryptographically bound to your merchant ID. Use them for subscriptions and card-on-file scenarios. Most major gateways now support enabling them transparently.


Webhooks: Handling Async Payment Events

Payments are not purely synchronous. Refunds, disputes, subscription renewals, and failed charges arrive via webhooks.

Loading diagram...

Critical Webhook Events to Handle

EventWhat to Do
payment.succeededConfirm order, send receipt, trigger fulfillment
payment.failedNotify customer, retry or cancel order
charge.refundedUpdate order status, adjust revenue records
charge.dispute.createdAlert team, gather evidence, respond within deadline
customer.source.updatedCard was replaced (lost/expired) — network token auto-handled this
payment_method.expiringNotify customer to update card before next billing

Idempotency rule: Webhooks can be delivered more than once. Always check if you've already processed an event ID before acting on it.


Refunds, Disputes, and Chargebacks

Refund (you initiate)

Loading diagram...

Dispute / Chargeback (bank initiates)

Loading diagram...
MetricHealthyDangerous
Chargeback rate< 0.5%> 1% (card networks may fine or terminate you)
Refund processing5-10 business daysVaries by issuer
Evidence deadlineTypically 7-21 daysMiss it = automatic loss

Always refund proactively when the customer has a valid complaint. A refund costs you the transaction. A chargeback costs you the transaction + a fee ($15-25) + damage to your chargeback ratio.


Idempotency and Retry Logic

Network failures happen. Without idempotency, a retry can double-charge the customer.

POST /v1/charges
Idempotency-Key: order_12345_attempt_1
ScenarioWithout Idempotency KeyWith Idempotency Key
Request times out, client retriesDouble chargeGateway returns original result
Network error mid-responseUnknown state — manual reconciliationSafe to retry
Webhook arrives before API responseRace conditionDeduplicate on charge_id

Rules:

  • Generate the key from your order ID + attempt number, not random UUIDs.
  • Keys typically expire after 24-48 hours at the gateway.
  • Store the idempotency key alongside the order so you can retry with the same key.

Architect's Cheat Sheet

DecisionRecommendation
Integration patternHosted fields or redirect — never direct API
What to storeToken, last4, brand, expiry, fingerprint, charge_id
CVVAuthorization only. Never stored. Period.
Gateway keysSecret Manager / environment variables — never in code
IdempotencyAlways send an idempotency key with charge requests
SubscriptionsUse network tokens for higher auth rates (+2-4%)
3DS2Always send browser/device data. Required in EU (PSD2/SCA)
WebhooksVerify signatures. Process async. Deduplicate on event ID
Refunds vs. chargebacksRefund proactively — chargebacks cost more + hurt your ratio
LoggingScrub all payment request/response bodies. Never log card data.
Checkout page scriptsCSP headers + SRI on all scripts (PCI DSS v4.0 Req 6.4.3)
Page tamper detectionMonitor checkout DOM for unauthorized changes (Req 11.6.1)

Conclusion

Keep card data in the gateway's environment, not yours. Use hosted fields or a redirect, receive tokens, store only the safe subset. Your compliance drops from 300+ controls to ~22, and the sensitive data problem is solved at the infrastructure layer — not patched at the application layer.

Think coat check: you never carry the coat, you carry the ticket. Design your entire payment stack around that principle, and PCI compliance becomes a paperwork exercise rather than an engineering overhaul.