Sync External APIs with Laravel HTTP Client

Hello web developers! In this tutorial, I’ll show you how to use Laravel’s built-in HTTP client to synchronize data between external APIs and your Laravel application. Whether you're integrating with third-party services like Stripe, Mailchimp, or Salesforce, Laravel’s HTTP client makes it easy to fetch, update, and synchronize data seamlessly.

I'll walk you through the process step by step with real-life examples.

Sync External APIs with Laravel HTTP Client

Sync External APIs with Laravel HTTP Client

 

Step 1: Set Up Laravel’s HTTP Client

Laravel provides a simple and powerful HTTP client based on Guzzle. To get started, make sure you have Laravel installed. You can use the HTTP client out of the box, so no extra packages are needed.

composer create-project --prefer-dist laravel/laravel api-sync

 

Step 2: Configuring Environment Variables

It’s best practice to store API credentials in your env file for external API integrations. Let’s say you want to integrate with Stripe, Mailchimp, and Salesforce. Add their API keys in the env file.

STRIPE_API_KEY=your_stripe_api_key
MAILCHIMP_API_KEY=your_mailchimp_api_key
SALESFORCE_API_KEY=your_salesforce_api_key

 

Step 3: Fetch Data from External APIs

Now, let's use Laravel’s HTTP client to fetch data from these services.

Example 1: Synchronizing Stripe Customers

To synchronize Stripe customer data, you can make a GET request to Stripe’s API.

use Illuminate\Support\Facades\Http;

public function syncStripeCustomers()
{
    $response = Http::withToken(env('STRIPE_API_KEY'))
        ->get('https://api.stripe.com/v1/customers');

    if ($response->successful()) {
        $customers = $response->json();
        // Process and save the data to your database
        foreach ($customers['data'] as $customer) {
            // Save or update customer data in your application
        }
    } else {
        // Handle the error response
        Log::error('Stripe API error: ' . $response->body());
    }
}

Example 2: Synchronizing Mailchimp Subscribers

Next, let’s fetch subscriber data from Mailchimp using their API.

public function syncMailchimpSubscribers()
{
    $response = Http::withBasicAuth('anystring', env('MAILCHIMP_API_KEY'))
        ->get('https://<dc>.api.mailchimp.com/3.0/lists/{list_id}/members');

    if ($response->successful()) {
        $subscribers = $response->json();
        // Process and save subscriber data
        foreach ($subscribers['members'] as $subscriber) {
            // Save or update subscriber data in your application
        }
    } else {
        Log::error('Mailchimp API error: ' . $response->body());
    }
}

Replace <dc> with the data center specific to your Mailchimp account and {list_id} with your Mailchimp audience list ID.

Example 3: Synchronizing Salesforce Contacts

To sync data from Salesforce, use their REST API.

public function syncSalesforceContacts()
{
    $response = Http::withToken(env('SALESFORCE_API_KEY'))
        ->get('https://your_instance.salesforce.com/services/data/vXX.X/sobjects/Contact');

    if ($response->successful()) {
        $contacts = $response->json();
        // Process and save contacts data
        foreach ($contacts['records'] as $contact) {
            // Save or update contact data in your application
        }
    } else {
        Log::error('Salesforce API error: ' . $response->body());
    }
}

 

Step 4: Handling API Errors

It’s essential to handle errors properly when dealing with external APIs. You can check if the request was successful using the successful() method or handle specific status codes.

$response = Http::withToken(env('STRIPE_API_KEY'))->get('https://api.stripe.com/v1/customers');

if ($response->failed()) {
    return response()->json(['error' => 'Failed to sync data'], 500);
}

You can also log the errors to troubleshoot.

 

Step 5: Scheduling the Sync

To automate the synchronization, you can set up a scheduled task in Laravel. Open the bootstrap/app.php file and add your sync method to the schedule.

use Illuminate\Console\Scheduling\Schedule;
 
->withSchedule(function (Schedule $schedule) {
    $schedule->call(new syncStripeCustomers)->daily();
    $schedule->call(new syncMailchimpSubscribers)->daily();
    $schedule->call(new syncSalesforceContacts)->daily();
})

Run the scheduler with the following command to sync the data daily.

php artisan schedule:work

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS