GoodData Export Dashboard API - php

I'm working on how do I export a dashboard from some specific project, like this link shows up.
The code I made, generates the link for download correctly, like expected. But the PDF file exported don't bring the values filtered like I aimed.
My problem happen below this comment:
// Execute the dashboard with context
... where I supose to set "all filters that affects the dashboard", like the link above says. But it does not specify how can I set the value of the filter.
I made all the code in PHP (replace all the "{some-thing}" to make this code work):
<?php
$login = '{email}';
$pass = '{password}';
$headers = array('accept' => 'Accept: application/json','content-type' => 'Content-Type: application/json; charset=utf-8');
$data = json_encode(array('postUserLogin'=>array('login'=> $login,'password'=> $pass,'remember'=>0)));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://secure.gooddata.com/gdc/account/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
$AuthSST = substr($output, strrpos($output, "GDCAuthSST=")+strlen("GDCAuthSST="), 17);
$headers = array('accept' => 'Accept: application/json',
'content-type' => 'Content-Type: application/json; charset=utf-8',
'cookie:' => 'Cookie: $Version=0; GDCAuthSST='.$AuthSST.' $Path=/gdc/account');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_URL, "https://secure.gooddata.com/gdc/account/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
$start = strrpos($output, "GDCAuthTT=")+strlen("GDCAuthTT=");
$finish = strrpos($output, "Path=/gdc");
$GDCAuthTT = substr($output, $start, ($finish-$start));
$headers = array('accept' => 'Accept: application/json',
'content-type' => 'Content-Type: application/json; charset=utf-8',
'cookie:' => 'Cookie: $Version=0; GDCAuthTT='.$GDCAuthTT.' $Path=/gdc/account');
// Authentication finished, now start the dashboard export API
// Execute the dashboard with context
$project_id = '{project_id}';
$filter_id = '{filter_id}';
$filter_obj = '{0000}';
$dash_obj = '{0000}';
$url = 'https://secure.gooddata.com/gdc/internal/projects/'.$project_id.'/executionContexts';
// Inside filters: constraint, promptUri, uri, id ||||||||| Inside executionContext: dashboard, links, name, type, user
$bode = json_encode(array('executionContext' => array('filters' => array(array(
'uri' => '/gdc/md/'.$project_id.'/obj/'.$filter_obj, // /elements?id=0000
'id' => $filter_id)),
'dashboard' => '/gdc/md/'.$project_id.'/obj/'.$dash_obj,
'type' => 'export'
)));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bode);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
// Export the Dashboard
$dash_tab = 'ae2b1ab3a87c';
$start = strrpos($output, "\"uri\":\"")+7;
$finish = strrpos($output, "\"}");
$url = "https://secure.gooddata.com/gdc/projects/".$project_id."/clientexport";
$request_url = "https://secure.gooddata.com/dashboard.html#";
$project = "project=/gdc/projects/".$project_id;
$dashboard = "&dashboard=/gdc/md/".$project_id."/obj/".$dash_obj;
$tab = "&tab=".$dash_tab."&export=1";
$ctx = "&ctx=".substr($output, $start, ($finish-$start));
$bode2 = json_encode(array('clientExport'=>array('url'=>$request_url.$project.$dashboard.$tab.$ctx, 'name'=>'{Dash_Name}')));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bode2);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
// Poll the URL from response Result:
$start = strrpos($output, "\"poll\":\"")+8;
$finish = strrpos($output, "\"}");
$poll = "https://secure.gooddata.com".substr($output, $start, ($finish-$start));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_URL, $poll);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
echo "Link: ".$poll;
echo "<br>Output: ".$output;
// Wait 90 seconds and then make the download, otherwise it returns 202 http code
sleep(90);
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Accept: application/json\r\n".
"Content-Type: application/json; charset=utf-8\r\n".
'Cookie: $Version=0; GDCAuthTT='.$GDCAuthTT.' $Path=/gdc/account'."\r\n",
'timeout' => 6000
)
);
$context = stream_context_create($opts);
$file = file_get_contents($poll."?download=true", false, $context);
file_put_contents("Dashboard.pdf", $file);
echo "<br><br>Link used: ".$poll."?download=true";
$errors= error_get_last();
echo "<br><br>".$errors['type'];
echo "<br>".$errors['message'];
curl_close($ch);
?>

