AngularJS stream audio from PHP server 2 - javascript

I have the following PHP code which authenticate to a third-party server using JWT and download the recorded audio from the server and then it serves the .mp3 to javascript which constructs an Audio object to playback the audio. How to do this more efficiently?
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
private function generate_jwt() {
$dev = preg_match("/blah.blah.com/", $_SERVER["HTTP_HOST"]);
$jwt = false;
date_default_timezone_set('UTC'); //Set the time for UTC + 0
//$key = file_get_contents($keyfile); //Retrieve your private key
$key = $dev ? self::DEV_KEY : self::PRODUCTION_KEY;
$id = $dev ? self::DEV_ID : self::PRODUCTION_ID;
$signer = new Sha256();
$privateKey = new Key($key);
$jwt = (new Builder())->setIssuedAt(time() - date('Z')) // Time token was generated in UTC+0
->set('application_id', $id) // ID for the application you are working with
->setId( base64_encode( mt_rand ( )), true)
->sign($signer, $privateKey) // Create a signature using your private key
->getToken(); // Retrieves the JWT
return $jwt;
}
public function playback($url) {
$response = "";
if (!empty($url)) {
//Create your JWT
$jwt = $this->generate_jwt();
//Add the JWT to your headers
$headers = array('Content-Type: application/json', "Authorization: Bearer " . $jwt);
$ch = curl_init();
//Make a request to $recording_url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$file = __TMPDIR__ . basename($url).".mp3";
file_put_contents($file, $response);
header('Pragma: public'); // required
header('Content-Type: audio/mpeg');
header('Content-length: ' . filesize($file));
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: filename="' . basename($file));
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
$len = readfile($file);
} else
error_log(__FILE__." ".__FUNCTION__." ".__LINE__.": Invalid url! ".$url);
}

Related

Message":"There was an error processing the request.","StackTrace":"","ExceptionType" - JQUERY

Here is my code, I keep on getting the same error response.
"{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}"
I can't figure it out. I'm using Eloqua APIs to get basic information such as total number of accounts, landing pages, users, images, etc. It's weird because I tried the API on POSTMAN application and it did work perfectly Screenshot of postman response to the API
PHP
$objetos = array("data/accounts", "data/contacts", "assets/emails", "assets/landingPages", "assets/images", "assets/forms", "system/users", "assets/microsites", "assets/customObjects");
for ($i = 0; $i < 9; $i++){
$url = 'http://secure.p03.eloqua.com/API/REST/1.0/' . $objetos[$i] . '?count=1';
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
$headers = array(
'Content-type: application/json',
'Authorization: BASIC "MY TOKEN"'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() ."/EloquaApi_lvl1.cer");
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
$data[$i] = curl_exec($ch);
curl_close($ch);
}
echo json_encode($data);
?>
JS
function getObjetos(){
$.get("objetos.php", function (data) {
console.log(data);
}, "json").done(function (data) {
console.log(data);
// rest of my code
}
Console
console.log response (click for image)
Try changing the url http://secure.p03.eloqua.com/API/REST/1.0/ to https
Use https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=KEY
My full PHP code here
$data = array();
$data['siteUrl'] = 'https://example.com';
$data['urlList'][] = 'https://example.com/news/1';
$ch = curl_init('https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=KEY');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'charset=utf-8',
'HTTP/1.1'
),
CURLOPT_POSTFIELDS => json_encode($data)
));
$response = curl_exec($ch);

How to connect to the Companies House API - with specific curl header and API key requirements?

