I want to achieve this workflow from my server, using PHP and a service account. Basically, I just want to generate a resume URI on my server, send it on my client and do the upload from my client. But the PHP SDK doesn't provide a method to do this !
I do not want to use Signed URL, as they do not allow me to control the file being uploaded. I just want to make a simple POST, like described in the page I linked, using the credentials (the Bearer token) loaded by the PHP SDK.
Is there anyway to do this without re-coding the entire auth part ?
Do you want to reproduce the steps provided in [1] to save the resumable session URI using PHP?
If this is the case, I can think on that you may build a simple PHP POST request using the file_get_contents() function (use http_build_query() function [2] to generate a URL-encoded query string to specify POST variables).
For example, for a resumable session (as shown in the documentaion [1]):
POST https://www.googleapis.com/upload/storage/v1/b/myBucket/o?uploadType=resumable HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: image/jpeg
X-Upload-Content-Length: 2000000
{
"name": "myObject"
}
You may try a PHP script for making this POST request. A possible option for a PHP script would be similar to this:
<?php
$post = http_build_query(array('name'=>'myObject')); // POST variable "name"
// Create the HTTP Headers
$headers = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/json\r\n"."charset=UTF-8\r\n"."X-Upload-Content-Type: image/jpeg\r\n"."X-Upload-Content-Length: 2000000\r\n",
'content' => $post
)
);
$s_context = stream_context_create($headers);
$uri = file_get_contents('https://www.googleapis.com/upload/storage/v1/b/myBucket/o?uploadType=resumable', false, $s_context);
?>
Could you try this PHP script and post your results?
[1] https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload
[2] http://php.net/manual/en/function.http-build-query.php
Related
I have an Ers 1000 with cloud plan from Sony and i am trying to setup ENDPOINT on the sony site in order to use some features. I am using a PHP server than run fine, but no way to get the endpoint validation on site website. I used a php page to get the "challenge" value, and i send it back to body using php "echo", this works fine with postman but no way on sony site. I noticed the way they post the challenge is harder that common post so i used
$source1 = json_decode(file_get_contents("php://input"));
And I finished with a page showing the body like a json :
$post = json_decode(file_get_contents('php://input'), true);
echo($post);
this give {"challenge":"1324111"}
on sony I enter this url : https://xxxserver.com/aibo/ where index.php have the code
any idea on how to implement this API endpoint? as sony error don't give details on what is wrong. thanks!
here are few points allowing me to do it :
header('Content-type: text/plain; charset=utf-8');
in an if loop :
http_response_code(200);
this line is important to read the data sent to body by sony :
$source1 = array();
$source1 = json_decode(file_get_contents("php://input"),true);
not gone deep with this one but it's the idea for the security key
$headers = apache_request_headers();
$token = $headers['X-Security-Token'];
about data sent back as json i use smary but the result will be like a blank page with only :
{ "challenge":"thesourcechallengekey"}
got from :
$source1['challenge'];
Note : i also noticed that .htaccess file could add too many restrictions, it was not origin of my issue but if i enable extra settings and controls to my php.ini it often block the Endpoint check, so try first removing all settings that are not mandatory in order to test the Endpoint.
About sending back the actions to aibo curl in PHP works fine, here is a small basic sample :
$post_url = 'https://public.api.aibo.com/v1/devices';
$data = '{}' ;
$postData = array();
header('Content-Type: application/json'); // Specify the type of data
// Setup cURL
$ch = curl_init($post_url);
curl_setopt_array($ch, array(
CURLOPT_SSL_VERIFYPEER => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$bearer)
));
Where $bearer = "Bearer yourbearercodehere";
And you have to edit the first URL to add sony API endpoint action link
I have been given a URL that I need PHP to post data to, anonymously, without the end user knowing about it.
The exact structure is:
https://example.com/api/rest/example/createSubscription?email=1#1.com&subscriberNumber=12345JD&subscriberGroup=shop&firstName=Joe&lastName=Bloggs&offerCode=ex1&licenseParameters="STARTDATE%3D2014-08-11%26ENDDATE%3D2014-09-11"
Obviously this is a dynamic URL and I have set it up to be. I am not sure about the best way to approach this issue. Would it be a PUT http_request? I have tried that using the following but it returns a 400 error.
$url = 'https://example.com/api/rest/example/createSubscription?email=1#1.com&subscriberNumber=12345JD&subscriberGroup=shop&firstName=Joe&lastName=Bloggs&offerCode=ex1&licenseParameters="STARTDATE%3D2014-08-11%26ENDDATE%3D2014-09-11"';
$options = array(
'method' => 'PUT',
'timeout' => 15,
'header' => "Content-type: html/txt",
);
$response = http_request($url, $options);
As for your last comment, if the subscription is created simply opening the url in the browser then it is a GET request.
You can perform a GET request using file_get_contents
It's really strange you use PUT method with GET paramater.
After checking php manual here you don't use correctly this methode. that's why the server can't understand your request.
you can look after this function to do a PUT request
I am working with a third party service that requires me to authenticate through OAuth1 to make requests. I can successfully authenticate and get data back with most of their calls using GET, however some calls they require POST and this is where the problem lies. To authenticate I am using the below:
$oauth = new OAuth(MY_KEY,MY_SECRET);
$oauth->setNonce(rand());
$oauth->setToken('','');
Then for a GET call I am doing something like below:
$array = array(
'partnerId'=>'1234'
);
$call = $oauth->fetch("https://domain.co.uk/api/getInfo/",$array);
$data = $oauth->getLastResponse();
This all works perfectly, and I can print out the $data
However with POST calls:
$oauth = new OAuth(MY_KEY,MY_SECRET);
$oauth->setNonce(rand());
$oauth->setToken('','');
$oauth->enableDebug();
$oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
$array = array(
'rid' => "$restaurantId",
'datetime' => "$datetime",
'partysize' => $covers,
'timesecurityID' => "$securityId",
'resultskey' => "$resultskey"
);
$call = $oauth->fetch("https://domain.co.uk/api/booking/?pid=1234&st=0",$array,OAUTH_HTTP_METHOD_POST);
$data = $oauth->getLastResponse();
I keep getting the error: Invalid Consumer Signature
Speaking to their tech guy he suggested
Your sbs value indicates that you’re signing with all of the POST
parameters, whereas you only need to sign with the query string. In
this case it would be “pid=1234&st=0”. Unfortunately, I’m not
familiar with the PHP libs and don’t have any recommendations on how
to alter the behavior.
and also mentioned common previous problems with a PHP implementation are:
The PHP HTTP lib will drop the query string once the method is
changed from GET to POST.
The PHP oAuth lib will use the post data
to sign the request rather than the query string or maybe both.
If I dump out the headers I get:
[sbs] => POST&https%3A%2F%2Fdomain.co.uk%2Fapi%2Fbooking%2F&datetime%3D2013-02-21T10%253A30%253A00%26oauth_consumer_key%3DMySiteV3TT%26oauth_nonce%3D1213111151%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1360835965%26oauth_token%3D%26oauth_version%3D1.0%26partysize%3D2%26pid%3D1531%26resultskey%3DfoqgEnYK%25252bIzRd6BV3T8eGQ%25253d%25253d%26rid%3D31852%26st%3D0%26timesecurityID%3D349367809
[headers_sent] => POST /api/booking/?pid=1234&st=0 HTTP/1.1
It looks like it is sending the OAuth data with the rest of the post, I just want this sent in the Authorization header (which it is also sending)
Authorization: OAuth oauth_consumer_key="MySite",oauth_signature_method="HMAC-SHA1",oauth_nonce="1772854358",oauth_timestamp="1360768712",oauth_version="1.0",oauth_token="",oauth_signature="2%2B7xb%2BJ5cdbUDC5UHfsdfsNpFM1pE%3D"
So I think I need to strip the OAuth data from the post request but keep it as a Authorization Header but just can't find the magic way to do that!
I've seen this. In fetch(), try urlencoding your $array and passing it in as a string of the form:
rid=[restaurantId]&datetime=[datetime]&...
Also give the header (final parameter of fetch()):
Content-Type: application/x-www-form-urlencoded
I have a basic API endpoint set up on my site, which a 3rd party site will use to verify certain info that is entered into a form by the user.
Here's the flow:
1. User is on 3rd party site.
2. User enters info into a form
3. Info is sent to my site's endpoint.
4. My site checks the information and returns a JSON object.
As you can see from #4, my API is currently set up to return a JSON object. After the info is checked, something like this happens:
header('content-type: application/json; charset=utf-8');
echo json_encode($response);
exit;
However, the 3rd party site is only set up to receive URL variables. Is there a way to pass back url variables programmatically? I realize I could theoretically send a new request, but it's not clear to me where that request should go (the internal workings of the 3rd party site aren't well documented), so I'd much prefer to send it as a response.
I hope this makes sense. Please comment if it doesn't. Thanks in advance!
You don't get to send GET/POST parameters in the response, but in the response body you can send whatever you want in whatever format you want - and they can use curl or file_get_content and parse it on their side (3rd party's website).
For example (on the 3rd party's website):
//setting a call to your server
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $body,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$url = 'https://'.$https_server;
// Here they call your server
$result = file_get_contents($url, false, $context, -1, 40000);
// Here you'll parse the $result
I'm trying to use a web service REST API for which I need to add a parameter for authorization (with the appropriate key, of course) to get a XML result. I'm developing in PHP. How can I add a parameter to the request header in such a situation?
Edit: The way I'm doing the request right now is $xml = simplexml_load_file($query_string);
Are you using curl? (recommended)
I assume that you are using curl to do these requests towards the REST API, if you aren't; use it.
When using curl you can add a custom header by calling curl_setopt with the appropriate parameters, such as in below.
curl_setopt (
$curl_handle, CURLOPT_HTTPHEADER,
array ('Authentication-Key: foobar')
); // make curl send a HTTP header named 'Authentication-key'
// with the value 'foobar'
Documentation:
PHP: cURL - Manual
PHP: curl_setopt - Manual
Are you using file_get_contents or similar?
This method is not recommended, though it is functional.
Note: allow_url_fopen needs to be enabled for file_get_contents to be able to access resources over HTTP.
If you'd like to add a custom header to such request you'll need to create yourself a valid stream context, as in the below snippet:
$context_options = array(
'http' =>array (
'method' => 'GET',
'header' => 'Authentication-Key'
)
);
$context = stream_context_create ($context_options);
$response = file_get_contents (
'http://www.stackoverflow.com', false, $context_options
);
Documentation:
PHP: file_get_contents - Manual
PHP: stream_context_create - Manual
PHP: Runtime Configuration, allow_url_fopen
I'm using neither of the above solutions, what should I do?
[Post OP EDIT]
My recommendation is to fetch the data using curl and then pass it off to the parser in question when all the data is received. Separate data fetching from the processing of the returned data.
[/Post OP EDIT]
When you use $xml = simplexml_load_file($query_string);, the PHP interpreter invokes it's wrapper over fopen to open the contents of a file located at $query_string. If $query_string is a remote file, the PHP interpreter opens a stream to that remote URL and retrieves the contents of the file there (if the HTTP response code 200 OK). It uses the default stream context to do that.
There is a way to alter the headers sent by altering that stream context, however, in most cases, this is a bad idea. You're relying on PHP to always open all files, local or remote, using a function that was meant to take a local file name only. Not only is it a security problem but it also could be the source of a bug that is very hard to track down.
Instead, consider splitting the loading of the remote content using cURL (checking the returned HTTP status code and other sanity checks) and then parsing that content into a SimpleXMLElement object to use. When you use cURL, you can set any headers you want to send with the request by invoking something similar to curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName' => 'value');
Hope this helps.