{{-- resources/views/pages/api.blade.php --}} Affiliation Leads API - Documentation @php $BASE_URL = rtrim(env('APP_URL'), '/') . '/api/v1'; @endphp
API
Affiliation Leads Collection
API Docs / v1 / Production
Production
REST API • Bearer Authentication • Lead Delivery

API documentation for affiliated lead delivery and tracking

This API is designed for Affiliators, not internal admin users. An affiliator authenticates using their own credentials, receives a Sanctum token, submits leads, and can later retrieve lead records together with related conversion data such as the linked client, its assigned administrator, conversion time, and first funding event. Every successfully created lead also returns a secure one-time profile access URL.

Overview
Current integration flow
The current version differs from the earlier dental-style draft. Authentication is now performed by the Affiliation entity, lead creation supports an optional assigned_to value, converted lead responses expose a compact client object with the first funding event, and lead creation returns a one-time URL that grants profile-only access until conversion.
Flow summary
What changed in the final implementation
1. Authentication principal Token issuance now authenticates the Affiliator account, not the normal admin users table.
2. Lead ownership Every API-created lead stores affiliate_id. The assigned_to field can optionally be sent in the request body and will assign the lead directly to a user.
3. Assigned fallback If assigned_to is not sent, the lead remains unassigned and is stored as null.
4. Lead retrieval When an affiliated lead is converted, the API returns a compact client object and its first funding event without exposing trading-account details.
5. One-time profile access The create response includes auto_login_url. The URL can be consumed once, opens only /client/account while the record remains a lead, and expires after 30 days if unused.
Main endpoints
Current recommended public contract
POST /auth/token Issue Sanctum token using affiliator credentials.
POST /new-lead Create a new lead and return its secure one-time auto_login_url.
GET /leads List only leads belonging to the authenticated affiliator, with optional filters.
GET /leads/{id} Retrieve a single affiliated lead with nested conversion data when available.
The creation endpoint is intentionally published as POST /new-lead, matching routes/api.php. Listing and single-lead retrieval continue to use GET /leads and GET /leads/{lead}.
Authentication
Issue bearer token
Authenticate using the affiliator credentials. The username field is the affiliator email-style username.
POST {{ $BASE_URL }}/auth/token
Field Type Required Description
username string Yes Affiliator username, stored as an email-formatted login.
password string Yes Affiliator password.
device_name string No Optional device label, for example affiliate-crm.
The response identity object should now describe the authenticated affiliator, not a backoffice user.
curl -X POST "{{ $BASE_URL }}/auth/token" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "affiliate@example.com",
    "password": "YourStrongPassword123!",
    "device_name": "affiliate-crm"
  }'
import axios from "axios";

const baseURL = "{{ $BASE_URL }}";

async function issueToken() {
  const res = await axios.post(`${baseURL}/auth/token`, {
    username: "affiliate@example.com",
    password: "YourStrongPassword123!",
    device_name: "affiliate-crm"
  }, {
    headers: { Accept: "application/json" }
  });

  console.log(res.data);
}

issueToken().catch(console.error);
<?php
$baseUrl = "{{ $BASE_URL }}";
$payload = [
    "username" => "affiliate@example.com",
    "password" => "YourStrongPassword123!",
    "device_name" => "affiliate-crm",
];

$ch = curl_init($baseUrl . "/auth/token");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Accept: application/json",
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);

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

echo "HTTP {$http}\n";
echo $response;
import requests

base_url = "{{ $BASE_URL }}"

response = requests.post(
    f"{base_url}/auth/token",
    json={
        "username": "affiliate@example.com",
        "password": "YourStrongPassword123!",
        "device_name": "affiliate-crm"
    },
    headers={"Accept": "application/json"},
    timeout=30
)

