Skip to content
All articles

Security13 min read

How to stop card testing when your app is behind Cloudflare

Stop card testing on Stripe: get the real visitor IP behind Cloudflare, limit payment attempts, cap retries on each PaymentIntent and respond to an attack.

Someone with a list of stolen card numbers needs to know which ones still work. Your checkout can tell them.

That's card testing. Attackers try card after card, often with small payments or by saving cards to an account. You're left with declined payments, disputes and fees.

We've dealt with it on PlayerBay, the marketplace we built and run. One evening, a group tried more than ten cards from four countries in about half an hour. When we investigated, we found a problem of our own: behind Cloudflare, we were logging Cloudflare's address instead of the visitor's. That had weakened one of the checks meant to catch this kind of attack. We fixed it and rebuilt the affected records.

This guide shows how to avoid that mistake, then covers another gap that's easy to miss: limiting new payments doesn't limit how many cards someone can try on each one.

How to spot card testing

Stripe lists these warning signs:

  • A jump in failed or blocked payments
  • A jump in requests that return a 402 error
  • Lots of suspicious small payments, often with nonsense names or email addresses

Also look for one account or address using many different cards. Any one sign can have an innocent cause, so look at them together. A popular launch can bring more declines, and a real customer might try a second card.

Don't only watch payments. Stripe says attackers also use card setup, which checks and saves a card without charging it. If you let customers save cards, protect that too.

Step 1: Find the visitor's real IP address

With Cloudflare's proxy turned on, visitors connect to Cloudflare, and Cloudflare connects to your app. The connection your app sees comes from Cloudflare.

If you use that address for limits, two things can go wrong:

  • Real customers share a limit. Many visitors can reach you through the same Cloudflare address.
  • Attackers are harder to track. One visitor's requests can arrive through different Cloudflare addresses, and your records don't show where they came from.

These are the headers you're likely to see:

Header What to know
CF-Connecting-IP The address that connected to Cloudflare. Cloudflare recommends this or True-Client-IP over X-Forwarded-For
True-Client-IP The same value under another name, available on Enterprise plans
X-Forwarded-For If the visitor sends this header, Cloudflare adds to it, so the first address may be made up
X-Real-IP Depends on your host. It may be the address of the proxy, not the visitor

Don't just take the first address in X-Forwarded-For. Its meaning depends on every proxy in between. Vercel, for example, replaces the header when there's another proxy in front, and doesn't pass on the outside addresses. Vercel also advises against adding a reverse proxy, so read its guidance before using one.

If a Cloudflare Worker calls your app, check that route separately. CF-Connecting-IP can work differently there, and in some cases the Worker can change it.

Step 2: Make sure the request came through Cloudflare

CF-Connecting-IP is just a header. If someone can reach your app without going through Cloudflare, they can send any address they like, then change it on every request to get around your IP limits.

Remember every way in, including your server's IP address, your host's default domain and preview deployments.

Use the strongest protection your host supports. Cloudflare Tunnel and Authenticated Origin Pulls are good options when you control the server. For Authenticated Origin Pulls, use your own certificate, because Cloudflare's shared one only proves that traffic came from Cloudflare's network. Our Cloudflare setup guide covers both.

If your host doesn't support those, Cloudflare can add a secret header to each request. Cloudflare rates this option "moderately secure":

  1. Generate a long, random secret and save it in your app's server settings.
  2. In Cloudflare, create a Request Header Transform Rule for your app's hostname.
  3. Choose Set static, name the header x-origin-secret, and use the secret as its value. This replaces anything the visitor sent under that name.
  4. Check that the header is arriving before you start blocking requests without it.

Transform Rules are available on every Cloudflare plan. The Free plan includes 10 active rules.

This function only trusts Cloudflare's header if the secret is correct:

import { createHash, timingSafeEqual } from "node:crypto"
import { isIP, isIPv4 } from "node:net"

const digest = (value: string) => createHash("sha256").update(value).digest()

export const getVisitorIp = (
  headers: Headers,
  secret: string | undefined
): string | null => {
  const sent = headers.get("x-origin-secret")
  if (!secret || !sent || !timingSafeEqual(digest(sent), digest(secret)))
    return null

  const ip = headers.get("cf-connecting-ip")?.trim() ?? ""
  return isIP(ip) && !ip.includes("%") ? ip : null
}

