Development Tip

API를 사용하여 기본 MailChimp 가입 양식 만들기

yourdevel 2020. 10. 24. 12:00
반응형

API를 사용하여 기본 MailChimp 가입 양식 만들기


저는 MailChimp를 처음 사용하며 도움이 필요합니다.

기본 뉴스 레터 가입 양식을 사용하여 미리 패키지화 된 HTML을 페이지에 삽입하기 만하면됩니다. 그러나 이것의 문제는 제출을 클릭하면 MailChimp 페이지로 리디렉션된다는 것입니다. ( MailChimp로 리디렉션하고 싶지 않습니다. 사용자가 제출을 누른 후 웹 사이트에 머물러 있기를 바랍니다. )

API와 많은 문서를 제공하지만 유용한 예제는 거의 없습니다. API를 사용하면 내 사이트 또는 응용 프로그램과 완전히 통합 할 수 있습니다. 그들의 문서에서 나에게 적용되는 것을 읽으면 링크를 클릭하여 더 많은 정보를 얻고 결국 원을 그리며 돌아 다니는 것 같습니다. 그들은 그것을하는 방법을 당신에게 말하지만 방법을 "보여주지"는 않습니다.

API 키를 얻을 수 있고 수많은 문서와 수많은 래퍼 및 플러그인 ... PHP, Drupal, Wordpress 등이 있습니다.

사전 패키징 된 솔루션과 관련하여 여기에서 혼란스러운 점은 일반 정적 HTML 페이지가 있고 Wordpress, PHP 또는 Drupal이 아니라는 것입니다. 그래서 어디서부터 시작해야할지 모르겠습니다. 나는 사용하기로되어있어 경우 POSTGET.

저는 API의 초보자가 아닙니다. Google Maps API를 사용하여 원하는 모든 작업을 수행 할 수 있습니다. 그러나 Google은 내가 배운 자세한 문서 외에도 실제 작업 예제를 제공합니다. API의 세부 사항을 파악하기 전에 실제로 작동하는지 확인하고 싶습니다.

온라인 문서에 확실한 예제 나 튜토리얼이 없는데 API를 사용하여 가장 기본적인 HTML 가입 양식을 만드는 방법을 묻고 있습니다.


편집 :

이 답변을 게시 한 이후 MailChimp는 API 버전 2 및 3을 출시했습니다. 버전 3은 2017 년부터 유일하게 지원되는 버전이 될 것입니다. 테스트 할 기회가 생기면 API 버전 3에 대한 답변을 업데이트하겠습니다.


MailChimp API v3.0

이 페이지 상단의 알림에 따라 2016 년 이후에는 모든 이전 버전의 API가 지원되지 않습니다.

내 솔루션은 API를 처리하기 위해 백그라운드에서 PHP를 사용하고 Ajax를 용이하게하기 위해 jQuery를 사용합니다.

1) API v3.0을 지원하는 PHP 래퍼를 다운로드합니다. 이 글을 쓰는 시점에서 v3.0을 지원하는 최신 MailChimp 문서에는 공식이 없지만 GitHub에 여러 개가 나열되어 있으므로이 문서를 선택 했습니다 .

2) store-address.php자신의 API 키와 목록 ID를 사용하여 다음 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 예제를 다운로드하십시오 ... ( 편집 : 링크가 죽었습니다. 그러나 유일한 중요한 부분은 여기에서 사용할 수있는 PHP 용 공식 API 래퍼입니다 .)

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) store-address.php적절한 위치 파일에 API 키와 목록 ID를 추가하여 Readme 파일의 지침을 따릅니다 .

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>

필수 조각 ...

  • index.html 은 위와 같이 구성되거나 유사합니다. jQuery를 사용하면 모양과 옵션이 무한합니다.

  • store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.

  • MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.


Here is an example using version 2.0 of Mailchimp API together with mailchimp-api (a minimal php abstraction class for dealing with the Mailchimp API).

<?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
}

?>

Read more about what you can send with the API call at the MailChimp API Documentation.


Here's another example of using version 2.0 of the Mailchimp API using the Official PHP Wrapper.

The difference between my example and others posted here is that I'm using the subscribe method of the Mailchimp_Lists class, accessible through instantiation of the Mailchimp class (->lists), rather than the generic call method.

$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
}

참고URL : https://stackoverflow.com/questions/5025455/create-a-basic-mailchimp-signup-form-using-their-api

반응형