I'm trying to figure out if a user is following another user on Soundcloud using the Soundcloud API and php.
So far I came across a solution which would either return an object (user) or a 404 error:
$test = json_decode($client->get('/users/{id1}/followers/{id2}'));
I've tried it multiple times with different user IDs but I always receive a the following error message:
'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 404.'
I know that this is supposed to be the error message which informs me that user2 is not following user1. However I've tried this snippet with ids where I know a reciprocal following exists for sure.
Any suggestions on how this can be solved?
Update (21.05.15):
I've read through some of the Soundcloud documentation and cam across a code snippet:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('YOUR_ACCESS_TOKEN');
// Follow user with ID 3207
$client->put('/me/followings/3207');
// Unfollow the same user
$client->delete('/me/followings/3207');
// check the status of the relationship
try {
$client->get('/me/followings/3207');
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
if ($e->getHttpCode() == '404')
print "You are not following user 3207\n";
}
?>
This is pretty much what I was referring to. However if I open a php page with this script the result is always one of three cases:
You are not following user 3207 (expected output)
No output (I'm following the user)
Uncaught exception 'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 404.'
The third option is either referring to $client->put or $client->delete
Here is how i would do this:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud(
'xxxxxxxxxxxxxxxxxxx160', 'xxxxxxxxxxxxxxxxxx34dd1 ');
$userid = 1672444;
$followerid = 383228;
$yesno = '';
try {
$response = json_decode($client->get('users/'.$userid.'/followers'), true);
$yesno = IdInArray($response, $followerid);
echo $yesno;
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
function IdInArray($response, $followerid){
echo $followerid.'<br/>';
for($i = 0; $i < count($response); ++$i) {
if($response[$i]['id'] == $followerid){
return 'yolo';
}
else{
return 'nolo';
}
}
}
?>
Related
I am using an OAuth library to connect to Etsy shop API. Code looks like this:
foreach ($transactions as $transactionSingle) {
try {
$oauth = new OAuth('xxx', 'xxx',
OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_token_secret);
$data = $oauth->fetch("https://openapi.etsy.com/v2/users/".$transactionSingle['buyer_id']."/profile", null, OAUTH_HTTP_METHOD_GET);
$json = $oauth->getLastResponse();
$results = json_decode($json, true);
} catch (OAuthException $e) {
return null;
}
}
Now the problem is that I run this code multiple times on foreach and if this URL is wrong and it fails to get any data - the whole function stops and doesn't continue anymore. It works perfectly until an old user ID is passed to URL and $oauth->fetch just reuturns message :
Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a
redirect)
Any ideas how to continue to run the function despite any errors?
The problem was in error cathing itself. Needed backslash on
catch (\OAuthException $e) {
}
Now the code catches the errors and continues if no code is provided inside catch.
I have this simple code, where I'm trying to access a page with an ID. Whenever I run this code, I get an error "Unsupported get request. Please read the Graph API documentation"
$leheid = $page['accounts'][$x]['id'];
try {
$page = $fb->get("$leheid?fields=events", $at);
$page = $page->getGraphPage();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo $e->getMessage();
}
Okay, but whenever I run the same code without a variable and with a string, no errors...
If I echo or print the same variable I get the right string with no spaces or anything else in there, so I'm quite confused...
Also, I tried $leheid. '....'
It's an old question but i would like to contribute and maybe help someone else with the same problem.
The reason why the code above didn't work, was because i mistyped the API response function
In short:
$page = $page->getPage();
should have been replaced with
$page = $page->getGraphPage()->asArray();
Which will also give you the response as an array
I am attempting to retrieve the number of fans for my Page via the PHP SDK. Here is all of my code so far.
$fbSession = \Facebook\FacebookSession::newAppSession(self::APP_ID, self::APP_SECRET);
$fbLikesResponse = null;
try {
$fbLikesRequest = new \Facebook\FacebookRequest($fbSession, 'GET', '/{myRealPageIDGoesHere}/insights/page_fans');
$fbLikesResponse = $fbLikesRequest->execute()->getGraphObject()->asArray();
} catch (\Facebook\FacebookRequestException $ex) {
$resp = new \stdClass();
$resp->error = $ex;
return $resp;
} catch (\Exception $ex) {
echo $ex->getMessage();
}
//Add items to response and to store
var_dump($fbLikesResponse);
I never get authentication/authorizaiton errors, but the data response value is always just 0. I can see on the Facebook page itself that there are more than 0 likes.
I really don't want to have to resort to screen-scraping to obtain how many likes my Facebook page has. Any idea why I only get 0s?
Clarification- this is for a server-side call for an analytics engine. No user authentication is involved, so I'm trying to figure out how to get hit the {node}/insights/page_fans endpoint without faking some sort of user login.
I am trying to validate bitcoin engine respond once executing with correct amount within the account balance and correct wallet I am getting transaction ID, but if I enter amount too much and fake wallet I am not receiving any error in return just a blank page with html, head and body elements. Is there is any debug mode or what I can do to receive any response?
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
I am using jsonRPCClient to connect with bitcoin engine.
however when I do that in console using RPC commands
I am getting this : Account has insufficient funds (code -6)
code for redirection
if ($message !== '') {
ob_start();
header("Location: mywallet.php?error=done");
die();
} else {
ob_start();
header("Location: mywallet.php?error=true");
die();
}
Update Yes correct I will more ob_start(); above, thing is that once trying (try,catch) event I am getting blank page upon SUCCESS (so not transaction ID like with normal way I am doing I am getting back transaction ID) upon FAIL I am getting Unable to connect to Bitcoin Server. What I just need sounds very simple, how do I verified that transaction is SUCCESSFUL or FAIL, SUCCESSFUL -> I got ID in return, FAIL -> I have got Error in return. SO I can divert users to right places on the page after form is submitted. Actualy I am doing is withdraw funds form, where user inserts amount and his wallet to get funds back from bitcoin account to his private account. Hope this will helps to understand.
UPDATE 2 I have changed construction for that and seems to is working very well, basically is looking for "Unable" word as transaction ID doesn't have that word and other exception I am getting is "Unable to connect to server..." Thank you for guiding me. Any feedback ?
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$e->getMessage();
}
// exit;
if (!strpos($e,'Unable') !== false){
header("Location: mywallet.php?error=done");
die();
} else {
header("Location: mywallet.php?error=true");
die();
}
What bitcoin php library are you using? Looks like maybe this one?
If that's the case, it doesn't return an error message, it throws BitCoinClientException
So you need something like
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
echo $e->getMessage();
}
Updating
The ob_start seems superfluous because you don't output anything before the header location. Unless you have output something before you've reached this point in which case you can't send a header. So you'd need to move the ob_start up towards the top of the script before any output.
Also you aren't sending message to the wallet.php script. Or are you done with it at that point?
RE: update 2
One thing I might add is the possibility of some other exception message occuring we haven't thought of yet that doesn't contain the "Unable." I'd do something more like:
$errorOccured = false;
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$errrorMessage = $e->getMessage();
$errorOccured = true;
}
if (!$errorOccured) {
...
}
else {
header("Location: mywallet.php?error=true&errormsg=" . $errorMessage);
...
}
This would require modifying mywallet.php to accept $errorMessage as an additional GET parameter so you can send it back to the user. Might be nice to additionally use another parameter for sending $message on success which would contain the transaction ID.
I have all of the files (facebook.php, base_facebook.php, index.php) in the same directory. My server(s) are Apache, and both support php.
My code:
<html>
<body>
<?php
try
{
echo("STARTING<br>");
require("facebook.php");
}
catch(Exception $e)
{
echo("ERROR1: $e");
}
try
{
$facebook = new Facebook("***","###");
}
catch(Exception $e)
{
echo("ERROR2: $e");
}
$token = $facebook->getAccessToken();
echo("Access token: ".$token."<br>");
My text output is as follows:
STARTING
ERROR1: Object id #1before create fb instance
Fatal error: Class 'Facebook' not found in /(FILE PATH)/index.php on line 16
Note: line 16 is: $facebook = new Facebook("***","###");
The first catch statement is printing: Object Id #1. Then it does my next print statement. Then it returns Fatal Error that is not caught. What am I missing here?
Why can the server not get the correct access token?
You failed to require the facebook.php, hence the ERROR1: Object id #1 - you're trying to echo out the exception error object. Try
catch ($e) {
die($e->getMessage());
}
instead.
You should not catch that kind of error. if a require fails, the only useful solution is to abort execution, because you've not gotten what you REQUIRED to continue execution.
Basically you've implemented a PHPized version of visual basic's on error resume next, with all the nasty stupidity that goes with it.
You should put the code before the header is sent :
Go here for further information : https://developers.facebook.com/docs/reference/php/
Basically, put this on very on top of your code :
<?php
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
?>
Then load your HTML (In MVC style will be better for maintenance ;-)