YouTube video list in JSON format - php

I have created a function in PHP for fetching a YouTube video list of my channel in JSON format but I'm getting blank array.
public function channels_list()
{
$method = $_SERVER['REQUEST_METHOD'];
if($method != 'GET')
{
json_output(400,array('status' => 400,'message' => 'Bad request.'));
}
else
{
$data = array();
$json_link="https://www.googleapis.com/youtube/v3/search?key='MY API KEY'&channelId='MY CHANNEL ID'&part=snippet,id&order=date&maxResults=10";
$json = file_get_contents($this->json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
foreach($obj['items'] as $post){
$jsondata['id'] = isset($post['id']['videoId']) ? $post['id']['videoId'] : "";
$jsondata['published_at'] = isset($post['snippet']['publishedAt']) ? $post['snippet']['publishedAt'] : "";
$jsondata['title'] = isset($post['snippet']['title']) ? $post['snippet']['title'] : "";
$jsondata['description'] = isset($post['snippet']['description']) ? $post['snippet']['description'] : "";
$jsondata['thumbnail'] = "https://i.ytimg.com/vi/{$id}/maxresdefault.jpg";
array_push($data, $jsondata);
}
json_output("200", array("list"=>$data),1);
}
}

Try this below code,I'm using this and it's working fine for me.
function get_youtube($url){
$youtube = "http://www.youtube.com/oembed?url=". $url ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
$url = // youtube video url
// Display Data
print_r(get_youtube($url));
Updated:
you don't need OAuth2 login for that. You can simply do it by setting your API key instead.
It's a playlistItems->list request.
Here's demonstration in api explorer: https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet&playlistId=PLjFEz-E0UPUxw3lFpnfV1dDA7OE7YIFRj&_h=2&
Instead of setting clientId and client Secret
set it's API key to your API key from cloud console in Public API access.
$client->setAPIKey($API_KEY);
Example:
$API_key = 'Your_API_Key';
$channelID = 'YouTube_Channel_ID';
$maxResults = 10;
$videoList = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.''));

Related

CURL Post Request to API Looping Through Database

I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);

REST API : Fat Secret API Invalid signature: oauth_signature in PHP

I am using Fat Secret API in my project and want to find the food names on search so I hard coded the food name say : banana and it is giving me error
8 Invalid signature: oauth_signature 'NECnoAOp6D2qLCg7YQ84fYyJYRE='
Below is my code
$consumer_key = "bcd69xxxxxxxxxxxxxxxxxxxxxxx52";
$secret_key = "62fe9xxxxxxxxxxxxxxxxxxxxxxxx54d";
$base = rawurlencode("GET")."&";
$base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";
$params = "format=json&";
$params = "method=foods.search&";
$params .= "oauth_consumer_key=$consumer_key&";
$params .= "oauth_nonce=".uniqid()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0&";
$params .= "search_expression=banana";
$params .= "oauth_callback=oob";
$params2 = rawurlencode($params);
$base .= $params2;
//encrypt it!
$sig= base64_encode(hash_hmac('sha1', $base, "62fe9d66898545a0b48d497a4394054d&", true));
$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig);
//$food_feed = file_get_contents($url);
list($output,$error,$info) = loadFoods($url);
echo '<pre>';
if($error == 0){
if($info['http_code'] == '200'){
echo $output;
} else {
die('Status INFO : '.$info['http_code']);
}
}else{
die('Status ERROR : '.$error);
}
function loadFoods($url)
{
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
return array($output,$error,$info);
}
Please Help me in this. I am new in OAuth and Fat Secret API, Please do share the necessary information if you know.
Thanks

Search Files Nothing Found

