How to use the Mastodon API to post a status update with an image - api

Using the Mastodon API, I'm trying to post a status update to Mastodon which includes an image. This is not working for me.
It is my understanding that, to post a status update that includes an image, I first have to post the image to Mastodon. This works for me, with a version of the code that is an answer to this question.
I then take the id of the media that has been successfully submitted, and try to post a status update, referencing that id as an included piece of media. This results in the status update being posted, but the media not being included.
The relevant part of my PHP curl statement is this:
$body = [
'status' => $desc,
'media_ids' => array($media_id)
];
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body));
The above posts a status update with $desc as the content, but without an inclusion of an image. The $media_id is an actual id, extracted from the json response after posting an image to https://mastodon.social/api/v1/media. The id looks like this: 1097111113111806655.
I'm guessing I'm not defining the body correctly. But, having tried a number of variations, I'm at a loss as to what it's supposed to be.
Any ideas?

Turns out, the trick is to post the body as JSON.
$headers = [
'Authorization: Bearer [TOKEN]',
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://[INSTANCE]/api/v1/statuses");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$status_data = array(
"status" => $desc,
"language" => "eng",
"visibility" => "public"
);
$status_data['media_ids'] = array($media_id);
$post_data = json_encode($status_data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
But... it seems there's more to it: When using the image ID immediately after a successful upload, the status update, with the image ID, doesn't always show the image ID. I'm surmising there's processing time, after uploading, during which including the image in a status update results in no image actually being included.
At first, after uploading an image, I waited a few seconds before also posting the status update. Then I upped that to 20 seconds, but even then the image wouldn't always be included in the status update. Now, I post the status update a full 30 minutes after uploading the image. This works.

Related

Using OAuth to access 3dCart api

Trying to authorize an 'app' in 3dcart
The api is fairly well documented using Swagger and they have this page w/ instructions https://apirest.3dcart.com/v1/getting-started/index.html#getting-started
You are supposed to make this first call, which is supposed to give you token you use in the subsequent step
https://apirest.3dcart.com/oauth/authorize?
Client_Id=22613fdfc5a6200bece02a29524XXXXX
&state=12345
&response_type=code
&store_url=www.***********.com
&redirect_uri=www.!!!!!!!!!!.com <============== WHAT SHOULD THIS BE
Using postman, I can play with the various parameters.
I beleive clientId should be the guid-ish string you get associated w/ each store that has subscribed to your app.
Store Url - i know this. Should I include the https:// protocol in the string?
It sounds like STATE is just something you pass in and the store parrots it back to you.
redirect_uri - not sure what this is/ should be
I can get status 200 OK, but i am getting an HTML page .
Pasting same URL in a browser, I am getting a login page. I login as an admin user and then get 404 because it is redirecting me to the redirect_uri
??? I really just want to login. I tried passing in a blank uri and omitting the parameter. Both yield
Status 400 Error 101 redirect_uri is required
Am I doing this correctly? Is there an example of authorizing so you can use the API?
I have downloaded the GIT repository. That helps a bit, but still missing something
tyia
Using the URL you're talking about will allow the customer to grant access to your application. The Redirect URI in the URL you have the customer click on MUST match the Redirect URI you have set up on your app in 3dcart Developer.
After that, there are 5 steps to getting the Authorization Token and then use it to work with the 3dcart API.
The redirect URI is your endpoint where 3dcart will send the code.
Step one:
Set up your Redirect URIs: under the Oauth tab on your application on 3dcart Developers
Step 2:
3dcart will post to this URL a "Code". You can get this from the URL with GET
$code = $_GET['code'];
Step 3:
Use Curl (or whatever) to make a postback to 3dcart with the code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://apirest.3dcart.com/oauth/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$data = array('Code' => $code, 'client_id' => '{your public app key}', 'client_secret' => '{your private app key}', 'grant_type' => 'authorization_code');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'application/x-www-form-urlencoded'
));
$response = curl_exec($ch);
Step 4:
parse the response to get the access_token:
$info = json_decode($response, true);
$access_token = $info['access_token'];
Step 5:
Use the Access token to make calls to 3dcart using the following parameters in curl
$auth = array(
"Content-Type: application/xml",
"Accept: application/json",
"Authorization: Bearer $access_token",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://apirest.3dcart.com/3dCartWebAPI/v2/{API END POINT}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $auth);
$response = curl_exec($ch);
curl_close($ch);

Twitch New API : URL (Helix)

Recently, Twitch bring a new API version using new endpoints etc..
I was working on the V5, but I didn't use Curl command line, I work with URL.
So I decide to look at the references of the new version, trying for example to getting the followers and found this :
https://api.twitch.tv/helix/users/follows?to_id='user ID'
So I replace the user_ID by an id (mine and/or another) and get :
{
"error":"Unauthorized",
"status":401,"message":"Must provide a valid Client-ID or OAuth token"
}
When I was working on the V5, I was putting the client_id and the oauth at the end of the URL like this :
https://api.twitch.tv/kraken/channels/CHANNELNAME?client_id=xXxXxXxXxX&oauth_token=aaaabbbbccc111
And it was working, but in the new API, I already have a parameter so I added the client_id and token after with a & connector... But still have the same error.
I also try to put them before the to_id parameter, but same...
So my question is really stupid but anyone know the URL format on the new API?
You should send your Client-ID in request's header now, not as a param in URL. But there's other problem with SSL/HTTPS in this case if you use curl.
Here is a solution to your problem
DEFINE (TWITCH_API_KEY,'YOUR_KEY_HERE');
$url = 'https://api.twitch.tv/helix/streams/metadata';
$ch = curl_init();
$headers=['Client-ID: '.TWITCH_API_KEY];
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;

google shortner api is not giving new urls

I have set up for google api shortner on my website and i have it to get new shortned urls when ever someone places there url on my site. This is the code i have:
if($REQUEST_METHOD=="POST"){
if(isset($add)){
$longUrl = $url;
$apiKey = 'My api key';
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);
in "my api key" i do have a api key and i do place it there and i do have shortner api enable in google. To echo the shortened url i use:
<?print $json->id;?>
which works fine. My problem is that if someone places the same url twice, it will give them the same shortned url and not a new unique one. Would any of you know what could be causing this problem? Is there something wrong in my coding?
Any help is much appreciated. Thank you
This is interesting situation I just ran into. If you authenticate using your api key, then indeed you get the same shortened url or id for every long url you pass in. That's actually what I want for my use case!
But if you authenticate using OAUTH then you get a new unique id for every long url you pass in, even when they are the same.
You can see this behavior in the api explorer when you toggle on and off OAUTH authentication:
https://developers.google.com/url-shortener/v1/url/insert
I don't see this documented anywhere, so its' hard to know whether this is a feature or a bug, or what we can expect in the future.

Generate Access Token in Bigcommerce

I have an issue when trying to generate Access Token by POST data to https://login.bigcommerce.com/oauth2/token. There is an exception error ('The remote server returned an error: (400) Bad Request.'). I don't know why but I already read the document at https://developer.bigcommerce.com/apps/callback#token
If I open that URL on any web browsers. It said that "The page you were looking for doesn't exist."
Could you please help me this?
Thank you,
Trung
If you are getting a 400 response to your POST request to https://login.bigcommerce.com/oauth2/token then that is indicating a problem with your data. The most likely causes are:
You are not including the following header in your POST request:
Content-Type: application/x-www-form-urlencoded
You are not URL encoding your POST data such as the following example:
client_id=236754&client_secret=m1ng83993rsq3yxg&code=qr6h3thvbvag2ffq&scope=store_v2_orders&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapp.example.com%2Foauth%26context%3Dstores%2Fg5cd38&context=stores%2Fabc123
Also note that the error response message body that you receive should have some more details about the source of the problem.
If you have confirmed the above points then maybe try giving a sample of your POST data or some information about what you are doing to URL encode your data. Make sure not to include your actual client ID, client secret, or redirect URI.
Try ussing cURL
$data = array( "client_id" => "sdfgdfgdfkxddfgdfgdfdfgdfgddfgdfg2",
"client_secret" => "sdfgsdfgsdfgsdfgsdfgdf",
"redirect_uri" => "https://youapp.com/oauth",
"grant_type" => "authorization_code",
"code" => $_GET["code"], "scope" => $_REQUEST["scope"], "context" => $_GET["context"], );
$postfields = http_build_query($data);
$ch = curl_init();
$url = "https://login.bigcommerce.com/oauth2/token";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);
$obj = json_decode($output);
var_dump($obj);
Firstly you need to get temporary authorization code, but sending GET request to https://login.bigcommerce.com/oauth2/authorize with parameters clientId, Scope, Context ("stores/{your_store_hash}") and redirect_url.
Only after this, you can change your temporary token to permanent token (see previous post).
This permanent token expires in 30-60 days, but I don't know how to renew it automatically without user action. If you know that, please write how.

Authentication Errors Trying to Access to the Google Analytics API via http (not using oAuth)

I'm trying to build a simple script to import page view counts for articles published via my CMS. I easily constructed my query using the Google Analytics API query builder which quickly returns the desired result. A scheduled job on my web server will run the query once per day and update and page view counts.
Because I'm only pulling in pageviews, I believe it wasn't necessary to go through the entire oAuth process. This Google account has only one web property and only one profile, so there isn't a routine needed to derive that.
I registered an app and created an API key. I have ensured that Google Analytics is turned on for this profile. Based on my reading of the API, I believe I can pass this key as an http parameter to properly authorize the query.
When I run the query via http, I get an authorization error (401). The query is included below:
https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A[MY ID]&metrics=ga%3Apageviews&start-date=2012-08-09&end-date=2012-08-23&max-results=50&key=[MY API KEY]
I've Googled many examples of this, but they all seemed to implementing a very elaborate (and in my use case unnecessary) authentication routine. But maybe I'm missing something.
Many thanks in advance.
Kris, frustrated Googler
Use this example to fix 401 error http://dumitruglavan.com/ganalytics-class-access-google-analytics-data-api-with-php/
You need to authorize:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'accountType' => 'GOOGLE',
'Email' => $email,
'Passwd' => $password,
'service' => 'analytics',
'source' => ''
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$auth = '';
if($info['http_code'] == 200) {
preg_match('/Auth=(.*)/', $output, $matches);
if(isset($matches[1])) {
$auth = $matches[1];
} else {
throw new Exception('Login failed with message: ' . $output);
}
}
And after authorize send authorization token in headers:
$headers = array("Authorization: GoogleLogin auth=$auth");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);