Getting Started with One-Ping in PHP
PHP powers over 75% of the web, from WordPress sites and WooCommerce stores to Laravel applications and custom APIs. One-Ping's REST API integrates effortlessly with any PHP application, giving you multi-channel notification capabilities with minimal code. Whether you prefer PHP's built-in cURL functions or the more modern Guzzle HTTP client, sending notifications takes just a few lines.
This guide covers every PHP integration pattern you need: basic cURL usage, Guzzle examples, a reusable helper class, Laravel integration with service providers and notifications, WordPress hooks for WooCommerce alerts, and error handling best practices for production deployments.
Quick Start
Get Your API Key
Sign up at app.one-ping.com and generate an API key from your dashboard. Store it in your environment configuration (e.g., .env file) as ONE_PING_API_KEY. Never hardcode API keys in your source files.
Configure Your Channels
In the One-Ping dashboard, set up the channels you want to use. Add your Telegram bot token, SMTP settings, Slack webhook URL, or Discord webhook URL. Channel configuration is done once and applies to all API calls.
Choose Your HTTP Client
Use PHP's built-in curl_* functions for zero-dependency integration, or install Guzzle (composer require guzzlehttp/guzzle) for a cleaner, more modern API. Both approaches are shown in the examples below.
Send Your First Notification
Make a POST request to https://api.one-ping.com/send with a JSON body containing your message, channels array, and recipient. Check the response for success or error details.
Basic Example with cURL
PHP's built-in cURL functions are available on virtually every PHP installation with no additional dependencies. Here is a complete function that sends a multi-channel notification:
<?php function sendOnePingNotification(string $message, array $channels, string $recipient): array { $apiKey = getenv('ONE_PING_API_KEY'); $payload = json_encode([ 'message' => $message, 'channels' => $channels, 'recipient' => $recipient ]); $ch = curl_init('https://api.one-ping.com/send'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', "Authorization: Bearer {$apiKey}", ], ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); if ($error) { throw new \RuntimeException("One-Ping request failed: {$error}"); } if ($httpCode !== 200) { throw new \RuntimeException("One-Ping API error (HTTP {$httpCode}): {$response}"); } return json_decode($response, true); } // Usage $result = sendOnePingNotification( 'New order #1234 from John Doe - $99.00', ['telegram', 'email', 'slack'], '[email protected]' ); echo 'Notification sent: ' . print_r($result, true);
Example with Guzzle
Guzzle is the most popular HTTP client for PHP and provides a cleaner, more modern API. Install it with Composer: composer require guzzlehttp/guzzle
<?php use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; $client = new Client([ 'base_uri' => 'https://api.one-ping.com', 'timeout' => 10, 'headers' => [ 'Authorization' => 'Bearer ' . getenv('ONE_PING_API_KEY'), 'Content-Type' => 'application/json', ], ]); try { $response = $client->post('/send', [ 'json' => [ 'message' => 'Server CPU usage exceeded 90%', 'channels' => ['telegram', 'discord', 'email'], 'recipient' => '[email protected]', ], ]); $result = json_decode($response->getBody(), true); echo "Notification sent successfully\n"; } catch (RequestException $e) { error_log('One-Ping error: ' . $e->getMessage()); }
Reusable One-Ping Helper Class
For production applications, encapsulate the One-Ping API in a reusable class with retry logic, error handling, and convenience methods:
<?php namespace App\Services; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Psr\Log\LoggerInterface; class OnePing { private Client $client; private ?LoggerInterface $logger; private int $maxRetries; public function __construct( string $apiKey = null, int $timeout = 10, int $maxRetries = 2, ?LoggerInterface $logger = null ) { $apiKey = $apiKey ?? getenv('ONE_PING_API_KEY'); $this->maxRetries = $maxRetries; $this->logger = $logger; $this->client = new Client([ 'base_uri' => 'https://api.one-ping.com', 'timeout' => $timeout, 'headers' => [ 'Authorization' => "Bearer {$apiKey}", 'Content-Type' => 'application/json', ], ]); } public function send( string $message, array $channels, string $recipient, array $metadata = [] ): array { $payload = [ 'message' => $message, 'channels' => $channels, 'recipient' => $recipient, ]; if (!empty($metadata)) { $payload['metadata'] = $metadata; } $lastException = null; for ($attempt = 0; $attempt <= $this->maxRetries; $attempt++) { try { $response = $this->client->post('/send', ['json' => $payload]); return json_decode($response->getBody(), true); } catch (RequestException $e) { $lastException = $e; $this->logger?->warning("One-Ping attempt {$attempt} failed: " . $e->getMessage()); if ($attempt < $this->maxRetries) { usleep(($attempt + 1) * 1000000); // Backoff: 1s, 2s, 3s } } } throw $lastException; } // Convenience methods public function toTelegram(string $message, string $recipient): array { return $this->send($message, ['telegram'], $recipient); } public function toSlack(string $message, string $recipient): array { return $this->send($message, ['slack'], $recipient); } public function toAll(string $message, string $recipient): array { return $this->send($message, ['telegram', 'email', 'slack', 'discord'], $recipient); } }
Laravel Integration
Laravel's service container and notification system make integrating One-Ping especially clean. Register the helper class as a service and use it anywhere in your application:
Service Provider Registration
// config/services.php return [ // ... other services 'one_ping' => [ 'api_key' => env('ONE_PING_API_KEY'), ], ]; // app/Providers/AppServiceProvider.php use App\Services\OnePing; public function register(): void { $this->app->singleton(OnePing::class, function ($app) { return new OnePing( apiKey: config('services.one_ping.api_key'), logger: $app->make('log') ); }); }
Using in Controllers and Events
// app/Http/Controllers/OrderController.php use App\Services\OnePing; class OrderController extends Controller { public function store(Request $request, OnePing $ping) { $order = Order::create($request->validated()); // Send multi-channel notification try { $ping->send( message: "New order #{$order->id} from {$order->customer_name} - \${$order->total}", channels: ['telegram', 'email', 'slack'], recipient: $order->customer_email, metadata: ['order_id' => (string) $order->id, 'source' => 'laravel'] ); } catch (\Exception $e) { \Log::error('Notification failed: ' . $e->getMessage()); } return response()->json($order, 201); } } // Using with Laravel Events and Listeners // app/Listeners/SendOrderNotification.php class SendOrderNotification { public function __construct(private OnePing $ping) {} public function handle(OrderCreated $event): void { $order = $event->order; $this->ping->send( "Order #{$order->id}: {$order->items_count} items, \${$order->total}", ['telegram', 'slack'], $order->customer_email ); } }
Laravel queued notifications: For high-traffic Laravel applications, dispatch notifications to a queue by wrapping the One-Ping call in a queued job. Use dispatch(new SendOnePingNotification($message, $channels, $recipient)) and implement the ShouldQueue interface on the job class. This prevents notification sending from blocking your HTTP responses.
WordPress Integration
One-Ping works great with WordPress for sending notifications on WooCommerce orders, form submissions, new user registrations, and custom plugin events. Here is how to integrate it using WordPress action hooks:
// In your theme's functions.php or a custom plugin function one_ping_send($message, $channels, $recipient) { $api_key = get_option('one_ping_api_key'); $response = wp_remote_post('https://api.one-ping.com/send', [ 'timeout' => 10, 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => "Bearer {$api_key}", ], 'body' => json_encode([ 'message' => $message, 'channels' => $channels, 'recipient' => $recipient, ]), ]); if (is_wp_error($response)) { error_log('One-Ping error: ' . $response->get_error_message()); return false; } return json_decode(wp_remote_retrieve_body($response), true); } // WooCommerce: Notify on new order add_action('woocommerce_new_order', function($order_id) { $order = wc_get_order($order_id); one_ping_send( sprintf( 'New WooCommerce order #%d from %s %s - $%s', $order->get_id(), $order->get_billing_first_name(), $order->get_billing_last_name(), $order->get_total() ), ['telegram', 'email', 'slack'], $order->get_billing_email() ); }); // WordPress: Notify on new user registration add_action('user_register', function($user_id) { $user = get_userdata($user_id); one_ping_send( "New user registered: {$user->user_email} ({$user->display_name})", ['telegram', 'slack'], '[email protected]' ); });
Integration Capabilities
Zero Dependencies (cURL)
PHP's built-in cURL extension is available on virtually every hosting environment. No Composer or package installation required for basic usage.
Modern Guzzle Support
For Composer-based projects, use Guzzle for a cleaner API with automatic JSON encoding, connection pooling, and middleware support.
Laravel Service Container
Register One-Ping as a singleton service in Laravel's container and inject it into controllers, listeners, and jobs with dependency injection.
WordPress Native
Use wp_remote_post for WordPress-compatible HTTP requests. Hook into WooCommerce, Contact Form 7, or any WordPress action.
Retry Logic Built In
The helper class includes configurable retry logic with exponential backoff for handling transient network errors and rate limits.
PHP 8.0+ Features
The examples use modern PHP features like named arguments, constructor promotion, and union types. Compatible with PHP 7.4+ with minor adjustments.
Error Handling Best Practices
Notifications should never break your application's primary functionality. Always wrap One-Ping calls in try-catch blocks and log errors instead of throwing them to the user:
// Safe notification sending pattern function safeSend(OnePing $ping, string $message, array $channels, string $recipient): void { try { $ping->send($message, $channels, $recipient); } catch (\Throwable $e) { // Log the error but do not interrupt the main flow error_log(sprintf( '[One-Ping] Notification failed: %s | Message: %s | Channels: %s', $e->getMessage(), substr($message, 0, 100), implode(',', $channels) )); } } // Rate limit handling function sendWithRateLimitHandling(OnePing $ping, string $message, array $channels, string $recipient): ?array { try { return $ping->send($message, $channels, $recipient); } catch (RequestException $e) { if ($e->getResponse()?->getStatusCode() === 429) { // Rate limited - wait and retry sleep(2); return $ping->send($message, $channels, $recipient); } throw $e; } }
Security reminder: Store your One-Ping API key in environment variables or a secure configuration file. In Laravel, use the .env file and config() helper. In WordPress, use wp_options or wp-config.php constants. Never commit API keys to version control or expose them in client-side code.
Common Use Cases
- WooCommerce orders: Notify your team on Slack and Telegram when new orders are placed, and send customers order confirmations via Email
- Contact Form 7: Alert your sales team on multiple channels when visitors submit contact or quote request forms
- Laravel e-commerce: Send order, shipping, and delivery notifications to customers on their preferred channel
- WordPress membership: Notify administrators when new users register or subscription payments are processed
- Server monitoring: Write PHP cron scripts that check application health and send alerts via Telegram and Discord
- Inventory management: Trigger stock alerts when WooCommerce product quantities fall below defined thresholds