Updating tumblr api call to use the new version of their api - php

My site used to automatically submit all user generated artwork to a tumblr blog using the code below. Tumblr have now changed their api to v2. Any help on updating the block of code as below to work with the new version of the api would be greatly received. Thanks.
//submit to tumblr blog
// Authorization info
$tumblr_email = 'XXXXXXXXXX#drawaplanet.com';
$tumblr_password = 'XXXXXXXXXXX';
$post_type = 'photo';
$caption = $userCaption;
$post_title = '';
$post_body = '';
$source = 'http://www.drawaplanet.com/drawaplanet/gallery/' . $filename;
$click_through_url = 'http://www.drawaplanet.com/planet.php?s=' . $source;
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'caption' => $caption,
'title' => $post_title,
'body' => $post_body,
'source' => $source,
'click-through-url' => $click_through_url,
'generator' => 'DRAWAPLANET'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);

Related

How to avoid saturing frecuency capping at my instagram application?

I am using instagram api to search specific hashtag getting top media and recent media but graphic shows 4 different calls, so the the 200 limit per hour are consumed really fast. I know about ig_hashtag_search , top_media and recent_media but what i dont know what is shadowIGHastag.
Is there a way to avoid overconsumption of my app?
This is how i use the api
function insthashtag()
{
include "../insta/define.php";
function makeApiCall($endpoint, $type, $params)
{
$ch = curl_init();
if ('POST' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_POST, 1);
} elseif ('GET' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
$hashtag = 'sedapal';
$hashtagId = '17843308429009249';
$hashtagSearchEndpoint = ENDPOINT_BASE . 'ig_hashtag_search';
$hashtagSearchParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,name',
'q' => $hashtag,
'access_token' => $accessToken
);
$hashtagSearch = makeApiCall($hashtagSearchEndpoint, 'GET', $hashtagSearchParams);
/* To get hashtagID */
/* echo '<pre>';
print_r($hashtagSearch);
die(); */
$hashtagDataEndpoint = ENDPOINT_BASE . $hashtagId;
$hashtagDataParams = array(
'fields' => 'id,name',
'access_token' => $accessToken
);
$hashtagData = makeApiCall($hashtagDataEndpoint, 'GET', $hashtagDataParams);
$hashtagTopMediaEndpoint = ENDPOINT_BASE . $hashtagId . '/top_media';
$hashtagTopMediaParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagTopMedia = makeApiCall($hashtagTopMediaEndpoint, 'GET', $hashtagTopMediaParams);
$topPost = $hashtagTopMedia['data'][0];
$topPost1 = $hashtagTopMedia['data'][1];
$topPost2 = $hashtagTopMedia['data'][3];
/* To get recent data
$hashtagRecentEndpoint = ENDPOINT_BASE . $hashtagId . '/recent_media';
$hashtagRecentParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagRecent = makeApiCall($hashtagRecentEndpoint, 'GET', $hashtagRecentParams);
$recentPost = $hashtagRecent['data'][0];
$recentPost2 = $hashtagRecent['data'][1]; */
/* $recentPost3 = $hashtagRecent['data'][2]; */
$return = [$topPost['media_type'], $topPost['media_url'], $topPost1['media_type'], $topPost1['media_url'], $topPost2['media_type'], $topPost2['media_url']];
$jsondata = json_encode($return, JSON_PRETTY_PRINT);
return $jsondata;

How to return errors from MailChimp API v3.0 batch operation

I’m struggling with the new MailChimp API and the batch functionality, specifically, how to return any errors from the underlying operations that were batched, not the batch operation itself.
My code is below and works to add the two test subscribers. The response only shows success for the overall batch:
[errored_operations] => 0
If I run it again, it will return a similar response, but with two errors:
[errored_operations] => 2
Other than that, there is no indication as to what failed or why. In this case, we know that it’s because the users are already subscribed. If I try to add a single user without the batch call, using POST /lists/{list_id}/members, I get a response that details exactly what failed.
stdClass Object
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Member Exists
[status] => 400
[detail] => mary#jackson.net is already a list member. Use PUT to insert or update list members.
[instance] =>
)
How can I capture individual errors when adding (or updating or deleting) hundreds of subscribers?
I have tried just looping through users, making multiple individual calls, and that works: it adds the users and/or provides detailed error reporting. But it seems goofy to make 500 calls when the API is set up to handle this in a single call. Thanks for any ideas!
Here is my code:
$list_id = 'xyz123';
$subscribers = array(
array(
'email' => 'jeff#jackson.net',
'status' => 'subscribed',
'firstname' => 'Jeff',
'lastname' => 'Jackson'
),
array(
'email' => 'mary#jackson.net',
'status' => 'subscribed',
'firstname' => 'Mary',
'lastname' => 'Jackson'
)
);
$add_subs_batch = add_subs_batch($list_id, $subscribers);
echo '<pre>add_subs_batch: ';
print_r($add_subs_batch);
echo '</pre>';
function add_subs_batch($list_id, $data) {
$method = 'POST';
$batch_path = 'lists/' . $list_id . '/members';
$result = mc_request_batch($method, $batch_path, $data);
if($result && $result->id) {
$batch_id = $result->id;
$batch_status = get_batch_status($batch_id);
return $batch_status;
}
else {
return $result;
}
}
function get_batch_status($batch_id, $i=1) {
$method = 'GET';
$target = 'batches/'.$batch_id;
$result = mc_request($method, $target, $data);
sleep(1); // wait 1 second and try
if($result->status == 'finished' ) {
return $result;
}
else {
return get_batch_status($batch_id, $i+1);
}
}
function mc_request_batch( $method, $batch_path, $data = false ) {
$api_key = '12345-us1';
$dataCenter = substr($api_key,strpos($api_key,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/';
$target = 'batches';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $target );
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT' );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if( $data ) {
$batch_data = new stdClass();
$batch_data->operations = array();
foreach ($data as $item) {
$batch = new stdClass();
$batch->method = $method;
$batch->path = $batch_path;
$batch->body = json_encode( array(
'email_address' => $item['email'],
'status' => $item['status'],
'merge_fields' => array(
'FNAME' => $item['firstname'],
'LNAME' => $item['lastname']
)
) );
$batch_data->operations[] = $batch;
}
$batch_data = json_encode($batch_data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $batch_data );
$response = curl_exec( $ch );
}
curl_close( $ch );
return json_decode($response);
}
You will get an id in response of the batch operation. This is 'Batch ID' which is a string that uniquely identifies the batch request.
To get the status of a batch request, you have to call a GET request to the URL, /batches/{batch_id}.
From the response, you can find a URL in response_body_url field which has the gzipped archive of the results of all the operations in the batch call.
Reference:
http://developer.mailchimp.com/documentation/mailchimp/reference/batches
http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-batch-operations/
Note
For security reasons, response_body_url is only valid for 10 minutes.
After 10 minutes, generate another with a GET call to
/3.0/batches/{batch_id}.
After you make the batch operation request, results are available for
7 days.

