mailchimp

In this tutorial we can see how to subscribe to the mailchimp subscribe list using php programmatically via api,

For this you need a mailchimp account, api key and list id 

you can see the tutorials to get api-key and list id using links

we are using PHP and curl for posting request to mailchimp servers, follow the steps and code, code is simple a php file with subscribe form in that you can enter firstname lastname and emails to subscribe to mailing list of mailchimp.

<?php

if($_POST){

    $data = [
        'email'     => $_POST['email'],
        'status'    => 'subscribed',
        'firstname' => $_POST['firstname'],
        'lastname'  => $_POST['lastname']
    ];
    
    // NOTE: status having 4 Option --"subscribed","unsubscribed","cleaned","pending"
    $res = syncMailchimp($data);
    
    if($res == 200){
        echo '<div class="alert alert-success" role="alert">Subscribed Successfull</div>';
    }else{
        echo '<div class="alert alert-danger" role="alert">Unable to Subscribe at the moment, try again later</div>';
    }
}


function syncMailchimp($data)
{
    $apiKey = 'YOUR_API_KEY;
    $listId = 'YOUR_LIST_ID';

    $memberId = md5(strtolower($data['email']));
    $dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
    $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;

    $json = json_encode([
        'email_address' => $data['email'],
        'status'        => $data['status'],
        'merge_fields'  => [
            'FNAME'     => $data['firstname'],
            'LNAME'     => $data['lastname']
        ]
    ]);

    $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);

    return $httpCode;
}

?>

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    <title>Subscribe To Mailchimp</title>
</head>

<body class="container">
    <h3>Subscribe To Mailchimp</h3>

    <form action="#" method="POST" id="suscribeForm">
        <div class="form-group">
            <label for="firstname">First Name</label>
            <input type="text" class="form-control" id="firstname" name="firstname" placeholder="First name" required> 
        </div>
        <div class="form-group">
            <label for="lastname">Last Name</label>
            <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Last Name" required>
        </div>
        <div class="form-group">
            <label for="email">Email address</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required>
        </div>
        <input type="submit" class="btn btn-primary" value="Submit"/>
    </form>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</body>

</html>

Just replace your API KEY and LIST ID and your are all set.

Note: we are using bootstrap and additional js to to look pretty you can avoid that if you don;t like, thanks


Please Comment your thoughts and feedback below and add something if you found good in anywhere to help others

Hit a like Button If you like the Post.

Many Thanks

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Other Articles

How to Stop Search Engines from Crawling your Website

search engine crawlers are very required to reach audience to your website, but if they hit continuous it will harm your website performance, If you want to prevent search engine crawler to crawl h

Html Dom parser to Extract the HTML data from Html page

Html Dom parser to Extract the HTML data from Html page  See the attached Zip file 

Subtract two angularjs dates

hey, Here you get how to subtract to date in angularjs with core functionality

Enable Drupal 8 Error Reporting

To Enable Drupal 8 Error Reporting, Put This code at top of sites/default/settings.php.

How to Manually Disable a WordPress Plugin

 Manually Disable a WordPress Plugin in Just 4 Steps :

How to render block in Drupal 8 theme template

Similar to Drupal 7, Drupal 8 also gives the customization using theme template, If you want to place a block using programmatically you have following options : 

Wordpress Revolution Slider error after upgrade to php 7

A recently got the error below after updating wordpress website to php 7, error causing the website blank and when the debug mode on we got this error, caused by revolution slider.

Reindex the Array keys

Sometimes we need to slice the array for certain values using program a code and at that time key of array is also unset. If you faced the same then you can use these options

Fix Bug Phpmyadmin [sql.lib.php] + Php7.2 + Ubuntu 16.04

I have faced this error recently , look like this    Warning in ./libraries/sql.lib.php#601

Install JAVA 8 on Ubuntu 18.04/16.04

Install java on Ubuntu 1)Install Oracle Java 8 

