Using wp_remote_post() to add subscriber in MailChimp - php

I am trying to submit a new subscriber via a form on a WordPress website. I am concentrating on sending the subscriber information to a list in MailChimp. I am getting the following error:
string(75) "cURL error 6: Could not resolve host: us19.api.mailchimp.com; Unknown error"
My question is whether there is an issue with the arguments being passed to the wp_remote_post() function?
This is my code:
<?php
$api_key = '[HIDDEN]';
$list_id = '[HIDDEN]';
$email = "[HIDDEN]";
$firstname = "[HIDDEN]";
$lastname = "[HIDDEN]";
$status = 'subscribed'; // subscribed, cleaned, pending
$args = array(
'method' => 'PUT',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'email_address' => $email,
'status' => $status
))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email)), $args );
var_dump($response);
?>

Related

PHP post request with file_get_content

Please someone to help me
I'm trying to POST a request with file_get_contents and I receive a 415 code error message. I'm not a pro dev and I want to know what is wrong in my source code. Here is my problem:
I generate a token which is a parameter of the second request
the generated token must be used for the POST request
I receive a 415 Error code message. I don't know how to correct that source
$tok=file_get_contents('https://restapi.bulksmsonline.com/rest/api/v1/sms/gettoken/username/xxxx/password/xxxx');
$toke =json_decode($tok, true);
$token=$toke['token'];
$data = json_encode(
array(
'from' => 'TEST',
'to' => '335546821546',
'type'=> 'Text',
'content'=> 'Test',
'sendDateTime'=> '2020/07/07'
)
);
$options = array('http' =>
array(
'method' => 'POST',
'header' => "Authorization Token " . base64_encode("$token"),
'content' => $data
)
);
$context = stream_context_create($options);
$url = 'https://restapi.bulksmsonline.com/rest/api/v1/sms/send';
$result = file_get_contents($url,false,$context);
If you are getting token and facing issue in post call only then i have noticed that you have missed a few Request Headers:
like Content-type, Content-length, I have check with the different URLs, It is working for me try it
<?php
$tok=file_get_contents('https://restapi.bulksmsonline.com/rest/api/v1/sms/gettoken/username/xxxx/password/xxxx');
$toke =json_decode($tok, true);
$token=$toke['token'];
$data = json_encode(
array(
'from' => 'TEST',
'to' => '335546821546',
'type'=> 'Text',
'content'=> 'Test',
'sendDateTime'=> '2020/07/07'
)
);
$options = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n" .
"Content-length: " . strlen($data) . "\r\n" .
"Authorization Token: " . base64_encode("$token") . "\r\n",
'content' => $data
)
);
$context = stream_context_create($options);
$url = 'https://restapi.bulksmsonline.com/rest/api/v1/sms/send';
$result = file_get_contents($url,false,$context);
var_dump($result);

using MailChimp API without cURL

I'm trying to use the MailChimp API to add subscribers to a list once they've checked a box on a form. I can do this with cURL, and it works fine, but the server that this will be on does not have it enabled. I'm trying to use file_get_contents(), but that gives me a 401 error. I've checked the API key and the list id, and they're both correct. I'm guessing that my syntax is messed up or that I've put something in the wrong place, but I'm not seeing the problem. What I've tried is below. Anyone have any ideas?
if (isset($_POST['mailtest']) == 'value1'){
$email = $_POST['email'];
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$mailchimp_api_key = 'apikey';
$mailchimp_list_id = 'listid';
$data = array(
'apikey' => $mailchimp_api_key,
'id' => $mailchimp_list_id,
'email' => $email
'status'=>'subscribed'
);
$memberId = md5(strtolower($email));
$dataCenter = substr($mailchimp_api_key ,strpos($mailchimp_api_key, '-')+1);
$endpoint = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $mailchimp_list_id . '/members/' . $memberId;
if ($fname && $lname) $data['merge_vars '] = array('FNAME' => $fname, 'LNAME' => $lname);
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/json",
"Connection: close\r\n" .
"Content-length: " . strlen($json_data) . "\r\n",
'data' => $json_data,
),);
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);
}
You need to set the Basic authentication header. As well it seems you're including your dataCentre in with your api key, so the below code might need some tweaking since I don't actually know what $mailchimp_api_key is set to.
// this is improper usage of isset. isset returns a boolean
// since you're not doing a strict match it'll always work,
// unless mailtest is null or isn't set.
if (isset($_POST['mailtest']) == 'value1') {
$email = $_POST['email'];
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$mailchimp_api_key = 'apikey';
$mailchimp_list_id = 'listid';
$data = array(
'apikey' => $mailchimp_api_key,
'id' => $mailchimp_list_id,
'email' => $email
'status'=>'subscribed'
);
$memberId = md5(strtolower($email));
$dataCenter = substr($mailchimp_api_key ,strpos($mailchimp_api_key, '-')+1);
$endpoint = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $mailchimp_list_id . '/members/' . $memberId;
if ($fname && $lname) {
$data['merge_vars '] = array('FNAME' => $fname, 'LNAME' => $lname);
}
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => implode(
"\r\n",
[
"Content-type: application/json",
"Content-length: " . strlen($json_data),
"Authorization: Basic " . base64_encode("anystring:$mailchimp_api_key") // see note above
]
),
'content' => $json_data,
)
);
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);
}