I am trying to connect to the UK Companies House API. Ideally, I am looking for a JavaScript solution.
But I am trying to get this PHP variant up and running. How do I gain access to the API, with the API key?
PHP:
public function GetCompanyHouse(){
$int = '00928555';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://data.companieshouse.gov.uk/doc/company/' . $int . '.json');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, '10');
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
switch($status)
{
case '200':
return json_decode($result);
break;
default:
return false;
break;
}
}
https://developer.companieshouse.gov.uk/api/docs/index/gettingStarted/apikey_authorisation.html
curl -XGET -u my_api_key:
https://api.companieshouse.gov.uk/company/00000006
Do I set this as a header?
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'u: my_api_key'
));
Is it possible to just do a JSON call like this? https://api.companieshouse.gov.uk/company/00000006?api_key=xxxxxx
Here is a jQuery model in the works
http://jsfiddle.net/NYEaX/1412/
$(document).ready(function() {
console.log("api");
xhr = new XMLHttpRequest();
$(document).ready(function() {
$.ajax({
url: 'https://api.companieshouse.gov.uk/search?q=subway',
type: 'GET',
datatype: 'json',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Basic bXlfYXBpX2tleTo=');
// xhr.setRequestHeader('X-GET', 'xx');
}
});
for me
curl -u "token": https://api.companieshouse.gov.uk/company/SC185088
in command prompt works
Here is some sample code, modify as needed...
$my_api_key = "blablablablabla";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.company-information.service.gov.uk/company/11263172');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, '10');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: '.$my_api_key
));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
Not an expert but the following has worked for me
//Function thanks to Stackoverflow member:
//https://stackoverflow.com/questions/7393719/human-readable-json-aka-add-spaces-and-breaks-to-json-dump
//https://stackoverflow.com/users/720204/som
function jsonToReadable($json){
$tc = 0; //tab count
$r = ''; //result
$q = false; //quotes
$t = "\t"; //tab
$nl = "\n"; //new line
for($i=0;$i<strlen($json);$i++){
$c = $json[$i];
if($c=='"' && $json[$i-1]!='\\') $q = !$q;
if($q){
$r .= $c;
continue;
}
switch($c){
case '{':
case '[':
$r .= $c . $nl . str_repeat($t, ++$tc);
break;
case '}':
case ']':
$r .= $nl . str_repeat($t, --$tc) . $c;
break;
case ',':
$r .= $c;
if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);
break;
case ':':
$r .= $c . ' ';
break;
default:
$r .= $c;
}
}
return $r;
}
//I'm searching time company incorporated, adjust your search variables/query to your needs
//I'm using the Advanced Search here but again adjust to your needs
//https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/reference/search/advanced-company-search
//My main issue was getting connected and rid of "Invalid authorisation" trying to connect to the service.
//Why they don't just issue a multi language toolkit I'll never know, it may save them some bandwith...
$incorporated_from= urlencode('2022-11-14');
$incorporated_to= urlencode('2022-11-14');
$curl = curl_init("https://api.company-information.service.gov.uk/advanced-search/companies?incorporated_from=".$incorporated_from."&incorporated_to=".$incorporated_to."&size=100");
//IMPORTANT!!! BASE64 Encode your API key but also add a colon ':' at the end of it before encoding.
//I found this finally worked if I pre-prepared the BASE64 encoding of my API key rather than let PHP do it on the fly
//So your headers variable will look something like
//$headers = array('Authorization: Basic BLAHBLAHBLAHBLAHBLAHBLAHUfsd5436ghZWY4Og==');
$headers = array('Authorization: Basic MY_COMPANIES_HOUSE_REST_API_KEY_WITH_COLON_AT_END_BASE64_ENCODED');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, true); // Comment out or use when debugging to show returning header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$results = curl_exec($curl);
//Make the JSON returned readable - thanks to Stackoverflow member "som", that created the function!
echo jsonToReadable($results);
if(curl_errno($curl))
{
echo 'Curl error : ' . curl_error($curl);
}
curl_close($curl);

Re-writing json api curl from javascript to php

