Skip to main content

Integrating Third-Party Services

Introduction Many Laravel dashboards integrate third-party services to enhance functionality, such as payment processing, SMS notifications, AI-powered insights,...

Alex

CEO

March 13, 2025
4 min read
Courses

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

  1. Register for a Stripe account and obtain API keys from the Stripe dashboard.
  2. Store keys securely in .env:
STRIPE_KEY=your-stripe-public-key
STRIPE_SECRET=your-stripe-secret-key
  1. 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

  1. Create a Twilio account and obtain API credentials.
  2. Store credentials securely in .env:
TWILIO_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-auth-token
TWILIO_FROM=your-twilio-phone-number
  1. 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

  1. Sign up for OpenAI API and get an API key.
  2. Store credentials in .env:
OPENAI_API_KEY=your-api-key
  1. 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 $summary in 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

  1. Store user last activity timestamps.
  2. Poll every minute to count active users:
$activeUsers = User::where('last_active', '>=', now()->subMinutes(5))->count();
  1. 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

  1. What is the purpose of handling webhooks when integrating Stripe into your Laravel application?
  2. How can you send an SMS in Laravel using Twilio? (Briefly outline the steps or code needed.)
  3. 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.

Ready to Turn This into Action?

We build the systems, integrations, and automation that replace manual work and disconnected tools. If something here resonated, we should talk.

Get in Touch See Our Work