Subscribe users to a list using MailChimp API v3 and CURL

I am wondering if anyone has worked with MailChimp API to subscribe users to the list.
I am wondering how it is done, from the documentation I am trying to accomplish.
curl --request POST \
--url 'https://usX.api.mailchimp.com/3.0/lists' \
--user 'anystring:apikey' \
--header 'content-type: application/json' \
--data '{"name":"Freddie'\''s Favorite Hats","contact":{"company":"MailChimp","address1":"675 Ponce De Leon Ave NE","address2":"Suite 5000","city":"Atlanta","state":"GA","zip":"30308","country":"US","phone":""},"permission_reminder":"You'\''re receiving this email because you signed up for updates about Freddie'\''s newest hats.","campaign_defaults":{"from_name":"Freddie","from_email":"freddie#freddiehats.com","subject":"","language":"en"},"email_type_option":true}' \
--include
My attempt was this:
$apiKey ='mykey';
$listID = 'id';
$email = 'my#email.com';
$data = array(
'email_address' => $email,
'status' => 'subscribed'
);
$body = json_encode($data);
$opts = array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'apikey ' . $apiKey
),
'body' => $body
);
$apiKeyParts = explode('-', $apiKey);
$shard = $apiKeyParts[1];
$url = '//' . $shard . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/';
$response = wp_remote_post( $url, $opts );
if ( is_wp_error( $response ) ) {
$result = $response->get_error_message();
} else {
// DEBUG
$result = print_r($response, true);
}
return $result;
However it never worked, I also found another post stating ("i got this to work") but for me it was returning false.

How can I utilize BLS.GOV API to extract data from their graphs to my website?

I'm very new to programming and using API. I am currently working on a project to take data from BLS.GOV using their API to port the data to my website! so far, BLS has given me this code:
$url = 'http://api.bls.gov/publicAPI/v2/timeseries/data/';
$method = 'POST';
$query = array(
'seriesid' => array('LEU0254555900', 'APU0000701111'),
'startyear' => '2002',
'endyear' => '2012'
);
$pd = json_encode($query);
$contentType = 'Content-Type: application/json';
$contentLength = 'Content-Length: ' . strlen($pd);
$result = file_get_contents(
$url, null, stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => $contentType . "\r\n" . $contentLength . "\r\n",
'content' => $pd
),
)
)
);
var_dump($http_response_header);
var_dump($result);
How would I be able to grab graph data with PHP from this link.

Post login with file_get_contents - not curl

One site requires login for three variables: username, password and token. This data is sent via POST.
token is also sent through a section.
I have all three variables, and I want to log in via file_get_contents.
How can that data be sent and the authentication is successful?
function file_post_contents()
{
$url = 'http://site.com/auth.php?' . session_name() . '=' . session_id();
$login = 'jhon';
$senha = 'doe';
$token = '123456';
$_SESSION["token"] = $token;
$postdata = http_build_query(
array(
'login' => $login,
'senha' => $senha,
'token' => $token,
$_SESSION["token"] => $token
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
if($login && $senha)
{
$opts['http']['header'] = ("Authorization: Basic " . base64_encode("$login:$senha"));
}
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);
}
Modified code. It does not work.
function file_post_contents()
{
$url = 'http://site.com/auth.php?' . session_name() . '=' . session_id();
$login = 'jhon';
$senha = 'doe';
$token = '123456';
$_SESSION["token"] = $token;
$postdata = http_build_query(
array(
'login' => $login,
'senha' => $senha,
'token' => $token
//, $_SESSION["token"] => $token
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded'
. "\r\n" . "Authorization: Basic " . base64_encode("$login:$senha"). "\r\n",
'content' => $postdata
)
);
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);
}
Your headers might be set wrong, try adding \r\n like so
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $postdata
)
);
and later down the code
$opts['http']['header'] = $opts['http']['header'] . "Authorization: Basic " . base64_encode("$login:$senha") . "\r\n";
You're overriding $opts['http']['header'] with the Basic auth. You're not adding it to the Content-type, you're replacing Content-type with it.

Categories