> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dncscrub.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript Examples

> JavaScript code examples for CCC APIs

# JavaScript Code Examples

Complete JavaScript examples for integrating with CCC APIs. These examples work in both Node.js and browser environments.

<Warning>
  In browser environments, API calls may be blocked by CORS. These APIs are designed for server-side use. For client-side applications, make calls through your backend.
</Warning>

## Scrub API - Basic Example

```javascript theme={null}
async function scrubPhoneNumber(phoneNumber, apiKey) {
  const url = `https://www.dncscrub.com/app/main/rpc/scrub?phoneList=${phoneNumber}&version=5&output=json`;

  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'loginId': apiKey
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const data = await response.json();
  return data[0];
}

// Usage
const result = await scrubPhoneNumber('7075276405', 'YOUR_API_KEY');
console.log(`Result Code: ${result.ResultCode}`);
console.log(`Reason: ${result.Reason}`);
```

## Scrub Multiple Phone Numbers

```javascript theme={null}
async function scrubMultipleNumbers(phoneNumbers, apiKey) {
  const phoneList = phoneNumbers.join(',');
  const url = `https://www.dncscrub.com/app/main/rpc/scrub?phoneList=${phoneList}&version=5&output=json`;

  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'loginId': apiKey
    }
  });

  const results = await response.json();

  // Categorize results
  const clean = results.filter(r => r.ResultCode === 'C');
  const doNotCall = results.filter(r => r.ResultCode === 'D');
  const wireless = results.filter(r => r.IsWirelessOrVoIP === '1');

  return {
    all: results,
    clean,
    doNotCall,
    wireless,
    summary: {
      total: results.length,
      cleanCount: clean.length,
      dncCount: doNotCall.length,
      wirelessCount: wireless.length
    }
  };
}

// Usage
const numbers = ['5039367187', '7075276405', '7072842774'];
const results = await scrubMultipleNumbers(numbers, 'YOUR_API_KEY');
console.log(`Clean: ${results.summary.cleanCount}`);
console.log(`DNC: ${results.summary.dncCount}`);
```

## Scrub with Unique Identifiers

```javascript theme={null}
async function scrubWithIds(records, apiKey) {
  // records = [{ phone: '5039367187', id: 'ACCT-001' }, ...]

  const phoneList = records
    .map(r => `${r.phone}|${r.id}`)
    .join(',');

  const url = `https://www.dncscrub.com/app/main/rpc/scrub?phoneList=${encodeURIComponent(phoneList)}&version=5&output=json`;

  const response = await fetch(url, {
    headers: { 'loginId': apiKey }
  });

  const results = await response.json();

  // Results have your ID in the Reserved field
  return results.map(r => ({
    phone: r.Phone,
    accountId: r.Reserved,  // Your unique ID
    resultCode: r.ResultCode,
    reason: r.Reason
  }));
}

// Usage
const records = [
  { phone: '5039367187', id: 'ACCT-001' },
  { phone: '7075276405', id: 'ACCT-002' }
];
const results = await scrubWithIds(records, 'YOUR_API_KEY');
```

## HTTP POST for Large Batches

```javascript theme={null}
async function scrubLargeBatch(phoneNumbers, apiKey) {
  const response = await fetch('https://www.dncscrub.com/app/main/rpc/scrub', {
    method: 'POST',
    headers: {
      'loginId': apiKey,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
      phoneList: phoneNumbers.join(','),
      version: '5',
      output: 'json'
    })
  });

  return await response.json();
}
```

## TCPA Authority API

```javascript theme={null}
async function checkReassigned(phoneNumber, consentDate, apiKey) {
  const url = `https://dataapi.dncscrub.com/v1.4/Data/TCPAAuthority?phoneNumber=${phoneNumber}&date=${consentDate}`;

  const response = await fetch(url, {
    headers: { 'loginId': apiKey }
  });

  const result = await response.json();

  return {
    phoneNumber: result.PhoneNumber,
    isReassigned: result.IsReassigned,
    isValid: result.IsValid,
    lineType: result.LineType,
    carrier: result.Carrier,
    location: `${result.Locale}, ${result.Region}`,
    timezone: result.TZ
  };
}

// Usage
const result = await checkReassigned('7075276405', '20210209', 'YOUR_API_KEY');

