Active Campaign PHP API Example

Generally at Server Academy we provide training on Windows Server for IT professionals but this time we are writing about using PHP (a server side web programming language) to interact with the Active Campaign (email marketing) API key. We were recently writing PHP code to create new email contacts with…

Generally at Server Academy we provide training on Windows Server for IT professionals but this time we are writing about using PHP (a server side web programming language) to interact with the Active Campaign (email marketing) API key.

We were recently writing PHP code to create new email contacts with Active Campaign and came up with this little function:

// Active Campaign API call
function ActiveCampaignAPICall($Endpoint, $Method = "get", $PostBody = "", $ReturnTransfer = true) {
    
    // Variables
    $EndpointRoot = "https://youraccountname.api-us1.com";
    
    // Create event in Active Campaign
    $curl = curl_init();
    
    // Determine the method
    switch(strtolower($Method)) {
        case "get":
            curl_setopt($curl, CURLOPT_HTTPGET, true);
            break;
        case "post":
            curl_setopt($curl, CURLOPT_POST, true);
            break;
        case "put":
            curl_setopt($curl, CURLOPT_PUT, true);
            break;
        case "delete":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
            break;
    }

    // Set the post body
    if($PostBody) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $PostBody);        
    }
    
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Api-Token: yourapitokengoeshere'));
    curl_setopt($curl, CURLOPT_URL, $EndpointRoot . $Endpoint);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, $ReturnTransfer);
    
    // Execute the curl request
    $result = curl_exec($curl);

    return $result;
}

This PHP function can be used like this to create a new contact in Active Campaign:

Get an existing contact

$contact = ActiveCampaignAPICall("/api/3/contacts/1234");

Create a new contact

$json = '{
	"contact": {
		"email": "johndoe@example.com",
		"firstName": "John",
		"lastName": "Doe",
		"phone": "7223224241"
	}
}';

$result = ActiveCampaignAPICall("/api/3/contacts", "post", $json);

Update an existing contact


$json = '{
	"contact": {
		"email": "johndoe@example.com",
		"firstName": "John",
		"lastName": "Friday"
,
		"phone": "12312341234"
	}
}';

$result = ActiveCampaignAPICall("/api/3/contact/sync", "post", $json);

Delete an existing contact

$result = ActiveCampaignAPICall("/api/3/contacts/17739", "delete");

I’m sure this function can be improved as I am no pro PHP developer…but hopefully some of you found it and the examples useful.

CREATE YOUR FREE ACCOUNT & GET OUR

FREE IT LABS

profile avatar

Paul Hill

Paul Hill is the founder of ServerAcademy.com and IT instructor to over 500,000 students online!