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

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:

Nodejs With Xampp

Hello Guys, We can easily connect the Nodejs with xampp by follow simple steps -

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.

Embed Google maps on website (Static address )

Here using this website  we can get the embed the static map on our website.

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

Schema API Drupal not accept the datatype like date or datetime

Schema  Api Drupal 7 and Drupal 8 not accept the datatypes Like data or datatime and generate the warning and sql syntax error while installing the drupal module in install  normally we

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

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

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:

Install JAVA 8 on Ubuntu 18.04/16.04

Install java on Ubuntu 1)Install Oracle Java 8 

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)

Subtract two angularjs dates

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

How to Install Civicrm into Drupal 7

There is a direct guide available on CiviCRM Website, Here we follow faster steps to do the same.

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

Easy Way to use tooltip with HTML tags

The easiest way to use tooltip on any tags of HTML 1. Span Tag

Facebook post customisation posted using web app using Facebook Open Graph

Facebook is Providing autoposting functionality using website application and provides to display you website content on your facebook page.

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.

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

Wordpress Error with php 7.1 - PHP Fatal error: Uncaught Error: [] operator not supported for strings

Hey, This is error caused by php7 and later,many application will face this error Reason behind is that the php 7 will not convert the blank variable with is define as string to array:

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;

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.  

Enable Drupal 8 Error Reporting

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

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