if (result.isReassigned === true) {
  console.log('DO NOT CALL - Number reassigned');
} else if (result.isReassigned === false) {
  console.log('Safe to call');
} else {
  console.log('Unable to determine - proceed with caution');
}
```

## Litigator API

```javascript theme={null}
async function checkLitigators(phoneNumbers, apiKey) {
  const phoneList = phoneNumbers.join(',');
  const url = `https://dataapi.dncscrub.com/v1.4/scrub/litigator?phoneList=${phoneList}`;

  const response = await fetch(url, {
    headers: { 'loginId': apiKey }
  });

  const results = await response.json();

  const litigators = results.filter(r => r.IsLitigator);
  const safe = results.filter(r => !r.IsLitigator);

  return { litigators, safe };
}

// Usage
const { litigators, safe } = await checkLitigators(['5039367187', '7075276405'], 'YOUR_API_KEY');
console.log(`Litigators found: ${litigators.length}`);
```

## Internal DNC Management

```javascript theme={null}
// Add to Internal DNC
async function addToInternalDNC(phoneNumber, apiKey) {
  const url = `https://www.dncscrub.com/app/main/rpc/pdnc?phoneList=${phoneNumber}&actionType=add`;

  const response = await fetch(url, {
    headers: { 'loginId': apiKey }
  });

  return response.ok;
}

// Remove from Internal DNC
async function removeFromInternalDNC(phoneNumber, apiKey) {
  const url = `https://www.dncscrub.com/app/main/rpc/pdnc?phoneList=${phoneNumber}&actionType=remove`;

  const response = await fetch(url, {
    headers: { 'loginId': apiKey }
  });

  return response.ok;
}
```

## TrustCall Premier API

```javascript theme={null}
// Add numbers to monitoring
async function addToTrustCall(numbers, apiKey) {
  const response = await fetch('https://trustcallapi.dncscrub.com/v1.4/trustcall/add', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'loginId': apiKey
    },
    body: JSON.stringify(numbers.map(phone => ({ Phone: phone })))
  });

  return await response.json();
}

// Check scores
async function getTrustCallScores(phoneNumbers, apiKey) {
  const phoneList = phoneNumbers.join(',');
  const url = `https://trustcallapi.dncscrub.com/v1.4/trustcall/get?phoneList=${phoneList}`;

  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      'loginId': apiKey
    }
  });

  return await response.json();
}
```

## Error Handling Wrapper

```javascript theme={null}
class CCCApiClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://www.dncscrub.com/app/main/rpc';
  }

  async request(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;

    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          'loginId': this.apiKey,
          ...options.headers
        }
      });

      if (response.status === 401) {
        throw new Error('Invalid API Key');
      }

      if (response.status === 429) {
        throw new Error('Rate limit exceeded');
      }

      if (!response.ok) {
        const error = await response.text();
        throw new Error(`API Error: ${error}`);
      }

      const contentType = response.headers.get('content-type');
      if (contentType?.includes('application/json')) {
        return await response.json();
      }
      return await response.text();

    } catch (error) {
      if (error.name === 'TypeError') {
        throw new Error('Network error - check your connection');
      }
      throw error;
    }
  }

  async scrub(phoneNumbers) {
    const phoneList = Array.isArray(phoneNumbers) ? phoneNumbers.join(',') : phoneNumbers;
    return this.request(`/scrub?phoneList=${phoneList}&version=5&output=json`);
  }
}

// Usage
const client = new CCCApiClient('YOUR_API_KEY');
try {
  const results = await client.scrub(['5039367187', '7075276405']);
  console.log(results);
} catch (error) {
  console.error('API Error:', error.message);
}
```

## HTML Form Example

A complete HTML example for browser-based scrubbing (through your backend):

```html theme={null}
<!DOCTYPE html>
<html>
<head>
  <title>Phone Scrubber</title>
</head>
<body>
  <h2>Phone Number Scrubber</h2>
  <form id="scrubForm">
    <label>Phone Number (10 digits):</label>
    <input type="text" id="phoneNumber" placeholder="5039367187" required>
    <button type="submit">Scrub</button>
  </form>
  <div id="results"></div>

  <script>
    document.getElementById('scrubForm').addEventListener('submit', async (e) => {
      e.preventDefault();

      const phone = document.getElementById('phoneNumber').value.replace(/\D/g, '');
      const resultsDiv = document.getElementById('results');

      // Call YOUR backend, which calls CCC API
      const response = await fetch(`/api/scrub?phone=${phone}`);
      const data = await response.json();

      resultsDiv.innerHTML = `
        <p><strong>Phone:</strong> ${data.Phone}</p>
        <p><strong>Result:</strong> ${data.ResultCode}</p>
        <p><strong>Reason:</strong> ${data.Reason}</p>
        <p><strong>Line Type:</strong> ${data.LineType}</p>
      `;
    });
  </script>
</body>
</html>
```
