Can anybody help me to rewrite the following request in curl or anything similar which is available in php 5.6? I'm new with http request in PHP and I'm not able to use the HttpRequest class cause it can't be found on the server. Other suggestions are welcome too. Maybe there is already a library?
$path = "content/images/calendarmotiv/";
$fail = true;
$tmp = $_FILES['imagetarget']['tmp_name'];
$name = basename($_FILES['imagetarget']['name']);
if(move_uploaded_file($tmp, $path.$name))
{
// http request body
$now = new DateTime('NOW');
$body = json_encode(array(
"name" => $name,
"width" => 1024.0,
"image_url" => base64_encode($path.$name),
"active_flag" => 1,
"application_metadata_url" => base64_encode($_POST["metadata"]))
);
$http_verb = "POST";
$content_md5 = md5($body);
$content_type = "application/json";
$date = str_replace("+0000", "GMT", $now->format(DateTime::RFC1123));
$request_path = "<a href='https://vws.vuforia.com/targets'> https://vws.vuforia.com/targets</a>";
// auth string for header
$string_to_sign = $http_verb . "\n" . $content_md5 . "\n" . $content_type . "\n" . $date . "\n" . $request_path;
$secret_key = "mykey";
$signature = hash_hmac("sha1", $string_to_sign, $secret_key);
$authstring = "VWS " . $secret_key . ":" . $signature;
// the request
$request = new HttpRequest($request_path, HttpRequest::METH_POST);
$request->setContentType($content_type);
$request->setBody($body);
$request->addHeaders(array(
"Date" => $date,
"Authorization" => $authstring));
$request->send();
echo $request->getRequestMessage();
echo $request->getResponseMessage();
}
I've created a Vuforia client class in PHP for basic operations with Vuforia target database:
https://github.com/FionNoir/VuforiaClient
Related
So, I had issue because I don't have OAuth 1, so to access to ETSY API I had to struggle.
finally I have this :
My function __construct() :
parent::__construct();
$this->allowForUser();
$this->etsyDb = new EtsyordersModel;
$this->client = new Etsy([
'identifier' => getApp()->getConfig('identifier'),
'secret' => getApp()->getConfig('secret'),
'scope' => 'listings_r transactions_r',
'callback_uri' => 'http://*****-*****.loc/etsyapp/next',
'access_token' => getApp()->getConfig('access_token'),
'access_token_secret' => getApp()->getConfig('access_token_secret'),
]);
And here is how I get the url to access my JSON with the result :
$key = rawurlencode($oauthtoken) . "&" . rawurlencode($tokensecret);
$method = "GET";
$baseurl = "https://openapi.etsy.com/v2/shops/24749672/receipts/";
$nonce = "1234";
$timenow = time();
$oauthversion = '1.0';
$paramstring = "oauth_consumer_key=" . $oauthconsumerkey . "&oauth_nonce=" . $nonce . "&oauth_signature_method=HMAC-SHA1" . "&oauth_timestamp=" . $timenow . "&oauth_token=" . $clientsecret . "&oauth_version=" . $oauthversion;
//
// Signature GET to retrieve signature OAuth
$encodeurl = $method . "&" . rawurlencode($baseurl) . "&" . rawurlencode($paramstring);
$signature = hash_hmac( 'sha1', $encodeurl, $key, TRUE );
$signature = base64_encode( $signature );
// url JSON shop ETSY
$curlurl = $baseurl . "?" . $paramstring . "&oauth_signature=" . $signature;
// get JSON content in $orders
$orders = file_get_contents($curlurl);
And so I get my JSON :
I got 90++ items, but because of the pagination, it show me only 25 items.
I tried to add active?limit=100&offset=0 to my $baseurl (at the end of it, as parameter for signature calculation) but it say oauth_problem=signature_invalid&. I tried to put it on the $paramstring
instead, but same result.
How can I have all my result shown, or how can I access to page 2, 3, etc... of the pagination?
I am on PHP 7.4, XAMPP (one of the last version), I don't have OAuth 1 so I used a combination of package Y0lk\OAuth1 and thephpleague\oauth1-client.
Thank you for your time.
I'm using this class to generate a direct upload form which includes the policy part.
https://designedbyaturtle.com/direct-upload-to-s3-using-aws-signature-v4-php/
The uploads are working but I want to be able to display the file from the url for users on the site without making the files public.
I understand the SDK has a simple method for this but I am hoping I can do it with the existing code as this already creates the policy. I'm wondering what are hte steps for creating this url from scratch? It seems excessive to include the entire bloated SDK for just one function.
I solved it by using these two classes and modifying them a bit to make a class with two functions geturl and getform instead of using the API, these work great for v4 signatures.
getform:
https://www.designedbyaturtle.co.uk/2015/direct-upload-to-s3-using-aws-signature-v4-php/
geturl:
https://gist.github.com/anthonyeden/4448695ad531016ec12bcdacc9d91cb8
Creating an S3 pre-signed URL is actually very easy for GET requests. PUT is fairly easy, but POST is complicated and requires a policy.
The challenge is creating the signing code. Amazon supports two versions v2 and v4. v2 is being phased out. v4 is somewhat complicated to code.
If you are only creating pre-signed URLs for GET requests, write your own code. For anything else, I seriously recommend using the SDK.
Below is a link to the source code to pre-sign an S3 URL using S3V4 using PHP without the AWS SDK.
S3LINK-V4.PHP
I wrote a function in php using #xmxmxmx answer and it is working fine with me
function AWS_S3_PresignDownload($AWSAccessKeyId, $AWSSecretAccessKey, $BucketName, $AWSRegion, $canonical_uri, $expires = 8400)
{
$encoded_uri = str_replace('%2F', '/', rawurlencode($canonical_uri));
// Specify the hostname for the S3 endpoint
if ($AWSRegion == 'us-east-1') {
$hostname = trim($BucketName . ".s3.amazonaws.com");
$header_string = "host:" . $hostname . "\n";
$signed_headers_string = "host";
} else {
$hostname = trim($BucketName . ".s3-" . $AWSRegion . ".amazonaws.com");
$header_string = "host:" . $hostname . "\n";
$signed_headers_string = "host";
}
$currentTime = time();
$date_text = gmdate('Ymd', $currentTime);
$time_text = $date_text . 'T' . gmdate('His', $currentTime) . 'Z';
$algorithm = 'AWS4-HMAC-SHA256';
$scope = $date_text . "/" . $AWSRegion . "/s3/aws4_request";
$x_amz_params = array(
'X-Amz-Algorithm' => $algorithm,
'X-Amz-Credential' => $AWSAccessKeyId . '/' . $scope,
'X-Amz-Date' => $time_text,
'X-Amz-SignedHeaders' => $signed_headers_string
);
// 'Expires' is the number of seconds until the request becomes invalid
$x_amz_params['X-Amz-Expires'] = $expires + 30; // 30seocnds are less
ksort($x_amz_params);
$query_string = "";
foreach ($x_amz_params as $key => $value) {
$query_string .= rawurlencode($key) . '=' . rawurlencode($value) . "&";
}
$query_string = substr($query_string, 0, -1);
$canonical_request = "GET\n" . $encoded_uri . "\n" . $query_string . "\n" . $header_string . "\n" . $signed_headers_string . "\nUNSIGNED-PAYLOAD";
$string_to_sign = $algorithm . "\n" . $time_text . "\n" . $scope . "\n" . hash('sha256', $canonical_request, false);
$signing_key = hash_hmac('sha256', 'aws4_request', hash_hmac('sha256', 's3', hash_hmac('sha256', $AWSRegion, hash_hmac('sha256', $date_text, 'AWS4' . $AWSSecretAccessKey, true), true), true), true);
$signature = hash_hmac('sha256', $string_to_sign, $signing_key);
return 'https://' . $hostname . $encoded_uri . '?' . $query_string . '&X-Amz-Signature=' . $signature;
}
Call it using
echo AWS_S3_PresignDownload('accessId', 'seceret', 's3BucketName', 'reGion', '/fileKey.ext', 60);
I try to use an API for sending sms. I've followed the code from this example, but converted to Guzzle:
Implementation example in PHP for POST Rest Request
<?php
…....
try
{
//POST
$httpClient = new Zend_Http_Client();
$httpClient->setUri("http://www.web2sms.ro/prepaid/message");
$httpClient->setMethod(Zend_Http_Client::POST);
$httpClient->setHeaders("Content-Type", "application/json");
//method param
$crtDate = new Zend_Date();
$apiKey = ""; //value provided
$nonce = $crtDate->get(Zend_Date::TIMESTAMP);
$method = "POST";
$url = "/prepaid/message";
$sender = "";
$recipient = "07xxxxxxxx";//To be fill in !
$message = "";
$visibleMessage = "How the message do you want to appear on the interface. If empty string than $message value will be shown";
$scheduleDate = ''; //Format yyyy-MM-dd HH:mm:ss
$validityDate = ''; //Format yyyy-MM-dd HH:mm:ss
$callbackUrl = '';
$secret = ""; // value provided
$string = $apiKey . $nonce . $method . $url . $sender . $recipient . $message . $visibleMessage . $scheduleDate . $validityDate . $callbackUrl . $secret;
$signature = hash('sha512', $string);
$httpClient->setAuth($apiKey, $signature);
$data = array(
"apiKey" => $apiKey,
"sender" => $sender,
"recipient" => $recipient,
message" => $message,
"scheduleDatetime" => $scheduleDate,
"validityDatetime" => $validityDate,
"callbackUrl" => $callbackUrl,
"userData" => "",
"visibleMessage" => $visibleMessage,
"nonce" => $nonce);
$httpClient->setRawData(Zend_Json::encode($data));
$httpResponse = $httpClient->request();
var_dump($httpResponse);
var_dump($httpResponse->getBody());
var_dump(json_decode($httpResponse->getBody()));
}
catch (Zend_Http_Client_Exception $e)
{
//
}
My Code with Guzzle:
$apiKey = "xxxxxxxxx";
$nonce = time();
$method = "POST";
$url = "http://www.web2sms.ro/prepaid/message";
$sender = "XXXXXXXX";
$recipient = "0768814244";
$message = "Un mesaj";
$visibleMessage = "How the message do you want to appear on the interface. If empty string than value will be shown";
$secret = "xxxxxxxxxx";
$string = $apiKey . $nonce . $method . $url . $sender . $recipient . $message . $visibleMessage . $secret;
$signature = hash('sha512', $string);
$client = new GuzzleHttp\Client([
'headers' => ['Content-Type' => 'application/json']
]);
$data = array(
"apiKey" => $apiKey,
"sender" => $sender,
"recipient" => $recipient,
"message" => $message,
"visibleMessage" => $visibleMessage,
"nonce" => $nonce);
$body = GuzzleHttp\json_encode($data);
$request = $client->request('POST', 'http://www.web2sms.ro/prepaid/message', ['auth' => [$apiKey, $signature], 'body' => $body]);
But still not working;
I receive this error:
Client error: `POST http://www.web2sms.ro/prepaid/message` resulted in a `401 Unauthorized` response:
{"error":{"code":268435459,"message":"IDS_App_Controller_Rest_Message__E_INVALID_REQUEST_DATA_WRONG_SIGNATURE"}}
What I am getting wrong??
I was able to solve it by changing $url to /prepaid/message.
I'm trying to rewrite an fopen() POST request to work with a proxy.
The code is based on an example on the Paypal site (https://www.x.com/developers/PayPal/documentation-tools/code-sample/216632).
My default workarounds for fopen() as well as for file_get_contents() and cURL lib don't work for the relatively complex post header and contents. (Either fail to go through proxy or get Invalid request: {0}, even when no proxy is set)
Here's the (simplified) post example code:
$url = trim('https://svcs.sandbox.paypal.com/AdaptiveAccounts/AddBankAccount');
$API_UserName = "sbapi_1287090601_biz_api1.paypal.com"; //TODO
$API_Password = "1287090610"; //TODO
$API_Signature = "ANFgtzcGWolmjcm5vfrf07xVQ6B9AsoDvVryVxEQqezY85hChCfdBMvY"; //TODO
$API_SANDBOX_EMAIL_ADDRESS = "rishaque#paypal.com"; //TODO
$API_DEVICE_IPADDRESS = "127.0.0.1"; //TODO
$API_AppID = "APP-80W284485P519543T";
$API_RequestFormat = "XML";
$API_ResponseFormat = "XML";
$xml = simplexml_load_string($xml_str);
$contents = $xml->asXML();
try
{
$params = array("http" => array(
"method" => 'POST',
"content" => $contents,
'header' => 'X-PAYPAL-SECURITY-USERID: ' . $API_UserName ."\r\n" .
'X-PAYPAL-SECURITY-PASSWORD: ' . $API_Password . "\r\n" .
'X-PAYPAL-SECURITY-SIGNATURE: ' . $API_Signature . "\r\n" .
'X-PAYPAL-REQUEST-DATA-FORMAT: ' . $API_RequestFormat . "\r\n" .
'X-PAYPAL-RESPONSE-DATA-FORMAT: ' . $API_ResponseFormat . "\r\n" .
'X-PAYPAL-APPLICATION-ID: ' . $API_AppID . "\r\n" .
'X-PAYPAL-SANDBOX-EMAIL-ADDRESS: ' . $API_SANDBOX_EMAIL_ADDRESS . "\r\n" .
'X-PAYPAL-DEVICE-IPADDRESS: ' . $API_DEVICE_IPADDRESS . "\r\n" ));
$ctx = stream_context_create($params);
$fp = #fopen($url, 'r', false, $ctx); // PROXIFY!
$response = stream_get_contents($fp);
if ($response === false) {
throw new Exception("php error message = " . "$php_errormsg");
}
fclose($fp);
// ... handle the response content ...
}
catch(Exception $e)
{
echo 'Message: ||' .$e->getMessage().'||';
}
?>
My proxy file_get_contents():
if (!empty($_context_params)) {
$http_arr = $_context_params['http'];
$http_arr['proxy'] = $proxy_path;
$http_arr['request_fulluri'] = true;
$_context_params['http'] = $http_arr;
}
else
{
$_context_params = array( 'http' => array( 'proxy' => $proxy_path, 'request_fulluri' => true ) );
}
return file_get_contents( $_url, false, stream_context_create( $_context_params ) );
My proxied fopen:
$parsed_proxy_path = parse_url($proxy_path);
$_proxy_name = $parsed_proxy_path['host'];
$_proxy_port = $parsed_proxy_path['port'];
$proxy_fp = fsockopen( $_proxy_name, $_proxy_port );
if ( !$proxy_fp )
return false;
$parsed_url = parse_url($_url);
$host = $parsed_url['host'];
$request = "GET $_url HTTP/1.0\r\nHost:$host\r\n\r\n";
fputs( $proxy_fp, $request );
return $proxy_fp;
My cURL experiment: (CodeIgniter curl lib takes care of proxy for me)
$http_params = $params['http'];
$this->curl->create($this->cfg->paypal_req_url);
$this->curl->option('header', true);$this->curl->option('verbose', true);
$this->curl->option('useragent', 'cURL/PHP');
$this->curl->http_header($http_params['header']);
$this->curl->http_header("Content-length: ".strlen($contents));
$this->curl->post(array("content"=> $contents));
$res = $this->curl->execute();
Any ideas where to go from here? I'm a bit stuck..
How do I debug the request going out from cURL? Is the request even reproducible with cURL?
Will it work with GET instead of POST?
Is XMLRPC an option?
Note: The example code works for me when not behind a proxy.
Thanks in advance,
Alex
Here's the code I used to get it to work with cURL.
Note: It uses the codeigniter cURL lib by Phil Sturgeon.
Note: I resolved to switching from XML to query string for the contents.
$contents = array(
"actionType"=>"PAY",
"cancelUrl"=>$cancel_url,
"returnUrl"=>$return_url,
"currencyCode"=>$currency,
"sender"=>$sendingmail,
"memo"=>$memo,
"requestEnvelope.errorLanguage"=>$error_lang,
"receiverList.receiver.amount"=>$amount,
"receiverList.receiver.email"=>$receivingmail,
);
if (isset($notification_url)) { $contents["ipnNotificationUrl"]=$notification_url; }
if ($receivingmail == $this->cfg->paypal_email) { $contents["feesPayer"]="SENDER"; }
if ($sendingmail == $this->cfg->paypal_email) { $contents["senderEmail"]=$sendingmail; }
// ------------------------------
// create request and add headers
// ------------------------------
$options = array( "useragent" => "cURL/PHP" );
$this->curl->create($this->cfg->paypal_req_url);
$this->curl->http_header("Content-type", "application/x-www-form-urlencoded");
$this->curl->http_header("X-PAYPAL-SECURITY-USERID", $this->cfg->paypal_user_name);
$this->curl->http_header("X-PAYPAL-SECURITY-SIGNATURE", $this->cfg->paypal_signature);
$this->curl->http_header("X-PAYPAL-SECURITY-PASSWORD", $this->cfg->paypal_password);
$this->curl->http_header("X-PAYPAL-APPLICATION-ID", $this->cfg->paypal_app_id);
$this->curl->http_header("X-PAYPAL-REQUEST-DATA-FORMAT", "NV");
$this->curl->http_header("X-PAYPAL-RESPONSE-DATA-FORMAT", "XML");
$this->curl->post($contents, $options);
$response = $this->curl->execute();
For those stuck with PHP4 it might be useful answering the original question of getting it to work through proxy with fopen?
Cheers,
Alex
I am able to get access_token for multiple permissions like emails, contacts, docs, etc. using oAuth 2.0. I have access_token
I got contacts using the following code.
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max- results='.$max_results.'&oauth_token='.$access_token;
$response_contacts= curl_get_file_contents($url);
Now i want to get users Emails using this access_token.
i used this url . but it gives 401 unauthorized Error
$url = 'https://mail.google.com/mail/feed/atom&oauth_token='.$access_token;
$response_emails= curl_get_file_contents($url);
please guide me how can i get emails using access_token.
I've seen references to the Gmail feed using oauth_token as a request parameter. However, once I used the OAuth Playground I discovered that you need to pass your OAuth information as an Authorization header, as you'll see below.
<?php
$now = time();
$consumer = ...; // your own value here
$secret = ...; // your own value here
$nonce = ...; // same value you've been using
$algo = "sha1";
$sigmeth = "HMAC-SHA1";
$av = "1.0";
$scope = "https://mail.google.com/mail/feed/atom";
$path = $scope;
$auth = ...; // an object containing outputs of OAuthGetAccessToken
$args = "oauth_consumer_key=" . urlencode($consumer) .
"&oauth_nonce=" . urlencode($nonce) .
"&oauth_signature_method=" . urlencode($sigmeth) .
"&oauth_timestamp=" . urlencode($now) .
"&oauth_token=" . urlencode($auth->oauth_token) .
"&oauth_version=" . urlencode($av);
$base = "GET&" . urlencode($path) . "&" . urlencode($args);
$sig = base64_encode(hash_hmac($algo, $base,
"{$secret}&{$auth->oauth_token_secret}", true));
$url = $path . "?oauth_signature=" . urlencode($sig) . "&" . $args;
// Create a stream
$opts = array(
"http" => array(
"method" => "GET",
"header" => "Authorization: OAuth " .
"oauth_version=\"{$av}\", " .
"oauth_nonce=\"{$nonce}\", " .
"oauth_timestamp=\"{$now}\", " .
"oauth_consumer_key=\"{$consumer}\", " .
"oauth_token=\"{$auth->oauth_token}\", " .
"oauth_signature_method=\"{$sigmeth}\", " .
"oauth_signature=\"{$sig}\"\r\n"
)
);
$context = stream_context_create($opts);
$out = file_get_contents($path, false, $context);
?>