🐘 PHP SDK
Enterprise-grade Voice, SMS, Email & AI API for PHP & Laravel applications
📦 Installation
The PHP package will be available via Composer when released:
# Coming soon!
composer require team-connect/api
# For now, use Guzzle HTTP client
composer require guzzlehttp/guzzle
🚀 Quick Start
Here's how you'll use the PHP SDK once it's available:
<?php
// Future SDK usage
require_once 'vendor/autoload.php';
use TeamConnect\TeamConnectAPI;
// Initialize with your API key
$api = new TeamConnectAPI('tc_live_your_api_key_here');
// Make a voice call
$callResult = $api->voice->makeCall([
'to' => '+447123456789',
'message' => 'Hello from Team Connect!'
]);
echo "Call initiated: " . $callResult->callId . "\n";
// Send an SMS
$smsResult = $api->sms->send([
'to' => '+447123456789',
'message' => 'Your verification code is 123456'
]);
echo "SMS sent: " . $smsResult->messageId . "\n";
// Send an email
$emailResult = $api->email->send([
'to' => 'customer@example.com',
'subject' => 'Welcome to our service',
'html' => '<h1>Welcome!</h1><p>Thanks for signing up.</p>'
]);
echo "Email sent: " . $emailResult->messageId . "\n";
// AI Chat
$aiResult = $api->ai->chat([
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Hello!']
]);
echo "AI Response: " . $aiResult->response . "\n";
🔐 Current Implementation (REST API)
Until the SDK is ready, use our REST API with Guzzle HTTP client:
<?php
// Using Guzzle HTTP Client (composer require guzzlehttp/guzzle)
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class TeamConnectAPI
{
private $apiKey;
private $client;
private $baseUrl = 'https://us-central1-customerservice-2156c.cloudfunctions.net';
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
$this->client = new Client([
'base_uri' => $this->baseUrl,
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
]);
}
public function makeRequest(string $service, string $action, array $data): array
{
try {
$response = $this->client->post('/executeAPI', [
'json' => [
'service' => $service,
'action' => $action,
'data' => $data,
'api_key' => $this->apiKey
]
]);
$body = $response->getBody()->getContents();
return json_decode($body, true);
} catch (RequestException $e) {
$response = $e->getResponse();
if ($response) {
$statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
$errorData = json_decode($body, true);
switch ($statusCode) {
case 401:
throw new Exception('Invalid API key');
case 402:
throw new Exception($errorData['error'] ?? 'Insufficient credits');
case 429:
throw new Exception('Rate limit exceeded');
default:
throw new Exception($errorData['error'] ?? 'API request failed');
}
}
throw new Exception('Network error: ' . $e->getMessage());
}
}
}
// Initialize the API
$api = new TeamConnectAPI('tc_live_your_api_key_here');
<?php
// Using cURL (built into PHP)
class TeamConnectAPICurl
{
private $apiKey;
private $baseUrl = 'https://us-central1-customerservice-2156c.cloudfunctions.net';
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
public function makeRequest(string $service, string $action, array $data): array
{
$payload = [
'service' => $service,
'action' => $action,
'data' => $data,
'api_key' => $this->apiKey
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->baseUrl . '/executeAPI',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json'
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception('cURL error: ' . $error);
}
$data = json_decode($response, true);
if ($httpCode !== 200) {
switch ($httpCode) {
case 401:
throw new Exception('Invalid API key');
case 402:
throw new Exception($data['error'] ?? 'Insufficient credits');
case 429:
throw new Exception('Rate limit exceeded');
default:
throw new Exception($data['error'] ?? "HTTP error: $httpCode");
}
}
return $data;
}
}
// Initialize the API
$api = new TeamConnectAPICurl('tc_live_your_api_key_here');
<?php
// Modern PHP 8+ OOP Implementation
declare(strict_types=1);
class TeamConnectAPI
{
private string $apiKey;
private string $baseUrl = 'https://us-central1-customerservice-2156c.cloudfunctions.net';
private int $timeout = 30;
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
/**
* Make API request with proper typing
*/
public function makeRequest(string $service, string $action, array $data): array
{
$payload = json_encode([
'service' => $service,
'action' => $action,
'data' => $data,
'api_key' => $this->apiKey
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => $payload,
'timeout' => $this->timeout
]
]);
$response = @file_get_contents($this->baseUrl . '/executeAPI', false, $context);
if ($response === false) {
throw new Exception('Failed to connect to API');
}
$httpCode = $this->getHttpResponseCode($http_response_header);
$data = json_decode($response, true);
if ($httpCode !== 200) {
match($httpCode) {
401 => throw new Exception('Invalid API key'),
402 => throw new Exception($data['error'] ?? 'Insufficient credits'),
429 => throw new Exception('Rate limit exceeded'),
default => throw new Exception($data['error'] ?? "HTTP error: $httpCode")
};
}
return $data;
}
private function getHttpResponseCode(array $headers): int
{
if (isset($headers[0])) {
preg_match('/(\d{3})/', $headers[0], $matches);
return (int)($matches[1] ?? 500);
}
return 500;
}
}
// Exception classes for better error handling
class TeamConnectException extends Exception {}
class InsufficientCreditsException extends TeamConnectException {}
class InvalidAPIKeyException extends TeamConnectException {}
class RateLimitException extends TeamConnectException {}
// Initialize the API
$api = new TeamConnectAPI('tc_live_your_api_key_here');
📞 Voice Calls
Make AI-powered voice calls to any phone number:
<?php
/**
* Make a voice call
*/
function makeCall(TeamConnectAPI $api, string $to, string $message, array $options = []): ?array
{
try {
$data = [
'to' => $to,
'message' => $message
];
// Add optional parameters
if (isset($options['from'])) {
$data['from'] = $options['from'];
}
if (isset($options['voice'])) {
$data['voice'] = $options['voice'];
}
if (isset($options['webhook_url'])) {
$data['webhook_url'] = $options['webhook_url'];
}
$result = $api->makeRequest('voice', 'make_call', $data);
if ($result['success']) {
return [
'call_id' => $result['result']['call_id'],
'status' => $result['result']['status'],
'to' => $result['result']['to'],
'from' => $result['result']['from'],
'cost' => $result['billing']['cost'] ?? null,
'credits_remaining' => $result['billing']['creditsRemaining'] ?? null
];
}
throw new Exception($result['error'] ?? 'Call failed');
} catch (Exception $e) {
error_log('Voice call error: ' . $e->getMessage());
return null;
}
}
// Example usage
$callResult = makeCall(
$api,
'+447123456789',
'Hi, this is Sarah from Dad-Link calling to confirm your appointment tomorrow at 2 PM. Can you please confirm if this time still works for you?',
[
'voice' => 'Polly.Amy',
'webhook_url' => 'https://yourapp.com/webhooks/call-status'
]
);
if ($callResult) {
echo "✅ Call initiated successfully!\n";
echo "Call ID: " . $callResult['call_id'] . "\n";
echo "Status: " . $callResult['status'] . "\n";
echo "Cost: " . $callResult['cost'] . "p\n";
if ($callResult['credits_remaining'] < 500) {
echo "⚠️ Low credits remaining: " . $callResult['credits_remaining'] . "p\n";
}
} else {
echo "❌ Call failed\n";
}
📋 Appointment System
<?php
// Laravel/PHP appointment confirmation
function confirmAppointment($appointment) {
global $api;
$message = sprintf(
"Hi %s, this is confirming your %s appointment tomorrow at %s. Reply YES to confirm or NO to reschedule.",
$appointment->customer_name,
$appointment->service_type,
$appointment->time
);
return makeCall(
$api,
$appointment->customer_phone,
$message,
['voice' => 'Polly.Amy']
);
}
💰 Payment Reminders
<?php
// Payment reminder system
function sendPaymentReminder($invoice) {
global $api;
$message = sprintf(
"Hello %s, this is a friendly reminder that your payment of £%s is due. You can pay online at %s or call us back.",
$invoice->customer_name,
number_format($invoice->amount, 2),
$invoice->payment_url
);
return makeCall(
$api,
$invoice->customer_phone,
$message
);
}
💬 SMS Messages
Send SMS messages to any mobile number:
<?php
/**
* Send SMS message
*/
function sendSMS(TeamConnectAPI $api, string $to, string $message, array $options = []): ?array
{
try {
$data = [
'to' => $to,
'message' => $message
];
if (isset($options['from'])) {
$data['from'] = $options['from'];
}
$result = $api->makeRequest('sms', 'send', $data);
if ($result['success']) {
return [
'message_id' => $result['result']['message_id'],
'status' => $result['result']['status'],
'to' => $result['result']['to'],
'from' => $result['result']['from'],
'cost' => $result['billing']['cost'] ?? null,
'credits_remaining' => $result['billing']['creditsRemaining'] ?? null
];
}
throw new Exception($result['error'] ?? 'SMS failed');
} catch (Exception $e) {
error_log('SMS error: ' . $e->getMessage());
return null;
}
}
// Example usage
$smsResult = sendSMS(
$api,
'+447123456789',
'Your verification code is 123456. Valid for 5 minutes.'
);
if ($smsResult) {
echo "✅ SMS sent successfully!\n";
echo "Message ID: " . $smsResult['message_id'] . "\n";
echo "Status: " . $smsResult['status'] . "\n";
echo "Cost: " . $smsResult['cost'] . "p\n";
} else {
echo "❌ SMS failed\n";
}
🔐 2FA System
<?php
// Generate and send 2FA code
function send2FACode($userPhone, $appName = 'Dad-Link') {
global $api;
$code = random_int(100000, 999999);
// Store in database with expiry
// DB::table('verification_codes')->insert([
// 'phone' => $userPhone,
// 'code' => $code,
// 'expires_at' => now()->addMinutes(5)
// ]);
$result = sendSMS(
$api,
$userPhone,
"Your {$appName} verification code: {$code}"
);
return ['code' => $code, 'sent' => $result !== null];
}
🚚 Order Updates
<?php
// Order status notifications
function sendOrderUpdate($order) {
global $api;
$message = sprintf(
"Your order #%s is %s. Track: %s",
$order->number,
$order->status,
$order->tracking_url
);
return sendSMS(
$api,
$order->customer_phone,
$message
);
}
📧 Email Sending
Send HTML emails with high deliverability:
<?php
/**
* Send HTML email
*/
function sendEmail(TeamConnectAPI $api, string $to, string $subject, string $html, array $options = []): ?array
{
try {
$data = [
'to' => $to,
'subject' => $subject,
'html' => $html,
'from_name' => $options['from_name'] ?? 'Team Connect'
];
$result = $api->makeRequest('email', 'send', $data);
if ($result['success']) {
return [
'message_id' => $result['result']['message_id'],
'status' => $result['result']['status'],
'to' => $result['result']['to'],
'subject' => $result['result']['subject'],
'cost' => $result['billing']['cost'] ?? null,
'credits_remaining' => $result['billing']['creditsRemaining'] ?? null
];
}
throw new Exception($result['error'] ?? 'Email failed');
} catch (Exception $e) {
error_log('Email error: ' . $e->getMessage());
return null;
}
}
/**
* Generate welcome email template
*/
function generateWelcomeEmail(string $customerName, string $dashboardUrl, string $companyName = 'Dad-Link'): string
{
return "
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: #007AFF; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
.content { padding: 20px; background: #f9f9f9; }
.footer { background: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; border-radius: 0 0 8px 8px; }
.btn { background: #007AFF; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block; margin: 16px 0; }
</style>
</head>
<body>
<div class=\"container\">
<div class=\"header\">
<h1>Welcome to {$companyName}!</h1>
</div>
<div class=\"content\">
<h2>Hi {$customerName},</h2>
<p>Thanks for signing up! Your account is now active and ready to use.</p>
<p>Get started by exploring our features:</p>
<ul>
<li>🎤 AI Voice Calls</li>
<li>💬 SMS Messaging</li>
<li>📧 Email Campaigns</li>
</ul>
<a href=\"{$dashboardUrl}\" class=\"btn\">Get Started</a>
</div>
<div class=\"footer\">
<p>© 2025 {$companyName}. All rights reserved.</p>
</div>
</div>
</body>
</html>";
}
// Example usage
$emailResult = sendEmail(
$api,
'customer@example.com',
'Welcome to Dad-Link - Your Account is Ready!',
generateWelcomeEmail('John Doe', 'https://team-connect.co.uk/dashboard.html'),
['from_name' => 'Dad-Link Team']
);
if ($emailResult) {
echo "✅ Email sent successfully!\n";
echo "Message ID: " . $emailResult['message_id'] . "\n";
echo "Cost: " . $emailResult['cost'] . "p\n";
} else {
echo "❌ Email failed\n";
}
🤖 AI Chat
Use GPT-4 for intelligent conversations:
<?php
/**
* AI Chat with GPT-4
*/
function aiChat(TeamConnectAPI $api, array $messages, string $model = 'gpt-4'): ?array
{
try {
$result = $api->makeRequest('ai', 'chat', [
'messages' => $messages,
'model' => $model
]);
if ($result['success']) {
return [
'response' => $result['result']['response'],
'model' => $result['result']['model'],
'tokens_used' => $result['result']['tokens_used'],
'cost' => $result['billing']['cost'] ?? null,
'credits_remaining' => $result['billing']['creditsRemaining'] ?? null
];
}
throw new Exception($result['error'] ?? 'AI chat failed');
} catch (Exception $e) {
error_log('AI chat error: ' . $e->getMessage());
return null;
}
}
// Example usage
$conversation = [
[
'role' => 'system',
'content' => 'You are a helpful customer service assistant for Dad-Link, a communication platform.'
],
[
'role' => 'user',
'content' => 'How do I integrate voice calls into my PHP application?'
]
];
$aiResult = aiChat($api, $conversation);
if ($aiResult) {
echo "✅ AI Response:\n";
echo $aiResult['response'] . "\n";
echo "Tokens used: " . $aiResult['tokens_used'] . "\n";
echo "Cost: " . $aiResult['cost'] . "p\n";
} else {
echo "❌ AI chat failed\n";
}
💬 Customer Support Bot
<?php
// Simple customer support chatbot
class CustomerSupportBot
{
private TeamConnectAPI $api;
private array $conversation;
public function __construct(TeamConnectAPI $api)
{
$this->api = $api;
$this->conversation = [
[
'role' => 'system',
'content' => 'You are a helpful customer support assistant for Dad-Link. Be friendly and provide accurate information about our communication services.'
]
];
}
public function sendMessage(string $userMessage): ?string
{
// Add user message to conversation
$this->conversation[] = [
'role' => 'user',
'content' => $userMessage
];
$result = aiChat($this->api, $this->conversation);
if ($result) {
// Add AI response to conversation
$this->conversation[] = [
'role' => 'assistant',
'content' => $result['response']
];
return $result['response'];
}
return null;
}
}
// Usage
$bot = new CustomerSupportBot($api);
$response = $bot->sendMessage('Hello, how can you help me?');
echo $response;
⚡ Framework Examples
Ready-to-use examples for popular PHP frameworks:
<?php
// Laravel Service Provider: app/Providers/TeamConnectServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\TeamConnectService;
class TeamConnectServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(TeamConnectService::class, function ($app) {
return new TeamConnectService(config('services.team_connect.api_key'));
});
}
}
// Laravel Service: app/Services/TeamConnectService.php
namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class TeamConnectService
{
private $apiKey;
private $client;
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
$this->client = new Client([
'base_uri' => 'https://us-central1-customerservice-2156c.cloudfunctions.net',
'timeout' => 30
]);
}
public function makeCall(string $to, string $message, array $options = []): ?object
{
try {
$response = $this->client->post('/executeAPI', [
'json' => [
'service' => 'voice',
'action' => 'make_call',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
]
]);
$result = json_decode($response->getBody()->getContents());
Log::info('Team Connect call initiated', [
'call_id' => $result->result->call_id ?? null,
'to' => $to
]);
return $result;
} catch (\Exception $e) {
Log::error('Team Connect call failed', [
'error' => $e->getMessage(),
'to' => $to
]);
return null;
}
}
public function sendSMS(string $to, string $message, array $options = []): ?object
{
try {
$response = $this->client->post('/executeAPI', [
'json' => [
'service' => 'sms',
'action' => 'send',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
]
]);
return json_decode($response->getBody()->getContents());
} catch (\Exception $e) {
Log::error('Team Connect SMS failed', [
'error' => $e->getMessage(),
'to' => $to
]);
return null;
}
}
}
// Laravel Controller: app/Http/Controllers/CommunicationController.php
namespace App\Http\Controllers;
use App\Services\TeamConnectService;
use Illuminate\Http\Request;
class CommunicationController extends Controller
{
private TeamConnectService $teamConnect;
public function __construct(TeamConnectService $teamConnect)
{
$this->teamConnect = $teamConnect;
}
public function makeCall(Request $request)
{
$validated = $request->validate([
'to' => 'required|string',
'message' => 'required|string'
]);
$result = $this->teamConnect->makeCall(
$validated['to'],
$validated['message']
);
if ($result && $result->success) {
return response()->json([
'success' => true,
'call_id' => $result->result->call_id
]);
}
return response()->json([
'success' => false,
'error' => 'Call failed'
], 500);
}
}
// Laravel Job: app/Jobs/SendAppointmentReminder.php
namespace App\Jobs;
use App\Services\TeamConnectService;
use App\Models\Appointment;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendAppointmentReminder implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
private Appointment $appointment;
public function __construct(Appointment $appointment)
{
$this->appointment = $appointment;
}
public function handle(TeamConnectService $teamConnect)
{
$message = sprintf(
"Hi %s, this is confirming your %s appointment tomorrow at %s. Reply YES to confirm.",
$this->appointment->customer_name,
$this->appointment->service_type,
$this->appointment->time->format('g:i A')
);
$teamConnect->makeCall(
$this->appointment->customer_phone,
$message,
['voice' => 'Polly.Amy']
);
}
}
// Usage in Laravel
// dispatch(new SendAppointmentReminder($appointment));
<?php
// Symfony Service: src/Service/TeamConnectService.php
namespace App\Service;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Psr\Log\LoggerInterface;
class TeamConnectService
{
private HttpClientInterface $httpClient;
private LoggerInterface $logger;
private string $apiKey;
private string $baseUrl = 'https://us-central1-customerservice-2156c.cloudfunctions.net';
public function __construct(
HttpClientInterface $httpClient,
LoggerInterface $logger,
string $teamConnectApiKey
) {
$this->httpClient = $httpClient;
$this->logger = $logger;
$this->apiKey = $teamConnectApiKey;
}
public function makeCall(string $to, string $message, array $options = []): ?array
{
try {
$response = $this->httpClient->request('POST', $this->baseUrl . '/executeAPI', [
'json' => [
'service' => 'voice',
'action' => 'make_call',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
]
]);
$data = $response->toArray();
$this->logger->info('Team Connect call initiated', [
'call_id' => $data['result']['call_id'] ?? null,
'to' => $to
]);
return $data;
} catch (\Exception $e) {
$this->logger->error('Team Connect call failed', [
'error' => $e->getMessage(),
'to' => $to
]);
return null;
}
}
}
// Symfony Controller: src/Controller/CommunicationController.php
namespace App\Controller;
use App\Service\TeamConnectService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class CommunicationController extends AbstractController
{
#[Route('/api/call', name: 'make_call', methods: ['POST'])]
public function makeCall(Request $request, TeamConnectService $teamConnect): JsonResponse
{
$data = json_decode($request->getContent(), true);
$result = $teamConnect->makeCall(
$data['to'] ?? '',
$data['message'] ?? ''
);
if ($result && $result['success']) {
return $this->json([
'success' => true,
'call_id' => $result['result']['call_id']
]);
}
return $this->json(['success' => false, 'error' => 'Call failed'], 500);
}
}
// services.yaml configuration
# config/services.yaml
parameters:
team_connect_api_key: '%env(TEAM_CONNECT_API_KEY)%'
services:
App\Service\TeamConnectService:
arguments:
$teamConnectApiKey: '%team_connect_api_key%'
<?php
// CodeIgniter 4 Library: app/Libraries/TeamConnect.php
namespace App\Libraries;
use CodeIgniter\HTTP\CURLRequest;
class TeamConnect
{
private $apiKey;
private $baseUrl = 'https://us-central1-customerservice-2156c.cloudfunctions.net';
public function __construct()
{
$this->apiKey = env('TEAM_CONNECT_API_KEY');
}
public function makeCall(string $to, string $message, array $options = []): ?array
{
$client = \Config\Services::curlrequest();
try {
$response = $client->post($this->baseUrl . '/executeAPI', [
'json' => [
'service' => 'voice',
'action' => 'make_call',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
],
'headers' => [
'Content-Type' => 'application/json'
]
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
log_message('error', 'Team Connect call failed: ' . $e->getMessage());
return null;
}
}
public function sendSMS(string $to, string $message, array $options = []): ?array
{
$client = \Config\Services::curlrequest();
try {
$response = $client->post($this->baseUrl . '/executeAPI', [
'json' => [
'service' => 'sms',
'action' => 'send',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
],
'headers' => [
'Content-Type' => 'application/json'
]
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
log_message('error', 'Team Connect SMS failed: ' . $e->getMessage());
return null;
}
}
}
// CodeIgniter Controller: app/Controllers/Communication.php
namespace App\Controllers;
use App\Libraries\TeamConnect;
class Communication extends BaseController
{
private TeamConnect $teamConnect;
public function __construct()
{
$this->teamConnect = new TeamConnect();
}
public function makeCall()
{
$to = $this->request->getPost('to');
$message = $this->request->getPost('message');
if (!$to || !$message) {
return $this->response->setJSON([
'success' => false,
'error' => 'Missing required fields'
])->setStatusCode(400);
}
$result = $this->teamConnect->makeCall($to, $message);
if ($result && $result['success']) {
return $this->response->setJSON([
'success' => true,
'call_id' => $result['result']['call_id']
]);
}
return $this->response->setJSON([
'success' => false,
'error' => 'Call failed'
])->setStatusCode(500);
}
}
<?php
// WordPress Plugin: team-connect/team-connect.php
/**
* Plugin Name: Team Connect API
* Description: Integrate voice calls, SMS, and email with Team Connect API
* Version: 1.0
* Author: Dad-Link
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
class TeamConnectWP
{
private $apiKey;
private $baseUrl = 'https://us-central1-customerservice-2156c.cloudfunctions.net';
public function __construct()
{
$this->apiKey = get_option('team_connect_api_key');
add_action('init', [$this, 'init']);
add_action('admin_menu', [$this, 'admin_menu']);
add_action('wp_ajax_team_connect_call', [$this, 'handle_call']);
add_action('wp_ajax_team_connect_sms', [$this, 'handle_sms']);
}
public function init()
{
// Initialize plugin
}
public function admin_menu()
{
add_options_page(
'Team Connect Settings',
'Team Connect',
'manage_options',
'team-connect',
[$this, 'admin_page']
);
}
public function admin_page()
{
if (isset($_POST['save_settings'])) {
update_option('team_connect_api_key', sanitize_text_field($_POST['api_key']));
echo '<div class="notice notice-success"><p>Settings saved!</p></div>';
}
$apiKey = get_option('team_connect_api_key', '');
?>
<div class="wrap">
<h1>Team Connect Settings</h1>
<form method="post">
<table class="form-table">
<tr>
<th scope="row">API Key</th>
<td>
<input type="text" name="api_key" value="<?php echo esc_attr($apiKey); ?>" class="regular-text" />
<p class="description">Enter your Team Connect API key</p>
</td>
</tr>
</table>
<?php submit_button('Save Settings', 'primary', 'save_settings'); ?>
</form>
</div>
<?php
}
public function makeCall(string $to, string $message, array $options = []): ?array
{
$response = wp_remote_post($this->baseUrl . '/executeAPI', [
'headers' => [
'Content-Type' => 'application/json'
],
'body' => json_encode([
'service' => 'voice',
'action' => 'make_call',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
]),
'timeout' => 30
]);
if (is_wp_error($response)) {
error_log('Team Connect call failed: ' . $response->get_error_message());
return null;
}
return json_decode(wp_remote_retrieve_body($response), true);
}
public function sendSMS(string $to, string $message, array $options = []): ?array
{
$response = wp_remote_post($this->baseUrl . '/executeAPI', [
'headers' => [
'Content-Type' => 'application/json'
],
'body' => json_encode([
'service' => 'sms',
'action' => 'send',
'data' => array_merge([
'to' => $to,
'message' => $message
], $options),
'api_key' => $this->apiKey
]),
'timeout' => 30
]);
if (is_wp_error($response)) {
error_log('Team Connect SMS failed: ' . $response->get_error_message());
return null;
}
return json_decode(wp_remote_retrieve_body($response), true);
}
public function handle_call()
{
check_ajax_referer('team_connect_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_die('Unauthorized');
}
$to = sanitize_text_field($_POST['to']);
$message = sanitize_textarea_field($_POST['message']);
$result = $this->makeCall($to, $message);
if ($result && $result['success']) {
wp_send_json_success([
'call_id' => $result['result']['call_id']
]);
} else {
wp_send_json_error('Call failed');
}
}
}
// Initialize plugin
new TeamConnectWP();
// Shortcode for contact forms
function team_connect_shortcode($atts) {
$atts = shortcode_atts([
'type' => 'call',
'to' => '',
'message' => ''
], $atts);
if ($atts['type'] === 'call' && $atts['to'] && $atts['message']) {
$teamConnect = new TeamConnectWP();
$result = $teamConnect->makeCall($atts['to'], $atts['message']);
if ($result && $result['success']) {
return '<p>Call initiated successfully!</p>';
}
}
return '<p>Call failed.</p>';
}
add_shortcode('team_connect', 'team_connect_shortcode');
⚠️ Error Handling
Robust error handling for production PHP applications:
<?php
// Custom exception classes
class TeamConnectException extends Exception {}
class InsufficientCreditsException extends TeamConnectException {}
class InvalidAPIKeyException extends TeamConnectException {}
class RateLimitException extends TeamConnectException {}
// Enhanced API client with retry logic
class TeamConnectAPIEnhanced
{
private string $apiKey;
private string $baseUrl = 'https://us-central1-customerservice-2-156c.cloudfunctions.net';
private int $timeout = 30;
private int $maxRetries = 3;
public function __construct(string $apiKey, array $options = [])
{
$this->apiKey = $apiKey;
$this->timeout = $options['timeout'] ?? 30;
$this->maxRetries = $options['max_retries'] ?? 3;
}
/**
* Make API request with retry logic
*/
public function makeRequestWithRetry(string $service, string $action, array $data): array
{
$lastException = null;
for ($attempt = 0; $attempt <= $this->maxRetries; $attempt++) {
try {
return $this->makeRequest($service, $action, $data);
} catch (Exception $e) {
$lastException = $e;
// Don't retry on these errors
if ($e instanceof InvalidAPIKeyException ||
$e instanceof InsufficientCreditsException) {
throw $e;
}
// Don't retry on last attempt
if ($attempt === $this->maxRetries) {
throw $e;
}
// Exponential backoff with jitter
$waitTime = (2 ** $attempt) + random_int(0, 1000000) / 1000000;
error_log("Request failed, retrying in {$waitTime}s... (attempt " . ($attempt + 1) . ")");
usleep($waitTime * 1000000);
}
}
throw $lastException;
}
private function makeRequest(string $service, string $action, array $data): array
{
$payload = json_encode([
'service' => $service,
'action' => $action,
'data' => $data,
'api_key' => $this->apiKey
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => $payload,
'timeout' => $this->timeout
]
]);
$response = @file_get_contents($this->baseUrl . '/executeAPI', false, $context);
if ($response === false) {
throw new TeamConnectException('Failed to connect to API');
}
$httpCode = $this->getHttpResponseCode($http_response_header ?? []);
$responseData = json_decode($response, true);
switch ($httpCode) {
case 200:
return $responseData;
case 401:
throw new InvalidAPIKeyException('Invalid or revoked API key');
case 402:
throw new InsufficientCreditsException(
$responseData['error'] ?? 'Insufficient credits. Please top up your account.'
);
case 429:
throw new RateLimitException('Rate limit exceeded');
default:
throw new TeamConnectException(
$responseData['error'] ?? "HTTP error: $httpCode"
);
}
}
private function getHttpResponseCode(array $headers): int
{
if (isset($headers[0])) {
preg_match('/(\d{3})/', $headers[0], $matches);
return (int)($matches[1] ?? 500);
}
return 500;
}
// Safe methods that handle errors gracefully
public function makeCallSafe(string $to, string $message, array $options = []): array
{
try {
$result = $this->makeRequestWithRetry('voice', 'make_call', array_merge([
'to' => $to,
'message' => $message
], $options));
return [
'success' => true,
'data' => $result['result'] ?? [],
'billing' => $result['billing'] ?? []
];
} catch (InsufficientCreditsException $e) {
error_log('💰 Credit Error: ' . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage(),
'code' => 'INSUFFICIENT_CREDITS',
'topup_url' => 'https://team-connect.co.uk/api-dashboard.html#topup'
];
} catch (InvalidAPIKeyException $e) {
error_log('🔐 Auth Error: ' . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage(),
'code' => 'INVALID_API_KEY'
];
} catch (RateLimitException $e) {
error_log('⏱️ Rate Limit: ' . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage(),
'code' => 'RATE_LIMIT_EXCEEDED'
];
} catch (Exception $e) {
error_log('❌ API Error: ' . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage(),
'code' => 'UNKNOWN_ERROR'
];
}
}
public function sendSMSSafe(string $to, string $message, array $options = []): array
{
try {
$result = $this->makeRequestWithRetry('sms', 'send', array_merge([
'to' => $to,
'message' => $message
], $options));
return ['success' => true, 'data' => $result['result'] ?? []];
} catch (Exception $e) {
error_log('SMS Error: ' . $e->getMessage());
return ['success' => false, 'error' => $e->getMessage()];
}
}
public function sendEmailSafe(string $to, string $subject, string $html, array $options = []): array
{
try {
$result = $this->makeRequestWithRetry('email', 'send', array_merge([
'to' => $to,
'subject' => $subject,
'html' => $html
], $options));
return ['success' => true, 'data' => $result['result'] ?? []];
} catch (Exception $e) {
error_log('Email Error: ' . $e->getMessage());
return ['success' => false, 'error' => $e->getMessage()];
}
}
}
// Usage with comprehensive error handling
$enhancedApi = new TeamConnectAPIEnhanced('tc_live_your_api_key_here', [
'timeout' => 30,
'max_retries' => 3
]);
// Safe method calls
$callResult = $enhancedApi->makeCallSafe(
'+447123456789',
'Hello, this is a test call with error handling.',
['voice' => 'Polly.Amy']
);
if ($callResult['success']) {
echo "✅ Call successful: " . $callResult['data']['call_id'] . "\n";
echo "💰 Cost: " . ($callResult['billing']['cost'] ?? 'Unknown') . "p\n";
} else {
echo "❌ Call failed: " . $callResult['error'] . "\n";
// Handle specific error codes
switch ($callResult['code'] ?? '') {
case 'INSUFFICIENT_CREDITS':
echo "💰 Please top up at: " . $callResult['topup_url'] . "\n";
break;
case 'INVALID_API_KEY':
echo "🔐 Please check your API key in the dashboard\n";
break;
case 'RATE_LIMIT_EXCEEDED':
echo "⏱️ Please slow down your requests\n";
break;
default:
echo "❓ Unknown error occurred\n";
}
}
💰 Pricing
Simple, transparent pricing with no monthly fees. Perfect for PHP applications:
Service | Price | Unit | PHP Example |
---|---|---|---|
📞 Voice Calls | 7p | per minute | $api->makeRequest('voice', 'make_call', $data) |
💬 SMS Messages | 3p | per message | $api->makeRequest('sms', 'send', $data) |
📧 Email Sending | 0.15p | per email | $api->makeRequest('email', 'send', $data) |
🤖 AI Processing | 15p | per request | $api->makeRequest('ai', 'chat', $data) |
💡 PHP Application Cost Example
Laravel SaaS with 10,000 users:
- 2,000 voice calls (2 min avg) = £280.00
- 10,000 SMS messages = £300.00
- 50,000 emails = £75.00
- 1,000 AI requests = £150.00
- Total: £805.00/month (vs £100k+ building in-house)
💳 Manage Credits: Visit your API Dashboard to top up credits and view usage analytics.
Need help? Contact us at support@team-connect.co.uk
← Back to API Dashboard | REST API Docs | Laravel Package
© 2025 Dad-Link. All rights reserved. | Last updated: 2025-08-05 15:19:02 UTC