You can specify the filter values using constraint object in the filter definition. The exact constraint format depends on the type of the filter. If the filter is type of list the constraint format is:
"constraint": {
"type": "list",
"elements": [
"/gdc/md/{project_id}/obj/{attribute_id}?id={element_id}",
...
]
}
if it is a date filter the constraint looks like:
"constraint": {
"from": "2006-07-01",
"to": "2008-03-31",
"type": "interval"
}
or
"constraint": {
"from": -5,
"to": 0,
"type": "floating"
}
Example of the whole executionContext object for POST with one list filter with 2 values selected:
{
"executionContext": {
"filters": [
{
"uri": "/gdc/md/{project_id}/obj/{attribute_id}",
"constraint": {
"type": "list",
"elements": [
"/gdc/md/{project_id}/obj/{displayForm_id}/elements?id={element_id_1}",
"/gdc/md/{project_id}/obj/{displayForm_id}/elements?id={element_id_2}"
]
},
"id": "{filter_id}"
}
],
"dashboard": "/gdc/md/{project_id}/obj/{dashboard_id}",
"type": "export"
}
}
You can see the valid example of filter constraint e.g. in the docs for handling drills or creating of saved view.

Related

Upload video using LinkedIn V2 API

I am trying to upload a video using LinkedIn API V2 but I am unable to post successfully video to my LinkedIn Individual Account.
Please help.
Returning Below Response from LinkedIn API:
SignatureDoesNotMatch
The request signature we calculated does not match the signature you provided. Check your key and signing method.
$person_id=LINKEDIN_ACCOUNT_ID;
$access_token= LINKEDIN_ACCESS_TOKEN;
$share_text='Video Upload and Share Text';
$author = "urn:li:person:".$person_id;
$r_url='https://api.linkedin.com/v2/assets?action=registerUpload';
$r_params = array(
'registerUploadRequest'=>array(
'recipes'=>array('urn:li:digitalmediaRecipe:feedshare-video'),
'owner' => $author,
)
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_URL, $r_url);
curl_setopt($handle, CURLOPT_VERBOSE, FALSE);
$header = array();
$header[] ='Authorization : Bearer '.$access_token;
$header[] = 'Content-Type: application/json; charset=UTF-8';
curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($r_params));
$json1 = curl_exec($handle);
$json1=json_decode($json1,true);
if($json1['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl']){
$target_url=$json1['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'];
$return_header=$json1['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['headers'];
$parts = parse_url($target_url);
parse_str($parts['query'], $query);
$amz_signature=$query['X-Amz-Signature'];
$target_header=array();
$target_header[]='Host: video-uploads-prod.s3-accelerate.amazonaws.com';
$target_header[]="Content-Type:".trim($return_header['Content-Type']);
$target_header[]="x-amz-server-side-encryption:".trim($return_header['x-amz-server-side-encryption']);
$target_header[]='x-amz-server-side-encryption-aws-kms-key-id:'.trim($return_header['x-amz-server-side-encryption-aws-kms-key-id']);
$video_path = DIR_PATH_TO_VIDEO_FILE.'example_video.mp4';
$post_data=array('file'=>$video_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $target_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($video_path));
$json2=curl_exec ($ch);
curl_close ($ch);
$json2=json_decode($json2,true);
$media_id=str_replace('urn:li:digitalmediaAsset:','', $json1['value']['asset']);
$return_data=array();
$check_url = 'https://api.linkedin.com/v2/assets/'.$media_id;
$handle = curl_init();
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($handle, CURLOPT_HEADER, FALSE);
curl_setopt($handle, CURLOPT_URL, $check_url);
$header = array();
$header[] ='Authorization : Bearer '.$access_token;
$header[] = 'Content-Type: application/json; charset=UTF-8';
curl_setopt($handle, CURLOPT_HTTPHEADER,$header);
$return_data= curl_exec($handle);
$return_data= json_decode($return_data,true);
$author = "urn:li:person:".$person_id;
$post_url = 'https://api.linkedin.com/v2/ugcPosts';
$media_data=array();
$media_data[0]=array(
'status'=>'READY',
'description'=>array('text'=>'Official LinkedIn Blog'),
'media'=>$media_id,
'title'=>array('text'=>"Official LinkedIn Blog"),
);
$params = array(
'author' => $author,
'lifecycleState' => 'PUBLISHED',
'specificContent' => array(
'com.linkedin.ugc.ShareContent' => array(
'shareCommentary' => array(
'text' => "Video media set in post",
),
'shareMediaCategory' => 'VIDEO',
'media'=>$media_data,
'originalUrl'=>'https://www.google.com'
)
),
'visibility' => array(
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC'
)
);
$handle = curl_init();
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_URL, $post_url);
curl_setopt($handle, CURLOPT_VERBOSE, FALSE);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($params));
$header = array();
$header[] ='Authorization : Bearer '.$access_token;
$header[] = 'Content-Type: application/json; charset=UTF-8';
$header[] = 'X-Restli-Protocol-Version:2.0.0';
curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
$json3 = curl_exec($handle);
$json3=json_decode($json3);
I need to upload video post to LinkedIn Account successfully but I am unable to understand that from LinkedIn documentation too. I have tried so much but not succeed.
Please someone who has successfully uploaded a video with V2 then please help.
Hi linkedin not released video uploads yet.You can use the article EP( "shareMediaCategory": "ARTICLE") to send videos to linkedin
I make use of the LinkedIn API from Zoonman to do the client post request, but this is out of the scope of the question.
Because i could not get the php curl functions to work properly, i am using the command line interface to do the request, and it works! See my code below.
BUT. even tough the upload works. When i do a request to get the status of the upload, it is still "WAITING_UPLOAD". So i think #augustine jenin is right, that it is not supported yet. (may 2019)
<?php
// first register upload
$data = [
"registerUploadRequest" => [
"recipes" => [
"urn:li:digitalmediaRecipe:feedshare-video"
],
"owner" => "urn:li:organization:" . $liPageId,
"serviceRelationships"=> [
[
"relationshipType"=> "OWNER",
"identifier" => "urn:li:userGeneratedContent"
]
]
]
];
$register = $client->post('assets?action=registerUpload', $data);
// get upload url and header
$uploadUrl = $register["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"];
$headers = $register["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["headers"];
$curlHeaders = "";
foreach($headers as $htype => $header) {
$curlHeaders .= ' -H "' . $htype . ':' . $header . '"';
}
// go upload the image to the url
$filePath = "/path/to/your/file";
$command = '/usr/bin/curl -v';
$command .= $curlHeaders;
$command .= ' --upload-file \'' . $filePath . '\' \'' . $uploadUrl . '\'';
// try it yourself by running this on the command line
//echo $command;
shell_exec($command);
?>

paypal MALFORMED REQUEST error in curl

I am facing MALFORMED_REQUEST in paypal API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"intent\":\"authorize\",
\"payer\":{
\"payment_method\":\"credit_card\",
\"funding_instruments\":[{
\"credit_card\":{
\"number\":\"5555555555554444\",
\"type\":\"mastercard\",
\"expire_month\":07,
\"expire_year\":22,
\"cvv2\":123,
\"first_name\":\"FName\",
\"last_name\":\"Lname\",
\"billing_address\":{
\"line1\":\"address,\",
\"city\":\"City\",
\"state\":\"state\",
\"postal_code\":\"postal_code\",
\"country_code\":\"country_code\"
}
}
}]
},
\"transactions\":[{
\"amount\":{
\"total\":\"10\",
\"currency\":\"CAD\",
\"details\":{
\"subtotal\":\"10\",
\"tax\":\"0\",
\"shipping\":\"0\"
}
}
}]}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer myAccessToken";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Here I am calling curl for authorization with paypal
jsonlint.com shows this json format is ok
But still I am getting response like,
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"9d7454a8637ae"}
Not getting exactly where I am wrong? Does any one know? Thanks in advance!
Your problem is the 07 in "expire_month": 07. I assume this value is meant to be a string. Not sure what you pasted in to jsonlint but it wasn't the JSON in your question.
As indicated in the comments, don't roll your own JSON. Use the tools available
$data = [
'intent' => 'authorize',
'payer' => [
'payment_method' => 'credit_card',
'funding_instruments' => [[
'credit_card' => [
'number' => '5555555555554444',
'type' => 'mastercard',
'expire_month' => '07',
'expire_year' => '22',
'hopefully you get the idea' => 'by now'
]
]]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
As the error indicates, your JSON is not formed correctly.You need not pass \ to escape your request parameters . Try removing those or try this sample code which works out of the box.
<?php
$data = 'response_type=token&grant_type=client_credentials';
$headers_arr = array();
$headers_arr[]="Accept-Encoding:application/json;charset=utf-8";
$headers_arr[]="Accept-Language:en_US";
// $headers_arr[]="Authorization:Bearer AZHFuBBAIG1rP98P7Svn2WOVatM5KAllu6KvrTE8GGT4gt9vdfj8TtR_1Cer:EBTMERCurtbf_4auykCeGWYGvwsy147bSb3xCuYpohmouVBGTaYFUIRwWgbx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "ARLg-BBMeTGLU5IHCsdIKEC_R_sMAkWM-yLsI5W5u9RuhvNhgolhYv-1cWmr:EJdAYxDx29McgMKOWjGK1OLHyaIxQBRuV9sWgfFSeMKGVBe-1jdiNgv5TLtP");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_arr);
$result = curl_exec($ch);
$res = json_decode($result);
$access_token = $res->access_token;
//now create a paypal payment
$headers_arr = array();
$headers_arr[]="Content-Type:application/json;charset=utf-8";
$headers_arr[] = "Authorization: Bearer $access_token";
// echo '<pre>';
// print_r($headers_arr);
$data_string = '{
"intent":"authorize",
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
"number":"4446283285273500",
"type":"visa",
"expire_month":11,
"expire_year":2018,
"cvv2":"874",
"first_name":"Betsy",
"last_name":"Buyer",
"billing_address":{
"line1":"111 First Street",
"city":"Saratoga",
"state":"CA",
"postal_code":"95070",
"country_code":"US"
}
}
}
]
},
"transactions":[
{
"amount":{
"total":"7.47",
"currency":"USD",
"details":{
"subtotal":"7.41",
"tax":"0.03",
"shipping":"0.03"
}
},
"description":"This is the payment transaction description."
}
]
}';
// echo data_string;
$chs = curl_init();
curl_setopt($chs, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/payments/payment');
curl_setopt($chs, CURLOPT_POST, true);
curl_setopt($chs, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($chs, CURLOPT_TIMEOUT, 45);
curl_setopt($chs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs, CURLOPT_POST, 1);
curl_setopt($chs, CURLOPT_HTTPHEADER, $headers_arr);
if(curl_exec($chs) === false)
{
echo 'Curl error: ' . curl_error($chs);
}
$results = curl_exec($chs);
$res = json_decode($results);
echo 'ress=<pre>';
print_r($results);

Stream Target in wowza

I have implemented for creating stream target through php with the help of curl.
<?php
$service_url = 'http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/liveSource';
$curl = curl_init($service_url);
$curl_post_data ='
{
"restURI": "http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/testlive"
"stream_target": {
"name": “defaultTarget”,
"provider": "rtmp",
"username": "liveSource",
"password": "Welcomehere",
"stream_name": “customTarget”,
"primary_url": "http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/liveSource",
} "https://api.cloud.wowza.com/api/v1/stream_targets"
}';
$headers = array(
'Content-Type: application/json; charset=utf-8',
'Accept: application/json; charset=utf-8'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response;
?>
But it is showing error as success as false with code 401
{"message":"The request requires user authentication","success":false,"wowzaServer":"4.4.0","code":"401"}
If you are trying to create a stream target in Wowza Streaming engine, I would start with a simple example as follows:
<?php
// Modify values here
$entryName = "ppSource";
$appName = "live";
$streamName = "myStream";
$userName = "user";
$password = "pass";
$profile = "rtmp";
$server = "localhost";
// End modification
$url = "http://{$server}:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/{$appName}/pushpublish/mapentries/{$entryName}";
$json = "{
\"restURI\": \"http://{$server}:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/{$appName}/pushpublish/mapentries/{$entryName}\",
\"serverName\":\"_defaultServer_\",
\"sourceStreamName\": \"{$streamName}\",
\"entryName\": \"{$entryName}\",
\"profile\": \"{$profile}\",
\"host\": \"{$server}\",
\"application\":\"{$appName}\",
\"userName\":\"{$userName}\",
\"password\":\"{$password}\",
\"streamName\":\"{$streamName}\"
}'";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
// curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
// curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-type:application/json; charset=utf-8',
'Content-Length: '.strlen($json)));
$contents = curl_exec($ch);
curl_close($ch);
$obj = json_decode($contents);
var_dump($obj);
However if you are trying to initiate a live stream through our cloud api, here is a small example (only) of what your request might look like:
// Modify values here
$cloudApiKey = "xxxxxxxxxxx";
$cloudApiAccessKey="xxxxxxxxxx";
// End modification
$url = "https://api.cloud.wowza.com/api/v1/live_streams";
$json = "{
\"live_stream\": {
\"id\": \"1234abcd\",
\"name\": \"MyLiveStream\",
\"transcoder_type\": \"transcoded\",
\"billing_mode\": \"pay_as_you_go\",
\"broadcast_location\": \"us_west_california\",
\"recording\": false,
\"encoder\": \"wowza_gocoder\",
\"delivery_method\": \"push\",
\"use_stream_source\": false,
\"aspect_ratio_width\": 1280,
\"aspect_ratio_height\": 720,
\"connection_code\": \"033334\",
\"connection_code_expires_at\": \"2015-11-25T12:06:38.453-08:00\",
\"source_connection_information\": {
\"primary_server\": \"6022e9.entrypoint.cloud.wowza.com\",
\"host_port\": 1935,
\"application\": \"app-464b\",
\"stream_name\": \"32a5814b\",
\"disable_authentication\": false,
\"username\": \"client2\",
\"password\": \"1234abcd\"
},
\"player_responsive\": true,
\"player_countdown\": false,
\"player_embed_code\": \"in_progress\",
\"player_hds_playback_url\": \"http://wowzadev-f.akamaihd.net/z/32a5814b_1#7217/manifest.f4m\",
\"player_hls_playback_url\": \"http://wowzadev-f.akamaihd.net/i/32a5814b_1#7217/master.m3u8\",
\"hosted_page\": true,
\"hosted_page_title\": \"MyLiveStream\",
\"hosted_page_url\": \"in_progress\",
\"hosted_page_sharing_icons\": true
}
}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-type:application/json; charset=utf-8',
'wsc-api-key: '.$cloudApiKey,
'wsc-access-key: '.$cloudApiAccessKey,
);
$contents = curl_exec($ch);
curl_close($ch);
This is obtained from the examples page and modified to fit into a PHP related request.
Thanks,
Matt

