# Radar

Stripe Radar provides advanced fraud prevention and risk management tools using machine learning to analyze payments and identify suspicious activity. It includes customizable rules, allow/block lists, and comprehensive fraud analytics to protect businesses from fraudulent transactions.

## Fraud Prevention

### Radar.EarlyFraudWarnings

Monitor and manage early fraud warnings from card networks:

```typescript { .api }
interface EarlyFraudWarning {
  id: string;
  object: 'radar.early_fraud_warning';
  actionable: boolean;
  charge: string;
  created: number;
  fraud_type: 'card_never_received' | 'fraudulent_card_application' | 'made_with_counterfeit_card' | 'made_with_lost_card' | 'made_with_stolen_card' | 'misc' | 'unauthorized_use_of_card';
  livemode: boolean;
  payment_intent?: string;
}

// Retrieve early fraud warning
const warning = await stripe.radar.earlyFraudWarnings.retrieve('issfr_123');

// List early fraud warnings
const warnings = await stripe.radar.earlyFraudWarnings.list({
  limit: 10,
  charge: 'ch_123'
});

// List warnings by creation date
const recentWarnings = await stripe.radar.earlyFraudWarnings.list({
  created: {
    gte: Math.floor(Date.now() / 1000) - (7 * 24 * 60 * 60) // Last 7 days
  }
});
```

### Radar.ValueLists

Create and manage lists of values for fraud prevention rules:

```typescript { .api }
interface ValueList {
  id: string;
  object: 'radar.value_list';
  alias: string;
  created: number;
  created_by: string;
  item_type: 'card_bin' | 'card_fingerprint' | 'case_sensitive_string' | 'country' | 'customer_id' | 'email' | 'ip_address' | 'sepa_debit_fingerprint' | 'string' | 'us_bank_account_fingerprint';
  list_items: {
    data: Array<{
      id: string;
      value: string;
      created: number;
      created_by: string;
    }>;
    has_more: boolean;
    url: string;
  };
  livemode: boolean;
  metadata: Record<string, string>;
  name: string;
}

// Create value list for blocked emails
const emailBlocklist = await stripe.radar.valueLists.create({
  alias: 'blocked_emails',
  name: 'Blocked Email Domains',
  item_type: 'email',
  metadata: {
    purpose: 'fraud_prevention'
  }
});

// Create IP address allowlist
const ipAllowlist = await stripe.radar.valueLists.create({
  alias: 'trusted_ips',
  name: 'Trusted IP Addresses',
  item_type: 'ip_address'
});

// Create country blocklist
const countryBlocklist = await stripe.radar.valueLists.create({
  alias: 'blocked_countries',
  name: 'High Risk Countries',
  item_type: 'country'
});

// Retrieve value list
const retrieved = await stripe.radar.valueLists.retrieve('rsl_123');

// Update value list
const updated = await stripe.radar.valueLists.update('rsl_123', {
  name: 'Updated Blocked Emails',
  metadata: {
    last_updated: new Date().toISOString()
  }
});

// List value lists
const valueLists = await stripe.radar.valueLists.list({
  limit: 10
});

// Delete value list
const deleted = await stripe.radar.valueLists.del('rsl_123');
```

### Radar.ValueListItems

Manage individual items within value lists:

```typescript { .api }
interface ValueListItem {
  id: string;
  object: 'radar.value_list_item';
  created: number;
  created_by: string;
  livemode: boolean;
  value: string;
  value_list: string;
}

// Add items to email blocklist
const blockedEmail = await stripe.radar.valueListItems.create({
  value_list: 'rsl_123',
  value: 'suspicious@example.com'
});

// Add multiple IPs to allowlist
const trustedIps = [
  '192.168.1.1',
  '10.0.0.1',
  '172.16.0.1'
];

for (const ip of trustedIps) {
  await stripe.radar.valueListItems.create({
    value_list: 'rsl_456',
    value: ip
  });
}

// Add country codes to blocklist
const blockedCountries = ['XX', 'YY'];
for (const country of blockedCountries) {
  await stripe.radar.valueListItems.create({
    value_list: 'rsl_789',
    value: country
  });
}

// Retrieve value list item
const item = await stripe.radar.valueListItems.retrieve('rsli_123');

// List items in value list
const items = await stripe.radar.valueListItems.list({
  value_list: 'rsl_123',
  limit: 100
});

// Delete value list item
const deletedItem = await stripe.radar.valueListItems.del('rsli_123');
```

## Fraud Analytics and Rules

### Custom Radar Rules

```typescript { .api }
// Example: Block payments from high-risk countries
// This would be configured in the Stripe Dashboard, but you can reference lists:

// Create a rule in Dashboard like:
// "Block if :ip_country: is in :blocked_countries:"
// where :blocked_countries: references your value list

// The API doesn't create rules directly, but you can manage the data that rules use
const highRiskCountries = await stripe.radar.valueLists.create({
  alias: 'high_risk_countries',
  name: 'High Risk Countries',
  item_type: 'country'
});

// Add countries to the list
const riskCountries = ['CN', 'RU', 'NG'];
for (const country of riskCountries) {
  await stripe.radar.valueListItems.create({
    value_list: highRiskCountries.id,
    value: country
  });
}
```

