Domain Reseller API Reference | Hostraha Documentation | Hostraha
+254 708 002 001support@hostraha.com
Client Portal

Domain Reseller API Reference

Programmatically manage domains with our comprehensive reseller API

Overview

The Domain Reseller API allows you to manage domain registrations, transfers, renewals, and other domain-related operations through a RESTful interface. This API is designed for resellers who want to integrate domain management capabilities into their applications.

Key Features

  • Domain Management: Register, transfer, renew, and manage domain names
  • DNS Management: Configure nameservers and DNS records
  • Contact Management: Update domain contact information
  • Security Features: Manage registrar locks and ID protection
  • Email Forwarding: Set up email forwarding rules
  • Pricing Information: Get real-time pricing for all TLDs
  • Domain Lookup: Check domain availability and get suggestions

API Version

Current API Version: v1.0
Last Updated: January 2024

Rate Limits

The API implements rate limiting to ensure fair usage:

  • Standard Rate: 100 requests per minute per IP address
  • Burst Rate: 200 requests per minute for short periods
  • Daily Limit: 10,000 requests per day per account

When rate limits are exceeded, the API returns a 429 Too Many Requests status code.

Base URL

https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php

Environment Support

The API is available in both production and staging environments:

  • Production: https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php
  • Staging: https://staging.hostraha.com/modules/addons/DomainsReseller/api/index.php

Authentication

The API uses a token-based authentication system with the following headers:

Headers Required

HeaderDescriptionExample
usernameEmail address of the reseller's client registered in WHMCSemail@example.com
actionAPI endpoint action to perform/order/domains/register
tokenSHA256 hash of API key using email and current time (base64 encoded)See token generation below

Token Generation

The token is generated using the following formula:

base64_encode(hash_hmac("sha256", "<api-key>", "<email>:<gmdate("y-m-d H")>"))

Parameters:

  • <api-key>: Your API key (obtained from your WHMCS admin panel)
  • <email>: The reseller's email address
  • <gmdate("y-m-d H")>: Current date and hour in GMT format (e.g., "24-01-15 14")

Security Best Practices

  • Keep API Keys Secure: Never expose your API key in client-side code or public repositories
  • Use HTTPS: Always use HTTPS for all API requests
  • Token Expiration: Tokens are valid for 1 hour, generate new tokens as needed
  • IP Whitelisting: Consider whitelisting your server IPs for additional security
  • Monitor Usage: Regularly check your API usage and logs

Example Authentication Setup

$endpoint = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php";
 $action = "/order/domains/renew";
 $params = [
     "domain" => "example.com",
     "regperiod" => "3",
     "addons" => [
         "dnsmanagement" => 0,
         "emailforwarding" => 1,
         "idprotection" => 1,
     ]
 ];

 $headers = [
     "username: email@example.com",
     "action: " . $action,
     "token: " . base64_encode(hash_hmac("sha256", "1234567890QWERTYUIOPASDFGHJKLZXCVBNM", "email@example.com:" . gmdate("y-m-d H")))
 ];

 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, "{$endpoint}{$action}");
 curl_setopt($curl, CURLOPT_POST, true);
 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

 $response = curl_exec($curl);
 curl_close($curl);

JavaScript Example

// Node.js example
 const crypto = require('crypto');

 function generateToken(apiKey, email) {
   const timestamp = new Date().toISOString().slice(2, 13).replace('T', ' ');
   const message = `${email}:${timestamp}`;
   const hash = crypto.createHmac('sha256', apiKey).update(message).digest('base64');
   return hash;
 }

 const headers = {
   'username': 'email@example.com',
   'action': '/order/domains/register',
   'token': generateToken('YOUR_API_KEY', 'email@example.com'),
   'Content-Type': 'application/json'
 };

 fetch('https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php/order/domains/register', {
   method: 'POST',
   headers: headers,
   body: JSON.stringify({
     domain: 'example.com',
     regperiod: '1'
   })
 })
 .then(response => response.json())
 .then(data => console.log(data));

Domain Registration

Register Domain

POST /order/domains/register

Register a new domain name.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name to register
regperiodnumericRegistration period in years
domainfieldsstringAdditional domain-specific fields
addonsobjectDomain add-ons (see Addons section)
nameserversobjectNameserver configuration (see Nameservers section)
contactsobjectContact information (see Contacts section)

Example Request