PHP cURL: how to set body to binary data?

I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?
The command line equivalent of what I'm trying to achieve is:
curl --request POST --data-binary "#myimage.jpg" https://myapiurl
You can just set your body in CURLOPT_POSTFIELDS.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Taken from here
Of course, set your own header type, and just do file_get_contents('/path/to/file') for body.
This can be done through CURLFile instance:
$uploadFilePath = __DIR__ . '/resource/file.txt';
if (!file_exists($uploadFilePath)) {
throw new Exception('File not found: ' . $uploadFilePath);
}
$uploadFileMimeType = mime_content_type($uploadFilePath);
$uploadFilePostKey = 'file';
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify array of form fields
*/
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
],
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
See - https://github.com/andriichuk/php-curl-cookbook#upload-file
to set body to binary data and upload without multipart/form-data, the key is to cheat curl, first we tell him to PUT, then to POST:
<?php
$file_local_full = '/tmp/foobar.png';
$content_type = mime_content_type($file_local_full);
$headers = array(
"Content-Type: $content_type", // or whatever you want
);
$filesize = filesize($file_local_full);
$stream = fopen($file_local_full, 'r');
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_INFILE => $stream,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
fclose($stream);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
credits: How to POST a large amount of data within PHP curl without memory overhead?
Try this:
$postfields = array(
'upload_file' => '#'.$tmpFile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
Below solution worked fine for me.
$ch = curl_init();
$post_url = "https://api_url/"
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$post = array(
'file' => '#' .realpath('PATH_TO_DOWNLOADED_ZIP_FILE')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Authorization: Bearer YOUR_ACCESS_TOKEN';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
refered: curl to php-curl
You need to provide appropriate header to send a POST with the binary data.
$header = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_POSTFIELDS, $arr_containing_file);
Your $arr_containing_file can for example contain file as expected (I mean, you need to provide appropriate expected field by the API service).
$arr_containing_file = array('datafile' => '#inputfile.ext');

Curl POST attachment

I need to attach a pdf file form local drive and post it to the API using PHP CURL.
Here is the RingCentral FaxOut API Documentation
$url = "https://service.ringcentral.com/faxapi.asp";
$data = array(
'Username' => 'XXXXXXXXX',
'Password' => 'XXXXXXXXX',
'Recipient' => 'XXXXXXXXXX|Navneet',
'Coverpage' => 'Default',
'Coverpagetext' => 'Testing Faxout API ',
'Resolution' => 'High',
"Sendtime" => date('d:m:y H:i:s'),
'Attachment' => file_get_contents(PATH_TO_FILE)
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
API do not return anything in response. I think, I'm not sending the attachment properly. The attachment should be in binary stream. I tried base64_encode but no success.
As given in the Request body example, header for attachment should be like this
Content-Disposition: form-data; name="Attachment"; filename="C:\example.doc"
<Document content is here>
-----------------------------7d54b1fee05aa
You can POST anything to the api with CURL, $doc in my example is anything you want to post , it can be a json_encoded file , a base64_encoded image or pdf or anything else.
$baseUri = https://service.ringcentral.com/faxapi.asp;
$doc = file_get_contents(PATH_TO_FILE);
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $baseUri);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ci, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ci, CURLOPT_POSTFIELDS, $doc);
// also you can specify any specific header like this :
$h1['Content-Disposition'] = 'Content-Disposition'. ': ' . 'form-data'; // headers are key-value pairs right ?
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h1)); // you can use this line for each header as a new key-value pair
$h2['name'] = 'name'. ': ' . 'Attachment';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h2));
$h3['filename'] = 'filename'. ': ' . 'C:\example.doc';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h3));
$response = curl_exec($ci);
**NOTE ** : its a good Idea to first of all check to see if your file_get_contents function works :
so in another php file check to see this :
echo file_get_contents(PATH_TO_FILE);
See if it echoes correctly
This is the function and how I generated the info for the request
function send_curl_request_with_attachment($method, $headers, $url, $post_fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if($headers != "" && count($headers) > 0){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec($ch);
curl_close($ch);
return $result;}
$token_slams = "Authorization: Bearer " . $access_token;
$authHeader = array(
$token_slams,
'Accept: application/form-data');
$schedule_path ='../../documents/' . $docs_record["document"];
$cFile = curl_file_create($schedule_path);
$post = array(
'old_record' => $old_record,
'employer_number' => $employer_number,
'payment_date' => $payment_date,
'fund_year' => $fund_year,
'fund_month' => $fund_month,
'employer_schedule'=> $cFile
);
send_curl_request_with_attachment("POST", $authHeader, $my_url, $post);

Categories