Darren Darren - 2 years ago 230
PHP Question

Mailchimp API returning strange response

I'm getting a strange issue using the Mailchimp API, I'm just trying to exchange my short lived code which I've got from them for an access token as per their OAuth documentation here.

However, I'm getting what appears to be some encoding issue with the response I'm getting back. This is what I have in PHP: (it can be reproduced even without substituting the correct client_id, client_secret etc.)

<?php

//### INITIALISE CURL #############################
$curl = curl_init();

//### SET CURL OPTIONS ############################
curl_setopt($curl, CURLOPT_URL,"https://login.mailchimp.com/oauth2/token" );

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, "grant_type=authorization_code&client_id=XXXXXXXXXXXX&client_secret=XXXXXXXXXXX&code=XXXXXXX&redirect_uri=https://mailchimp.test.com" );
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type: multipart/form-data"));

//### EXECUTE CURL ###############################
$result = curl_exec($curl);
if(curl_getinfo($curl, CURLINFO_HTTP_CODE) =='0') {
echo curl_error($curl);
}
curl_close($curl);

echo $result;

?>


I get this response ($result):

�M�� �0 F�UJ�N�NQ� %`��' "�Ћ���nb��f=�&9����i'f��]�~j*$��W��Reg��_T1-���;�oc

How can I fix this so that the response I get is correct as per the example response on Mailchimp's docs? (below)

Example Response:

{"access_token":"5c6ccc561059aa386da9d112215bae55","expires_in":0,"scope":null}

Answer Source

If you add the following to your code you will get the correct response:

curl_setopt($curl, CURLOPT_ENCODING, '');

For example

curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_ENCODING, '');

Found this here:

https://github.com/drewm/mailchimp-api/pull/69/files

See this article also which may clear up the matter

https://kb.mailchimp.com/campaigns/design/i-have-strange-characters-in-my-content

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download