Skip to content

Commit ac986ea

Browse files
committed
fixed
1 parent e6ff2a0 commit ac986ea

File tree

3 files changed

+139
-23
lines changed

3 files changed

+139
-23
lines changed

config/sms-notify.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,37 @@
1313
'base_url' => env('NOTIFI_API_URL', 'https://notifi.lk/api/v1'),
1414
],
1515

16+
/*
17+
|--------------------------------------------------------------------------
18+
| HTTP Client Configuration
19+
|--------------------------------------------------------------------------
20+
*/
21+
'http' => [
22+
'timeout' => env('NOTIFI_TIMEOUT', 30),
23+
'connect_timeout' => env('NOTIFI_CONNECT_TIMEOUT', 10),
24+
'verify' => env('NOTIFI_SSL_VERIFY', true), // Set to false for local development
25+
'allow_redirects' => true,
26+
'http_errors' => false, // Don't throw exceptions for HTTP error status codes
27+
],
28+
1629
/*
1730
|--------------------------------------------------------------------------
1831
| Default Settings
1932
|--------------------------------------------------------------------------
2033
*/
2134
'defaults' => [
2235
'country_code' => '94', // Sri Lanka
23-
'retry_attempts' => 3,
24-
'retry_delay' => 1, // seconds
36+
'retry_attempts' => env('NOTIFI_RETRY_ATTEMPTS', 3),
37+
'retry_delay' => env('NOTIFI_RETRY_DELAY', 1), // seconds
38+
],
39+
40+
/*
41+
|--------------------------------------------------------------------------
42+
| Development/Testing Configuration
43+
|--------------------------------------------------------------------------
44+
*/
45+
'development' => [
46+
'mock_responses' => env('NOTIFI_MOCK_RESPONSES', false),
47+
'log_requests' => env('NOTIFI_LOG_REQUESTS', false),
2548
]
2649
];

src/Exceptions/NotifyException.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class NotifyException extends Exception
1111
*/
1212
public static function invalidCredentials(): self
1313
{
14-
return new self('Notifi.lk USER_ID and API_KEY are required. Please check your configuration.');
14+
return new self('Notify.lk USER_ID and API_KEY are required. Please check your configuration.');
1515
}
1616

1717
/**
@@ -35,23 +35,23 @@ public static function emptyMessage(): self
3535
*/
3636
public static function apiError(string $message, int $code = 0): self
3737
{
38-
return new self("Notifi.lk API Error: {$message}", $code);
38+
return new self("Notify.lk API Error: {$message}", $code);
3939
}
4040

4141
/**
4242
* Create a new exception for invalid sender ID.
4343
*/
4444
public static function invalidSenderId(string $senderId): self
4545
{
46-
return new self("Invalid sender ID: {$senderId}. Sender ID must be registered with Notifi.lk");
46+
return new self("Invalid sender ID: {$senderId}. Sender ID must be registered with Notify.lk");
4747
}
4848

4949
/**
5050
* Create a new exception for network errors.
5151
*/
5252
public static function networkError(string $message): self
5353
{
54-
return new self("Network Error: Unable to connect to Notifi.lk API. {$message}");
54+
return new self("Network Error: Unable to connect to Notify.lk API. {$message}");
5555
}
5656

5757
/**

src/Services/NotifyService.php

Lines changed: 110 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace TeamInfinityDev\SmsNotify\Services;
44

55
use Illuminate\Support\Facades\Http;
6+
use Illuminate\Support\Facades\Log;
67
use TeamInfinityDev\SmsNotify\Exceptions\NotifyException;
78

89
class NotifyService
@@ -13,6 +14,9 @@ class NotifyService
1314
protected $baseUrl;
1415
protected $retryAttempts;
1516
protected $retryDelay;
17+
protected $httpOptions;
18+
protected $logRequests;
19+
protected $mockResponses;
1620

1721
public function __construct()
1822
{
@@ -22,6 +26,9 @@ public function __construct()
2226
$this->baseUrl = config('sms-notify.api.base_url');
2327
$this->retryAttempts = config('sms-notify.defaults.retry_attempts', 3);
2428
$this->retryDelay = config('sms-notify.defaults.retry_delay', 1);
29+
$this->httpOptions = config('sms-notify.http', []);
30+
$this->logRequests = config('sms-notify.development.log_requests', false);
31+
$this->mockResponses = config('sms-notify.development.mock_responses', false);
2532

2633
$this->validateConfig();
2734
}
@@ -38,6 +45,60 @@ protected function validateConfig()
3845
}
3946
}
4047

48+
/**
49+
* Get HTTP client with configuration
50+
*
51+
* @return \Illuminate\Http\Client\PendingRequest
52+
*/
53+
protected function getHttpClient()
54+
{
55+
$client = Http::timeout($this->httpOptions['timeout'] ?? 30)
56+
->connectTimeout($this->httpOptions['connect_timeout'] ?? 10)
57+
->retry($this->retryAttempts, $this->retryDelay * 1000);
58+
59+
// SSL verification - can be disabled for local development
60+
if (isset($this->httpOptions['verify'])) {
61+
$client = $client->withOptions(['verify' => $this->httpOptions['verify']]);
62+
}
63+
64+
// Allow redirects
65+
if (isset($this->httpOptions['allow_redirects'])) {
66+
$client = $client->withOptions(['allow_redirects' => $this->httpOptions['allow_redirects']]);
67+
}
68+
69+
// Add User-Agent
70+
$client = $client->withHeaders([
71+
'User-Agent' => 'Laravel-SMS-Notify/1.1.1',
72+
'Accept' => 'application/json',
73+
]);
74+
75+
return $client;
76+
}
77+
78+
/**
79+
* Log request details if enabled
80+
*
81+
* @param string $method
82+
* @param string $url
83+
* @param array $data
84+
* @param array $response
85+
*/
86+
protected function logRequest(string $method, string $url, array $data, array $response)
87+
{
88+
if ($this->logRequests) {
89+
Log::info('SMS Notify API Request', [
90+
'method' => $method,
91+
'url' => $url,
92+
'data' => array_merge($data, [
93+
'api_key' => '***HIDDEN***', // Hide sensitive data
94+
'user_id' => substr($this->userId, 0, 3) . '***'
95+
]),
96+
'response_status' => $response['status_code'] ?? 'unknown',
97+
'response_success' => $response['success'] ?? false,
98+
]);
99+
}
100+
}
101+
41102
/**
42103
* Format phone number
43104
*
@@ -74,6 +135,22 @@ public function send($to, string $message, array $options = []): array
74135
$numbers = is_array($to) ? $to : [$to];
75136
$formattedNumbers = array_map([$this, 'formatNumber'], $numbers);
76137

138+
// Return mock response in development
139+
if ($this->mockResponses) {
140+
$mockResponse = [
141+
'success' => true,
142+
'data' => [
143+
'message_id' => 'mock_' . uniqid(),
144+
'status' => 'queued',
145+
'recipients' => count($formattedNumbers),
146+
],
147+
'status_code' => 200,
148+
];
149+
150+
$this->logRequest('POST', $this->baseUrl . '/send', ['to' => $formattedNumbers, 'message' => $message], $mockResponse);
151+
return $mockResponse;
152+
}
153+
77154
$payload = array_merge([
78155
'user_id' => $this->userId,
79156
'api_key' => $this->apiKey,
@@ -83,35 +160,51 @@ public function send($to, string $message, array $options = []): array
83160
], $options);
84161

85162
try {
86-
$response = Http::retry($this->retryAttempts, $this->retryDelay * 1000)
87-
->post($this->baseUrl . '/send', $payload);
88-
89-
if ($response->status() === 401) {
90-
throw NotifyException::apiError('Invalid credentials', 401);
91-
}
92-
93-
if ($response->status() === 429) {
94-
throw NotifyException::rateLimitExceeded();
95-
}
163+
$response = $this->getHttpClient()->post($this->baseUrl . '/send', $payload);
96164

97-
return [
165+
$result = [
98166
'success' => $response->successful(),
99167
'data' => $response->json(),
100168
'status_code' => $response->status(),
101169
];
102-
} catch (NotifyException $e) {
103-
return [
170+
171+
// Handle specific error cases
172+
if ($response->status() === 401) {
173+
$result['success'] = false;
174+
$result['error'] = 'Invalid credentials';
175+
} elseif ($response->status() === 429) {
176+
$result['success'] = false;
177+
$result['error'] = 'API rate limit exceeded. Please try again later.';
178+
} elseif (!$response->successful()) {
179+
$result['success'] = false;
180+
$result['error'] = $response->json()['message'] ?? 'API request failed';
181+
}
182+
183+
$this->logRequest('POST', $this->baseUrl . '/send', $payload, $result);
184+
return $result;
185+
186+
} catch (\Illuminate\Http\Client\ConnectionException $e) {
187+
$error = [
104188
'success' => false,
105-
'error' => $e->getMessage(),
106-
'status_code' => $e->getCode(),
189+
'error' => 'Connection failed: ' . $e->getMessage() . '. Check your internet connection and SSL settings.',
190+
'status_code' => 0,
107191
];
192+
193+
$this->logRequest('POST', $this->baseUrl . '/send', $payload, $error);
194+
return $error;
195+
108196
} catch (\Exception $e) {
109-
return [
197+
$error = [
110198
'success' => false,
111-
'error' => $e->getMessage(),
199+
'error' => 'Request failed: ' . $e->getMessage(),
112200
'status_code' => $e->getCode(),
113201
];
202+
203+
$this->logRequest('POST', $this->baseUrl . '/send', $payload, $error);
204+
return $error;
114205
}
115206
}
116207

208+
209+
117210
}

0 commit comments

Comments
 (0)