Introduction
Many Laravel dashboards integrate third-party services to enhance functionality, such as payment processing, SMS notifications, AI-powered insights, and real-time analytics. This chapter will guide you through integrating Stripe for payments, Twilio for SMS notifications, OpenAI for AI-driven features, and analytics tools to track dashboard performance.
Payment Processing with Stripe
1. Setting Up Stripe
- Register for a Stripe account and obtain API keys from the Stripe dashboard.
- Store keys securely in
.env:
STRIPE_KEY=your-stripe-public-key
STRIPE_SECRET=your-stripe-secret-key
- Install the Stripe PHP SDK:
composer require stripe/stripe-php
2. Creating Charges and Subscriptions
- One-Time Payment Example:
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$charge = $stripe->charges->create([
'amount' => 5000, // in cents (e.g., $50.00)
'currency' => 'usd',
'source' => $request->stripeToken,
'description' => 'Dashboard subscription fee',
]);
- Subscription Example: (Using Stripe Checkout for hosted payments)
$session = $stripe->checkout->sessions->create([
'payment_method_types' => ['card'],
'subscription_data' => ['items' => [['price' => 'price_id']]],
'success_url' => route('dashboard') . '?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('dashboard'),
]);
3. Handling Webhooks
- Stripe notifies the app of payment events (e.g., successful payments, failed transactions).
- Register a webhook in the Stripe Dashboard and handle events in Laravel:
Route::post('/webhook/stripe', [StripeWebhookController::class, 'handle']);
- Example webhook handler:
public function handle(Request $request) {
$event = $request->json()->all();
if ($event['type'] === 'invoice.payment_succeeded') {
// Mark invoice as paid in database
}
return response()->json(['status' => 'success']);
}
SMS Notifications with Twilio
1. Setting Up Twilio
- Create a Twilio account and obtain API credentials.
- Store credentials securely in
.env:
TWILIO_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-auth-token
TWILIO_FROM=your-twilio-phone-number
- Install the Twilio PHP SDK:
composer require twilio/sdk
2. Sending SMS Messages
use Twilio\Rest\Client;
$twilio = new Client(env('TWILIO_SID'), env('TWILIO_AUTH_TOKEN'));
$message = $twilio->messages->create(
$user->phone, [
'from' => env('TWILIO_FROM'),
'body' => 'Your dashboard report is ready!'
]
);
3. Handling Responses and Delivery
- Twilio can send delivery status updates via webhooks.
- Implement a webhook endpoint to log delivery statuses.
4. Use Case – Two-Factor Authentication (2FA)
- Send OTP codes via Twilio for secure logins.
- Generate and store OTPs, then verify on user login.
AI-Driven Features with OpenAI (GPT) Integration
1. Setting Up OpenAI
- Sign up for OpenAI API and get an API key.
- Store credentials in
.env:
OPENAI_API_KEY=your-api-key
- Install OpenAI PHP client:
composer require openai-php/client
2. Using OpenAI for Smart Dashboard Features
Example: Automated Report Summary
use OpenAI\Client;
$client = new Client(env('OPENAI_API_KEY'));
$response = $client->completions()->create([
'model' => 'text-davinci-003',
'prompt' => 'Summarize recent sales data.',
'max_tokens' => 100,
]);
$summary = $response['choices'][0]['text'];
- Display
$summaryin the UI to summarize complex data.
Example: AI-Powered Chatbot
- Integrate OpenAI to provide intelligent customer support responses.
3. Optimizing API Usage
- Implement caching to reduce API costs.
- Set a usage quota to prevent excessive requests.
Real-Time Analytics Integration
1. External Analytics Services (Google Analytics, Mixpanel, Heap)
- Track dashboard usage metrics using Google Analytics.
- Embed GA’s tracking code into Laravel Blade layouts:
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
</script>
2. Internal Analytics (Laravel Telescope)
- Monitor database queries, failed jobs, and logs.
composer require laravel/telescope
php artisan telescope:install
php artisan migrate
- Access analytics at
/telescope.
3. Real-Time Data Feeds
Example: Live Active Users Count
- Store user last activity timestamps.
- Poll every minute to count active users:
$activeUsers = User::where('last_active', '>=', now()->subMinutes(5))->count();
- Use Livewire or Laravel Echo to update the UI dynamically.
4. Ensuring Performance
- Load scripts asynchronously.
- Use webhooks instead of polling where possible.
- Optimize API calls with rate limits and caching.
Summary
By the end of this chapter, we have: ✅ Integrated Stripe for payments with webhook handling. ✅ Implemented SMS notifications using Twilio. ✅ Integrated AI-driven insights via OpenAI API. ✅ Added real-time analytics with Laravel Telescope and Google Analytics.
Quiz – Third-Party Integrations
- What is the purpose of handling webhooks when integrating Stripe into your Laravel application?
- How can you send an SMS in Laravel using Twilio? (Briefly outline the steps or code needed.)
- Give one example of how integrating the OpenAI API could enhance a dashboard application.
With these third-party services integrated, your Laravel dashboard is now fully equipped for dynamic interactions, automation, and enhanced user engagement. In the next chapter, we will focus on scalability and performance optimization.