### Payment Monitoring

```typescript { .api }
// Monitor payment outcomes for fraud analysis
app.post('/webhook', (req, res) => {
  const event = stripe.webhooks.constructEvent(
    req.body,
    req.headers['stripe-signature'],
    endpointSecret
  );

  switch (event.type) {
    case 'radar.early_fraud_warning.created':
      const warning = event.data.object;
      console.log('Early fraud warning:', {
        charge: warning.charge,
        fraud_type: warning.fraud_type,
        actionable: warning.actionable
      });
      
      // Take action on high-risk warnings
      if (warning.actionable) {
        handleFraudWarning(warning);
      }
      break;
      
    case 'charge.dispute.created':
      const dispute = event.data.object;
      
      // Analyze dispute patterns
      analyzeDisputePattern(dispute);
      break;
      
    case 'payment_intent.payment_failed':
      const failedPayment = event.data.object;
      
      // Check if failure was due to fraud prevention
      if (failedPayment.last_payment_error?.decline_code) {
        logFraudPrevention(failedPayment);
      }
      break;
  }

  res.json({ received: true });
});

async function handleFraudWarning(warning: any) {
  // Retrieve the charge details
  const charge = await stripe.charges.retrieve(warning.charge);
  
  // Add customer email to watch list if needed
  if (charge.billing_details?.email) {
    await stripe.radar.valueListItems.create({
      value_list: 'suspicious_emails_list_id',
      value: charge.billing_details.email
    });
  }
  
  // Refund if appropriate
  if (warning.fraud_type === 'unauthorized_use_of_card') {
    await stripe.refunds.create({
      charge: warning.charge,
      reason: 'fraudulent'
    });
  }
}
```

### Risk Assessment Integration

```typescript { .api }
// Create PaymentIntent with Radar context
const paymentIntent = await stripe.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  customer: 'cus_123',
  payment_method_types: ['card'],
  metadata: {
    order_id: 'order_12345',
    user_id: 'user_789'
  },
  // Radar will automatically analyze this payment
  radar_options: {
    session: 'session_abc123' // Optional: link to checkout session
  }
});

// Check outcome after confirmation
const confirmedPayment = await stripe.paymentIntents.confirm(paymentIntent.id, {
  payment_method: 'pm_card_visa'
});

// Access Radar outcome
const outcome = confirmedPayment.charges?.data[0]?.outcome;
if (outcome) {
  console.log('Radar risk assessment:', {
    risk_level: outcome.risk_level, // 'normal', 'elevated', 'highest'
    risk_score: outcome.risk_score, // 0-100
    reason: outcome.reason,
    seller_message: outcome.seller_message
  });
}
```

### Advanced List Management

```typescript { .api }
// Create comprehensive fraud prevention lists
async function setupFraudPrevention() {
  // 1. Blocked email domains
  const emailBlocklist = await stripe.radar.valueLists.create({
    alias: 'blocked_email_domains',
    name: 'Blocked Email Domains',
    item_type: 'string'
  });
  
  const suspiciousDomains = [
    '10minutemail.com',
    'tempmail.org',
    'guerrillamail.com'
  ];
  
  for (const domain of suspiciousDomains) {
    await stripe.radar.valueListItems.create({
      value_list: emailBlocklist.id,
      value: domain
    });
  }
  
  // 2. Trusted customer IDs
  const trustedCustomers = await stripe.radar.valueLists.create({
    alias: 'trusted_customers',
    name: 'Trusted Customers',
    item_type: 'customer_id'
  });
  
  // 3. Blocked card BINs
  const blockedBins = await stripe.radar.valueLists.create({
    alias: 'blocked_card_bins',
    name: 'Blocked Card BINs',
    item_type: 'card_bin'
  });
  
  return {
    emailBlocklist,
    trustedCustomers,
    blockedBins
  };
}

// Maintenance: Clean up old entries
async function cleanupValueLists() {
  const valueLists = await stripe.radar.valueLists.list({ limit: 100 });
  
  for (const list of valueLists.data) {
    const items = await stripe.radar.valueListItems.list({
      value_list: list.id,
      limit: 100
    });
    
    // Remove outdated items (example: older than 6 months)
    const sixMonthsAgo = Math.floor(Date.now() / 1000) - (6 * 30 * 24 * 60 * 60);
    
    for (const item of items.data) {
      if (item.created < sixMonthsAgo) {
        await stripe.radar.valueListItems.del(item.id);
      }
    }
  }
}
```

Stripe Radar provides comprehensive fraud protection through machine learning-based risk assessment, customizable rules, and detailed analytics, helping businesses reduce chargebacks and fraudulent transactions while maintaining a smooth experience for legitimate customers.