javascript - 使用 Mailchimp API 3.0 获取并显示成员(member)状态(或错误)

标签 javascript php curl mailchimp

创建 Mailchimp 注册表单。

想先检查成员(member)状态,然后根据需要添加或更新。

第一步是打开与 Mailchimp 3.0 API 的连接,获取成员状态并显示状态或错误。

这是我到目前为止所拥有的:

表单的 HTML:

        <!--Newsletter-->
    <section title="Newsletter" id="newsletter" class="basicbox">
        <h2>Sign Up for the Newsletter</h2>
        <!-- Begin MailChimp Signup Form -->
        <div id="newsletter-form">
            <form id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" method="post" action="#" target="_blank">
                <fieldset id="mc_embed_signup">
                    <p><input type="text" name="fname" class="required" placeholder="First name" title="It would be great to know your name."></p>
                    <p><input type="text" name="lname" class="required" placeholder="Last name" title="It would be great to know your last name."></p>
                    <p><input type="email" name="email" class="required email" placeholder="Your email address" title="Hey, I need your email address so I know where to send the newsletter." ></p>

                    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
                    <p><small>I respect your privacy and will not share your contact information.</small></p>
                </fieldset>
            </form>
        </div>
    </section>
    <!--End mc_embed_signup-->

表单的 JS(位于同一 HTML 文档的底部,结束 </body 标记之前:

<!-- Begin JavaScript -->
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.32/jquery.form.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.min.js"></script>

    <!--  validate newsletter form-->
    <script>
    $(function() {
    $('#mc-embedded-subscribe-form').validate({
      rules: {
                fname: {
                    required: true,
                    minlength: 2
                },
                lname: {
                    required: true,
                    minlength: 2
                },
        email: {
          required: true,
          email: true
        },
      },
      messages: {
                fname: {
                    required: "Oh come on, I really need to know your name.",
                    minlength: "Surely your name is longer than one character."
                },
                lname: {
                    required: "I'm normally not formal, but what is your surname?",
                    minlength: "Surely your name is longer than one character."
                },
        email: {
          required: "Hey, I need your email address so I know where to send the newsletter."
        },
      },
          submitHandler: function(form) {
          $(form).ajaxSubmit({
            url: 'process_mc_status.php',
            success: function() {
                $('#mc-embedded-subscribe-form').hide();
                $('#newsletter-form').append("<p class='thanks'>Working on adding your awesome self to the list.</p>")
              }
            });
          }
        });

                // How to now display the status?
                // $('#newsletter-form').append("<p class='thanks'>"), $user_status, "</p>"

这是 PHP,位于 process_mc_status.php 中:

<?php

// Let's track errors in a log //
    $fp = fopen(dirname(__FILE__).'errorlog.txt', 'w');
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_STDERR, $fp);

  // Your Mailchimp account info //

    // Data Center
    $datacent = '{dataCenter}';

    // List ID
    $listid = '{listID}';

    // API key
    $mc_apikey = '{APIKey}';


  // Email cleamup and member ID (leid) //

    // Grab email address
    $email = "strip_tags($_POST['email'])";

      // Make email all lowercase
      $email = strtolower($email);

      // member ID, is email covert to md5
      $leid = md5($email);


    // first and last name variables //
      // $fname = strip_tags($_POST['fname']);
      // $lname = strip_tags($_POST['lname']);

      $json_data = "";

  // MailChimp API 3.0 URL for member status //

    //  /3.0/lists/{$listid}/members/{$leid}
    $mc_url = "https://" . $datacent . ".api.mailchimp.com/3.0/lists/" . $listid . "/members/" . $leid;




  // Get status from Mailchimp //


    // create a new cURL resource
    $ch = curl_init();

    // Let's track errors in a log //
        $fp = fopen(dirname(__FILE__).'errorlog.txt', 'w');
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_STDERR, $fp);

    // Gete connection going //
      curl_setopt($ch, CURLOPT_URL, $mc_url);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.$mc_apikey));
      curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 10);
      curl_setopt($ch, CURLOPT_HTTPGET, true);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

      // $json_data contains the output string
        // this method
        // curl_setopt($ch,CURLOPT_GET,count($fields));
       //  curl_setopt($ch, CURLOPT_GETFIELDS, $json_data);
          // OR
        // this method
        $json_data = curl_exec($ch);

      // Check for errors
      $info = curl_getinfo($ch);
      $errno = curl_errno($ch);
      if( $json_data === false || $errno != 0 ) {
          // Do error checking
      } else if($info['http_code'] != 200) {
          // Got a non-200 error code.
          // Do more error checking
      }

    // close cURL resource, and free up system resources
    curl_close($ch);

  // Get status from JSON //
    $user_status = var_dump(json_decode($json_data->status));

    echo $json_data;
    echo "<br><br><br>";
    echo 'User status is: '.$user_status;


?>

上面的内容命中了mailchimp服务器,它将所有用户数据转储到页面,但status的值为NULL。如何从成员(member)信息中提取状态?也尝试过$user_status = $json_data['status'];具有相同的结果。

最佳答案

您正在为 $user_status 变量分配字符串值 'status'。无论 json 数据是什么,它总是会回显 'status'

试试这个:

// Get status from JSON //
json_decode($json_data, true);
$user_status = $json_data['status'];

然后按照您想要在屏幕上显示的方式打印它:

echo "<br><br><br>";
echo 'User status is: '.$user_status;

关于javascript - 使用 Mailchimp API 3.0 获取并显示成员(member)状态(或错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32484386/

相关文章:

javascript - Chart js : I'm getting the labels crossed on my pieChart and doughnut. 无法获取图表本身

javascript - 按下 ctrl 并单击带有 javascript 事件的链接时,如何禁用 firefox "new tab"操作?

php - mysql查询更新重复条目

php - 如何获取 cURL 获取的最后一个 URL?

cURL命令Dload速度的单位?

javascript - 如何使用javascript删除Android webview中的内置边距

javascript - 如何用jquery填充选择框?

php - 如何在 Linux 服务器上使用 php 获取客户端的 MAC 地址

javascript - Laravel VueJS - 找不到元素 : #navigation

curl - 访问在 Vagrant 中运行的 Docker 容器