简体   繁体   中英

MailChimp group options select in php

I tried to find the answer for the last 5 hours but I finally caved in and am reaching out for help.

Basically, this code worked great until I needed to select a group option. I'm not sure if I'm creating my interests array properly, I may have to use 'merge_vars' but really would like some guidance before I spend another 5 hours blindly walking into walls.

Note for my group name I've been using the entire string "group[3117]"

Action.php

<?php
session_start();
if(isset($_POST['submit'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$interest = $_POST['group[3117]'];

if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
    // MailChimp API credentials
    $apiKey = '+ insert api key here +';
    $listID = 'insert list id';
    $interest = 'insert group name'; // YOUR INTEREST/GROUP ID

    // MailChimp API URL
    $memberID = md5(strtolower($email));
    $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
    $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;

    // member information
    $json = json_encode([
        'email_address' => $email,
        'status'        => 'subscribed',
        'merge_fields'  => [
            'FNAME'     => $fname,
            'LNAME'     => $lname
        ],
            'interests'        => array(
        $interest => true
        ),
    ]);

    // send a HTTP POST request with curl
    $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);

    // store the status message based on response code
    if ($httpCode == 200) {
        $_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
    } else {
        switch ($httpCode) {
            case 214:
                $msg = 'You are already subscribed.';
                break;
            default:
                $msg = 'Some problem occurred, please try again.';
                break;
        }
        $_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
    }
}else{
    $_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
}
}
// redirect to homepage
header('location:index.php');  

Index.php

<?php session_start(); // place it on the top of the script ?>
<?php
$statusMsg = !empty($_SESSION['msg'])?$_SESSION['msg']:'';
unset($_SESSION['msg']);
echo $statusMsg;
?>
<form method="post" action="action.php">
<p><label>First Name: </label><input type="text" name="fname" /></p>
<p><label>Last Name: </label><input type="text" name="lname" /></p>
<p><label>Email: </label><input type="text" name="email" /></p>
<p><select name="group[3117]" class="REQ_CSS" id="mce-group[3117]">
<option value=""></option>
<option value="1">Los Angeles</option>
<option value="2">Seattle</option>
<option value="4">Portland</option> </p>
<p><input type="submit" name="submit" value="SUBSCRIBE"/></p>
</form>

Here's the solution, there's a lot of manual data entry but it works, if someone has an easier method please let me know. Enter the MailChimp API playground. Select your list / subresources / interest-categories / interest name / subresources / interests / response . scroll down and there will be a unique "id" for interest. (ignore category id) Here is the code, credit goes Mukesh Chapegan and CodexWorld

Name this page Action.php

<?php
$email =  $_POST['email'];
$memberHash = md5($email);
$first_name = $_POST['fname'];
$last_name =  $_POST['lname'];
$interest = $_POST['location'];   
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // YOUR API KEY
$server = 'us14.'; //last part of ur api key
$list_id = 'XXXXXXX'; // YOUR LIST ID
$auth = base64_encode( 'user:'.$api_key );   
$data = array(
    'apikey'        => $api_key,
    'email_address' => $email,
    'status'        => 'subscribed',
    'merge_fields'  => array(
        'FNAME' => $first_name,
        'LNAME'    => $last_name
        ),
    'interests'        => array(
            $interest => true
            ),
    );
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'api.mailchimp.com/3.0/lists/'.$list_id.'/members/'.$memberHash);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
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_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
$result_obj = json_decode($result);
echo $result_obj->status;
echo '<br>';
echo '<pre>'; print_r($result_obj); echo '</pre>';
?>

Here is the HTML form. name this index.php Note I named the select element to location and the option values to the interest id I obtained through the API playground.

<?php session_start(); // place it on the top of the script ?>
<?php
    $statusMsg = !empty($_SESSION['msg'])?$_SESSION['msg']:'';
    unset($_SESSION['msg']);
    echo $statusMsg;
?>

<form method="post" action="action.php">
    <p><label>First Name: </label><input type="text" name="fname" /></p>
    <p><label>Last Name: </label><input type="text" name="lname" /></p>
    <p><label>Email: </label><input type="text" name="email" /></p>
 <p> <select name="location" class="REQ_CSS" id="mce-group[3117]">
<option value=""></option>
<option value="f3eb68268d">Los Angeles</option>
<option value="3204c60199">Seattle</option>
<option value="3c5b8d638a">Portland</option> </p>
</select>

    <p><input type="submit" name="submit" value="SUBSCRIBE"/></p>
</form>

If this answer helps please upvote so it's easier to find. I looked for this solution for a very very long time and found a lot of questions but few answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM