Add a contact to ActiveCampaign via API

Home » Snippets » Add a contact to ActiveCampaign via API
0

Created with:

Visibility: 

public

Creator: Alex

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
function wpturbo_add_contact_to_activecampaign($email) {
    // Set the API endpoint URL
    $url = 'https://your-activecampaign-url.com/api/3/contacts';

    // Set your ActiveCampaign API key
    $api_key = 'your-activecampaign-api-key';

    // Set the request headers
    $headers = array(
        'Content-Type: application/json',
        'Api-Token: ' . $api_key
    );

    // Set the request data
    $data = array(
        'contact' => array(
            'email' => $email
        )
    );

    // Prepare and send the API request
    $args = array(
        'method'  => 'POST',
        'headers' => $headers,
        'body'    => json_encode($data),
    );

    // Send the request using wp_remote_request() function
    $response = wp_remote_request($url, $args);

    // Check if the request was successful
    if (is_wp_error($response)) {
        // Handle the error
        return false; // or throw an exception, log the error, etc.
    } else {
        // Contact added successfully
        return true;
    }
}
				

This function, wpturbo_add_contact_to_activecampaign(), takes an email parameter and uses the ActiveCampaign API to add a contact with that email address to your ActiveCampaign account. It uses the wp_remote_request() function, which is the recommended way to make HTTP requests in WordPress.

First, you need to provide the API endpoint URL and your ActiveCampaign API key. Replace 'https://your-activecampaign-url.com/api/3/contacts' with the actual API endpoint URL and 'your-activecampaign-api-key' with your ActiveCampaign API key.

The function sets the request headers, including the content type and the API token. It then prepares the request data, which includes the email address of the contact to be added.

The API request is sent using the wp_remote_request() function, which performs an HTTP request to the provided URL with the specified arguments. It sends a POST request with the request headers and the request data in JSON format.

After sending the request, the function checks if the request was successful. If there was an error, it returns false. Otherwise, it returns true to indicate that the contact was added successfully.

Remember to replace the placeholder values with your actual ActiveCampaign API endpoint URL and API key before using this code.

Register an account to save your snippets or go Pro to get more features.