{
  "domain": "example.com",
  "regperiod": "1",
  "addons": {
    "dnsmanagement": 1,
    "emailforwarding": 0,
    "idprotection": 1
  },
  "nameservers": {
    "ns1": "ns1.example.com",
    "ns2": "ns2.example.com"
  },
  "contacts": {
    "registrant": {
      "firstname": "John",
      "lastname": "Doe",
      "email": "john@example.com",
      "address1": "123 Main St",
      "city": "New York",
      "state": "NY",
      "postcode": "10001",
      "country": "US",
      "phonenumber": "+1-555-123-4567"
    }
  }
}

Example Response

{
  "result": "success",
  "message": "Domain registration initiated successfully",
  "data": {
    "domain": "example.com",
    "orderid": "12345",
    "status": "pending",
    "estimated_completion": "2024-01-15T10:30:00Z",
    "price": "12.99",
    "currency": "USD"
  }
}

Error Response Example

{
  "result": "error",
  "message": "Domain is not available for registration",
  "error_code": "DOMAIN_UNAVAILABLE",
  "data": {
    "domain": "example.com",
    "suggestions": [
      "example.net",
      "example.org",
      "myexample.com"
    ]
  }
}

Domain Transfer

Transfer Domain

POST /order/domains/transfer

Transfer an existing domain to your account.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name to transfer
eppcodestringEPP/transfer authorization code
regperiodnumericRegistration period in years
domainfieldsstringAdditional domain-specific fields
addonsobjectDomain add-ons
nameserversobjectNameserver configuration
contactsobjectContact information

Example Request

{
  "domain": "example.com",
  "eppcode": "ABC123XYZ",
  "regperiod": "1",
  "addons": {
    "dnsmanagement": 1,
    "emailforwarding": 0,
    "idprotection": 1
  },
  "nameservers": {
    "ns1": "ns1.example.com",
    "ns2": "ns2.example.com"
  },
  "contacts": {
    "registrant": {
      "firstname": "John",
      "lastname": "Doe",
      "email": "john@example.com",
      "address1": "123 Main St",
      "city": "New York",
      "state": "NY",
      "postcode": "10001",
      "country": "US",
      "phonenumber": "+1-555-123-4567"
    }
  }
}

Domain Renewal

Renew Domain

POST /order/domains/renew

Renew an existing domain registration.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name to renew
regperiodnumericRenewal period in years
addonsobjectDomain add-ons

Example Request

{
  "domain": "example.com",
  "regperiod": "1",
  "addons": {
    "dnsmanagement": 1,
    "emailforwarding": 1,
    "idprotection": 0
  }
}

Domain Management

Release Domain

POST /domains/{domain}/release

Release a domain for transfer to another registrar.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name to release
transfertagstringTransfer tag/authorization code

Example Request

{
  "domain": "example.com",
  "transfertag": "RELEASE123"
}

Get EPP Code

GET /domains/{domain}/eppcode

Retrieve the EPP/transfer authorization code for a domain.

Path Parameters

  • domain: Domain name

Example Request

GET /domains/example.com/eppcode

Get Contact Details

GET /domains/{domain}/contact

Retrieve contact information for a domain.

Example Request

GET /domains/example.com/contact

Save Contact Details

POST /domains/{domain}/contact

Update contact information for a domain.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
contactdetailsobjectContact details (see Contact Details section)

Example Request

{
  "domain": "example.com",
  "contactdetails": {
    "Registrant": {
      "firstname": "Jane",
      "lastname": "Smith",
      "email": "jane@example.com",
      "address1": "456 Oak Ave",
      "city": "Los Angeles",
      "state": "CA",
      "postcode": "90210",
      "country": "US",
      "phonenumber": "+1-555-987-6543"
    }
  }
}

Get Registrar Lock

GET /domains/{domain}/lock

Check the registrar lock status of a domain.

Example Request

GET /domains/example.com/lock

Save Registrar Lock

POST /domains/{domain}/lock

Update the registrar lock status of a domain.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
lockstatusstringLock status (locked/unlocked)

Example Request

{
  "domain": "example.com",
  "lockstatus": "locked"
}

Get DNS Records

GET /domains/{domain}/dns

Retrieve DNS records for a domain.

Example Request

GET /domains/example.com/dns

Save DNS Records

POST /domains/{domain}/dns

Update DNS records for a domain.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
dnsrecordsarrayDNS records (see DNS Records section)

Example Request

{
  "domain": "example.com",
  "dnsrecords": [
    {
      "hostname": "@",
      "type": "A",
      "address": "192.168.1.1",
      "priority": 0,
      "recid": "12345"
    },
    {
      "hostname": "www",
      "type": "CNAME",
      "address": "example.com",
      "priority": 0,
      "recid": "12346"
    }
  ]
}

Request Domain Deletion

POST /domains/{domain}/delete

Request deletion of a domain.

Example Request

{
  "domain": "example.com"
}

Transfer Sync

POST /domains/{domain}/transfersync

Synchronize domain transfer status.

Example Request

{
  "domain": "example.com"
}

Domain Sync

POST /domains/{domain}/sync

Synchronize domain information.

Example Request

{
  "domain": "example.com"
}

Email Forwarding

Get Email Forwarding

GET /domains/{domain}/email

Retrieve email forwarding rules for a domain.

Example Request

GET /domains/example.com/email

Save Email Forwarding

POST /domains/{domain}/email

Update email forwarding rules for a domain.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
prefixarrayEmail prefixes
forwardtoarrayForward-to email addresses

Example Request

{
  "domain": "example.com",
  "prefix": ["info", "contact", "support"],
  "forwardto": ["admin@example.com", "support@example.com"]
}

ID Protection

Toggle ID Protection

POST /domains/{domain}/protectid

Enable or disable ID protection for a domain.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
statusintegerProtection status (1=enable, 0=disable)

Example Request

{
  "domain": "example.com",
  "status": 1
}

Domain Lookup

Check Domain Availability

POST /domains/lookup

Check the availability of domain names.

Request Parameters

ParameterTypeRequiredDescription
searchTermstringDomain name to search
punyCodeSearchTermstringPunycode version of search term
tldsToIncludearrayTLDs to include in search
isIdnDomainbooleanWhether it's an IDN domain
premiumEnabledbooleanInclude premium domains

Example Request

{
  "searchTerm": "example",
  "tldsToInclude": ["com", "net", "org"],
  "isIdnDomain": false,
  "premiumEnabled": true
}

Get Domain Suggestions

POST /domains/lookup/suggestions

Get domain name suggestions based on a search term.

Request Parameters

ParameterTypeRequiredDescription
searchTermstringBase search term
punyCodeSearchTermstringPunycode version of search term
tldsToIncludearrayTLDs to include
isIdnDomainbooleanWhether it's an IDN domain
premiumEnabledbooleanInclude premium domains
suggestionSettingsarraySuggestion configuration

Example Request

{
  "searchTerm": "mybusiness",
  "tldsToInclude": ["com", "net", "co", "io"],
  "isIdnDomain": false,
  "premiumEnabled": false,
  "suggestionSettings": {
    "maxSuggestions": 10,
    "includeHyphenated": true
  }
}

Nameserver Management

Get Nameservers

GET /domains/{domain}/nameservers

Retrieve nameserver configuration for a domain.

Example Request

GET /domains/example.com/nameservers

Save Nameservers

POST /domains/{domain}/nameservers

Update nameserver configuration for a domain.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
ns1stringPrimary nameserver
ns2stringSecondary nameserver
ns3stringTertiary nameserver
ns4stringQuaternary nameserver
ns5stringQuinary nameserver

Example Request

{
  "domain": "example.com",
  "ns1": "ns1.example.com",
  "ns2": "ns2.example.com",
  "ns3": "ns3.example.com"
}

Register Nameserver

POST /domains/{domain}/nameservers/register

Register a custom nameserver.

Request Parameters

ParameterTypeRequiredDescription
domainstringDomain name
nameserverstringNameserver hostname
ipaddressstringNameserver IP address

Example Request

{
  "domain": "example.com",
  "nameserver": "ns1.example.com",
  "ipaddress": "192.168.1.100"
}

Modify Nameserver

POST /domains/{domain}/nameservers/modify

Modify an existing nameserver's IP address.

Request Parameters

ParameterTypeRequiredDescription
nameserverstringNameserver hostname
currentipaddressstringCurrent IP address
newipaddressstringNew IP address

Example Request

{
  "nameserver": "ns1.example.com",
  "currentipaddress": "192.168.1.100",
  "newipaddress": "192.168.1.200"
}

Delete Nameserver

POST /domains/{domain}/nameservers/delete

Delete a custom nameserver.

Request Parameters

