Soundcloud resolve on PHP - php

I'm trying to setup a simple app that should:
get the client ID of an artist from its URL
display the two latest tracks
However I'm not that practical with soundcloud and i just know basic php. I started to play with soundcloud but i wasn't able to handle it. A problem i have is that any code i write, it gets
Fatal error: Uncaught exception 'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 302.'
The easiest setup come straight from the documentation and is an example to retrieve the comments from the track id, starting from a give URL.
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('my_client','my_secret');
// a permalink to a track
$track_url = 'https://url_to_a_track';
// resolve track URL into track resource
$track = json_decode($client->get('resolve', array('url' => $track_url), array('CURLOPT_FOLLOWLOCATION', TRUE )));
// now that we have the track id, we can get a list of comments, for example
foreach (json_decode($client->get('tracks/' . $track->id . 'comments')) as $c)
print 'Someone said: ' . $c->body . ' at ' . $c->timestamp . "\n"; ?>
Just added ('CURLOPT_FOLLOWLOCATION', TRUE) because I've read about it around the web... And I always get the fatal error... why?

'How can I use the soundcloud API resolve resource with PHP?'
to use the resolve resource of the soundcloud API with php, following frafor's code, do:
$client->setCurlOptions(array(CURLOPT_FOLLOWLOCATION => 1));
$response = json_decode($client->get('resolve',array('url' => $track_url)));
?>
So first CURLOPT_FOLLOWLOCATION and then the API call, your where almost there! :)
Hope it helps someone!
Cheers,
T

the soundcloud servers have switched to secure and they now use https protocol for API / JSON as well.
My apps were not working any more so these are the other cURL options to get the JSON.
SSL verification must both be set to disable. I got it working only with this.
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
);
Hope it helps.

I've been able to solve it. If the resources are public, then you don't need to authenticate. Here's the code that:
Get user URL from a wordpress custom-field
Retrieve ID from json object
Retrieve the latest 2 tracks and display 2 embedded players
It just need your own Client ID you can get easily by registering on soundcloud developers section, and then substitute it to {Your_ID}
// get user URL from Wordpress custom field
$sc_url = get_post_meta(get_the_id(), 'sc_url', true);
// if $sc_url is not empty, do
if (!empty($sc_url)) {
$unparsed_json = file_get_contents('https://api.soundcloud.com/resolve.json?url='.$sc_url.'&client_id={Your_ID}');
$json_object = json_decode($unparsed_json);
// retrieve the user ID from json_object
$roster_id = $json_object->{'id'};
// get last two tracks from the user and generate embed code for each tracks
$tracks_json = file_get_contents('http://api.soundcloud.com/users/'.$roster_id.'/tracks?client_id={Your_ID}&order=latest&limit=2&format=json');
$tracks = json_decode($tracks_json);
foreach ($tracks as $track){
$trackID = $track->id;
echo '<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F'.$trackID.'"></iframe>';
}}
Hope it can help others :)

Related

Pulling content from Instagram using just cUrl

I am trying to show Instagram content from a user (mines) on a website. My client-side page would make an AJAX request to my server-side script, which in turn, would do the necessary stuff to pull the content from Instagram API (using cUrl) and send back a JSON response.
Sadly, I am little bit confused with the Authentication instructions, particularly Step One: Direct your user to our authorization URL.
In order to get an access_token to work with the API, I need to pass client_id, redirect_uri, and code. I have the client_id and redirect_uri. The problem is the last item, code, which gets found after redirecting from https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code. The redirected page will be REDIRECT-URI?code=CODE which has the CODE to use to make the request to get the access_token.
Is there a way to "automate" this last part ? Or more precisely, is it possible to make a request (using cUrl) and then grabbing this CODE
Hopefully, this is clear. Unlike other APIs, Instagram seems to make things difficult. My goal is so that when users come on the page, they will see a gallery of images from my Instagram account. They shouldn't need to log into Instagram or do anything to see these images.
Edit
$clientId = 'XXX';
$clientSecret = 'YYY';
$redirectUri = 'ZZZ';
// step 1: authorize
$url = "https://instagram.com/oauth/authorize/?client_id={$clientId}&redirect_uri={$redirectUri}&response_type=code";
try {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url
));
$data = json_decode(curl_exec($ch), true);
// how to get CODE from response?
curl_close($ch);
} catch(Exception $e) {
echo $e->getMessage();
}

Bing Search API - where is the App ID

