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

Comments

Add new comment

Other Articles

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 : 

Check the size of folder, files and directories using SSH

Following commands(In Bold) used for different purpose  1. Use df -h For check out the used space, free space and total space From all the partitions.

Install Apache Solr on Ubuntu

Install Apache Solr 7.7 on Ubuntu 18.04 & 16.04 LTS This tutorials explains how to install solr 7 on ubuntu system 1) Install or Check Java

Render menu on page template in custom way Drupal 8

If you want to render the menu items in custom way in page or node twig template of drupal 8 then this article is for you :  

Send file as Email attachment using hook_mail_alter drupal 7 programmatically (example webform submit)

Hi guys, In this tutorial we can see how we can send files as attachments in drupal 7 on webform submit using a hook_mail_alter 

Drupal 8 mutlisite setup

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

Import Database using xampp mysql command prompt windows

As we all know the xampp is most popular tool at machine level programming work, but sometime we need to deal with the bigger databases to import into mysql of xampp that provide and we import that

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.

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.

Bootstrap subtheme dropdown Drupal 7

Steps to create sub theme and mutilevel dropdown :-

Scroll to top button with html and jquery

Are you searching to add a button scroll to top, then this article is for you.

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)

Render a drupal node d8 twig template

Render a Drupal node in drupal 8 twig template and module PHP code is a bit different from Drupal 7 because Drupal 8 uses Symfony and twig format, follow the step and you will available to render a

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

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.

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

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.

Subtract two angularjs dates

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

Render a drupal node d7

If you want to render a node in drupal 7 it is pretty easy, you just a node id or nid of node for doing this: simply

Search word or file Using SSH(Putty)

Fastest and efficient way is to use grep command For search in a file : grep "wordtofind" config.php

Important SSH Commands

Copy folder from one location to another by excluding specified folder .  - rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude

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 

Recent Posts

Drupal 8: check user is logged in or not in *.html.twig

In the new era the drupal8 twig is introduce, so old basic php drupal hook is not useful in theme templates.

Add text to ckeditor textarea using jquery

In most of case we need to add or fill up form fields using jquery or Js, if you have trobble in loading data in textarea having ckeditor working already then this tutorial helps you.

How to Add a Custom Date Format in Drupal 8

In drupal 8 there is easiest way to add the date format is simply go link for your website

Retrieve the query used in mysql views

we can create the database views for many reason, but if we forget what query you was used to create the views or need to find out using which query results are generating here is the solution:

Send file as Email attachment using hook_mail_alter drupal 7 programmatically (example webform submit)

Hi guys,

In this tutorial we can see how we can send files as attachments in drupal 7 on webform submit using a hook_mail_alter 

[SOLVED] PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

If you get the same error like below in VScode editor then you are the right place to 

Redirect Old Domain to New Domain via .htaccess

Usually we develop the site on developement or subdomain and when we finally mirgate the to new domain then some of thing will remain or page redirect happens in  sometimes , so In this case .htacc

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