create post wordpress.com using rest api

I want to make php app to create post on wordpress.com using REST api.
I use this code:
<?php
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'client_id' => 12345,
'redirect_uri' => 'http://example.com/wp/test.php',
'client_secret' => 'L8RvNFqyzvqh25P726jl0XxSLGBOlVWDaxxxxxcxxxxxxx',
'code' => $_GET['code'], // The code fromthe previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_token = $secret->access_token;
$post = array(
'title'=>'Hello World',
'content'=>'Hello. I am a test post. I was created by
the API',
'date'=>date('YmdHis'),
'categories'=>'API','tags=tests'
);
$post = http_build_query($post);
$apicall = "https://public-api.wordpress.com/rest/v1/sites/mysite.wordpress.com/posts/new";
$ch = curl_init($apicall);
curl_setopt($ch, CURLOPT_HTTPHEADER, array
('authorization: Bearer ' . $access_token,"Content-Type: application/x-www-form-urlencoded;
charset=utf-8"));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$return = curl_exec($ch);
echo "<pre>";
print_r($return);
exit;
?>
but I get this error:
{"error":"unauthorized","message":"User cannot publish posts"}
Can help me?
Thanks
Standard way to create posts is to use cookies and nonce.
However I found a more easy way to do it.
Install Basic-Auth plugin to your wordpress.
Create wordpress user with username admin and password admin (both credentials are insecure, used for demonstration purposes only)
Create post using code:
$username = 'admin';
$password = 'admin';
$rest_api_url = "http://my-wordpress-site.com/wp-json/wp/v2/posts";
$data_string = json_encode([
'title' => 'My title',
'content' => 'My content',
'status' => 'publish',
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rest_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Basic ' . base64_encode($username . ':' . $password),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
// ...
} else {
// ...
}
Note that in example above version 2 of REST API is used.
The answer is right that we can use the "Basic-Auth" plugin to make a Rest API request.
But, #vallez want to create a post on wordpress.com website.
And wordpress.com provide the oAuth support for authentication.
Recently I have created a post which demostrate about using the oAuth to create a post on wordpress.com. You can read the article at create the post on wordpress.com site using oAuth and Rest API
Below are the steps to successfully create a post with oAuth on wordpress.com.
Step 1: Add authentication details to get auth key.
$auth_args = array(
'username' => '',
'password' => '',
'client_id' => '',
'client_secret' => '',
'grant_type' => 'password', // Keep this as it is.
);
$access_key = get_access_key( $auth_args );
Below is the function get_access_key() which return the access key.
Step 2: Get Access Key.
/**
* Get Access Key.
*
* #param array $args Auth arguments.
* #return mixed Auth response.
*/
function get_access_key( $args ) {
// Access Token.
$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $args );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$auth = json_decode($auth);
// Access Key.
return $auth->access_token;
}
Step 3: Set post arguments and pass it create the post.
$post_args = array(
'title' => 'Test Post with oAuth',
'content' => 'Test post content goes here..',
'tags' => 'tests',
'post_status' => 'draft',
'categories' => 'API',
);
Step 4: Create a post with the access key.
Now, We have access key and the create post arguments. So, Lets pass them to function create_post().
create_post( $access_key, $post_args );
Step 5: Create a post with access key.
/**
* Create post with access key.
*
* #param string $access_key Access key.
* #param array $post_args Post arguments.
* #return mixed Post response.
*/
function create_post( $access_key, $post_args )
{
$options = array (
'http' => array(
'ignore_errors' => true,
'method' => 'POST',
'header' => array(
0 => 'authorization: Bearer ' . $access_key,
1 => 'Content-Type: application/x-www-form-urlencoded',
),
'content' => http_build_query( $post_args ),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/',
false,
$context
);
return json_decode( $response );
}

php publish video to facebook wall

I'm trying to create an app that will upload & publish a video to user's wall.
following the api docs there are no examples of publishing
https://developers.facebook.com/…/reference/v2.2/user/videos
I've looked up for similar questions in here but they're all old referring to fb api.
the API returns a message that I should use curl, when I'm using curl
it returns false.
is there any php example of publishing video?
example of my code:
$url = 'https://graph-video.facebook.com/me/videos';
$cfile = new CURLFile('test.mp4','video/mp4','video');
$post_params = array(
'title' => "myTitle",
'name' => "blahblah",
'source' => $cfile,
'access_token' => $token
);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
//execute post
$result = curl_exec($ch);
Thanks!
I found the answer for that using FB API & CURLFile, hope it would help someone else
$url = 'https://graph-video.facebook.com/me/videos';
$cfile = new CURLFile(realpath('test.flv'),'video/x-flv');
$movie_data = array('file' => $cfile);
$post_params = array(
'title' => "ffff",
'name' => "tablished businesses”",
'source' => $cfile,
'access_token' => $token
);
$request = new FacebookRequest(
$session,
'POST',
'/me/videos',
$post_params
);
$response = $request->execute();
the $response contains the id of the video.
enjoy

mailchimp api 2.0 subscribe through php?

I need an example of how to subscribe a email address to mailchimp newsletter.
Please check new api link here:
https://bitbucket.org/mailchimp/mailchimp-api-php
This is new malichimp api and I am not sure how to use it. :(
For MailChimp 2.0 API, not for 1.3.
Please somebody provide an example on how to subscribe user to mailchimp.
Thank You.
Edit1: Already tried following code, but not working:
$merge_vars = array('MM1'=>$mm1);
$MailChimp = new Mailchimp($apikey);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $listid,
'email' => array('email'=>$email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => false,
));
print_r($result);
But not working. Throwing following error:
Fatal error: Call to a member function call() on a non-object in subscribe.php on line 22
Referring to the documentation, this should be like so:
$merge_vars = array('MM1'=>$mm1);
$listid = 'YOURLISTID';
$MailChimp = new Mailchimp($apikey);
$result = $MailChimp->lists->subscribe($listid,
array('email'=>"contact#twittstrap.com"),
$merge_vars,
false,
true,
false,
false
);
print_r($result);
Tested and working.
this might be helpful for some, simple mailchimp subscriber API code sample with php
mailchimp subscriber API code example in PHP
Here is with Try & Catch (example for when dup emails)
header('Content-Type: application/json');
include_once 'Mailchimp.php';
$api_key = '';
$list_id = '';
$email = 'hello#email.com';
$merge_vars = array();
$Mailchimp = new Mailchimp($api_key);
$Mailchimp_Lists = new Mailchimp_Lists($Mailchimp);
try{
$subscriber = $Mailchimp_Lists->subscribe(
$list_id,
array('email'=>htmlentities($email)),
$merge_vars,
false,
false,
false,
false
);
echo json_encode(array('status' => !empty($subscriber['leid'])?'submitted':'error'));
} catch(Mailchimp_Error $e){
echo json_encode(array(
'status' => 'error',
'message' => $e->getMessage()
));
}
Readmore about subscribe() : https://apidocs.mailchimp.com/api/2.0/lists/subscribe.php
Subscribe through php using curl.
$apikey = 'xxxxxxxxxx'; //your apikey
$listId = 'xxxxxxxxxx'; // your list id
$endpoint = "http://yourdatacenter.api.mailchimp.com/3.0/lists/"; // find your datacenter in your apikey( xxxxxxxxxxxxxxxxxxxxxxxx-us13 <= this is your datacenter)
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => 'yourvalid_email_address',
'status' => 'subscribed',
'merge_fields' => array());
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint.$listId.'/members/');
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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
echo "<pre>"; // Response form mailchimp
print_r(json_decode($result,true));
Here is example may it helpful for some one.
mailchimp subscriber api example

Categories