I am trying to search (filter) for files in a Dropbox folder, but no files are being found when there are files that match the filter. I am not using the PHP library provided by Dropbox.
Here is an extract of the code:
class Dropbox {
private $headers = array();
private $authQueryString = "";
public $SubFolders = array();
public $Files = array();
function __construct() {
$this->headers = array('Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.DROPBOX_APP_KEY.'", oauth_token="'.DROPBOX_OAUTH_ACCESS_TOKEN.'", oauth_signature="'.DROPBOX_APP_SECRET.'&'.DROPBOX_OAUTH_ACCESS_SECRET.'"');
$this->authQueryString = "oauth_consumer_key=".DROPBOX_APP_KEY."&oauth_token=".DROPBOX_OAUTH_ACCESS_TOKEN."&oauth_signature_method=PLAINTEXT&oauth_signature=".DROPBOX_APP_SECRET."%26".DROPBOX_OAUTH_ACCESS_SECRET."&oauth_version=1.0";
}
public function GetFolder($folder, $fileFilter = "") {
//Add the required folder to the end of the base path for folder call
if ($fileFilter == "")
$subPath = "metadata/sandbox";
else
$subPath = "search/sandbox";
if (strlen($folder) > 1) {
$subPath .= (substr($folder, 0, 1) != "/" ? "/" : "")
.$folder;
}
//Set up the post parameters for the call
$params = null;
if ($fileFilter != "") {
$params = array(
"query" => $fileFilter
);
}
//Clear the sub folders and files logged
$this->SubFolders = array();
$this->Files = array();
//Make the call
$content = $this->doCall($subPath, $params);
//Log the files and folders
for ($i = 0; $i < sizeof($content->contents); $i++) {
$f = $content->contents[$i];
if ($f->is_dir == "1") {
array_push($this->SubFolders, $f->path);
} else {
array_push($this->Files, $f->path);
}
}
//Return the content
return $content;
}
private function doCall($urlSubPath, $params = null, $filePathName = null, $useAPIContentPath = false) {
//Create the full URL for the call
$url = "https://api".($useAPIContentPath ? "-content" : "").".dropbox.com/1/".$urlSubPath;
//Initialise the curl call
$ch = curl_init();
//Set up the curl call
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($params != null)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$fh = null;
if ($filePathName != null) {
$fh = fopen($filePathName, "rb");
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_INFILE, $fh);
curl_setopt($context, CURLOPT_INFILESIZE, filesize($filePathName));
}
//Excecute and get the response
$api_response = curl_exec($ch);
if ($fh != null)
fclose($fh);
//Process the response into an array
$json_response = json_decode($api_response);
//Has there been an error
if (isset($json_response->error )) {
throw new Exception($json_response["error"]);
}
//Send the response back
return $json_response;
}
}
I then call the GetFolder method of Dropbox as such:
$dbx = new Dropbox();
$filter = "MyFilter";
$dbx->GetFolder("MyFolder", $filter);
print "Num files: ".sizeof($dbx->Files);
As I am passing $filter into GetFolder, it uses the search/sandbox path and creates a parameter array ($params) with the required query parameter in it.
The process works fine if I don't provide the $fileFilter parameter to GetFolder and all files in the folder are returned (uses the metadata/sandbox path).
Other methods (that are not in the extract for brevity) of the Dropbox class use the $params feature and they to work fine.
I have been using the Dropbpox API reference for guidance (https://www.dropbox.com/developers/core/docs#search)
At first glance, it looks like you're making a GET request to /search but passing parameters via CURLOPT_POSTFIELDS. Try using a POST or encoding the search query as a query string parameter.
EDIT
Below is some code that works for me (usage: php search.php <term>). Note that I'm using OAuth 2 instead of OAuth 1, so my Authorization header looks different from yours.
<?php
$access_token = '<REDACTED>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.dropbox.com/1/search/auto');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Bearer ' . $access_token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('query' => $argv[1]));
$api_response = curl_exec($ch);
echo "Matching files:\n\t" . join("\n\t",
array_map(function ($file) {
return $file['path'];
}, json_decode($api_response, true)))."\n";
?>

How to send and receive data via HTTP header using cURL?

