Here we can add subscribe to Mailchimp using programmatically PHP
This method is very easy and simple anyone can use this code and implement it into core PHP, all PHP frameworks like WordPress, laravel, etc
Step 1:
we need to create a Mailchimp account using Gmail account.
after we need to API key and listing id Mailchimp provides API key and listing id following image help for find out it.
Step 2:
Implement the following code into your PHP file and replace your API key and listing id.
<?php $fname = "Testing"; $lname = "Testing"; $email = "mailchimptesting@gmail.com"; if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){ // MailChimp API credentials $apiKey = '867c5754098e6fd502eed29952ec31d4-us21'; //replace your mailchimp API key $listID = '9aab796b80'; //replace your listing id listing id // MailChimp API URL $memberID = md5(strtolower($email)); $dataCenter = substr($apiKey,strpos($apiKey,'-')+1); $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID; // member information $json = json_encode([ 'email_address' => $email, 'status' => 'subscribed', 'merge_fields' => [ 'FNAME' => $fname, 'LNAME' => $lname ] ]); // send a HTTP POST request with curl $ch = curl_init($url); curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // store the status message based on response code if ($httpCode == 200) { $_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to Mailchmp.</p>'; } else { switch ($httpCode) { case 214: $msg = 'You are already subscribed.'; break; default: $msg = 'Some problem occurred, please try again.'; break; } $_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>'; } }else{ $_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>'; } echo $_SESSION['msg']; ?>