Quick q. Mailchimp API 3.0 - mailchimp-api-v3.0

Can i use the first script or i need to use the curl option for mailchimp 3.0? I read some posts that the first one may be depreciated.. is that correct? Note that i'm not running on WordPress. Thank you for your fast answers.
<?php
require("vendor/autoload.php");
use \DrewM\MailChimp\MailChimp;
$mc = new MailChimp('apikey');
$email = $_POST['email'];
$subscriber_hash = $mc->subscriberHash($email);
$response = [];
$list_id = 'listid';
$resp = $mc->get("/lists/$list_id/members/$subscriber_hash";
if ($mc->success()) {
$response['message'] = 'Thank you for subscribing to the mailing list';
// User successfully subscribed - set HTTP status code to 200
http_response_code(200);
} else {
$response['message'] = $mc->getLastError();
// User not subscribed - set HTTP status code to 400
http_response_code(400);
}
// Return json-formatted response
echo json_encode($response);
?>
Or should i use this one?
function mc_checklist($email, $debug, $apikey, $listid, $server) {
$userid = md5($email);
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/lists/'.$listid.'/members/' . $userid);
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_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
if ($debug) {
var_dump($result);
}
$json = json_decode($result);
echo $json->{'status'};
}
This row is only for stackoverflow not alowing me to post that much code without including more details.

The first is not deprecated. It uses this wrapper to make API calls using the same API version that the second block of code uses. It's just simpler to work with so you don't have to write separate CURL requests for every call. You can also take a look at some of its source code and notice that it uses CURL anyway to make its calls.
So either way will use CURL, and whichever option you choose is simply a matter of preference.
Hopefully that clears it up for you!

Related

Mock Curl response for testing in laravel

I am trying to unit test a function(updateMeeting) in laravel which uses a curl request inside it. I tried many google links but nothing worked. can you guys give me suggestions on this matter.
following are relevant methods. $this->meeting is a MeetingModel
public function updateMeeting($meetingId){
$meeting = $this->meeting->find($meetingId);
$endpoint = \Config::get('api_backend_endpoint');
$response = $this->curlPut($endpoint);
if ($response->http_status_code != 200) {
if(Input::get('source') == 'ajax') {
$apiResponse = app(ApiResponse::class);
$message = 'ERROR Updating Meeting ' . $meeting->name;
return $apiResponse->failed($message);
}
return Redirect::route('meetings.show', $meetingId)
->withInput()
->with('message', 'An error occurred hiding meeting with message: ' . $response->errors);
}
$meeting->save();
}
following is curlPut method
private function curlPut($url, $payload = array())
{
$data_string = json_encode($payload);
$ch = curl_init();
//send through our payload as post fields
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$buffer = json_decode(curl_exec($ch));
curl_close($ch);
return $buffer;
}
Use a webservice like https://www.mocky.io/. Instead of requesting the real API, you send your requests to their API. You can create mock endpoints which return a response you can define.

Mailchimp API status 200 for members who are already subscribed

The following code is working and subscribing new members successfully. However, the status returns 200 even if the email address is already subscribed. I have checked that $member_id is hashing correctly, and despite identical values it still returns 200.
$result = array(
'status' => sync_mailchimp($data)
);
var_dump($result) // 200
function sync_mailchimp($data) {
// Setup our Mailchimp info
$api_key = 'xxxxx';
$list_id = 'ab8abde5bb';
$member_id = md5(strtolower($data['email'])); // lowercase hash of the email
$datacenter = 'us16';
$url = 'https://' . $datacenter . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . $member_id;
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status']
]);
// Send via curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
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);
return $httpcode;
}
I was also having the same issue while using a similar snippet.
Reading the MailChimp API 3.0 docs relating to managing subscribers (specifically the section Subscribe an Address), it was clear that this method was not the correct way to add a new subscriber.
The request type needs to be a POST
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
and must be sent to the endpoint
https://<data_center>.api.mailchimp.com/3.0/lists/<list_id>/members/
The request body containing the JSON is identical.
The response code will be 200 when an email address is added to the list successfully, and 400 when the email address already exists on the list.
Note that this method will not work for updating an existing subscriber – to do that, the request type must be PATCH, and you must use the original endpoint ending with the hashed email address.

Codeigniter hit an url and get back

I am using codeigniter 3.0 in my webapp. I want to hit an URL then get back to a view. Lets say on clicking a button, I want to hit an API then return back to the same view with success message. Can anyone help?
My API is http://wmlab.in/api/getData.php?username=web
I tried file('http://wmlab.in/api/getData.php?username=web') but it is not working.
use curl to do that and also install curl if your server did not have curl.
url="http://wmlab.in/api/getData.php?username=web";
function getUrlContent($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$data = curl_exec($ch);
echo $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode>=200 && $httpcode<300) ? $data : false;
}
$content=getUrlContent($url);
echo $content;
You can use file_get_contents('http://wmlab.in/api/getData.php?username=web') or can use curl;
For Curl use below code:-
$channel = curl_init();
curl_setopt( $channel, CURLOPT_URL, "http://wmlab.in/api/getData.php?username=web" );
curl_setopt( $channel, CURLOPT_RETURNTRANSFER, 1 );
$response= curl_exec ( $channel );
curl_close ( $channel );
// after curl response redirect to othe page
redirect('anypage');
For file get content use below code:-
$response=file_get_contents('http://wmlab.in/api/getData.php?username=web')
// after response redirect to othe page
redirect('anypage');
Hope it will help you.
it should be work
$result=file_get_contents('http://wmlab.in/api/getData.php?username=web');

How you should retrieve google plus +1 count for an url?

Using the rpc method:
$url = 'http://www.google.com';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
echo intval( $json[0]['result']['metadata']['globalCounts']['count'] );
or using the +1 button scrapping method?
$url = 'http://www.google.com';
$result = file_get_contents('https://plusone.google.com/_/+1/fastbutton?url='.urlencode($url));
preg_match( '/window\.__SSR = {c: ([\d]+)/', $result, $matches );
echo (isset($matches[0])) ? (int) str_replace('window.__SSR = {c:', '', $matches[0]) : 0;
Having an explanation of differences or possible side effects would be great.
Note: Both methods works as 2014/04/05.
Given that neither are official / supported by Google, I'd propably use the first method and fallback to the second in case that fails. The second method is more error-prone, since you're parsing source code that can change at any time (not that calling a service you're not supposed to be calling is any better, but apparently there are no other options).

Tweeting Automatically to twitter

I have used followint curl functionality to tweet automatically from my codeigniter page but I am getting an HTTP responce code 401 (not authorised).
the code is:
var $accounts_table = 'accounts';
var $update_url = 'http://twitter.com/statuses/update.xml';
function update_status($username, $password, $message)
{
$ch = curl_init($this->update_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username .':'.$password);
curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $httpcode;
// if we were successfull we need to update our last_message
if ($httpcode == '200')
{
$this->db->where('active', '1');
$this->db->update($this->accounts_table, array('last_message' => $message));
return TRUE;
}
else
{
return FALSE;
}
}
Please kindly help me to solve out this issue.
Thanks in advance.
AFAIK, twitter has moved onto OAuth.ie, no more basic authentication.
Read More about OAuth here.
OAuth supported libraries.

Resources