Trying to make a fast API query to the Bing Search API (via Azure Datamarket).
Can make it work with PHP and the AccountKey. This integration is quite slow though (about 1.2s query time compared to <0.5s on bing.com).
Tried to make it faster by querying through javascript. Followed these instructions (http://www.bing.com/developers/s/APIBasics.html).
Problem: Do not have an App ID. Do not understand the section "obtaining an app ID". I've an account on azure and everything, but stuck here. I have an account key, a customer ID, an app Name ... but none of these work.
Where can I find the AppID ?
Actually, it seems that APP ID is retired. We don’t suggest customer use this method currently.
Bing Search API has updated to 2.0 and moved to Windows Azure Marketplace.
To authenticate a Bing Search API request with Windows Azure Marketplace, you must obtain an account key. This mode of authentication replaces the AppID used in the Bing Search API 2.0. You can obtain your account key by using either at the Account Keys page.
Here is test code snippet in PHP:
$url = 'https://api.datamarket.azure.com/Bing/Search/';
$accountkey = '<your_account_key>';
$searchUrl = $url.'Image?$format=json&Query=';
$queryItem = 'Bing';
$context = stream_context_create(array(
'http' => array(
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountkey . ":" . $accountkey)
)
));
$request = $searchUrl . urlencode( '\'' . $queryItem . '\'');
echo($request);
$response = file_get_contents($request, 0, $context);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value){
echo('<li class="resultlistitem"><a href="' . $value->MediaURL . '">');
echo('<img src="' . $value->Thumbnail->MediaUrl. '"></li>');
}
echo("</ul>");
We can get more details at Migration Guide.
If you want to use APPID, you can see the “Getting An AppID” section of the guide, it has provided the link Bing Developer Center to create an appid.
Click the link, it leads us to a page with Bing servers list, as the figure shows:
Find the Search API and click the “sign in” sutitle, it leads to the page with your applications list, click button “request a new application id”, fill the form of your basic app information:
Submit and the browser will redirect to the page with app ids list:
read the article you liked:
Getting an AppID
The AppID parameter is a value that enables the API
to validate that a request is from a registered Bing application developer.
Getting an AppID is a straightforward process. First, go to the Bing
Developer Center and sign in with your Windows Live ID. After signing
in, you will be presented with a link to create a new AppID. Click the
link, then supply basic information about your application and review
the Terms of Use. (For more information, see Appendix: Terms of Use
Overview.) After you have supplied the information and reviewed the
Terms of Use, you will be presented with an AppID.

Having trouble with methods for Vimeo's new API

I'd like to use the method vimeo.videos.getInfo to get the info on a private video uploaded to my account. I'll only ever use this application on one website, so I'm hard coding the access token into the code.
I'm using the official PHP library for the Vimeo API (https://github.com/vimeo/vimeo.php).
So here's what I have so far...
$vimeo = new Vimeo($apiKey, $apiSecret, $accessToken);
All good. At first, when I tried the sample code from the example:
$user_data = $vimeo->request('/me');
print_r($user_data);
That returned an empty array:
Array (
[body] =>
[status] => 0
[headers] => Array
(
)
)
I noticed they mentioned if the array is returning empty, it probably had something to do with an invalid SSL certificate. Right now, I'm just developing on localhost, so I set CURLOPT_SSL_VERIFYPEER to false (thanks to these instructions: http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/). I added it to the array on line 112 in vimeo.php:
$curl_opt_defaults = array(
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false);
As soon as I did that, I was able to return the information about the authenticated user.
But this still is returning an empty array:
$params = array(
'video_id' => 95307197
);
$videos = $vimeo->request('vimeo.videos.getInfo', $params);
print_r($videos);
Same with any methods I try to put in there. Did I do the CURLOPT_SSL_VERIFYPEER thing wrong or is something else wrong with my syntax?
I thought that I might share my solution which took me some time to figure out. I also wanted to access private video data, namely the number pf time the video played. Here are my steps:
Create an app on Vimeo and get the Client Identifier, Client Secret, and generate an Access Token with the properties Public, Private, and Interact. You may need to add or remove properties based on your access need.
Download from Vimeo the PHP source code.
Strangely, at least in my case, the code had a wrong syntax on line 473 in the statement $name = array_slice(explode("/", $file_path), -1)[0]; to solve it remove the [0] at the end! In fact I didn't need to call this function to know if it did any harm, but this solved my problem. Am on Dreamweaver by the way.
More strangely, the PHP code provided my Vimeo can not do authentication with their new system so you need to add this code curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); before every $response = curl_exec($curl); statement. This should be 3 additions.
Finally, create your own PHP script to access the private video.
Here is my Code:
require("../Vimeo PHP path/autoload.php");
use Vimeo\Vimeo;
$client_id = "*****"; //your Vimeo number here
$client_secret = "*****"; //your Vimeo number here
$access_token = "*****"; //your Vimeo number here
$vim = new Vimeo($client_id, $client_secret, $access_token);
$response = $vim->request("/videos/****"); //your Vimeo PRIVATE video ID here
echo $response["body"]["stats"]["plays"];
In my case I did echo for the number of plays only, but you can print the whole body. Hope this helps someone too.
Thanks to this example I solved the same issue, in the current api at _request method(line 125) add the curl option CURLOPT_SSL_VERIFYPEER and set it to false so you will have an array like this:
$curl_opt_defaults=array(CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER=>false);
and that's all :) hope this helps someone else.
Hopefully this helps someone else. The Vimeo API documentation is all out of whack and the new API docs link back to the older API docs, which only adds to the confusion.
The new API doesn't use the methods from the Advanced API, it uses the endpoints here https://developer.vimeo.com/api/endpoints
Here is the code that eventually worked for me:
$videos = $vimeo->request("/videos/$video_id");
print_r($videos);