ParameterTypeRequiredDescription
nameserverstringNameserver hostname to delete

Example Request

{
  "nameserver": "ns1.example.com"
}

Pricing

Get Domain Pricing

GET /order/pricing/domains/{type}

Get pricing information for domain operations.

Path Parameters

  • type: Pricing type (register/renew/transfer)

Query Parameters

  • domain: Domain name

Example Request

GET /order/pricing/domains/register?domain=example.com

Account Information

Get Credits

GET /billing/credits

Retrieve account credit balance.

Example Request

GET /billing/credits

Get API Version

GET /version

Get the current API version.

Example Request

GET /version

Get Available TLDs

GET /tlds

Retrieve list of available top-level domains.

Example Request

GET /tlds

Get TLDs Pricing

GET /tlds/pricing

Get pricing information for all available TLDs.

Example Request

GET /tlds/pricing

Get Domain Information

GET /domains/{domain}/information

Retrieve comprehensive information about a domain.

Example Request

GET /domains/example.com/information

Data Models

Nameservers

{
  "ns1": "string (required)",
  "ns2": "string (required)",
  "ns3": "string (optional)",
  "ns4": "string (optional)",
  "ns5": "string (optional)"
}

DNS Records

{
  "hostname": "string (required)",
  "type": "string (required)",
  "address": "string (required)",
  "priority": "numeric (required)",
  "recid": "string (required)"
}

Contacts

{
  "registrant": "contact object (required)",
  "tech": "contact object (required)",
  "billing": "contact object (required)",
  "admin": "contact object (required)"
}

Addons

{
  "dnsmanagement": "numeric (optional)",
  "emailforwarding": "numeric (optional)",
  "idprotection": "numeric (optional)"
}

Response Format

All API responses follow a standard JSON format:

{
  "result": "success|error",
  "message": "Response message",
  "data": {
    // Response data specific to the endpoint
  }
}

Error Codes

The API uses standard HTTP status codes and custom error codes to provide detailed information about errors.

HTTP Status Codes

CodeStatusDescriptionAction Required
200OKRequest completed successfullyNone
201CreatedResource created successfullyNone
400Bad RequestInvalid parameters or malformed requestCheck request parameters
401UnauthorizedInvalid authentication credentialsVerify API key and token
403ForbiddenInsufficient permissions or account suspendedContact support
404Not FoundResource not foundVerify resource exists
429Too Many RequestsRate limit exceededWait and retry with exponential backoff
500Internal Server ErrorServer error occurredRetry later or contact support
503Service UnavailableService temporarily unavailableRetry later

Custom Error Codes

Error CodeDescriptionHTTP StatusSolution
DOMAIN_UNAVAILABLEDomain is not available for registration400Choose a different domain name
INVALID_EPP_CODEEPP/transfer authorization code is invalid400Verify EPP code with current registrar
DOMAIN_LOCKEDDomain is locked and cannot be transferred400Unlock domain at current registrar
INSUFFICIENT_CREDITSAccount has insufficient credits402Add credits to your account
INVALID_CONTACT_INFOContact information is invalid or incomplete400Provide valid contact information
DNS_ERRORDNS configuration error400Check DNS record format and values
REGISTRAR_ERRORError from domain registrar500Contact support with error details
MAINTENANCE_MODEAPI is in maintenance mode503Wait for maintenance to complete

Error Response Format

All error responses follow this standard format:

{
   "result": "error",
   "message": "Human-readable error message",
   "error_code": "MACHINE_READABLE_CODE",
   "timestamp": "2024-01-15T10:30:00Z",
   "request_id": "req_123456789",
   "data": {
     // Additional error context (optional)
   }
 }

Troubleshooting Common Issues

Authentication Errors

  • 401 Unauthorized: Check that your API key is correct and not expired
  • Token Generation: Ensure you're using the correct timestamp format (y-m-d H)
  • Email Mismatch: Verify the email in the token matches the username header

Rate Limiting

  • 429 Too Many Requests: Implement exponential backoff in your retry logic
  • Daily Limits: Monitor your daily API usage to avoid hitting limits
  • Burst Protection: Space out requests to avoid triggering burst limits

Domain-Specific Issues

  • Domain Unavailable: Use the domain lookup endpoint before attempting registration
  • Transfer Issues: Ensure the domain is unlocked and EPP code is valid
  • Contact Information: Provide complete and valid contact details for all required fields

