简体   繁体   中英

Using MailChimp API V2 without Github error

I have worked alot with MailChimp (the older versions) but then I lately had to update to the newer V2 due to some new functions. Now I can't get my code to work and no matter what & where I search, the only solutions I can find is with help from the GitHub repository https://github.com/mailchimp/mcapi2-php-examples which cannot work in this project.

My code:

<?php
include "../../system/function/db.php";

$espid = urlencode(make_safe($_GET['espid']));
$apikey = urlencode($_GET['apikey']);
$usX = explode("-", $apikey);
$listid = urldecode($_GET['listid']);
$data = array(
        'apikey'=> $apikey,
        'filters' => array( 'list_id' => $listid ),
    );
$payload = json_encode($data);
$submit_url = "http://" . $usX[1] . ".api.mailchimp.com/1.3/?method=campaigns";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode(json_encode(json_decode($result)), true);
$data = $data['data'];
foreach ($data as $id) {
    $ids .= $id['id'] . ",";
}
$campaigns = explode(",", $ids);


foreach ($campaigns as $campaign) {
    if (!empty($campaign)) {
        $data = array(
                'apikey'=> $apikey,
                'cid' => $campaign,
            );
        $payload = json_encode($data);

        $submit_url = "https://" . $usX[1] . ".api.mailchimp.com/2.0/reports/opened.json";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $submit_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
        $result = curl_exec($ch);
        curl_close ($ch);
        echo '<pre>'; var_dump($result); echo '</pre>';


    }
}

?> 

The error:

string(97) "{"status":"error","code":-100,"name":"ValidationError","error":"You must specify a apikey value"}"

I have tried replacing the variable with just a string of the API key, which didn't do anything different - I cant figure out if I might be sending the information "wrong" to the MailChimp server.

Can you guys help me from here? Hope your understand and thanks!

You don't need to urlencode your CURLOPT_POSTFIELDS data that's been JSON Encoded. Just use the raw $payload variable and it should work. (this is true of both of your calls in this example).

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