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 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.

send Variable to Js File From PHP in drupal Custom Module

If we need to use the php variable in our js file we can use Core Drupal.settings Functionality :  example:

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)

Changing the year range in the form's date element drupal form api

Drupal form api ap usually used to build the custom form to extended the functionality of drupal according to your need.

Test payment Card Numbers For online payment

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

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".

Prevent to Load a js file on particular page using hook_js_alter Drupal 7

Drupal provided the lots of hook to extents its functionality, using this we can prevent a js file to load on particular page using HOOK_JS_ALTER

Flexslider Arrows Changed by arrow Images

Flexslider uses the arrows of its own flexslider family icons, if you want to change or replace with yours images you can do using following css.  

Export Mysql database using SSH

Export The database directly from command line is Easy and Fast. Follow these steps to export the database using SSH (putty terminal)

Drupal 7 Multisite setup

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

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

Important Mysql Commands that will we used with ssh

Commands Access monitor: mysql -u [username] -p; (will prompt for password) Show all databases: show databases;

Import Mysql database using SSH

Follow these steps to Import the database Mysql (Putty Terminal). 1. Login to your putty terminal. 2.You need to login in to Mysql, for this type

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 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 : 

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 Multiple PHP 7.3 / 7.2 / 7.1 on Ubuntu 18.04 / Ubuntu 16.04

If you want to Install Multiple PHP version on ubuntu/Linux system then this tutorial is for you. and on ubuntu shell using root user and follows steps below:

List of Most of File Type extension for drupal File field

List of Most of File Type extension for drupal File field : 

Render block and views block drupal 7 programmatically

This is article is for Drupal 7 to render block in templates and custom blocks using php codes Actually there is very simple ways to render block pro-grammatically 

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.

How To Set or Change Timezone on Ubuntu 18.04 & Ubuntu 16.04

Sometimes we need to check logs or working cron according to our country time, then we need to change the timezone of the server, and if you have ubuntu you can change easily by single command

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.

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.

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".