首页 文章

使用他们的API创建一个基本的MailChimp注册表单

提问于
浏览
73

我是MailChimp的新手,需要一些帮助 .

使用他们的基本简报注册表单...您只需将一些预先打包的HTML嵌入到您的页面中 . 但问题是单击提交重定向到MailChimp页面 . (我不想重定向到MailChimp,我希望用户在点击提交后留在自己的网站上 . )

它们提供了API和大量文档,但只提供了一些有用的示例 . 该API应该允许我与我的网站或应用程序完全集成 . 似乎当我在他们的文档中阅读适用于我的内容时,我点击该链接以获取更多信息,我最终绕圈子走了 . 他们告诉你如何做,但他们没有“告诉你”如何做到这一点 .

我可以获得一个API密钥,他们有大量的文档,以及一大堆包装和插件...... PHP,Drupal,Wordpress等...

关于他们的预打包解决方案的混乱是我只有一个常规的静态HTML页面,它知道从哪里开始...我不应该 POST 米应该使用 POSTGET .

我不是API的新手......我非常擅长让Google Maps API做我想做的事情 . 但是,除了详细的文档之外,Google还提供了真实的工作示例,这就是我学习它的方式 . 在我掌握API的细节之前,我只想看到它的实际应用 .

在他们的在线文档中没有任何可靠的示例或教程,我问如何使用他们的API创建最基本的HTML注册表单 .

