I want to put the latest video from my channel on my website. This returns the following error:
Warning: file_get_contents(https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCD---------&maxResults=1&key=A---------------): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in C:\xampp\htdocs\inc\latestVideo.php on line 15
My code:
<?php
$API_key = 'A---------------';
$channelID = 'UCD---------';
$maxResults = 1;
$videoList = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.''));
if(isset($item->id->videoId)){
echo '<div class="youtube-video">
<iframe width="280" height="150" src="https://www.youtube.com/embed/'.$item->id->videoId.'" frameborder="0" allowfullscreen></iframe>
<h2>'. $item->snippet->title .'</h2>
</div>';
}
?>
You should actually be doing a curl
curl \
'https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC_x5XG1OV2P6uZZ5FSM9Ttw&maxResults=1&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
Notice how an Authorization bearer token is required on the header in addition to the API key. Also channelId needs to be id.
To understand how to do a curl call from PHP check this out ->
php curl: I need a simple post request and retrival of page example
Reference of the api is here -> https://developers.google.com/youtube/v3/code_samples/code_snippets?apix_params=%7B%22part%22%3A%22snippet%2CcontentDetails%2Cstatistics%22%2C%22id%22%3A%22UC_x5XG1OV2P6uZZ5FSM9Ttw%22%7D&apix=true
You can even try in the interactive editor.
Related
It is my first time trying to connect Sheet from Smartsheet using API with PHP.
I cannot seem to connect and give me this error
Notice: Trying to get property of non-object in C:\xampp\htdocs\smartsheet\test.php on line 22
The variable $sheetObj is empty.
And in Authorization: Bearer, what does Bearer means? Is it a token name or it is always Bearer?
My future plan is to write into the row of smartsheet using PHP. Can anyone give me advice what went wrong with my code?
$baseURL = "https://api.smartsheet.com/1.1";
$sheetsURL = $baseURL . "/sheets/";
$getSheetURL = $baseURL . "/sheet/xxxxxxxxxxx";
$rowsURL = $baseURL . "/sheet/xxxxxxxxxxx/rows";
$accessToken = "xxxxxxxxxxxxxxxxxx";
// Create Headers array for cURL
$headers = array(
"Authorization: Bearer " . $accessToken,
"Content-Type: application/json"
);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
Both stmcallister and Kim provided good information on how to troubleshoot your issue and some likely causes.
There were actually two issues with the code you provided.
As Scott mentioned you must point to the 2.0 version of the API.
$baseURL = "https://api.smartsheet.com/2.0";
You have a typo in your $getSheetURL. As is documented here the url is /sheets/{sheetId}. So your code should have the following:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
Here is your code in a working state. Make sure to replace YOUR_TOKEN and also take a look at the output from var_dump (which I added to your code) to see what message it gives you.
<?php
$baseURL = "https://api.smartsheet.com/2.0";
$getSheetURL = $baseURL. "/sheets/4925037959505796";
$accessToken = "YOUR_TOKEN";
$headers = array("Authorization: Bearer ". $accessToken);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
// Remove this line when done debugging
var_dump($getSheetResponseData);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
?>
Search here on SO for the (partial) error message "Trying to get property of non-object" and you'll see lots of related posts. Essentially, this error means that your code is treating something as an object that's not actually an object. This would happen, for instance, when you try to access the name property of $sheetObj if the API request had previously failed for some reason and the contents of $sheetObj is therefore not actually an object.
I'm not very familiar with PHP, but I'd suspect (based on the error message, combined with the fact that you say "var_dump($getSheetResponseData) is Bool(false)) that the "Get Sheet" request may not be returning a successful response. To troubleshoot, I'd suggest that you try running the exact same "Get Sheet" request (i.e., with identical URI, including sheet Id) using a tool like Postman (https://www.getpostman.com/) or via the commandline with cURL, and see if you get a successful response. If you can get your request working via Postman or cURL, it should be straightforward to update your code to send the same request, resulting in a successful response. See this section of the Smartsheet API docs for info about API Troubleshooting techniques using Postman or cURL: http://smartsheet-platform.github.io/api-docs/#api-troubleshooting.
Version 1.1 of the Smartsheet API is no longer supported. You'll want to use version 2.
To do this just change $baseURL to this:
$baseURL = "https://api.smartsheet.com/2.0";
Also, each of the objects in the API will be represented by plural endpoints. So, to get a sheet you'll use:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
To get the rows you'll use:
$rowsURL = $baseURL. "/sheets/xxxxxxxxxxx/rows";
Bearer is the type of Authorization header that you're passing to the API, and the type that is required by the Smartsheet API.
Hello to use the smartsheet API connection to PHP, the API version 2.0 is used, because the older version is obsolete, the code for the connection is as follows:
$baseURL = "https://api.smartsheet.com/2.0/sheets";
// Insertar access token generado en SmartSheet
$accessToken = "YOUR_TOKEN";
// Creación del Headers Array para el Curl
$headers = array(
"Authorization: Bearer $accessToken",
"Content-Type: application/json");
//Conexión de la API de SmartSheet
$curlSession = curl_init($baseURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
//Establece la sesión del Curl
$smartsheetData = curl_exec($curlSession);
// Asignar respuesta a un objeto PHP
$createObj = json_decode($smartsheetData);
I am working with a Wordpress site with CPanel and a MySQL database. I want to be able to read data from a MongoDB held on Parse.com. Eventually, I want to change Wordpress's login.php script to search through the MongoDB and create users if necessary.
I am having lots of trouble connecting to the database.
Here is my php script:
<?php
$url = 'http://mercury.example.com:2234/parse/login';
$data = array('username' => 'username', 'password' => 'password');
$appID = "X-Parse-Application-Id: parseAppID";
$restKey = "X-Parse-REST-API-Key: praseRESTapiKey";
$session = "X-Parse-Revocable-Session: 1";
$contentType = "Content-Type: application/json";
$context = array(
'http'=> array(
"method" => "GET",
"header" => $appID . $restKey . $session . $contentType,
"content" => http_build_query($data)));
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
The errors I am receiving are:
Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in C:\wamp\www\parseDB.php on line 26
Warning: file_get_contents(http://mercury.example.com:2234/parse/login): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\wamp\www\parseDB.php on line 26
From my understanding, the 403 error means the web server is returning the "forbidden" status code.
I am testing my php script on localhost using WAMP. A colleague of mine tried to run a similar command on Bash and received a response. (I broke it out so it is easier to read).
curl -X GET
-H "X-Parse-Application-Id: parseAppID"
-H "X-Parse-REST-API-Key: parseRESTapiKey"
-H "X-Parse-Revocable-Session: 1"
-G --data-urlencode 'username=username' --data-urlencode 'password=password'
http://mercury.example.com:2234/parse/login
I have been stuck on this for 2 days so far, and I have no idea what is going on. I appreciate all the help I can get.
EDIT
Here is my final solution:
$url = 'http://mercury.example.com:3432/parse/login';
$data = array('username' => 'USERNAME', 'password' => 'PASSWORD!');
$context = array(
'http'=> array(
'method' => "GET",
'header' => "X-Parse-Application-Id: APPID\r\n" .
"X-Parse-REST-API-Key: RESTAPIKEY\r\n" .
"X-Parse-Revocable-Session: 1" .
"Content-Type: application/json\r\n",
'content' => http_build_query($data)
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
Look at the stream_content_create example at http://php.net/manual/en/function.stream-context-create.php which explains how to pass headers properly. At this time, you slam each header together without any line feeds which will make them look like concatenated string:
X-Parse-Application-Id: parseAppIDX-Parse-REST-API-Key: praseRESTapiKeyX-Parse-Revocable-Session: 1Content-Type: application/json
Hint - add \r\n after each header line.
Instead of file_get_contents you could also use curl methods.
I am working on a project, to help me learn how to use curl through PHP. I am attempting to get data from the Twitch-API using my own account for testing.
I have successfully authenticated my account with my domain by using:
https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=...&redirect_uri=...&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription&state=...
I have removed client_id, redirect_uri and state to show the link I used.
Once successfully authenticated it returns back to a domain that I specify (redirect_uri), once it gets back to that domain the website only knows the authentication key that is generated once accepted by the user, from twitch.
Example auth: 3ofbaoidzkym72ntjua1gmrr66o0nd
Now I would like to be able to get the username of the user, there is documentation on it:
curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-X GET https://api.twitch.tv/kraken/user
I am attempting to do this in PHP, but I don't understand the curl functions... Here's what I've got so far:
<?php if(isset($_GET['code']) && isset($_GET['scope'])) { ?>
<pre>
<?php
$auth = $_GET['code'];
$twitch = curl_init();
$headers = array();
$headers[] = 'Accept: application/vnd.twitchtv.v3+json';
$headers[] = 'Authorization: OAuth ' .$auth;
curl_setopt($twitch, CURLOPT_HEADER, $headers);
curl_setopt($twitch, CURLOPT_URL, "https://api.twitch.tv/kraken/user");
curl_exec($twitch);
?>
</pre>
<?php }; ?>
When I attempt to run this section of code, I get some errors:
HTTP/1.1 401 Unauthorized
Server: nginx
Date: Sat, 08 Aug 2015 13:43:51 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 89
Connection: keep-alive
Status: 401 Unauthorized
X-API-Version: 3
WWW-Authenticate: OAuth realm='TwitchTV'
Cache-Control: max-age=0, private, must-revalidate
Vary: Accept-Encoding
X-UA-Compatible: IE=Edge,chrome=1
X-Request-Id: 4bc2e0bfadf6817366b4eb19ab5751bf
X-Runtime: 0.007862
Accept-Ranges: bytes
X-Varnish: 1641121794
Age: 0
Via: 1.1 varnish
X-MH-Cache: rails-varnish-5cb970; M
{"error":"Unauthorized","status":401,"message":"Token invalid or missing required scope"}
But I am unsure on how to fix this problem as, to me, it seems I am/have done everything that the documentation says to do...
How should I go about fixing this issue?
Edit:
It seems to work if I request using my twitch username:
curl -H 'Accept: application/vnd.twitchtv.v3+json' \
-X GET https://api.twitch.tv/kraken/users/test_user1
My Code for using the username:
<?php
$auth = urlencode($_GET['code']);
$twitch = curl_init();
$headers = array();
$headers[] = 'Accept: application/vnd.twitchtv.v3+json';
#$headers[] = 'Authorization: OAuth ' .$auth;
curl_setopt($twitch, CURLOPT_HTTPHEADER , $headers);
curl_setopt($twitch, CURLOPT_URL, "https://api.twitch.tv/kraken/users/...");
curl_exec($twitch);
?>
But I wouldn't know the user's username unless I get it from the statement which is producing an error and store it in a database.
Edit:
Reading into the documentation abit more, it requires the scope as well as the access token. I have been able to get this:
Example:
Array
(
[0] => Accept: application/vnd.twitchtv.v3+json
[1] => Authorization: OAuth code=scn89zerug002sr6r95z9ngbxmd0d2&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription
)
But I still get the error...
Edit:
So I read through the documentation EVEN MORE and now I have gotten to this:
class twitch {
var $base_url = "https://api.twitch.tv/kraken/";
var $client_id = "...";
var $client_secret = "...";
var $return_url = "...";
var $scope_array = array('user_read','channel_read','channel_subscriptions','user_subscriptions','channel_check_subscription');
public function get_access_token($code,$state) {
$ch = curl_init($this->base_url . "oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirect_url,
'code' => $code
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
curl_close($ch);
echo "<pre>".print_r($this->redirect_url,true)."</pre>";
echo "<pre>".print_r($response,true)."</pre>";
return $response["access_token"];
}
};
$auth = new twitch();
print_r($auth->get_access_token($_GET['code'],$_GET['state']));
But this time there is another error, saying that my 'redirect_uri' => $this->redirect_url is different to the one which is held by twitch.
Array
(
[error] => Bad Request
[status] => 400
[message] => Parameter redirect_uri does not match registered URI
)
I have even copied and pasted from the twitch website to my variable and the other way around, I still get the same error... Now I'm even more stuck, but at least a step closer.
Right I'm going to do this with you as I do it :d So far I've been able to get one user, the reason you're getting errors is because you're not setting any curl options. I taught myself using this https://github.com/paypal/rest-api-curlsamples/blob/master/execute_all_calls.php which I found MASSIVELY helpful when learning curl. The code itself is basic but it's so easy to read. I managed to understand it and make it 100% more complicated :D
First things first, I'll show you how I got the test user.
What you want to do is set the options, I'll keep to the simple method first.
The 2 methods are CURLOPT_HEADER and CURL_RETURNTRANSFER. Your url you can set with the init function.
$twitch=curl_init('https://api.twitch.tv/kraken/users/test_user1');
curl_setopt($twitch,CURLOPT_HTTPHEADER,array('Accept: application/vnd.twitchtv.v3+json'));//must be an array.
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
$info=curl_getinfo($twitch);
print_r($result);
This will get you your test user and hopefully show you a little bit about what you're doing wrong. If you wanted to use the array method, then you must use your curl options as the array key so that the set function know what to set what as. (don't ask me how it all technically works :S)
I'll update to show you how to get an authorisation and data once I've worked it out. But the basic principles are you need to send post data and set CURLOPT_POST to true and include the postdata CURLOPT_POSTFIELDS which must be a json array as your application requires json I believe?
Anyway the array:
curl_set_opts($twitch,array(CURLOPT_HEADER=>array('Accept: application/vnd.twitchtv.v3+json',CURLOPT_RETURNTRANSFER=true));
Seeing as you already know how to authorise a user I'll skip that bit, although I'd recommend using something a little more secure than a $_GET. Maybe a session variable would be a bit better.
To get a specific user using the Auth that is returned. You want to do something like this: (Sorry I can't test it myself, I don't have a twitch dev account)
$twitch=curl_init('https://api.twitch.tv/kraken/user');
curl_setopt($twitch,CURLOPT_HEADER,array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$_SESSION['token']));
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
print_r($result);
//don't forget to close!
curl_close($twitch);
$user=json_decode($result);
echo$user->display_name;
That should work although I have no idea how you're getting a oAuth token lol
if you wanted to be a really cool programmer 8| I'd recommend doing some classes for this. Like this
class twitch{
private$token,$twitch,$url="http://api.twitch.tv/kraken/";
protected$code,$state,$report;
private static$details;
public function __construct($code,$state){
$this->code=$code;
$this->state=$state;
self::$details=(object)array('client_id'=>'id','client_secret'=>'secret','return_url'=>'redirect');
$result=$this->makeCall('oauth2/token',true);
print_r($result);
}
protected function makeCall($extention,$auth=false,$object=true){
$this->twitch=curl_init($this->url.$extention);
//$opts=array(CURLOPT_)
if($auth!==false){
$opts=array(CURLOPT_FOLLOWLOCATION=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode(array('client_id'=>self::$details->client_id,'client_secret'=>self::$details->client_secret,'grant_type'=>'authorization_code','code'=>$this->code,'redirect_uri'=>self::$details->return_url)));
}else{
$opts=array(CURLOPT_HEADER=>array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$this->token),CURLOPT_RETURNTRANSFER=>true);
}
curl_setopt_array($this->twitch,$opts);
$result=curl_exec($this->twitch);
$this->report=array('info'=>curl_getinfo($this->twitch),'error'=>curl_error($this->twitch));
curl_close($this->twitch);
return($object===true)?json_decode($result):$result;
}
protected function userDetails(){
return$this->makeCall('user');
}
public function user(){
return$this->userDetails();
}
}
I have got the following cURL command that is running expectedly:
curl -X POST
-H "Content-Type: application/json"
-d '{"duplicateEntitiesIds": [21,31,41]}'
{URL}:3003/v1/entities/5/merge
And I am trying to replicate that with Guzzle, which however fails, returning a 400 status code:
$request = $httpClient->post('{URL}:3003/v1/entities/'.$mainEntityId.'/merge',
['json' =>
['duplicateEntitiesIds' => $duplEntitiesIdsToArray]
]
);
$response = $request->send();
I have tried to change my post body , but it keeps failing. Any ideas would be appreciated.
NOTE
The data should be sent in the following format:
{"duplicateEntitiesId": [2,3,4]}
I am very suck. I am trying to send to a php array of device id's with urban airship. I am using the first example found here. Everything works, with "audience"=>"all". Every registered device gets hit. I need to make a query of a database, that has a bunch of device id's in it, and send to those device id's. What do I change "audience"=>"all" to so I can do that. I have tried everything!
Here is the code incase the link breaks:
<?php
define('APPKEY','XXXXXXXXXXXXXXX'); // Your App Key
define('PUSHSECRET', 'XXXXXXXXXXXXXXX'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
$contents = array();
$contents['badge'] = "+1";
$contents['alert'] = "PHP script test";
$contents['sound'] = "cat.caf";
$notification = array();
$notification['ios'] = $contents;
$platform = array();
array_push($platform, "ios");
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo $content; // just for testing what was sent
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
echo "Got negative response from server, http code: ".
$response['http_code'] . "\n";
} else {
echo "Wow, it worked!\n";
}
curl_close($session);
?>
It depends on what device OS you are trying to send to. Via their documentation here:
http://docs.urbanairship.com/reference/api/v3/push.html#atomic-selectors
you will need to set the correct device type to it's corresponding ID. For example:
android:
"audience" : {
"apid" : "b8f9b663-0a3b-cf45-587a-be880946e880"
}
ios:
"audience" : {
"device_token" : "C9E454F6105B0F442CABD48CB678E9A230C9A141F83CF4CC03665375EB78AD3A"
}
I found a possible solution for this from urban airship help center... They suggest this. And its working for me.
You can send to multiple device tokens or APIDs in a single request. I would suggest using our new API v3 and batching up your requests. There are a couple ways to do this:
1) Send to multiple devices in one payload
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '{"audience" : {"OR": [{"device_token":"<DeviceToken1>"}, {"device_token":"<DeviceToken2>"}, {"device_token":"<DeviceToken3>"}]}, "notification" : {"alert" : "Hello iOS devices!"}, "device_types" : ["ios"]}' https://go.urbanairship.com/api/push/
OR
2) Put multiple payloads together in one batch
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '[{"audience": {"device_token": "<DeviceToken1>"}, "notification": {"alert": "Hello, I was sent along with a batch of other pushes!"}, "device_types": ["ios"]}, {"audience": {"device_token": "<DeviceToken2>"}, "notification": {"alert": "I was also sent with a batch of other pushes!"}, "device_types": ["ios"]}, {"audience": {"device_token": "<DeviceToken3>"}, "notification": {"alert": "Me three!"}, "device_types": ["ios"]}]' https://go.urbanairship.com/api/push/
Switched to the PHP 2 library for Urban Airship and I was able to send to individual device tokens. I was also able to read tokens out of an array, and assign the array value as the target. Version 2 found here.