Hello great stackoverflow, am trying to re-write the api below from javascript to php in other to be able to make json curl but displays error below
Warning: curl_setopt() expects exactly 3 parameters, 4 given in C:\xampp\htdocs\firstcare\curl.php on line 15
js curl
curl -X POST
"http://my_api.com/accesstoken?grant_type=client_credentials"
-H "Content-Type: application/x-www-form-urlencoded"
-d 'client_id=$myClient_id'
-d 'client_secret=$myClient_secret
php curl conversion
<?php
// 0 means unlimited timeout
ini_set('max_execution_time', 0);
$data = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'client_id' => 'myclient_id',
'client_secret' => 'myclient_secret'
);
$url='http://my_api.com/accesstoken?grant_type=client_credentials';
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url,$data);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
echo '<pre>' . print_r($json, true) . '</pre>';
?>
Thanks
Error was thrown because curl_setopt requires 3 parameters - you've passed 4 here:
curl_setopt($ch, CURLOPT_URL,$url,$data);
May I suggeest guzzlehttp, wrapper for curll...also u seem to be passing headers in $data as the forth paramenter remove $data. If u want to sent cllient id as GET append the $url with http_build_query()
Try these codes
<?php
// 0 means unlimited timeout
ini_set('max_execution_time', 0);
$postdata = array(
'client_id' => 'myclient_id',
'client_secret' => 'myclient_secret'
);
$header = array(
'Content-Type' => 'application/x-www-form-urlencoded',
);
$url='http://my_api.com/accesstoken?grant_type=client_credentials';
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
echo '<pre>' . print_r($json, true) . '</pre>';
?>

How to Send a push notification through GCM using XHR (Ajax)

This is my curl command to send notification through terminal. It works properly but how to send notification on button click(using XHR request)
curl --header "Authorization: key=AIzaSyCjrU5SqotSg2ybDLK0dMusvY" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"f5xzshqcfDE2qiKGJu858nFhqGCuk0uuUC6vm\"]}"
You can write a php script to serve the purpose and just make an XHR request with client ,like javascript or any other of your choice.
Here is my php script I did it some months ago and it is working.
<?php
$message = "\": 3,\"title\": \"High score alert!\",\"\": true,\"custom_field\": { \"score\": 51,\"headlines\": \"And now for something completely different...\" }}";
$apiKey = "Your Key";
$registrationIDs = array("Registration id");
$url = 'https://android.googleapis.com/gcm/send';
// Set POST variables
$notify = array(
"alert"=> "great match!",
"title"=> "Portugal vs. Denmark",
"icon" => "myicon",
"badge"=>3,
"vibrate"=>true,
"notification"=>"message"
);
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "payload" => $notify,
"notification"=>json_encode($notify)));
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init(); // Open connection
curl_setopt($ch, CURLOPT_URL, $url );
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
var_dump( $url );
var_dump($headers);
var_dump(json_encode( $fields ));
$result = curl_exec($ch); // Execute post
if($result === false)
die('Curl failed ' . curl_error());
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$response = json_decode($result);
print_r($response);
?>

Properly returning JSON format to page

I am attempting to capture a latitude and longitude and then pass it to Google Maps to return some data and then exact the zip code out of the response and use that.
When I call it directly to a browser I get a response on the page that ends up being like:
{"zip":"90029"}
But when I attempt to view it in Chrome's developer tools, it states "This request has no response data". So it seems as though my JSON is not being encoded properly, or I am not returning it to the page properly in a JSON format type header.
I've tried various things, and nothing seems to work properly in order to get it return the JSON data.
Here's my present code:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$now = #date("Ymd-His");
$myFile = "loc" . $now . ".txt";
$fh = fopen("locations/" . $myFile, 'w') or die("can't open file");
$lat = $_REQUEST['lat'];
$long = $_REQUEST['long'];
$type = $_REQUEST['type'];
$phone = $_REQUEST['phone'];
$loc = $_REQUEST['typed_location'];
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$address = json_decode($curlData, true);
$temp_data = $address['results'][0]['formatted_address'];
$temp = explode(", ", $temp_data);
$temp_2 = explode(" ", $temp[2]);
$zip = $temp_2[1];
fwrite($fh, $zip);
fclose($fh);
$array = array("zip" => $zip);
$t = json_encode($array);
echo $t;
For anyone else looking to solve this problem - when using cross domains, be sure to allow for the Access-Control by setting the following as a header:
header("access-control-allow-origin: *");

Categories