Recharge API Integration with PHP
Recharge API Integration with PHP: Complete Developer Guide
Integrating recharge API with PHP opens up endless possibilities for building powerful recharge applications, websites, and business solutions. This comprehensive guide will walk you through the complete process of integrating mobile recharge API using PHP, from basic setup to advanced implementation with real-world code examples.
Why PHP for Recharge API Integration?
PHP is the most popular server-side scripting language for web development, powering over 78% of all websites. Its simplicity, extensive library support, and built-in functions for HTTP requests make it ideal for API integration. PHP's cURL library provides excellent support for making API calls, handling responses, and processing JSON data - all essential for recharge API integration.
Prerequisites for Integration
PHP 7.4+
PHP 7.4 or higher with cURL extension enabled
API Credentials
A1Topup API key and authentication tokens
Web Server
Apache/Nginx with SSL certificate for secure API calls
Step-by-Step PHP Integration Guide
Get API Credentials
First, register with A1Topup to get your API credentials. You'll receive:
// Your API Configuration
$api_key = "YOUR_API_KEY_HERE";
$api_secret = "YOUR_API_SECRET_HERE";
$api_url = "https://api.a1topup.com/v1/";
$auth_token = base64_encode($api_key . ":" . $api_secret);
Create API Helper Class
Create a reusable PHP class for API calls:
class A1TopupAPI {
private $api_key;
private $api_secret;
private $base_url;
public function __construct($api_key, $api_secret) {
$this->api_key = $api_key;
$this->api_secret = $api_secret;
$this->base_url = "https://api.a1topup.com/v1/";
}
private function makeRequest($endpoint, $data = []) {
$url = $this->base_url . $endpoint;
$auth = base64_encode($this->api_key . ":" . $this->api_secret);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Basic ' . $auth,
'Content-Type: application/json',
'Accept: application/json'
]);
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'status' => $http_code,
'response' => json_decode($response, true)
];
}
// API Methods will be added here
}
Implement Recharge Methods
Add recharge methods to your API class:
// Add these methods to A1TopupAPI class
public function checkOperator($mobile_number) {
return $this->makeRequest('operator/check', [
'mobile' => $mobile_number
]);
}
public function getBalance() {
return $this->makeRequest('account/balance');
}
public function recharge($mobile_number, $amount, $operator_id) {
return $this->makeRequest('recharge/process', [
'mobile' => $mobile_number,
'amount' => $amount,
'operator' => $operator_id,
'reference_id' => uniqid('RECH_')
]);
}
public function checkStatus($transaction_id) {
return $this->makeRequest('transaction/status', [
'transaction_id' => $transaction_id
]);
}
Usage Example
Complete usage example:
// Initialize API
$api = new A1TopupAPI('your_api_key', 'your_api_secret');
// Check account balance
$balance = $api->getBalance();
if ($balance['status'] == 200) {
echo "Balance: ₹" . $balance['response']['balance'];
}
// Check operator
$operator = $api->checkOperator('9876543210');
if ($operator['status'] == 200) {
echo "Operator: " . $operator['response']['operator_name'];
echo "Circle: " . $operator['response']['circle'];
}
// Process recharge
$recharge = $api->recharge('9876543210', 299, 'JIO');
if ($recharge['status'] == 200) {
echo "Recharge Successful!";
echo "Transaction ID: " . $recharge['response']['transaction_id'];
echo "Status: " . $recharge['response']['status'];
} else {
echo "Error: " . $recharge['response']['message'];
}
Complete PHP Implementation
recharge_api.php - Complete Implementation
<?php
/**
* A1Topup Recharge API Integration - Complete Implementation
* File: recharge_api.php
*/
class A1TopupRechargeAPI {
private $api_key;
private $api_secret;
private $base_url = "https://api.a1topup.com/v1/";
public function __construct($api_key, $api_secret) {
$this->api_key = $api_key;
$this->api_secret = $api_secret;
}
/**
* Make API request
*/
private function apiCall($endpoint, $method = 'GET', $data = null) {
$url = $this->base_url . $endpoint;
$auth = base64_encode($this->api_key . ':' . $this->api_secret);
$headers = [
'Authorization: Basic ' . $auth,
'Content-Type: application/json',
'Accept: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
}
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
return ['error' => true, 'message' => 'cURL Error: ' . $error];
}
curl_close($ch);
$result = json_decode($response, true);
return [
'success' => ($http_code == 200),
'status' => $http_code,
'data' => $result
];
}
/**
* Check mobile operator
*/
public function checkOperator($mobile_number) {
return $this->apiCall('operator/lookup', 'POST', [
'mobile' => $mobile_number
]);
}
/**
* Get account balance
*/
public function getBalance() {
return $this->apiCall('account/balance', 'GET');
}
/**
* Process mobile recharge
*/
public function processRecharge($mobile, $amount, $operator, $circle = null) {
$data = [
'mobile' => $mobile,
'amount' => $amount,
'operator' => $operator,
'reference_id' => 'RCH_' . time() . '_' . rand(1000, 9999)
];
if ($circle) {
$data['circle'] = $circle;
}
return $this->apiCall('recharge/process', 'POST', $data);
}
/**
* Check transaction status
*/
public function checkTransaction($transaction_id) {
return $this->apiCall('transaction/status/' . $transaction_id, 'GET');
}
/**
* Get recharge plans
*/
public function getPlans($operator, $circle = null) {
$endpoint = 'plans/' . $operator;
if ($circle) {
$endpoint .= '/' . $circle;
}
return $this->apiCall($endpoint, 'GET');
}
}
// Usage Example
$api = new A1TopupRechargeAPI('YOUR_API_KEY', 'YOUR_API_SECRET');
// Example 1: Check balance
$balance = $api->getBalance();
if ($balance['success']) {
echo "Current Balance: ₹" . $balance['data']['balance'] . "\\n";
}
// Example 2: Process recharge
$recharge = $api->processRecharge('9876543210', 299, 'JIO', 'MUMBAI');
if ($recharge['success']) {
echo "Recharge Successful!\\n";
echo "Transaction ID: " . $recharge['data']['transaction_id'] . "\\n";
echo "Status: " . $recharge['data']['status'] . "\\n";
} else {
echo "Recharge Failed: " . $recharge['data']['message'] . "\\n";
}
?>
Error Handling & Best Practices
Comprehensive Error Handling
// Proper error handling
try {
$result = $api->processRecharge($mobile, $amount, $operator);
if ($result['success']) {
// Success handling
$transaction_id = $result['data']['transaction_id'];
$status = $result['data']['status'];
// Store in database
$this->saveTransaction($transaction_id, $status);
return [
'success' => true,
'transaction_id' => $transaction_id,
'message' => 'Recharge successful'
];
} else {
// API error
$error_msg = $result['data']['message'] ?? 'Unknown error';
// Log error
error_log("Recharge failed: " . $error_msg);
return [
'success' => false,
'error' => $error_msg,
'status_code' => $result['status']
];
}
} catch (Exception $e) {
// Exception handling
error_log("Exception: " . $e->getMessage());
return [
'success' => false,
'error' => 'System error occurred',
'exception' => $e->getMessage()
];
}
Security Best Practices
- Never expose API keys in client-side code
- Use environment variables for configuration
- Implement rate limiting to prevent abuse
- Validate all inputs before API calls
- Use HTTPS only for API communication
- Log all transactions for audit trail
// Secure configuration
$config = [
'api_key' => getenv('A1TOPUP_API_KEY'),
'api_secret' => getenv('A1TOPUP_API_SECRET'),
'api_url' => getenv('A1TOPUP_API_URL')
];
// Input validation
function validateRechargeInput($mobile, $amount, $operator) {
if (!preg_match('/^[6-9]\d{9}$/', $mobile)) {
throw new InvalidArgumentException('Invalid mobile number');
}
if ($amount < 10 || $amount > 1000) {
throw new InvalidArgumentException('Amount must be between ₹10-₹1000');
}
$valid_operators = ['JIO', 'AIRTEL', 'VI', 'BSNL'];
if (!in_array($operator, $valid_operators)) {
throw new InvalidArgumentException('Invalid operator');
}
return true;
}
Common API Methods & Endpoints
Operator Lookup
POST /operator/lookup
{ "mobile": "9876543210" }
Check Balance
GET /account/balance
No parameters required
Process Recharge
POST /recharge/process
{ "mobile": "xx", "amount": 299, "operator": "JIO" }
Transaction Status
GET /transaction/status/{id}
Path parameter: transaction_id
Benefits of PHP API Integration
Integrating A1Topup recharge API with PHP provides numerous advantages for developers and businesses alike. The combination of PHP's simplicity and A1Topup's robust API infrastructure creates a powerful platform for building recharge solutions.
Rapid Development
PHP's extensive libraries and A1Topup's comprehensive documentation enable quick integration and deployment.
Enterprise Security
Built-in security features including SSL encryption, authentication tokens, and secure API endpoints.
High Performance
99.9% API uptime with average response times under 2 seconds for instant recharge processing.
Easy Maintenance
Clean, modular code structure with comprehensive error handling for easy maintenance and updates.
Start Building with PHP API Today!
Get your API credentials and start integrating recharge services with PHP. Download our complete PHP SDK with examples and documentation.