React Hooks Guide for Fraud Buster API Integration


Comprehensive Guide on Using the useAPI Custom Hook


Overview

Welcome to the useAPI Hook guide! This document provides step-by-step instructions to help you integrate and utilize the useAPI custom React hook for seamless API interactions.

The useAPI hook simplifies sending API requests and managing responses, including handling loading states, errors, and dynamic location data for enhanced fraud detection.


Prerequisites

Before proceeding, ensure you have the following:

  • Node.js and npm installed.
  • Basic knowledge of React and JavaScript/ES6.
  • A working React project where you want to implement the useAPI hook.
  • An API key provided by Hive Forensics AI.

Setup Instructions

Step 1: Create the useAPI Hook

Create a new folder named hooks inside your src directory and add a file called useAPI.js.

mkdir src/hooks
touch src/hooks/useAPI.js

useAPI.js

import { useState } from 'react';

/**
 * Custom React Hook for API Requests
 */
const useAPI = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  /**
   * Fetch user's location using IP or Geolocation
   */
  const getLocation = async () => {
    const url = 'https://ipinfo.io/json?token=your_token_here'; // Replace with your IP info token
    try {
      const response = await fetch(url);
      const data = await response.json();
      return data.city && data.country ? `${data.city}, ${data.country}` : 'Unknown Location';
    } catch {
      return 'Unknown Location';
    }
  };

  /**
   * Send a POST request to the Fraud Buster API
   * @param {string} url - API endpoint
   * @param {Object} data - Payload
   * @param {string} apiKey - API Key
   * @returns {Object} - API Response
   */
  const postData = async (url, data, apiKey) => {
    setIsLoading(true);
    setError(null);

    try {
      const location = await getLocation(); // Append user's location
      const requestData = { ...data, location }; // Add location to the request body

      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': apiKey,
        },
        body: JSON.stringify(requestData),
      });

      if (!response.ok) {
        throw new Error('API Request Failed');
      }

      const result = await response.json();
      setIsLoading(false);
      return result;
    } catch (err) {
      setError(err.message);
      setIsLoading(false);
      throw err;
    }
  };

  return { postData, isLoading, error };
};

export default useAPI;

Step 2: Import and Use the useAPI Hook

Example Component

import React, { useState } from 'react';
import useAPI from '../hooks/useAPI';

const FraudChecker = () => {
  const { postData, isLoading, error } = useAPI();
  const [response, setResponse] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const transactionData = {
      product: "Rolex Watch",
      amount: 9500,
      location: "Florida",
      time: "2024-03-04T10:30:00Z",
      customerProfile: "Tech Enthusiast",
      onlinePurchase: true,
      paymentMethod: "Amex",
      shippingAddress: "PO BOX 8877 Los Angeles CA 90210",
      billingAddress: "18803 SW 92 Ave Miami Florida 33157",
      customerEmail: "sam@protonmail.com",
      customerName: "Steven Smith",
      isVPN: false,
      clientBrowser: "Chrome",
      deviceType: "Desktop",
      ipAddress: "352.168.1.186",
      deviceFingerprint: "abcd1234efgh5678",
      transactionFrequency: 2,
      accountAge: 365,
      emailDomain: "protonmail.com",
      addressMismatch: true,
      twoFactorAuth: false,
      referralSource: "Google Search",
      proxyOrVPN: true,
      orderQuantity: 1,
      strictness: 50
    };

    try {
      const result = await postData(
        process.env.REACT_APP_FRAUD_BUSTER_URL,
        transactionData,
        process.env.REACT_APP_FRAUD_BUSTER_API_KEY
      );
      setResponse(result);
    } catch (err) {
      console.error('Error:', err.message);
    }
  };

  return (
    <div>
      <h1>Fraud Buster Test</h1>
      <form onSubmit={handleSubmit}>
        <button type="submit">Check Transaction</button>
      </form>
      {isLoading && <p>Loading...</p>}
      {error && <p>Error: {error}</p>}
      {response && <pre>{JSON.stringify(response, null, 2)}</pre>}
    </div>
  );
};

export default FraudChecker;

Step 3: Handle UI States

The useAPI hook provides isLoading and error states, enabling a better user experience by displaying progress indicators or error messages.

if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;

Response Format

A typical API response looks like this:

{
  "transactionId": "821c09c1-fdaa-4199-b3ea-c4b715f8a150",
  "ConfidenceLevel": "Medium",
  "Result": "Failed"
}

Risk Level Definitions

Risk LevelDescription
0Critical Risk - Immediate Failure
1High Risk - Manual Verification Required
2Failed
3Monitor Closely - Review Logs
4Low Risk - Auto Approved
5Safe Zone - Pass
6Caution - Review Recommended
7Additional Verification Needed (Fallback)

Additional Information

  • Security: Always store API keys in environment variables.
  • Testing: Use tools like Postman or cURL to test endpoints before integrating.
  • Debugging: Log responses and errors during development to simplify debugging.

FAQ

For more details and troubleshooting, visit our FAQ section.