Use Drush in Cron to execute the task in multiple Drupal Instance..

As many of us using drush as command line tool for drupal for various task because it is easy to use and save time for searching dependency of module and libraries for various of module, In this tu

check if a string contains a specific word with PHP

In PHP sometimes we need to find the specific word in the string for the programitically use the code, there is a function called "

Drupal 8 mutlisite setup

In Drupal 8 Multisite setup is almost same as the Drupal 7.

Drupal 7 Multisite setup

Here is some links will helps to create a multisite of drupal 7 

Drupal site maintenance not affecting front page

function HOOK_preprocess_page(&$vars) { global $user;

Drupal 7 content type template

Open the template.php file in your theme for editing. Look for a function called yourthemename_preprocess_page (replace the yourthemename with your theme’s name).

Drupal 8 Opcache Problem with xampp

;Put this code in php.ini (C:\xampp\php\php.ini) zend_extension=php_opcache.dll [opcache] ; Determines if Zend OPCache is enabled opcache.enable=1 ; Determines if Zend OPCach

Creating a Self-Signed SSL Certificate linux/centos

Self Signed certificates are those are signed by the same individual whose identity it certifies.

Test payment Card Numbers For online payment

This article is for developers who develop eCommerce or payment gateway system for apps and website.

How To Install Webmin on Ubuntu 18.04

Webmin is open source control panel for linux machine, it is mainly use for server as file transfer, email configuration and other servers configuration using modern user interface.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 54 bytes)

Sometimes we get this php error on long page load or load many files are at once Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 54 bytes)

Get average number with PHP

<?php //put all integer in array $array = array(9,18,9,5,6,45); //Calculate the average. $average = array_sum($array) / count($array);

what is namespace in PHP?

https://stackoverflow.com/questions/3384204/what-are-namespaces

Recent Posts

Create a Flag link programmatically and render flag link in twig template drupal 8

This article is refer to generate the flag link programmatically and render in drupal 8 twig template, before in drupal 7 its was quiet easy to render or generate flag link in just a single line of

Jquery prevent enter to submit form

If you want to prevent the form submit using jquery, then this page helps you to doing this.

Code:

Play Pause HTML5 Video using Jquery

HTML5 video playing on any web page is very easy, in this tutorial we can show you how to add video on html and make it play and pause without using html controls.

Import and Export Drupal 8 Views, Or Import and Export any configuration Drupal 8

Import and Export configuration is the basic protocol to staging the website or production website deployment, In Drupal 7, we need the extra modules to import and export or we can use features mod

How to override different version of Jquery in Drupal 8 using theme

Drupal 8 use its own jquery version by default and if you want to use the other version of jQuery instead of default than this tutorials steps is for you, sometimes we need different version to oth

How you can get Mailchimp API KEY

By Follow steps below, you can find the api key or create the api key at mailchimp and use it to your website to connected the site with mailchimp to collect the subscribe in fastest way.

How to get your MailChimp LIST ID

Mailchimp is marketing automation platform and is provide email for marketing your product or business whatever you like, today its most trusted service providing all over the globe.

Drupal 8 add custom menu classes to using menu.html.twig

In Drupal 8 Twig templates give extra power to drupal to add dynamic content in twig style, In this tutorial we can see how we can add the custom menu classes to menu ul li using menu.html.twig.

How to create the directories and sub directories in one command linux

Many times we are want to create multiple directories and sub-directories under it and usually we do cd and mkdir one by one, it is very time consuming and it sometimes slow down our workflow.

Create Node drupal 8 programmatically with image upload using custom module

As we know drupal 8 use symphony, so module structure of drupal 8 is change and workflow functionality of doing thing also change.

Uncaught TypeError: CKEDITOR.tools.object.keys is not a function

Intergation of code snippet with ckeditor, cause this error "Uncaught TypeError: CKEDITOR.tools.object.keys is not a function".