Rate Limiting

The API implements rate limiting to ensure fair usage. Please implement appropriate retry logic with exponential backoff in your applications.

Rate Limit Headers

The API includes rate limit information in response headers:

X-RateLimit-Limit: 100
 X-RateLimit-Remaining: 95
 X-RateLimit-Reset: 1642233600
 X-RateLimit-Reset-Time: 2024-01-15T11:00:00Z

Exponential Backoff Implementation

// PHP Example
 function makeApiRequest($url, $data, $headers, $retries = 3) {
     $attempt = 0;
     $baseDelay = 1; // Start with 1 second delay
     
     while ($attempt < $retries) {
         $response = curl_request($url, $data, $headers);
         
         if ($response['status'] === 429) {
             $attempt++;
             if ($attempt < $retries) {
                 $delay = $baseDelay * pow(2, $attempt - 1); // Exponential backoff
                 sleep($delay);
                 continue;
             }
         }
         
         return $response;
     }
     
     throw new Exception('Max retries exceeded');
 }

 // JavaScript Example
 async function makeApiRequest(url, data, headers, retries = 3) {
     let attempt = 0;
     const baseDelay = 1000; // Start with 1 second delay
     
     while (attempt < retries) {
         try {
             const response = await fetch(url, {
                 method: 'POST',
                 headers: headers,
                 body: JSON.stringify(data)
             });
             
             if (response.status === 429) {
                 attempt++;
                 if (attempt < retries) {
                     const delay = baseDelay * Math.pow(2, attempt - 1);
                     await new Promise(resolve => setTimeout(resolve, delay));
                     continue;
                 }
             }
             
             return await response.json();
         } catch (error) {
             attempt++;
             if (attempt >= retries) throw error;
         }
     }
 }

Best Practices

General Guidelines

  • Always use HTTPS: Never make API requests over HTTP
  • Validate inputs: Always validate domain names and other inputs before sending
  • Handle errors gracefully: Implement proper error handling for all API calls
  • Log requests: Log API requests and responses for debugging
  • Use timeouts: Set appropriate timeouts for API requests (30-60 seconds)
  • Cache responses: Cache static data like TLD pricing when appropriate

Domain Registration Best Practices

  • Check availability first: Always use the domain lookup endpoint before attempting registration
  • Validate contact information: Ensure all required contact fields are provided and valid
  • Use appropriate nameservers: Configure nameservers that are actually running
  • Handle premium domains: Check if a domain is premium before registration
  • Monitor registration status: Implement webhook handling for registration status updates

DNS Management Best Practices

  • Validate DNS records: Ensure DNS records follow proper format and RFC standards
  • Use appropriate TTL values: Set reasonable TTL values for DNS records
  • Implement DNS validation: Validate DNS records before submission
  • Handle DNS propagation: Account for DNS propagation delays in your application

Security Best Practices

  • Secure API key storage: Store API keys in environment variables or secure key management systems
  • Rotate API keys: Regularly rotate your API keys
  • Monitor API usage: Set up alerts for unusual API usage patterns
  • Implement request signing: Consider implementing additional request signing for sensitive operations
  • Use IP whitelisting: Whitelist your server IPs for additional security

Performance Optimization

  • Batch operations: Use bulk domain lookup when checking multiple domains
  • Implement caching: Cache pricing and TLD information
  • Use connection pooling: Reuse HTTP connections when possible
  • Optimize request frequency: Avoid making unnecessary API calls

Implementation Examples

Complete Domain Registration Flow