print(response.status_code)
print(response.json())
Success response
{
  "status": true,
  "token_type": "Bearer",
  "access_token": "1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "affiliate": {
    "id": 4,
    "company_name": "Alpha Media LTD",
    "username": "affiliate@example.com"
  }
}
Lead creation
Create affiliated lead
The authenticated affiliator creates the lead. The API stores affiliate_id automatically. Send status to set the lead's initial status. If omitted, it defaults to New. If assigned_to is supplied, the lead is routed directly to that user. A successful response also returns a one-time URL for profile-only access to /client/account.
POST {{ $BASE_URL }}/new-lead
Field Type Required Description
first_namestringYesLead first name.
last_namestringYesLead last name.
emailstringNoLead email. Must be unique when present.
phonestringNoLead phone. Must be unique when present.
statusstringNoInitial lead status, up to 255 characters. For example, Contacted. Defaults to New when omitted, null, empty, or whitespace-only. Leading and trailing whitespace is trimmed.
assigned_tointegerNoOptional admin/user ID that should immediately own the lead.
countrystringNoCountry name.
citystringNoCity name.
sourcestringNoTraffic source.
campaignstringNoCampaign label.
utm_sourcestringNoUTM source.
utm_mediumstringNoUTM medium.
utm_campaignstringNoUTM campaign.
prioritystringNoOne of: low, medium, high.
notesstringNoFree-text notes.
doctor_notesstringNoOptional internal notes.
Server-side behavior:
• affiliate_id is always taken from the authenticated affiliator token.
• lead_code is auto-generated when omitted.
• Use the lead status values agreed with your administrator, including their spelling and capitalization, so leads appear under the expected status filters.
• A status value other than a string or null, or a string longer than 255 characters after trimming, returns HTTP 422 with an errors.status message.
• created_by and updated_by should not be attributed to the affiliator.
curl -X POST "{{ $BASE_URL }}/new-lead" \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe",
    "email": "john@demo.com",
    "phone": "+41790000000",
    "status": "Contacted",
    "assigned_to": 12,
    "country": "Italy",
    "city": "Milan",
    "source": "facebook",
    "campaign": "Spring Funnel",
    "utm_source": "facebook",
    "utm_medium": "cpc",
    "utm_campaign": "spring-2026",
    "priority": "medium",
    "doctor_notes": "Interested in premium package",
    "notes": "Requested callback in afternoon"
  }'
import axios from "axios";

const baseURL = "{{ $BASE_URL }}";
const token = "<TOKEN>";

async function createLead() {
  const res = await axios.post(`${baseURL}/new-lead`, {
    first_name: "John",
    last_name: "Doe",
    email: "john@demo.com",
    phone: "+41790000000",
    status: "Contacted",
    assigned_to: 12,
    country: "Italy",
    city: "Milan",
    source: "facebook",
    campaign: "Spring Funnel",
    utm_source: "facebook",
    utm_medium: "cpc",
    utm_campaign: "spring-2026",
    priority: "medium",
    doctor_notes: "Interested in premium package",
    notes: "Requested callback in afternoon"
  }, {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
      "Content-Type": "application/json"
    }
  });

  console.log(res.data);
}

createLead().catch(console.error);
<?php
$baseUrl = "{{ $BASE_URL }}";
$token = "<TOKEN>";

$payload = [
    "first_name" => "John",
    "last_name"  => "Doe",
    "email"      => "john@demo.com",
    "phone"      => "+41790000000",
    "status"     => "Contacted",
    "assigned_to"=> 12,
    "country"    => "Italy",
    "city"       => "Milan",
    "source"     => "facebook",
    "campaign"   => "Spring Funnel",
    "utm_source" => "facebook",
    "utm_medium" => "cpc",
    "utm_campaign" => "spring-2026",
    "priority"   => "medium",
    "doctor_notes" => "Interested in premium package",
    "notes" => "Requested callback in afternoon",
];

$ch = curl_init($baseUrl . "/new-lead");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $token",
        "Accept: application/json",
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);

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

echo "HTTP {$http}\n";
echo $response;
import requests

base_url = "{{ $BASE_URL }}"
token = "<TOKEN>"