Posting a like via app on facebook only returns true and does nothing

I was trying to get the feeds of friends' fan pages with a cURL and to post a like via app.
The cURL GET works fine, but when it comes to liking the object (that has for sure likes enabled because it's facebook), all I get is a boolean (and no action).
I had seen on SO that you post a like with
($access_token, "https://graph.facebook.com/$post_id/likes", 'POST')
However, it is not working (it says either that the app has no permissions to do that, or that I need a valid url).
I have tried all possible solutions but nothing seems to work. The profile is mine, the access token too, and I gave publish_stream permissions to my own app.
After having given a try to the SDK PHP Likbrary, I tried a direct cURL post, with the following code:
function likeit($url){
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $url);
curl_exec($ch);
curl_close($ch);
}
The execution i a puzzle. When it does not return an OAuth Exception it returns boolean and stops there (there is no way for me to "like" the post I want to like). The last attempt (but I've tried them all, even the whole url in some tests) is
foreach ($feeds->data as $feed_data)
$message = $feed_data->message;
$title = $feed_data->name;
$link = $feed_data->link;
$id = $feed_data->id;
$myaccesstoken = "longlastingaccesstokenstring";
$post=likeit($myaccesstoken, "https://graph.facebook.com/$post_id/likes", 'POST');
Does anybody have a suggestion on how to do this? It seems trivial and yet there is no way for me to accomplish it. Thank you so much in advance!
I've found a solution, and thus am posting it here for future reference (hoping it is helpful for anybody with the same problem):
the only problem was that after the new permissions with facebook I needed to re-authorize my app.
After that, it is possible to post a like with the SDK facebook library, normally:
$facebook->api("/$id/likes", 'post', array(
'access_token' => $myaccesstoken));
No need to use cURL directly. Hope this helps someone with the same question.

Rendering SoundCloud widget for a private track using PHP API

I am trying to render a SoundCloud HTML5 widget using the PHP API, but every time I run the command I think should return the HTML for the widget, I simply get an Exception:
The requested URL responded with HTTP code 302
I realise this is a redirect. What I don't know is why that's all I ever get, or what to do about it to actually get the widget HTML.
The documentation on the API says that to embed the widget using PHP you should do this:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
// get a tracks oembed data
$track_url = 'http://soundcloud.com/forss/flickermood';
$embed_info = $client->get('/oembed', array('url' => $track_url));
// render the html for the player widget
print $embed_info['html'];
I'm running this:
// NB: Fully authorised SoundCloud API instance all working prior to this line
// $this->api refers to an authorised instance of Services_Soundcloud
try {
$widget = array_pop(
json_decode( $this->api->get('oembed', array('url' => $track_url)) )
);
print_r($widget);
} catch (Exception $e)
{
print_r($e->getMessage());
}
where "track_url" is actually the URL I get back when asking SoundCloud for a track object earlier in the app using the same API.
I'm not actually sure this URL is correct in the first place, because the track object I get back gives the 'uri' in the form:
[uri] => https://api.soundcloud.com/tracks/62556508
The documentation examples all have a straight http://soundcloud.com/username/track-permalink URL - but even using a known path to a public track the attempt to run the API oembed method fails... I still get a 302 Exception.
Finally, there are mentions of setting "allow_redirects" to false in the 'get' command, but this has no effect when I add to the parameters used to build the query to the API. I also tried adding additional cURL options, but that too had no effect.
I have definitely enabled API access to the track within SoundCloud.
Kind of banging my head off the wall on this. If anyone has any pointers I'd be very grateful to hear them. Just for clarity's sake, I am able to access all the user data, comments etc. via the API instance I have created, so it appears to be working fine.
Thanks for pointing this out. There was a bug in the documentation that lead you astray. Sorry about that. I've updated the docs to fix the bug. Here's the updated code sample:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setCurlOptions(array(CURLOPT_FOLLOWLOCATION => 1));
// get a tracks oembed data
$track_url = 'http://soundcloud.com/forss/flickermood';
$embed_info = json_decode($client->get('oembed', array('url' => $track_url)));
// render the html for the player widget
print $embed_info->html;
Note the differences:
You need to set CURLOPT_FOLLOWLOCATION to 1 as mentioned in the comments above.
You need to wrap the return from $client->get in json_decode
The result is an stdClass object, not an Array and so the html property has to be accessed using the -> operator.
Hope that helps. Feel free to comment in case you're still having problems and I'll amend my answer.

Categories