export const ipLimitKey = (ip: string): string => {
  const mapped = ip.replace(/^::ffff:/i, "")
  if (isIPv4(mapped)) return mapped

  const address = new URL(`http://[${ip}]`).hostname.slice(1, -1)
  const [start = "", end] = address.split("::")
  const left = start ? start.split(":") : []
  const right = end ? end.split(":") : []
  const zeros = Array<string>(8 - left.length - right.length).fill("0")
  const groups = [...left, ...zeros, ...right]

  return `${groups.slice(0, 4).join(":")}::/64`
}

If getVisitorIp returns null, don't start the payment. There's no fallback to X-Forwarded-For, because that would bring back the problem you just fixed. If the secret is missing from your settings, every request is refused, so set up an alert for that.

ipLimitKey is for your limits. One person or device can often use many IPv6 addresses within the same /64 block, so the function groups each block together. If you need an address for a fraud investigation, save the exact one separately.

Step 3: Count attempts before you call Stripe

Stripe says simple filters based on one thing, such as IP address, usually aren't enough on their own. Attackers can switch addresses, while real customers may share one at work, at school or on a mobile network.

Use a few limits together:

Count What it helps catch Watch out for
Attempts per account One account making lots of attempts Attackers creating more accounts
Attempts per IP address Several accounts using one connection Real customers sharing an address
Different cards per account One person trying lots of cards Families and businesses with several cards
Failures per payment Repeated tries on one payment Real customers mistyping their details

For different cards, Stripe's card fingerprint can show when the same card number is used again. Apple Pay and Google Pay may use a substitute number, so the same card can look like a different one.

Timing matters too. If you check a count now and update it after Stripe replies, lots of requests can pass the check at once. Count the attempt first, in one database operation. This example uses MongoDB:

import type { Db } from "mongodb"

type Counter = { _id: string; count: number; expiresAt: Date }
type Limit = { key: string; max: number; windowMs: number }

const countAttempt = async (db: Db, { key, max, windowMs }: Limit) => {
  const windowStart = Math.floor(Date.now() / windowMs) * windowMs
  const counter = await db
    .collection<Counter>("payment_limits")
    .findOneAndUpdate(
      { _id: `${key}:${windowMs}:${windowStart}` },
      {
        $inc: { count: 1 },
        $setOnInsert: { expiresAt: new Date(windowStart + windowMs) },
      },
      { upsert: true, returnDocument: "after" }
    )
  return counter !== null && counter.count <= max
}

export const allowPaymentAttempt = async (
  db: Db,
  limits: readonly Limit[]
): Promise<boolean> => {
  const results = await Promise.all(
    limits.map((limit) => countAttempt(db, limit))
  )
  return results.every(Boolean)
}

Add an index once so MongoDB removes old counters:

await db
  .collection("payment_limits")
  .createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })

Then check the limits on your server before you create a payment or return one that already exists:

const ip = getVisitorIp(request.headers, process.env.ORIGIN_SECRET)
if (!ip) return new Response("Payment unavailable", { status: 403 })

const hour = 60 * 60 * 1000
const allowed = await allowPaymentAttempt(db, [
  { key: `account:${user.id}`, max: 5, windowMs: hour },
  { key: `ip:${ipLimitKey(ip)}`, max: 20, windowMs: hour },
])
if (!allowed) return new Response("Try again later", { status: 429 })

Get user.id from the signed-in session on your server, never from the request body. The numbers only show how it works. They aren't PlayerBay's limits or a recommendation. Base yours on your normal traffic, and log what you would have blocked before you start blocking.

Here's what else to know about this code:

  • Blocked attempts still count, so someone who keeps trying stays blocked until the window ends.
  • Each window starts at a fixed time. Someone could use up one limit just before it resets, then the next one straight after. Use a sliding window if that's a problem.
  • If the database is down, the code throws an error. Return an error and don't call Stripe. Set up an alert too, because real customers won't be able to pay either.
  • Accounts and IP addresses can be personal data. Only keep them as long as you need to, and include them in your privacy policy. MongoDB removes expired records in the background, not at the exact second they expire.

Step 4: Limit failures on each payment

Say you allow five new payments an hour. You might expect that to mean five cards an hour, but it doesn't.

