I am trying to connect to Windows Azure REST API, but always get issue like this:
The MAC signature found in the HTTP request '...' is not the same as any computed signature.
I can't get correct signature. I also tried on Objective-C and with different methods of Windows Azure REST API, but always get the same error. There are full listing on PHP:
function send_request($url, $headers)
{
if ($curl = curl_init())
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
return curl_exec($curl);
curl_close($curl);
}
return false;
}
function encode_string_to_sign($string_to_sign, $key)
{
$hash = hash_hmac("sha256", $string_to_sign, $key, true);
$signature = base64_encode($hash);
return $signature;
}
header("Content-Type: application/xhtml+xml");
// GET Container Metadata
$url = "http://snip.blob.core.windows.net/elements?restype=container&comp=metadata";
$access_key_1 = "...";
$access_key_2 = "...";
$current_date = "Thu, 28 Feb 2013 21:10:00 GMT";
$canonicalized_headers = "x-ms-date:$current_date\nx-ms-version:2009-09-19";
$canonicalized_resource = "/snip/elements\ncomp:metadata\nrestype:container";
$string_to_sign = "GET\n\n\n\n\n\n\n\n\n\n\n\n" . $canonicalized_headers . "\n" . $canonicalized_resource;
$signature = utf8_encode(encode_string_to_sign($string_to_sign, $access_key_1));
$headers = array("Authorization: SharedKey snip:" . $signature, "x-ms-date: " . $current_date, "x-ms-version: 2009-09-19");
echo send_request($url, $headers);
?>
If you are using PHP, why not using Windows Azure PHP SDK to do it? https://github.com/WindowsAzure/azure-sdk-for-php
which had been well tested against real server.
Related
I'm using coinbase pro API to fetch some data and to make some trades but API is returning
{"message":"IP does not match IP whitelist"}
I'm using Rest API with correct API keys. I'm sure API keys are authenticated correctly and while creating API keys, I've entered correct IP address of my server. I rechecked IP 5 times but it's correct. Below is my sample code
<?php
function signature($request_path='', $body='', $timestamp=false, $secret = '', $method='GET') {
$body = is_array($body) ? json_encode($body) : $body;
$timestamp = $timestamp ? $timestamp : time();
$what = $timestamp.$method.$request_path.$body;
return base64_encode(hash_hmac("sha256", $what, base64_decode($secret), true));
}
function make_request($url, $method, $headers, $body = ''){
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
if ($method == "POST") {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
// "accept" => "application/json"
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute
$result_json = curl_exec($ch);
curl_close($ch);
return $result_json;
}
try {
$apiurl = "https://api.pro.coinbase.com";
$secret = "SUPER_SECRET";
$api_key = "API_KEY";
$passphrase = "PASSPHRASE";
$method = "GET";
$requestPath = "/accounts";
$body = "";
$url = $apiurl . $requestPath;
$data["name"] = "";
$body = json_encode($data);
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$list = explode(" ", $user_agent);
$user_agent = $list[0];
$timestamp = (string) time();
$string = $timestamp . $method . $requestPath;
$sig = signature($requestPath, '', $timestamp, $secret);
$headers = [
"CB-ACCESS-KEY: ".$api_key,
"CB-ACCESS-SIGN: ".$sig,
"CB-ACCESS-TIMESTAMP: ".$timestamp,
"CB-ACCESS-PASSPHRASE: ".$passphrase,
"User-Agent:". $user_agent,
"Content-Type: application/json",
];
$result_json = make_request($url, $method, $headers);
var_dump($result_json);
die;
}
catch(Exception $e){
var_dump($e->getMessage());
die;
}
I've searched a lot for this problem and been struggling with it since 2 days. If anyone can help or point me in right direction? That would be highly appreciated.
Thanks & Regards.
I have rented a number through sinch.com and while I am able to successfully send an SMS to my own verified telephone number, I am unable to send SMS to various other telephone numbers.
function sendSignInText($phone_number, $first_name) {
$key = "xxxx-xxx-xxx-xxx-xxxxxxxx";
$secret = "xxxxxxxx";
$message = $first_name . ', thanks you for signing in. We will text you when we\'re ready for you';
$phone = $phone_number;
$body = json_encode(array('From' => $rented_number, 'Message'=>$message, ));
$timestamp = date("c");
$path = "/v1/sms/" . $phone;
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:" . $timestamp;
$content_md5 = base64_encode( md5( utf8_encode($body), true ));
$string_to_sign =
"POST\n".
$content_md5."\n".
$content_type."\n".
$canonicalized_headers."\n".
$path;
$signature = base64_encode(hash_hmac("sha256", utf8_encode($string_to_sign), base64_decode($secret), true));
$authorization = "Application " . $key . ":" . $signature;
$service_url = 'https://messagingapi.sinch.com'.$path;
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'content-type: '.$content_type,
'x-timestamp:' . $timestamp,
'authorization:' . $authorization
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
// #todo: checking response / working with results
curl_close($curl);
}
It could be an issue with the number transferring from a sandbox version of the app. Sinch recommends you play in a sandbox before putting it out into production. So it was working as a sandbox version with my own personal telephone number and is still working as a production app with my own number but doesn't work with other, non-verified numbers. Any help would be greatly appreciated, thanks.
I have the script below written in Ruby. I was wondering is anyone can help me convert it to PHP. I know this is a big ask. I am looking to convert the ruby script to a PHP curl request.
See the link to the documentation https://www.sinch.com/docs/rest-apis/api-documentation/#applicationsignedrequest
The first code is the SAMPLE ruby script. While the second below it is what i have attempted to write in PHP on my own. Without success because i get "Invalid signature error".
require "base64"
require "openssl"
require "time"
require "net/http"
require "uri"
require "json"
to = "+4412345678"
message = "Test sms message"
key = "wwwwwwwwwxxxxxxxx" //Key as supplied by sinch.com
secret = "zzzzzzzyyyyyyyyy" // Secret as supplied by sinch.com
body = "{\"message\":\"" + message + "\"}"
timestamp = Time.now.iso8601
http_verb = "POST"
path = "/v1/sms/" + to
scheme = "Application"
content_type = "application/json"
digest = OpenSSL::Digest.new('sha256')
canonicalized_headers = "x-timestamp:" + timestamp
content_md5 = Base64.encode64(Digest::MD5.digest(body.encode("UTF-8"))).strip
string_to_sign = http_verb + "\n" + content_md5 + "\n" + content_type + "\n" + canonicalized_headers + "\n" + path
signature = Base64.encode64(OpenSSL::HMAC.digest(digest, Base64.decode64(secret), string_to_sign.encode("UTF-8"))).strip
authorization = "Application " + key + ":" + signature
uri = URI.parse("https://messagingApi.sinch.com" + path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
headers = {"content-type" => "application/json", "x-timestamp" => timestamp, "authorization" => authorization}
request = Net::HTTP::Post.new(uri.request_uri)
request.initialize_http_header(headers)
request.body = body
puts JSON.parse(http.request(request).body)
Below is my script and i have no problem accepting an entirely new script. I am a super ruby rookie. Please help.
$to="+4412345678";
$text="Hello there test message";
$curl_post_data = array(
'Message' => $text
);
$curl_post_data=json_encode($curl_post_data);
$timestamp=date("c");
$key = "wwwwwwwwwwwxxxxxxxxxxx";
$secret = "zzzzzzzzzzzzyyyyyyyyyyy";
$http_verb="POST";
$path = "/v1/sms/".$to."";
$scheme = "Application ";
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:".$timestamp."";
$content_md5=base64_encode( md5($curl_post_data,true) );
$string_to_sign = array(
'http_verb' => $http_verb,
'content_md5' => $content_md5,
'content_type' => $content_type,
'canonicalized_headers' =>$canonicalized_headers
);
$signature = hash_hmac("sha256", $secret,json_encode($string_to_sign));
$authorization = "".$scheme."".$key.":".$signature."";
$service_url = 'https://messagingapi.sinch.com/v1/sms/'.$to.'';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8', 'x-timestamp: '.$timestamp.'','authorization: '.$authorization.''));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
?>
Any help will do please, Stackoverflow has been a useful resource whenever am stuck with something, i hope my question helps others too.
I got it to work, had to rewrite a few things. Anyway, here's a working code for anyone that might need it.
<?php
$to="+4412345678";
$text2="Test sms message from PHP";
$curl_post_data = array(
'message' => $text2
);
$timestamp=date("c");
$key = "wwwwwwwwwwwwwxxxxxxxxxxxxxxx";
$secret ="zzzzzzzzzzzzyyyyyyyyyyyyyy";
$http_verb="POST";
$path = "/v1/sms/".$to."";
$scheme = "Application";
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:".$timestamp."";
$content_md5=md5(json_encode($curl_post_data),true);
$string_to_sign ="".$http_verb."\n".$content_md5."\n".$content_type."\n".$canonicalized_headers."\n".$path."\n";
$signature = hash_hmac("sha256", base64_encode($secret),utf8_encode($string_to_sign) true);
$signature=base64_encode($signature);
$authorization = "".$scheme."".$key.":".$signature."";
$curl_post_data=json_encode($curl_post_data);
$service_url = 'https://messagingapi.sinch.com/v1/sms/'.$to.'';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8','x-timestamp:'.$timestamp.'','authorization:'.$authorization.''));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
?>
Completely working code. Also, thanks to 'Stephen' for basical porting from Ruby to PHP. It saves me a lot of time.
Some notes:
Key should be copied from apps menu of sinch account as is (without any conversion)
String to sign shouldn't contain new line at the end. Also, please check every changes by setting default values from commented code.
In the PHP hash_hmac function cody should be defined before secret (in Ruby arguments should be defined in other order)
If actual headers will contain charset definition - string_to_sign should contain it too. I have deleted them at all.
$key = 'key';
$secret = 'secret';
$message = 'your message';
$phone = '+000000000000';
$body = json_encode(array('message'=>$message));
$timestamp = date("c");
// {{{ test values for checking code (from docs)
/*
$phone="+46700000000";
$key = "5F5C418A0F914BBC8234A9BF5EDDAD97";
$secret ="JViE5vDor0Sw3WllZka15Q==";
$timestamp='2014-06-04T13:41:58Z';
$body = '{"message":"Hello world"}';
*/
// result:
// content-md5 should be 'jANzQ+rgAHyf1MWQFSwvYw=='
// signature should be 'qDXMwzfaxCRS849c/2R0hg0nphgdHciTo7OdM6MsdnM='
// }}}
$path = "/v1/sms/" . $phone;
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:" . $timestamp;
$content_md5 = base64_encode( md5( utf8_encode($body), true ));
$string_to_sign =
"POST\n".
$content_md5."\n".
$content_type."\n".
$canonicalized_headers."\n".
$path;
$signature = base64_encode(hash_hmac("sha256", utf8_encode($string_to_sign), base64_decode($secret), true));
$authorization = "Application " . $key . ":" . $signature;
$curl_post_data=json_encode($curl_post_data);
$service_url = 'https://messagingapi.sinch.com'.$path;
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'content-type: '.$content_type,
'x-timestamp:' . $timestamp,
'authorization:' . $authorization
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
// #todo: checking response / working with results
curl_close($curl);
I have little trouble when i try to use bitcoin exchange API via python.
I have example function in PHP:
function bitmarket_api($method, $params = array())
{
$key = "my_key";
$secret = "my_secret";
$params["method"] = $method;
$params["tonce"] = time();
$post = http_build_query($params, "", "&");
$sign = hash_hmac("sha512", $post, $secret);
$headers = array(
"API-Key: " . $key,
"API-Hash: " . $sign,
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://www.bitmarket.pl/api2/");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($curl);
return json_decode($ret);
}
And it is my python implementation:
def bitmarket_api(method, params):
key = 'my_key'
secret = 'my_secret'
url = 'https://www.bitmarket.pl/api2/'
params['method'] = method
params['tonce'] = timestamp()
post = urllib.urlencode(params)
sign = base64.b64encode(str(HMAC(secret, post, sha512).digest()))
headers = {}
headers['API-Key:'] = key
headers['API-Hash:'] = sign
req = urllib2.Request(url, post, headers)
res = urllib2.urlopen(req, post)
return json.load(res)
So, when i try to to invoke info method (or other method) i get 'Invalid API key' error.
I was looking for solution, and i was trying several other approach with no succes.
Can u guys help me? I think problem can be in headers...
Please excuse my poor English. I try to do my best, but I'm still making mistakes.
Use the Python HMAC Auth lib with Requests lib
https://github.com/bazaarvoice/python-hmac-auth
Nice and tidy to let your build your client without too much trouble.
I have the ZF first old function working before but somehow ZF it was failing, and then i made the unittest module.
I am trying to use the google translation v2 but it never works anymore, did Google stop there service for public use or is it PHP Bug or somewhere else confusing very much.
Always returning 403 with both following functions.
Any idea whats going wrong?
<?php
## Test: How to's
/*
$ php tst.php
403
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}sun#sun-M14xR2:/var/www/html/vooyz.com/unittest$
*/
// V1 - Old not working
function googleTranslatePostV1($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
$http_response = '';
$text = urlencode($text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1.0&q=" . $text . "&langpair=$srcLang|$destLang");
$http_response = curl_exec($ch);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Curl way not working
function googleTranslatePostV2($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'https://www.googleapis.com/language/translate/v2';
$http_response = '';
$text = urlencode($text);
$postArr = array('key' => 'sdfdsfdsfds',
'q' => $text,
'source' => $srcLang,
'target' => $destLang);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_POSTFIELDS,'hl=en&ie=UTF8&text=-->this+is+a+test<--&langpair=en%7Car');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postArr);
$http_response = curl_exec($ch);
var_dump($http_response);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Google way
function googleTranslateV2Method1($text, $destLang = 'nl', $srcLang = 'en') {
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_TranslateService.php';
$client = new Google_Client();
$client->setApplicationName('Google Translate PHP Starter Application');
$client->setDeveloperKey('dsfdsfdsf');
$service = new Google_TranslateService($client);
//$langs = $service->languages->listLanguages();
//print "<h1>Languages</h1><pre>" . print_r($langs, true) . "</pre>";
$translations = $service->translations->listTranslations($text, 'hi');
return $translations;
}
echo googleTranslatePostV1("V1: " . "How are you?") . "\n";
echo googleTranslatePostV2("V2: " . "How are you?") . "\n";
echo googleTranslateV2Method1("V2: " . "How are you?") . "\n";
?>
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}
http://code.google.com/apis/language/translate/overview.html : Google
Translate API is available as a paid service. See the Pricing and FAQ
pages for details.