كل المستندات

أمثلة الدمج

أمثلة دمج جاهزة لواجهة كشف الاحتيال بلغات Node.js وPython وcURL، مع معالجات Webhook لقرارات السماح والمراجعة والحظر.

أمثلة الكود

أمثلة تكامل كاملة توضح إرسال الأحداث ومعالجة القرارات داخل تطبيقك.

Node.js
const axios = require("axios");

async function submitEvent(eventData) {
  try {
    const response = await axios.post(
      "https://api.naiza.ai/api/v1/events",
      eventData,
      {
        headers: {
          "x-api-key": process.env.NAIZA_API_KEY,
          "Content-Type": "application/json",
        },
      },
    );

    const { decision, score } = response.data;

    if (decision === "BLOCK") {
      throw new Error("Access denied due to fraud detection");
    }

    if (decision === "REVIEW") {
      return { require2FA: true, score };
    }

    return { allowed: true, score };
  } catch (error) {
    console.error("Fraud check failed:", error);
    return { allowed: true }; // Fail open
  }
}

// Usage in login endpoint
app.post("/login", async (req, res) => {
  const { email, password } = req.body;
  const user = await authenticateUser(email, password);

  const fraudCheck = await submitEvent({
    eventName: "user.login",
    eventCategory: "AUTHENTICATION",
    customer: {
      externalId: user.id,
      email: email,
    },
    device: {
      fingerprint: req.body.deviceFingerprint,
    },
    ip: req.ip,
    userAgent: req.headers["user-agent"],
    sessionId: req.sessionID,
    metadata: {
      login_method: "password",
      auth_result: "success",
    },
  });

  if (fraudCheck.require2FA) {
    return res.json({ nextStep: "2fa_required" });
  }

  if (!fraudCheck.allowed) {
    return res.status(403).json({ error: "Access denied" });
  }

  res.json({ token: sessionToken });
});
Python
import requests
import os
from flask import Flask, request, jsonify

app = Flask(__name__)

def submit_event(event_data):
    try:
        response = requests.post(
            'https://api.naiza.ai/api/v1/events',
            headers={
                'x-api-key': os.environ['NAIZA_API_KEY'],
                'Content-Type': 'application/json'
            },
            json=event_data
        )

        response.raise_for_status()
        data = response.json()

        if data['decision'] == 'BLOCK':
            return {'allowed': False, 'reason': 'blocked'}

        if data['decision'] == 'REVIEW':
            return {'allowed': True, 'require_2fa': True}

        return {'allowed': True, 'score': data['score']}

    except requests.exceptions.RequestException as e:
        print(f'Fraud check failed: {e}')
        return {'allowed': True}  # Fail open

@app.route('/login', methods=['POST'])
def login():
    data = request.json
    email = data.get('email')
    password = data.get('password')

    user = authenticate_user(email, password)

    fraud_check = submit_event({
        'eventName': 'user.login',
        'eventCategory': 'AUTHENTICATION',
        'customer': {
            'externalId': user['id'],
            'email': email,
        },
        'device': {
            'fingerprint': data.get('device_fingerprint'),
        },
        'ip': request.remote_addr,
        'userAgent': request.headers.get('User-Agent'),
        'sessionId': request.cookies.get('session_id'),
        'metadata': {
            'login_method': 'password',
            'auth_result': 'success',
        },
    })

    if not fraud_check['allowed']:
        return jsonify({'error': 'Access denied'}), 403

    if fraud_check.get('require_2fa'):
        return jsonify({'nextStep': '2fa_required'})

    return jsonify({'token': session_token})
PHP
<?php

function submitEvent(array $eventData): array {
    $apiKey = getenv('NAIZA_API_KEY');

    $ch = curl_init('https://api.naiza.ai/api/v1/events');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($eventData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'x-api-key: ' . $apiKey,
        'Content-Type: application/json'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 201) {
        return ['allowed' => true]; // Fail open on error
    }

    $data = json_decode($response, true);

    if ($data['decision'] === 'BLOCK') {
        return ['allowed' => false];
    }

    if ($data['decision'] === 'REVIEW') {
        return ['allowed' => true, 'require2FA' => true];
    }

    return ['allowed' => true, 'score' => $data['score']];
}
Ruby
require 'net/http'
require 'json'

def submit_event(event_data)
  uri = URI('https://api.naiza.ai/api/v1/events')

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.path, {
    'x-api-key' => ENV['NAIZA_API_KEY'],
    'Content-Type' => 'application/json'
  })
  request.body = event_data.to_json

  response = http.request(request)
  data = JSON.parse(response.body)

  if data['decision'] == 'BLOCK'
    { allowed: false }
  elsif data['decision'] == 'REVIEW'
    { allowed: true, require_2fa: true }
  else
    { allowed: true, score: data['score'] }
  end
rescue StandardError => e
  Rails.logger.error("Fraud check failed: #{e}")
  { allowed: true } # Fail open
end