3 回答

  • 7

    EDITED:

    自发布此答案以来,MailChimp已发布其API的第2版和第3版 . 版本3将是2017年开始的唯一支持版本 . 一旦我有机会测试它,我将更新API版本3的答案 .


    MailChimp API v3.0

    As per notification at the top of this page,2016年之后将不再支持API的所有先前版本 .

    我的解决方案在后台使用PHP来处理API,并使用jQuery来方便Ajax .

    1)下载支持API v3.0的PHP包装器 . 在撰写本文时,最新的MailChimp文档中没有任何官方列出支持v3.0,但有几个列在GitHub上,所以我选择了this one .

    2)使用您自己的API密钥和列表ID创建以下PHP文件 store-address.php ,然后将其放在与步骤1中的包装器相同的目录中 . 请记住遵循包装器的文档,但它们看起来都非常相似 .

    <?php // for MailChimp API v3.0
    
    include('MailChimp.php');  // path to API wrapper downloaded from GitHub
    
    use \DrewM\MailChimp\MailChimp;
    
    function storeAddress() {
    
        $key        = "xxxxxxxxxxxxxxx-us1";
        $list_id    = "xxxxxx";
    
        $merge_vars = array(
            'FNAME'     => $_POST['fname'],
            'LNAME'     => $_POST['lname']
        );
    
        $mc = new MailChimp($key);
    
        // add the email to your list
        $result = $mc->post('/lists/'.$list_id.'/members', array(
                'email_address' => $_POST['email'],
                'merge_fields'  => $merge_vars,
                'status'        => 'pending'     // double opt-in
                // 'status'     => 'subscribed'  // single opt-in
            )
        );
    
        return json_encode($result);
    
    }
    
    // If being called via ajax, run the function, else fail
    
    if ($_POST['ajax']) { 
        echo storeAddress(); // send the response back through Ajax
    } else {
        echo 'Method not allowed - please ensure JavaScript is enabled in this browser';
    }
    

    3)创建HTML / CSS / JavaScript(jQuery)表单(不需要在PHP页面上,访问者永远不会看到PHP在后台使用 . )

    响应是JSON,因此您必须正确处理它 .

    这是我的 index.html 文件的样子:

    <form id="signup" action="index.html" method="get">
        First Name: <input type="text" name="fname" id="fname" />
        Last Name: <input type="text" name="lname" id="lname" />
        email Address (required): <input type="email" name="email" id="email" />
        <input type="submit" id="SendButton" name="submit" value="Submit" />
    </form>
    <div id="message"></div>
    
    <script src="jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        $('#signup').submit(function() {
            $("#message").html("Adding your email address...");
            $.ajax({
                url: 'inc/store-address.php', // proper url to your "store-address.php" file
                type: 'POST', // <- IMPORTANT
                data: $('#signup').serialize() + '&ajax=true',
                success: function(msg) {
                    var message = $.parseJSON(msg),
                        result = '';
                    if (message.status === 'pending') { // success
                        result = 'Success!  Please click the confirmation link that will be emailed to you shortly.';
                    } else { // error
                        result = 'Error: ' + message.detail;
                    }
                    $('#message').html(result); // display the message
                }
            });
            return false;
        });
    });
    </script>
    

    MailChimp API版本1:

    (原始答案)

    在摸索了一段时间之后,我找到了一个使用jQuery的PHP示例的网站 . 从那以后,我能够使用包含基本注册表单的jQuery创建一个简单的HTML页面 . PHP文件在后台“隐藏”,用户从未看到它们,jQuery仍然可以访问和使用它们 .

    1)在这里下载PHP 5 jQuery示例...( EDIT :链接已经死了 . 但是,唯一重要的部分是PHP的官方API包装器,可用HERE . )

    http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip

    如果您只有PHP 4,只需下载MCAPI 1.2版并替换上面相应的 MCAPI.class.php 文件 .

    http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip

    2)通过将API密钥和列表ID添加到适当位置的 store-address.php 文件,按照自述文件中的说明进行操作 .

    3)您可能还想收集用户的姓名和/或其他信息 . 您必须使用相应的合并变量将数组添加到 store-address.php 文件 .

    这是我的 store-address.php 文件的样子,我还收集了名字,姓氏和电子邮件类型:

    <?php
    
    function storeAddress() {
    
        require_once('MCAPI.class.php');  // same directory as store-address.php
    
        // grab an API Key from http://admin.mailchimp.com/account/api/
        $api = new MCAPI('123456789-us2');
    
        $merge_vars = Array( 
            'EMAIL' => $_GET['email'],
            'FNAME' => $_GET['fname'], 
            'LNAME' => $_GET['lname']
        );
    
        // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
        // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
        $list_id = "123456a";
    
        if ($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype'])) {
            // It worked!   
            return 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.';
        } else {
            // An error ocurred, return error message   
            return '<b>Error:</b>&nbsp; ' . $api->errorMessage;
        }
    
    }
    
    // If being called via ajax, autorun the function
    if($_GET['ajax']) { 
        echo storeAddress(); 
    }
    

    4)创建HTML / CSS / jQuery表单 . 它不需要在PHP页面上 .

    这是我的 index.html 文件的样子:

    <form id="signup" action="index.html" method="get">
        First Name: <input type="text" name="fname" id="fname" />
        Last Name: <input type="text" name="lname" id="lname" />
        email Address (required): <input type="email" name="email" id="email" />
        HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
        Text: <input type="radio" name="emailtype" value="text" />
        <input type="submit" id="SendButton" name="submit" value="Submit" />
    </form>
    <div id="message"></div>
    
    <script src="jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        $('#signup').submit(function() {
            $("#message").html("Adding your email address...");
            $.ajax({
                url: 'inc/store-address.php', // proper url to your "store-address.php" file
                data: $('#signup').serialize() + '&ajax=true',
                success: function(msg) {
                    $('#message').html(msg);
                }
            });
            return false;
        });
    });
    </script>
    

    Required pieces...

    • index.html 如上构造或类似 . 使用jQuery,外观和选项是无止境的 .

    • store-address.php 文件作为PHP示例的一部分在Mailchimp网站上下载,并使用 API KEYLIST ID 进行了修改 . 您需要将其他可选字段添加到数组中 .

    从Mailchimp站点下载

    • MCAPI.class.php 文件(PHP 5版本1.3或PHP 4版本1.2) . 将它放在与 store-address.php 相同的目录中,或者您必须更新 store-address.php 中的URL路径,以便它可以找到它 .
  • 66

    下面是使用 version 2.0 的Mailchimp API和mailchimp-api(用于处理Mailchimp API的最小php抽象类)的示例 .

    <?php
    
    include('MailChimp.php');
    
    $MailChimp = new MailChimp('API_KEY');
    $result = $MailChimp->call('lists/subscribe', array(
        'id'                => 'LIST_ID',
        'email'             => array( 'email' => $_POST['email'] ),
        'merge_vars'        => array(
            'MERGE2' => $_POST['name'] // MERGE name from list settings
            // there MERGE fields must be set if required in list settings
        ),
        'double_optin'      => false,
        'update_existing'   => true,
        'replace_interests' => false
    ));
    
    if( $result === false ) {
        // response wasn't even json
    }
    else if( isset($result->status) && $result->status == 'error' ) {
        // Error info: $result->status, $result->code, $result->name, $result->error
    }
    
    ?>
    

    通过MailChimp API Documentation了解有关API调用可以发送的内容的更多信息 .

  • 21

    这是使用Official PHP Wrapper使用Mailchimp API 2.0版的另一个示例 .

    区别我的例子和其他人在这里发布的是我正在使用Mailchimp_Lists类的subscribe方法,可以通过实例化Mailchimp类( ->lists )来访问,而不是通用的call方法 .

    $api_key = "MAILCHIMP_API_KEY";
    $list_id = "MAILCHIMP_LIST_ID";
    
    require('Mailchimp.php');
    $Mailchimp = new Mailchimp($api_key);
    $subscriber = $Mailchimp->lists->subscribe($list_id, array('email' => $_POST['email']));
    
    if ( ! empty($subscriber['leid'])) {
        // Success
    }
    

相关问题