I am trying to build a simple API to allow a client to send me data over HTTPS.
I created a class that will take a username/password then it does a database look up. If the user is found then it issues a token. Then the token will be send back to the requester via HTTP header.
Once a username, password and a token sent back then the script reads the data sent from the client via $_POST request and processes it.
The challenge that I am having is sending the token to the requester via cURL and receiving the USERNAME, PASSWORD & TOKEN from the HTTP header correctly.
My question is how can I correctly send the token via HTTP header in the generateToken() method? Also how can I read the HTTP headers once the request is made?
Below is my class: api.php file
<?php
require('../classes/connection.php');
class api {
private $user_name;
private $user_password;
private $user_token;
private $db;
private $keepAlive = 120; //2 minutes = 120 seconds
private $authorizes = false;
private $token = '';
private $ch;
private $user_ready = false;
function api($database, $server){
//establish a database connection
$this->db = new connection($database, $server);
$this->ch = curl_init();
//read user_name, password, token from the header and set it
if(isset($_SERVER['API-User-Name']))
$this->user_name = $_SERVER['API-User-Name'];
if(isset($_SERVER['API-User-Password']))
$this->user_password = $_SERVER['API-User-Password'];
if(isset($_SERVER['API-User-Token']))
$this->user_token = $_SERVER['API-User-Token'];
//check if the user is allowed
if( $this->authenticateAccess() === true ){
$this->authorizes = true;
//ensure the token is valid otherwise generate a new token
if( $this->isValidToken() )
$this->user_ready = true;
else
$this->generateToken();
}
}
//return weather to process the send data
public function isUserReady(){
return $this->user_ready;
}
//return weather the user is authorized
private function isAutherized(){
return $this->authorizes;
}
//return the set token
private function getToken(){
return $this->token;
}
//check if the requester is authorized to access the system
private function authenticateAccess(){
//unauthorized old session
$this->unautherizeExpiredTokens();
if( $this->ch === false)
return false;
if( empty($this->user_name) || empty($this->user_password) )
return false;
//ensure HTTPS is used
if( !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')
return false;
//read the user information
$get_user = $this->db->getDataSet('SELECT ip_addreses, user_password, token_expires_on, current_token
FROM api_users
WHERE user_name = ?
LIMIT 1', array($this->user_name));
if( count($get_user) != 1)
return false;
$data = $get_user[0];
//remove bad values if any
$ip_addreses = preg_replace("/[^0-9,.]/", "", $data['ip_addreses']);
$allowed_ips = explode(',', $ip_addreses);
//ensure the IP address is allowed
if( !isset($_SERVER['REMOTE_ADDR']) || !in_array($_SERVER['REMOTE_ADDR'], $allowed_ips) )
return false;
//check if the password is valid
if( password_verify($this->password, $data['user_password'] ) )
return true;
else
return false;
}
//check if the token is valid
private function isValidToken(){
if( !$this->isAutherized() )
return false;
//unauthorized old session
$this->unautherizeExpiredTokens();
if( empty($this->user_token) )
return false;
$get_user = $this->db->getDataSet('SELECT token_expires_on, current_token
FROM api_users
WHERE user_name = ? AND current_token = ?
LIMIT 1', array($this->user_name, $this->user_token ));
if( count($get_user) != 1)
return false;
$data = $get_user[0];
if( empty($data['token_expires_on']) || $data['current_token'] != $this->user_token )
return false;
//make sure that the token is not expired
if( !empty($data['token_expires_on']) && time() > $data['token_expires_on'])
return false;
}
//generate a new token
private function generateToken(){
//generate a token
$token = md5(uniqid(mt_rand(), true));
//set expiration date for this token
$expire_on = time() + $this->keepAlive;
//Save the new token in the database with expiration time = $this->keepAlive seconds
$update = $this->db->processQuery('UPDATE api_users
SET current_ip = ?,
current_token = ?,
token_expites_on = ?
WHERE user_name = ?', array($_SERVER['REMOTE_ADDR'], $token, $expire_on ));
//if the token is saved in the database then send the new token via cURL header.
if($update){
//set the token as a header value and then sent it back to the requester.
$this->token = $token;
$curl_header = array();
$curl_header[] = 'API-User-Token: ' . $token;
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_header);
return $token;
} else
return false;
}
//remove old tokens
private function unautherizeExpiredTokens(){
$this->db->processQuery('UPDATE api_users
SET current_ip = NULL,
current_token = NULL,
token_expites_on = NULL
WHERE token_expites_on IS NOT NULL AND token_expites_on <= ?', array( time() ) );
}
}
?>
And to use this class I would do the following form the API access link. Once I figure out how to ready the http data then there will be no need to pass the $username and $password to the class instead it will be ready in the class from the header.
Therefore, the access.php file will look like the following
include('api.php');
$request = new api('database_name','serverIPaddress');
if( $request->isUserReady() ){
//process transaction all transactions
$_POST['notes']; //// take the data validated it and then insert into the database
echo 'Bingo!';
} else {
echo 'You are not authorized to use this API';
}
?>
To use this API the client will have to call it like so client.php file will looks like this:
<?php
$curl_header = array();
$curl_header[] = 'API-User-Name: test';
$curl_header[] = 'API-User-Password: password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://mydomainname.com/api/access.php");
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_header);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
?>
Just use CURLOPT_HTTPHEADER:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-THING_ONE: abcdefghijklmnopqrstuvwxyz',
'X-THING_TWO: 12345678910'
));
I prefer to set the header as an array outside of the curl_setopt like this:
$curl_headers = array();
$curl_headers[] = 'X-THING_ONE: abcdefghijklmnopqrstuvwxyz';
$curl_headers[] = 'X-THING_TWO: 12345678910';
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
EDIT: Okay, it looks like you know how CURLOPT_HEADER works. But looking at your code there seems to be a typo right here.
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('API-Token: ' . $this->getToken() ));
Why do you have $this->ch in CURLOPT_HEADER & CURLOPT_HTTPHEADER but just $ch for CURLOPT_RETURNTRANSFER? Shouldn’t that be like this?
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('API-Token: ' . $this->getToken() ));
EDIT: In addition to that typo, it seems that the original poster needs to know how to get the parameters on the receiving side:
Also how can I read the HTTP headers once the request is made?
Easy. They are accessed via $_SERVER predefined variable in PHP. So you would grab them like this:
$_SERVER['X-API-User-Name'];
$_SERVER['X-API-User-Password'];
$_SERVER['X-API-User-Token'];
And you can check what is passed while debugging by doing this:
echo '<pre>';
print_r($_SERVER);
echo '</pre>';

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

Categories