response = requests.post(
    f"{base_url}/new-lead",
    json={
        "first_name": "John",
        "last_name": "Doe",
        "email": "john@demo.com",
        "phone": "+41790000000",
        "status": "Contacted",
        "assigned_to": 12,
        "country": "Italy",
        "city": "Milan",
        "source": "facebook",
        "campaign": "Spring Funnel",
        "utm_source": "facebook",
        "utm_medium": "cpc",
        "utm_campaign": "spring-2026",
        "priority": "medium",
        "doctor_notes": "Interested in premium package",
        "notes": "Requested callback in afternoon"
    },
    headers={
        "Authorization": f"Bearer {token}",
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    timeout=30
)

print(response.status_code)
print(response.json())
Success response
{
  "status": true,
  "message": "Lead created successfully.",
  "auto_login_url": "https://example.com/client/auto-login/ONE_TIME_TOKEN",
  "auto_login_url_expires_at": "2026-08-26T09:48:22+02:00",
  "data": {
    "id": 145,
    "affiliate_id": 4,
    "assigned_to": 12,
    "campaign_id": null,
    "lead_code": "AFF20260727-Q8R7L2XM",
    "first_name": "John",
    "last_name": "Doe",
    "email": "john@demo.com",
    "phone": "+41790000000",
    "status": "Contacted",
    "source": "facebook",
    "country": "Italy",
    "city": "Milan",
    "created_at": "2026-07-27T09:48:22+02:00",
    "updated_at": "2026-07-27T09:48:22+02:00",
    "converted_at": null,
    "assigned_user": {
      "id": 12,
      "name": "Sales Agent 12",
      "email": "agent12@example.com"
    },
    "affiliate": {
      "id": 4,
      "company_name": "Alpha Media LTD",
      "username": "affiliate@example.com"
    },
    "client": null
  }
}
The response's top-level status is a boolean indicating whether the request succeeded. data.status contains the saved lead status. The examples above return Contacted. Omitting status from the request returns "status": "New" inside data.
Store or deliver auto_login_url immediately. The raw token is returned only by POST /new-lead, is stored in the database only as a SHA-256 hash, can be used once, and is not returned later by the list or single-lead endpoints. Before conversion, the resulting session can access and update only the profile at /client/account; MT4 and all other client routes remain unavailable.
Lead listing
List affiliator leads
Returns only leads belonging to the authenticated affiliator. Response can include nested converted client information.
GET {{ $BASE_URL }}/leads
Query param Type Description
per_pageintegerItems per page, from 1 to 100. Default: 15.
searchstringSearch in first name, last name, email, phone, and lead code.
statusstringFilter by lead status.
campaign_idintegerFilter by campaign id.
assigned_tointegerFilter by internal assigned user.
registered_fromdate|datetimeInclude leads registered on or after this value.
registered_todate|datetimeInclude leads registered on or before this value.
first_deposit_fromdate|datetimeInclude converted leads whose first successful MT4 deposit occurred on or after this value.
first_deposit_todate|datetimeInclude converted leads whose first successful MT4 deposit occurred on or before this value.
Date-only values such as 2026-07-01 use the application timezone and are expanded to the start or end of that day. First-deposit filtering uses the earliest transaction where action=Deposit and status=success; leads without a converted client or without a successful deposit are excluded whenever a first-deposit filter is supplied.
curl "{{ $BASE_URL }}/leads?per_page=25®istered_from=2026-07-01®istered_to=2026-07-31&first_deposit_from=2026-07-01&first_deposit_to=2026-07-31" \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Accept: application/json"
import axios from "axios";

const baseURL = "{{ $BASE_URL }}";
const token = "<TOKEN>";

async function listLeads() {
  const res = await axios.get(`${baseURL}/leads`, {
    params: {
      per_page: 25,
      registered_from: "2026-07-01",
      registered_to: "2026-07-31",
      first_deposit_from: "2026-07-01",
      first_deposit_to: "2026-07-31"
    },
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json"
    }
  });

  console.log(res.data);
}

listLeads().catch(console.error);
import requests

base_url = "{{ $BASE_URL }}"
token = "<TOKEN>"

response = requests.get(
    f"{base_url}/leads",
    params={
        "per_page": 25,
        "registered_from": "2026-07-01",
        "registered_to": "2026-07-31",
        "first_deposit_from": "2026-07-01",
        "first_deposit_to": "2026-07-31"
    },
    headers={
        "Authorization": f"Bearer {token}",
        "Accept": "application/json"
    },
    timeout=30
)