// Complete domain registration example
 class DomainManager {
     private $apiKey;
     private $email;
     private $endpoint;
     
     public function __construct($apiKey, $email) {
         $this->apiKey = $apiKey;
         $this->email = $email;
         $this->endpoint = 'https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php';
     }
     
     private function generateToken($action) {
         $timestamp = gmdate('y-m-d H');
         $message = $this->email . ':' . $timestamp;
         return base64_encode(hash_hmac('sha256', $this->apiKey, $message, true));
     }
     
     private function makeRequest($action, $data = []) {
         $headers = [
             'username: ' . $this->email,
             'action: ' . $action,
             'token: ' . $this->generateToken($action),
             'Content-Type: application/json'
         ];
         
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $this->endpoint . $action);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_TIMEOUT, 30);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
         
         $response = curl_exec($ch);
         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         curl_close($ch);
         
         return [
             'status' => $httpCode,
             'data' => json_decode($response, true)
         ];
     }
     
     public function checkDomainAvailability($domain) {
         return $this->makeRequest('/domains/lookup', [
             'searchTerm' => $domain
         ]);
     }
     
     public function registerDomain($domain, $contacts, $nameservers, $addons = []) {
         // First check availability
         $availability = $this->checkDomainAvailability($domain);
         if ($availability['data']['result'] !== 'success' || !$availability['data']['data']['available']) {
             throw new Exception('Domain is not available for registration');
         }
         
         // Proceed with registration
         return $this->makeRequest('/order/domains/register', [
             'domain' => $domain,
             'regperiod' => '1',
             'contacts' => $contacts,
             'nameservers' => $nameservers,
             'addons' => $addons
         ]);
     }
     
     public function getDomainInfo($domain) {
         return $this->makeRequest('/domains/' . $domain . '/information');
     }
 }

 // Usage example
 $domainManager = new DomainManager('YOUR_API_KEY', 'email@example.com');

 try {
     // Check availability
     $availability = $domainManager->checkDomainAvailability('example.com');
     if ($availability['data']['data']['available']) {
         // Register domain
         $result = $domainManager->registerDomain('example.com', [
             'registrant' => [
                 'firstname' => 'John',
                 'lastname' => 'Doe',
                 'email' => 'john@example.com',
                 'address1' => '123 Main St',
                 'city' => 'New York',
                 'state' => 'NY',
                 'postcode' => '10001',
                 'country' => 'US',
                 'phonenumber' => '+1-555-123-4567'
             ]
         ], [
             'ns1' => 'ns1.example.com',
             'ns2' => 'ns2.example.com'
         ], [
             'dnsmanagement' => 1,
             'idprotection' => 1
         ]);
         
         echo "Domain registered successfully: " . $result['data']['data']['orderid'];
     }
 } catch (Exception $e) {
     echo "Error: " . $e->getMessage();
 }

Webhook Handler Example

// Webhook handler for domain status updates
 class WebhookHandler {
     public function handleDomainStatusUpdate($payload) {
         $event = $payload['event'];
         $domain = $payload['data']['domain'];
         $status = $payload['data']['status'];
         
         switch ($event) {
             case 'domain.registered':
                 $this->handleDomainRegistered($domain, $payload['data']);
                 break;
             case 'domain.transferred':
                 $this->handleDomainTransferred($domain, $payload['data']);
                 break;
             case 'domain.renewed':
                 $this->handleDomainRenewed($domain, $payload['data']);
                 break;
             case 'domain.expired':
                 $this->handleDomainExpired($domain, $payload['data']);
                 break;
             default:
                 error_log("Unknown event: " . $event);
         }
     }
     
     private function handleDomainRegistered($domain, $data) {
         // Send confirmation email to customer
         $this->sendRegistrationConfirmation($domain, $data);
         
         // Update your database
         $this->updateDomainStatus($domain, 'active');
         
         // Set up DNS records if needed
         if (!empty($data['nameservers'])) {
             $this->configureDNS($domain, $data['nameservers']);
         }
     }
     
     private function handleDomainTransferred($domain, $data) {
         // Notify customer of successful transfer
         $this->sendTransferConfirmation($domain, $data);
         
         // Update domain status
         $this->updateDomainStatus($domain, 'transferred');
     }
     
     private function handleDomainRenewed($domain, $data) {
         // Send renewal confirmation
         $this->sendRenewalConfirmation($domain, $data);
         
         // Update expiration date
         $this->updateDomainExpiration($domain, $data['expiration_date']);
     }
     
     private function handleDomainExpired($domain, $data) {
         // Send expiration notification
         $this->sendExpirationNotification($domain, $data);
         
         // Update domain status
         $this->updateDomainStatus($domain, 'expired');
     }
 }

 // Webhook endpoint
 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     $payload = json_decode(file_get_contents('php://input'), true);
     
     // Verify webhook signature (if implemented)
     if ($this->verifyWebhookSignature($payload, $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'])) {
         $handler = new WebhookHandler();
         $handler->handleDomainStatusUpdate($payload);
         
         http_response_code(200);
         echo json_encode(['status' => 'success']);
     } else {
         http_response_code(401);
         echo json_encode(['error' => 'Invalid signature']);
     }
 }

Support

For technical support or questions about the API, please contact our support team at support@hostraha.com.