ActiveCampagin API Laravel Integration Code Examples | 2023

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

ActiveCampaign is a popular marketing automation tool that enables businesses to manage their email marketing, marketing automation, CRM, and sales automation. Laravel, a robust PHP framework, can help streamline the process of integrating ActiveCampaign with web applications. This article will provide a step-by-step guide on setting up ActiveCampaign in Laravel and a real-life example of its integration.

This article will teach us how to integrate ActiveCampaign into your Laravel projects. We will discover the benefits of using ActiveCampaign API and guide you through the process with a step-by-step tutorial.

Article Highlights

  • ActiveCampaign is a powerful marketing automation platform that can be easily integrated into your Laravel applications.
  • ActiveCampaign API allows you to interact with the ActiveCampaign platform programmatically, providing access to features like managing contacts, campaigns, and automations.
  • This guide provides step-by-step instructions on setting up ActiveCampaign in Laravel.
  • Prerequisites for integrating ActiveCampaign with Laravel include having an ActiveCampaign account, API key, a Laravel installation, familiarity with the Laravel framework, and Composer for package management.
  • Install the ActiveCampaign API PHP library using Composer: composer requires activecampaign/api-php. Verify the library has been added to the composer.json file.
  • Configure ActiveCampaign API in Laravel by creating a configuration file config/activecampaign.php, adding API credentials to the .env file and updating the configuration array.
ActiveCampaign Laravel

Steps to Setup ActiveCampaign in Laravel

  • Step 1: Install ActiveCampaign API PHP library. 
  • Step 2: Configure ActiveCampaign API in Laravel. 
  • Step 3: Creating an ActiveCampaign API Service.

ActiveCampaign Laravel Service Code Example

<?php

namespace App\Http\Controllers;

use App\Services\ActiveCampaignService;

class ContactsController extends Controller
{
    protected $activeCampaignService;

    public function __construct(ActiveCampaignService $activeCampaignService)
    {
        $this->activeCampaignService = $activeCampaignService;
    }

    public function listContacts()
    {
        $response = $this->activeCampaignService->getContacts();
        // Handle the response, e.g., display the contacts or return as JSON
    }

    public function createContact()
    {
        $email = 'john.doe@example.com';
        $firstName = 'John';
        $lastName = 'Doe';

        $response = $this->activeCampaignService->addContact($email, $firstName, $lastName);
        // Handle the response, e.g., display a success message or redirect to another page
    }
}

Table of Contents

In this article, we will cover the following topics.

  1. Using the ActiveCampaign API.
  2. Importance of integrating ActiveCampaign with Laravel.
  3. Prerequisites.
  4. Steps by Steps guide to Integrate ActiveCampaign with Laravel.
  5. Real ActiveCampaign API in Laravel Example.
  6. ActiveCampaign Laravel Service Code Example.
  7. Integrate ActiveCampaign API into Web Applications.
  8. Use ActiveCampagin API in Laravel: Code Examples Summary.

Using the ActiveCampaign API

The ActiveCampaign API allows you to interact with the ActiveCampaign platform, enabling you to manage contacts, create and send campaigns, track website activity, and much more. By integrating ActiveCampaign with Laravel, you can leverage the power of email marketing automation and CRM tools directly within your Laravel applications.

ActiveCampaign is a marketing automation and customer relationship management (CRM) platform that helps businesses streamline their marketing efforts and improve customer engagement. 

The ActiveCampaign API (Application Programming Interface) allows developers to interact with the platform programmatically, providing access to various features and data such as contacts, campaigns, automation, lists, and more.

The API is based on RESTful principles, which means it uses standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources identified by URLs. It supports data exchange in JSON format, making its integration with various programming languages and frameworks easy. 

The ActiveCampaign API also provides comprehensive documentation that guides developers on how to authenticate, make requests, handle responses, and access specific features.

Why Integrate ActiveCampaign with Laravel

Laravel is a popular PHP framework that simplifies web application development. Integrating ActiveCampaign with Laravel helps you leverage the power of both platforms, allowing you to manage contacts, send emails, and create automations directly from your Laravel application. This integration simplifies your workflow, reduces the need for manual tasks, and makes it easier to track customer interactions.

 Integrating ActiveCampaign with Laravel offers several benefits:

Seamless integration.

By leveraging the ActiveCampaign API, Laravel developers can easily access and interact with the platform’s features and data, creating a seamless user experience between their web application and ActiveCampaign.