print(response.status_code)
print(response.json())
List response example
{
  "status": true,
  "filters": {
    "registered_from": "2026-07-01T00:00:00+02:00",
    "registered_to": "2026-07-31T23:59:59+02:00",
    "first_deposit_from": "2026-07-01T00:00:00+02:00",
    "first_deposit_to": "2026-07-31T23:59:59+02:00"
  },
  "data": {
    "current_page": 1,
    "data": [
      {
        "id": 145,
        "affiliate_id": 4,
        "assigned_to": 12,
        "campaign_id": 8,
        "lead_code": "AFF20260703-Q8R7L2XM",
        "first_name": "John",
        "last_name": "Doe",
        "email": "john@demo.com",
        "phone": "+41790000000",
        "status": "client",
        "source": "facebook",
        "country": "Switzerland",
        "city": "Zurich",
        "created_at": "2026-07-03T10:48:22+02:00",
        "updated_at": "2026-07-05T09:15:19+02:00",
        "converted_at": null,
        "affiliate": {
          "id": 4,
          "company_name": "Alpha Media LTD",
          "username": "affiliate@example.com"
        },
        "assigned_user": {
          "id": 12,
          "name": "Sales Agent 12",
          "email": "agent12@example.com"
        },
        "client": {
          "id": 98,
          "lead_id": 145,
          "assigned_to": 12,
          "converted_at": "2026-07-04T14:20:00+02:00",
          "first_funding_event": {
            "amount": "500.00",
            "currency": "USD",
            "created_at": "2026-07-05 09:12:11"
          }
        }
      }
    ],
    "per_page": 25,
    "total": 1
  }
}
Single resource
Get one lead with nested conversion data
Returns one lead belonging to the authenticated affiliator. If the lead has been converted, the related client node is included.
GET {{ $BASE_URL }}/leads/{lead}
Path param Type Description
idintegerLead primary key.
If the lead exists but belongs to another affiliator, the endpoint should return a not found style response rather than leaking ownership details.
curl "{{ $BASE_URL }}/leads/145" \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Accept: application/json"
import axios from "axios";

const baseURL = "{{ $BASE_URL }}";
const token = "<TOKEN>";
const leadId = 145;

async function getLead() {
  const res = await axios.get(`${baseURL}/leads/${leadId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json"
    }
  });

  console.log(res.data);
}

getLead().catch(console.error);
import requests

base_url = "{{ $BASE_URL }}"
token = "<TOKEN>"
lead_id = 145

response = requests.get(
    f"{base_url}/leads/{lead_id}",
    headers={
        "Authorization": f"Bearer {token}",
        "Accept": "application/json"
    },
    timeout=30
)

print(response.status_code)
print(response.json())
Single lead response example
{
  "status": true,
  "data": {
    "id": 145,
    "affiliate_id": 4,
    "assigned_to": 12,
    "campaign_id": 8,
    "lead_code": "AFF20260703-Q8R7L2XM",
    "first_name": "John",
    "last_name": "Doe",
    "email": "john@demo.com",
    "phone": "+41790000000",
    "status": "client",
    "source": "facebook",
    "country": "Switzerland",
    "city": "Zurich",
    "created_at": "2026-07-03T10:48:22+02:00",
    "updated_at": "2026-07-05T09:15:19+02:00",
    "converted_at": null,
    "affiliate": {
      "id": 4,
      "company_name": "Alpha Media LTD",
      "username": "affiliate@example.com"
    },
    "assigned_user": {
      "id": 12,
      "name": "Sales Agent 12",
      "email": "agent12@example.com"
    },
    "client": {
      "id": 98,
      "lead_id": 145,
      "assigned_to": 12,
      "converted_at": "2026-07-04T14:20:00+02:00",
      "first_funding_event": {
        "amount": "500.00",
        "currency": "USD",
        "created_at": "2026-07-05 09:12:11"
      }
    }
  }
}
Response design
How nested data is returned
This section documents the nested JSON structure returned by the current controllers and model relationships.
Node Type Meaning
auto_login_url string Returned only by POST /new-lead. A single-use URL for profile-only access while the record remains a lead.
auto_login_url_expires_at datetime The ISO-8601 expiry of the unused one-time link. The default validity period is 30 days.
affiliate object|null The affiliator who submitted the lead.
assigned_user object|null The internal CRM user currently assigned to the lead.
client object|null Present only after conversion. Contains the client ID, lead ID, assigned administrator, conversion timestamp, and first funding event.
client.first_funding_event object|null The earliest successful funding event, limited to amount, currency, and created_at.
Trading-account implementation details are intentionally excluded from the affiliate response.
Error handling
Status codes and validation responses
Use JSON error responses consistently. Unique email and unique phone should return field-specific validation messages.
Status Meaning Typical case
200OKSuccessful GET request.
201CreatedLead created successfully.
401UnauthorizedInvalid affiliator credentials or missing token.
404Not foundLead does not exist or does not belong to this affiliator.
422Validation failedInvalid body, duplicate email, duplicate phone.
500Server errorUnexpected exception.
Duplicate email example
{
  "message": "The given data was invalid.",
  "errors": {
    "email": [
      "A lead with this email already exists."
    ]
  }
}
Duplicate phone example
{
  "message": "The given data was invalid.",
  "errors": {
    "phone": [
      "A lead with this phone already exists."
    ]
  }
}
Copied to clipboard