When a card fails, Stripe's PaymentIntent goes back to requires_payment_method so the customer can try again. With Stripe's default automatic confirmation, the browser can do that using your publishable key and the payment's client secret. The next card can go straight to Stripe without reaching your server, so your server limits never see it.

Hiding the Pay button won't stop an attacker who already has the client secret.

Stripe sends a payment_intent.payment_failed event when an attempt fails. After verifying the webhook signature, count those failures and cancel the payment when it reaches your limit:

import type { Db } from "mongodb"
import type Stripe from "stripe"

type FailedPayment = { _id: string; eventIds: string[] }

const CAN_STOP: ReadonlySet<Stripe.PaymentIntent.Status> = new Set([
  "requires_payment_method",
  "requires_confirmation",
  "requires_action",
])

export const handleFailedPayment = async ({
  db,
  stripe,
  event,
  maxFailures,
}: {
  db: Db
  stripe: Pick<Stripe, "paymentIntents">
  event: Stripe.PaymentIntentPaymentFailedEvent
  maxFailures: number
}) => {
  const { id } = event.data.object
  const payment = await db
    .collection<FailedPayment>("failed_payments")
    .findOneAndUpdate(
      { _id: id },
      { $addToSet: { eventIds: event.id } },
      { upsert: true, returnDocument: "after" }
    )
  if (!payment || payment.eventIds.length < maxFailures) return

  const current = await stripe.paymentIntents.retrieve(id)
  if (CAN_STOP.has(current.status)) await stripe.paymentIntents.cancel(id)
}

Stripe can send the same event more than once. Saving each event's ID means a repeat isn't counted as another failure. If canceling fails, the function throws an error. Return an error to Stripe so it sends the event again, and the next try can cancel the payment.

The function gets the payment's current status from Stripe because the event may be out of date. It leaves payments alone if they've been paid, are processing or have been authorized for later capture. The status can still change between that check and the cancellation. If Stripe then refuses to cancel, the next webhook retry checks the status again.

If the payment is canceled, show a clear message and make the customer start a new one. That must go through the limits in step 3. Remove old records from failed_payments once you no longer need them.

Work out the real limit

Multiply new payments by the failures you allow on each one. With five new payments an hour and three failures each, one account could make about 15 failed attempts an hour.

For tighter control, use webhooks to count failures and different cards across the whole account. Check those totals before creating or returning a payment, and cancel the account's other open payments if it goes over.

What this can't stop

Webhooks arrive after an attempt, so a few more cards could be tried before the payment is canceled. This limits the damage, but it isn't an exact cap.

If you need to check every attempt first, Stripe's manual confirmation method requires your secret key each time. Your server can then check the limits before every confirmation. This changes your checkout, including extra steps such as 3D Secure, so test every payment method you accept before switching.

If customers can save cards, protect that process too. The code above doesn't cover SetupIntents, so they need their own limits and failure handling.

Step 5: Add more protection

Check for bots with Turnstile

Add Cloudflare Turnstile before customers create a payment or save a card, and check its token on your server with Siteverify. The widget does nothing on its own. If you set an action, check it as well as the hostname.

Tokens last five minutes and are meant to be used once. Cloudflare says two checks made very close together may both pass, so you still need your own limits.

Turnstile also has the gap from step 4. Checking it when you create a payment doesn't check later card attempts that go straight to Stripe.

Make people sign in

Stripe says requiring sign-in or checking the session before payment can reduce card testing. It also gives you an account to limit.

Attackers can make new accounts, so protect sign-up too. If you offer guest checkout, use a session created by your server, and remember that an attacker can start a new one.

Give Stripe more to work with

If you use the latest Payment Element or Checkout, Stripe adds its own protection, including limits, AI models and CAPTCHAs. Its results depend on your integration and the information you send:

  • Keep Stripe's advanced fraud detection on. Stripe says this information has the biggest impact on preventing card testing.
  • Load Stripe.js throughout the shopping experience, as Stripe recommends, not just at checkout. Check your privacy and consent rules first.
  • Send accurate customer details when you have them. Email, name, billing address and IP address all help. Don't send Cloudflare's address as the customer's.

As of November 2026, Stripe includes card testing protection in every Radar plan. Custom rules need Radar Plus or Pro. They can use values such as card_count_for_ip_address_hourly, which counts the cards linked to an IP address in the past hour. Test a rule on past payments before turning it on.

Use Cloudflare to block floods

A Cloudflare rate limit can stop a burst of requests before it reaches your app, but it can't replace your own payment limits:

  • Free and Pro plans count by IP address.
  • The Free plan includes one rule with a 10-second window, so slower attacks can stay under the limit.
  • Counts generally aren't shared between data centers.
  • Your Cloudflare rules don't see card attempts sent straight from the browser to Stripe.

What to do during an attack

  1. Stop delivery. Hold suspicious orders, especially digital goods you can't get back.
  2. Slow or pause the part being attacked. That could be new payments, saved cards or guest checkout. Existing PaymentIntents may still work, so cancel suspicious ones that haven't been paid.
  3. Find what the attempts have in common. Compare accounts, IP addresses, card fingerprints, amounts and times. One match doesn't prove fraud.
  4. Refund suspicious payments that went through. Stripe recommends this to help avoid disputes. Make sure your refund process can't pay twice.
  5. Don't keep retrying saved cards on accounts linked to the attack. Include subscriptions and automatic retries in that check.
  6. Check your keys. If payments were made without going through your app, your Stripe secret key may have leaked. Replace it and find out how it was exposed.
  7. Watch what happens next. Make sure failures go down and real customers can still pay.

Save what you need to investigate, but never log full card numbers or security codes. Keep messages to blocked customers general too. Telling someone which limit they reached helps an attacker avoid it.

If you find you've been saving the wrong IP address, fix that before relying on those records. Only correct old records if you have a reliable source, and note what you changed. Don't guess.

Test your protection

We ran the functions in this guide with a temporary MongoDB database and a stand-in for Stripe:

Test Result
Send a fake CF-Connecting-IP with no secret or the wrong one No address is trusted
Leave the secret out of the app's settings No address is trusted
Send only X-Forwarded-For, with the correct secret No address is trusted
Use two IPv6 addresses in the same /64 block They share one limit
Make 50 attempts at once with a limit of 5, and repeat for 10 accounts 5 are allowed each time
Try 20 accounts at once from one address with a limit of 8 8 are allowed in total
Send the same failed-payment event more than once It counts as one failure
Reach the limit of 3 failures The payment is canceled once
Reach the limit after a payment is paid, processing, authorized or canceled It's left alone
Have Stripe's cancellation fail, then send the event again The payment is canceled

These tests don't cover your Cloudflare settings, live Stripe events or the route example in step 3. Before launch, check that:

  • Your app gets your real address through Cloudflare, over both IPv4 and IPv6.
  • Payments are refused if someone bypasses Cloudflare, including through your host's default domain.
  • In Stripe's test environment, repeated declines cancel the PaymentIntent, and the next card is refused.
  • A real customer can fix a mistake and pay.

Don't test this with real stolen cards or lots of live payments. Use Stripe's test cards in a test environment.

What is card testing?

Card testing is when someone uses your checkout or card-saving form to find out whether stolen card details work. It's also called carding, account testing, enumeration or card checking.

How do I get a visitor's real IP address behind Cloudflare?

For normal traffic through Cloudflare's proxy, read CF-Connecting-IP, but only after confirming the request came through Cloudflare. Otherwise, someone who connects directly to your app can fake it. If a Worker calls your app, check that setup separately.

Can X-Forwarded-For be spoofed?

Yes. A visitor can send their own X-Forwarded-For header. Cloudflare adds to an existing one instead of replacing it, so the first address may be fake. Other proxies and hosts can handle the header differently.

Does Cloudflare stop card testing?

Not on its own. Its bot checks and rate limits can reduce attacks on your app, but your rules don't see cards sent straight from the browser to Stripe. You also need payment limits on your server, failure handling and Stripe's fraud protection.

Can one Stripe PaymentIntent be used to try several cards?

Yes. After a failed attempt, a PaymentIntent returns to requires_payment_method and can be tried with another card. With automatic confirmation, the browser can do this without calling your server again. Count failures using webhooks and cancel the PaymentIntent at your limit, or use manual confirmation to check each attempt first.

Should I refund card testing payments?

Stripe recommends refunding fraudulent payments to help avoid disputes. Stop any delivery first, review related payments, and make sure each refund can only happen once.

Cover: Photo by JERO SenneGs on Unsplash

More articles to read

Have something to build? Tell us what you're working on. You'll hear back directly from one of the founders.