Enhanced marketing automation.

Integrating ActiveCampaign into Laravel applications enables developers to automate marketing tasks such as email campaigns, lead nurturing, and customer segmentation, leading to more efficient and targeted marketing efforts.

Improved customer relationship management.

Integrating ActiveCampaign with Laravel allows developers to manage and analyze customer data within their web applications, enabling them better to understand customer needs, preferences, and behavior.

Streamlined workflows.

Integrating the ActiveCampaign API in Laravel applications can help developers automate routine tasks, such as adding or updating contacts, managing lists, or triggering automations, streamlining workflows and improving productivity.

Customization and flexibility.

The ActiveCampaign API provides a high level of customization, allowing Laravel developers to tailor the integration to their specific needs, whether a simple contact form or a complex marketing automation workflow.

Integrating the ActiveCampaign API with Laravel provides businesses with powerful tools for marketing automation, CRM, and customer engagement, all within the context of their Laravel web applications. This integration can lead to more efficient marketing efforts, better customer relationships, and streamlined workflows.

Integrate ActiveCampaign with Laravel

Follow these steps to set up ActiveCampaign in your Laravel application:

Prerequisites 

Before getting started, make sure you have the following:

  • ActiveCampaign account and API key. 
  • Laravel installation and familiarity with the Laravel framework.
  • Composer for package management.

ActiveCampaign account and API key

To get started with integrating ActiveCampaign API into your Laravel application, you’ll need an ActiveCampaign account. Depending on your needs, you can sign up for a free trial or choose a paid plan. Once you have an account, you must generate an API key, a unique identifier that allows your application to authenticate and access the ActiveCampaign API. The API key is in your account settings under the “Developer” section.

Laravel installation and familiarity with the Laravel framework

Before integrating ActiveCampaign with Laravel, it’s crucial to have a working Laravel installation and basic familiarity with the Laravel framework. You should have PHP, Composer, and Laravel installed on your development environment. Familiarity with Laravel concepts such as routing, controllers, middleware, and models will be essential as you work with the ActiveCampaign API. If you’re new to Laravel, you can follow the official documentation and tutorials to gain a solid understanding of the framework.

Composer for package management

Composer is a dependency management tool for PHP that helps you manage and organize your project’s dependencies, including libraries and packages. It is an essential tool for Laravel development, simplifying installing and updating third-party packages in your application.

To integrate ActiveCampaign API into your Laravel application, you may use a Composer package specifically designed for this purpose, such as the “activecampaign/api-php” package. This package provides a PHP wrapper around the ActiveCampaign API, making working with the API in your Laravel application easy. You’ll need Composer installed on your development environment to install the package. You can then run the following command to add the package to your project:

composer require activecampaign/api-php

Once you have the prerequisites, you can integrate the ActiveCampaign API into your Laravel application, using the API key you obtained earlier and leveraging the Laravel framework features and the Composer package to interact with the API.

Install ActiveCampaign API PHP library

We need to perform the following steps to install the ActiveCampaign API PHP library.

  • Add the library to your Laravel project using Composer
  • Verifying the library has been added to the composer.json file
Add the library to your Laravel project using Composer

To install the ActiveCampaign API PHP library in your Laravel project, you must use Composer, the package management tool for PHP. The library provides a convenient wrapper around the ActiveCampaign API, making working with the API in your Laravel application easier.

To add the library to your project, open a terminal or command prompt, navigate to your Laravel project’s root directory, and run the following command:

composer require activecampaign/api-php

This command tells Composer to download and install the “activecampaign/api-php” package containing the ActiveCampaign API PHP library and add it as a dependency in your Laravel project.

Verifying the library has been added to the composer.json file

Once the installation is complete, you should verify that the library has been added to your project’s composer.json file. 

The composer.json file contains the list of dependencies for your Laravel project and is located in the root directory of your project.

Open the composer.json file in your favorite text editor or IDE, and look for the “require” section. You should see an entry for “activecampaign/api-php” with its version number:

{
    "require": {
        ...
        "activecampaign/api-php": "^3.0",
        ...
    },
}

The version number might differ depending on the library’s latest version available at the time of installation. If you see the “activecampaign/api-php” entry in your composer.json file, it confirms that the ActiveCampaign API PHP library has been successfully added to your Laravel project.

Now that the library is installed, you can use it to interact with the ActiveCampaign API in your Laravel application.

Configure ActiveCampaign API in Laravel

To configure ActiveCampaign API in Laravel, perform the following steps.

  • Create a configuration file config/activecampaign.php
  • Adding API credentials to .env file 
  • Adding the credentials to the configuration file

Create a configuration file config/activecampaign.php

To configure the ActiveCampaign API in your Laravel application, create a new configuration file named activecampaign.php inside the config directory. This file will store your API settings and make managing and accessing them easier throughout your application.

Inside the activecampaign.php file, add the following content:

<?php

return [
    'url' => env('ACTIVECAMPAIGN_URL', ''),
    'api_key' => env('ACTIVECAMPAIGN_API_KEY', ''),
];

This configuration file retrieves the ActiveCampaign URL and API key from the .env file using the env() helper function.

Adding API credentials to the .env file

Add your ActiveCampaign API credentials to your Laravel project’s .env file to store them securely. The .env file is located in the root directory of your project and is used to store sensitive information such as API keys, passwords, and other configurations.

Open the .env file and add the following lines, replacing your_activecampaign_url and your_activecampaign_api_key with your actual ActiveCampaign URL and API key:

ACTIVECAMPAIGN_URL=your_activecampaign_url
ACTIVECAMPAIGN_API_KEY=your_activecampaign_api_key

Adding the credentials to the config

With the configuration file and .env file set up, the ActiveCampaign API credentials are now accessible through the Laravel configuration system. To access the credentials in your application, you can use the config() helper function as follows:

$activeCampaignUrl = config('activecampaign.url');
$activeCampaignApiKey = config('activecampaign.api_key');

Now that the ActiveCampaign API is configured in your Laravel application, you can use the installed “activecampaign/api-php” library to interact with the API using the provided credentials.

Creating an ActiveCampaign API Service

To create an ActiveCampaign API service, you need to perform the following steps:

  • Generate a new service provider using artisan command  
  • Register the service provider in config/app.php
  • Binding the ActiveCampaign API client to the service container

Generate a new service provider using artisan command

To create an ActiveCampaign API service, you’ll first generate a new service provider using Laravel’s artisan command. Service providers are the central place in Laravel to configure and bootstrap your application’s services. Open a terminal or command prompt, navigate to your Laravel project’s root directory, and run the following command:

php artisan make:provider ActiveCampaignServiceProvider

This command will create a new file named ActiveCampaignServiceProvider.php in the app/Providers directory.

Registering the service provider in config/app.php

After creating the service provider, you must register it in your Laravel application. To do this, open the config/app.php file and look for the provider’s array. Add the following entry to the array:

App\Providers\ActiveCampaignServiceProvider::class,

Binding the ActiveCampaign API client to the service container

Now that the service provider is registered, you can bind the ActiveCampaign API client to the Laravel service container. The service container is a powerful tool for managing class dependencies and performing dependency injection in Laravel.

Now, open the app/Providers/ActiveCampaignServiceProvider.php file and update it as follows:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use ActiveCampaign;

class ActiveCampaignServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(ActiveCampaign::class, function ($app) {
            return new ActiveCampaign(
                $app['config']['activecampaign']['api_key'],
                $app['config']['activecampaign']['url']
            );
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

ActiveCampaign API in Laravel Code Examples

Here are two examples of using the ActiveCampaign API in Laravel, one for fetching a list of contacts and another for adding a new contact.

Fetching a list of contacts

To fetch a list of contacts, you can use the following code inside a controller or any other part of your Laravel application:

use ActiveCampaign;

// ...

$activeCampaign = app(ActiveCampaign::class);
$response = $activeCampaign->api('contact/list', []);

In the above code example, we first import the ActiveCampaign class using the use statement. Then, we retrieve the ActiveCampaign API client instance from the service container using the app() helper function. 

Finally, we call the api() method on the API client instance, passing the contact/list endpoint and an empty array (since we’re not sending any additional parameters in this case).

Adding a new contact

The example code below demonstrates adding a new contact to ActiveCampaign using their API. This example uses the PHP library activecampaign/api-php, but the same concept can be applied to other languages and libraries.

To add a new contact, you can use the following code:

use ActiveCampaign;

// ...

$activeCampaign = app(ActiveCampaign::class);

$data = [
    'email' => 'john.doe@example.com',
    'first_name' => 'John',
    'last_name' => 'Doe',
];

$response = $activeCampaign->api('contact/add', $data);

In the above code example, we first import the ActiveCampaign class using the use statement and retrieve the API client instance from the service container. We then create an associative array named $data containing the contact’s email, first name, and last name. Finally, we call the api() method on the API client instance, passing the contact/add endpoint and the $data array containing the contact information.

The above two examples demonstrate how to interact with the ActiveCampaign API in Laravel using the API client instance registered in the service container. You can use similar methods to interact with other endpoints and resources in the ActiveCampaign API.

A Full ActiveCampaign Laravel Service Example

The following example demonstrates how to create an ActiveCampaign Laravel service for interacting with the ActiveCampaign API in a more structured and reusable way.

  1. Create a new service class:

First, create a new directory named Services inside your app directory. Then, create a new file named ActiveCampaignService.php inside the Services directory.

  1. Define the ActiveCampaignService class:

Inside the ActiveCampaignService.php file, add the following content:

<?php

namespace App\Services;

use ActiveCampaign;

class ActiveCampaignService
{
    protected $client;

    public function __construct(ActiveCampaign $client)
    {
        $this->client = $client;
    }

    public function getContacts()
    {
        return $this->client->api('contact/list', []);
    }

    public function addContact($email, $firstName, $lastName)
    {
        $data = [
            'email' => $email,
            'first_name' => $firstName,
            'last_name' => $lastName,
        ];

        return $this->client->api('contact/add', $data);
    }
}

The above code example defines a new class named ActiveCampaignService inside the App\Services namespace. The class has a constructor that accepts an instance of the ActiveCampaign class, which Laravel’s dependency injection system will inject. We store the ActiveCampaign instance in the $client property.

We then define two methods: getContacts() and addContact($email, $firstName, $lastName). The getContacts() method calls the contact/list endpoint of the ActiveCampaign API, while the addContact() method calls the contact/add endpoint with the provided contact information. Both methods return the response from the ActiveCampaign API.

  1. Use the ActiveCampaign Service in your application

Now that you have created the ActiveCampaignService, you can use it in your controllers or other parts of your Laravel application.

Here’s an example of using the service in a controller:

<?php

namespace App\Http\Controllers;

use App\Services\ActiveCampaignService;

class ContactsController extends Controller
{
    protected $activeCampaignService;

    public function __construct(ActiveCampaignService $activeCampaignService)
    {
        $this->activeCampaignService = $activeCampaignService;
    }

    public function listContacts()
    {
        $response = $this->activeCampaignService->getContacts();
        // Handle the response, e.g., display the contacts or return as JSON
    }

    public function createContact()
    {
        $email = 'john.doe@example.com';
        $firstName = 'John';
        $lastName = 'Doe';

        $response = $this->activeCampaignService->addContact($email, $firstName, $lastName);
        // Handle the response, e.g., display a success message or redirect to another page
    }
}

In this example, we import the ActiveCampaignService class and inject it into the ContactsController through the constructor. We store the service instance in the $activeCampaignService property. In the listContacts() and createContact() methods, we use the ActiveCampaignService to interact with the ActiveCampaign API.

Using a dedicated service class like ActiveCampaignService, you can centralize your ActiveCampaign API interactions in one place, making your code more organized, reusable, and maintainable.

Using ActiveCampagin API in Laravel

Integrating the ActiveCampaign API into Laravel applications allows developers to leverage ActiveCampaign’s marketing automation features, such as managing contacts, campaigns, and automation, directly from their web applications. This integration helps streamline marketing efforts, improve user engagement, and increase conversions.

To integrate ActiveCampaign with Laravel, you need an ActiveCampaign account, API key, a Laravel installation, familiarity with the Laravel framework, and Composer for package management. Start by installing the ActiveCampaign API PHP library using Composer and configuring the API credentials in your Laravel application.

Create an ActiveCampaign API Service by generating a new service provider, registering it, and binding the ActiveCampaign API client to the service container. You can then use the ActiveCampaign API to fetch contact lists, add new contacts, or manage campaigns and automation.

When integrating the API into your web application, correctly handle API responses and errors, displaying relevant messages to users or logging errors as needed.

Following these steps, you can successfully integrate the ActiveCampaign API into your Laravel web applications and take advantage of ActiveCampaign’s powerful marketing automation features.

Our ActiveCampaign Article Series

This is one of many articles in our series on the ActiveCampaign email marketing software. Feel free to check out the entire series below to dig deeper into ActiveCampaign.

Get Started at ActiveCampaign

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.