I want to develop a bridging application to web service. I Tried using the encrypted TIMESTAMP, SIGNATURE, AND AUTHORIZATION code with ARC (google add on for web service) to test if my encryption codes are correct and it worked. In my php script All requirements (parameters) are already provided but I always get Unauthorized access even though the password and username are correct. Please help. i'm using php curl. Thank for your help.
this is my php script :
<?php
$data = "xxx";
$secretKey = "xxx";
$url = "http://someurl";
$nik = "xxx";
date_default_timezone_set('UTC');
$tStamp = strval(time()-strtotime('1970-01-01 00:00:00'));
$signature = hash_hmac('sha256', $data."&".$tStamp, $secretKey, true);
$encodedSignature = base64_encode($signature);
$urlencodedSignature = urlencode($encodedSignature);
$pcareUname = "zzz";
$pcarePWD = "zzz";
$kdAplikasi = "zzz";
$encodedAuthorization = base64_encode($pcareUname.":".$pcarePWD.":".$kdAplikasi);
//showing result from encode
echo "X-cons-id: " .$data;
echo "X-timestamp:" .$tStamp;
echo "X-signature: " .$encodedSignature;
echo "X-authorization: " .$encodedAuthorization";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.$nik);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-cons-id: $data",
"X-timestamp: $tStamp",
"X-signature: $signature",
"X-authorization: Basic $encodedAuthorization"
));
$result = curl_exec($ch);
curl_close($ch);
echo($result);
?>
Related
I've been trying to translate some PHP code to Python 3 but can't quite get it to work. In PHP I have the following:
$request = "https://api.example.com/token";
$developerKey = "Basic VVVfdFdfsjkUIHDfdsjYTpMX3JQSDNJKSFQUkxCM0p0WWFpRklh";
$data = array('grant_type'=>'password',
'username'=>'name',
'password'=>'pass',
'scope'=>'2346323');
$cjconn = curl_init($request);
curl_setopt($cjconn, CURLOPT_POST, TRUE);
curl_setopt($cjconn, CURLOPT_HTTPHEADER, array('Authorization: '.$developerKey));
curl_setopt($cjconn, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($cjconn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($cjconn, CURLOPT_POSTFIELDS,http_build_query($data));
$result = curl_exec($cjconn);
curl_close($cjconn);
$tokens = json_decode($result,true);
$accesstoken = $tokens['access_token'];
echo $accesstoken."\n";
I tried converting it to the following in Python:
import pycurl, json
url = 'https://api.example.com/token'
data = json.dumps({"grant_type":"password",
"username":"name",
"password":"pass",
"scope":"2346323"})
key = 'Basic VVVfdFdfsjkUIHDfdsjYTpMX3JQSDNJKSFQUkxCM0p0WWFpRklh'
c = pycurl.Curl()
c.setopt(pycurl.URL,url)
c.setopt(pycurl.HTTPHEADER,['Authorization: {}'.format(key)])
c.setopt(pycurl.POST,1)
c.setopt(pycurl.POSTFIELDS,data)
c.perform()
But I get the following error:
<faultstring>String index out of range: -1</faultstring>
How can I correct this, or is there a more pythonic solution?
If anyone is interested in the solution, I came up with the following which worked:
def getToken(self):
"""Retrieves the token from provider"""
#The data to be passed to retrieve the token
tokenData = {'grant_type':'password',
'username':TOKENUSERNAME,
'password':TOKENPASSWORD,
'scope':TOKENSCOPE}
#The header parameters
header_params = {'Authorization':KEY}
#Make the request for the token
r = requests.post(TOKENURL,data=tokenData,headers=header_params)
#Check the status code
if r.status_code not in [200,203]:
self.log.logentry("There was an error retrieving the data from Linkshare: {}:{}".format(r.status_code,r.text))
sys.exit()
#Extract the data from the response
data = r.json()
#Parse the access token
token = {'token':data['access_token'],
'type':data['bearer']}
return token
I'm stuck trying to convert some sample Ruby API code from https://vircurex.com/welcome/api?locale=en to PHP. Here is the Ruby Code provided:
t = Time.now.gmtime.strftime("%Y-%m-%dT%H:%M:%S");
trx_id = Digest::SHA2.hexdigest("#{t}-#{rand}")
user_name = "MY_USER_NAME"
secret_word = "123456789"
tok = Digest::SHA2.hexdigest("#{secret_word};#{user_name};#{t};#{trx_id};create_order;sell;10;btc;50;nmc")
Order.call_https("https://vircurex.com", "/api/create_order.json?account=#{user_name}&id=#{trx_id}&token=#{tok}×tamp=#{t}&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc")
def self.call_https(my_url,my_params)
uri = URI.parse(my_url)
http = Net::HTTP.new(uri.host, '443')
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
response=""
resp=""
http.start do |http|
cmd = my_params
req = Net::HTTP::Get.new(cmd)
response = http.request(req)
resp = response.body
end
return ActiveSupport::JSON.decode(resp)
end
Here is what I attempted to come up with so far in PHP, but i know nothing of Ruby, so it is hard to figure out what the original code is doing:
date_default_timezone_set("UTC");
$t = date("Y-m-d H:i:s", time());
$trx_id = hash("sha256", $t."-".rand()); // i think this is wrong
$user_name = "MY_USER_NAME";
$secret_word = "123456789";
$tok = hash("sha256", $secret_word.";".$user_name.";".$t.";".$trx_id.";create_order;sell;10;btc;50;nmc");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$username&id=$trx_id&token=$tok×tamp=$t&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$resp = curl_exec($ch);
return json_decode($resp);
Can someone familiar with both languages please help me out? Thanks!
I get the following response with my code:
stdClass Object
(
[status] => 8003
[statustxt] => Authentication failed
)
So obviously, something is not being translated correctly. I just need to generate some working PHP code to use with the API listed. You can create an account to test the code if you like.
The problem is on two lines:
First, change this line:
$t = date("Y-m-d H:i:s", time());
to:
$t = date("Y-m-d\TH:i:s", time());
And second, fix this:
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$username&id=$trx_id&token=$tok×tamp=$t&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc");
by changing $username param into $user_name:
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$user_name&id=$trx_id&token=$tok×tamp=$t&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc");
I successfully received a valid response from Vircurex with another API call, as the create_order API is currently disabled as reported on Vircurex site. In any case, I've had no authentication problems.
I'm trying to retrieve data from Twitter by connecting to twitter API and make some requests the my code below but I get nothing in return... I just requested the bearer token and successfully received it.
This is the code in PHP:
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?
count=10&screen_name=twitterapi";
$headers = array(
"GET".$url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: My Twitter App v1.0.23",
"Authorization: Bearer ".$bearer_token."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
$retrievedhtml = curl_exec ($ch); // execute the curl
print_r($retrievedhtml);
when using the print_r nothing is shown at all and when using the var_dump i find "bool(false)"
Any idea with what could be wrong with this?
Regards,
Try outputting any potential cURL errors with
curl_error($ch);
after the curl_exec command. That might give you a clue about what's going wrong. Completely empty responses usually point to something going wrong with the cURL operation itself.
Your headers are wrong... do not include
"GET".$url." HTTP/1.1"
in your headers.
Further, you may print out the HTTP return code by
$info = curl_getinfo($ch);
echo $info["http_code"];
200 is success, anything in the 4xx or 5xx range means something went wrong.
I built based on comments I found in a Twitter dev discussion by #kiers. Hope this helps!
<?php
// Get Token
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch,CURLOPT_POST, true);
$data = array();
$data['grant_type'] = "client_credentials";
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$screen_name = 'ScreenName'; // add screen name here
$count = 'HowManyTweets'; // add number of tweets here
$consumerKey = 'EnterYourTwitterAppKey'; //add your app key
$consumerSecret = 'EnterYourTwitterAppSecret'; //add your app secret
curl_setopt($ch,CURLOPT_USERPWD, $consumerKey . ':' . $consumerSecret);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$bearer_token = json_decode($result);
$bearer = $bearer_token->{'access_token'}; // this is your app token
// Get Tweets
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?count='.$count.'&screen_name='.$screen_name);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer ' . $bearer));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$cleanresults = json_decode($result);
// Release the Kraken!
echo '<ul id="twitter_update_list">';
foreach ( $cleanresults as $tweet ) {
// Set up some variables
$tweet_url = 'http://twitter.com/'.$screen_name.'/statuses/'.$tweet->id_str; // tweet url
$urls = $tweet->entities->urls; // links
$retweet = $tweet->retweeted_status->user->screen_name; // there is a retweeted user
$time = new DateTime($tweet->created_at); // lets grab the date
$date = date_format($time, 'M j, g:ia'); // and format it accordingly
$url_find = array();
$url_links = array();
if ( $urls ) {
if ( !is_array( $urls ) ) {
$urls = array();
}
foreach ( $urls as $url ) {
$theurl = $url->url;
if ( $theurl ) {
$url_block = ''.$theurl.'';
$url_find[] = $theurl; // make array of urls
$url_links[] = $url_block; // make array of replacement link blocks for urls in text
}
}
}
if ( $retweet ) { // add a class for retweets
$link_class = ' class="retweet"';
} else {
$link_class = '';
}
echo '<li'.$link_class.'>';
$new_text = preg_replace('##([\\d\\w]+)#', '$0', $tweet->text); // replace all #mentions with actual links
$newer_text = preg_replace('/#([\\d\\w]+)/', '$0', $new_text); // replace all #tags with actual links
$text = str_replace( $url_find, $url_links, $newer_text); // replace all links with actual links
echo $text;
echo '<br /><a class="twt-date" href="'.$tweet_url.'" target="_blank">'.$date.'</a>'; // format the date above
echo '</li>';
}
echo '</ul>';
I put together some files on github, named "Flip the Bird." Hope this helps...
I created PHP library supporting application-only authentication and single-user OAuth. https://github.com/vojant/Twitter-php.
Usage
$twitter = new \TwitterPhp\RestApi($consumerKey,$consumerSecret);
$connection = $twitter->connectAsApplication();
$data = $connection->get('/statuses/user_timeline',array('screen_name' => 'TechCrunch'));
I am trying to create a mysql user and assign it to the created database.
I have tried setting $db_host as IP address, FQD, localhost (since I am running from the same server) etc. All of these has no success.
Any advice on what I'm doing wrong? (xmlapi.php is being incuded fine)
include("xmlapi.php");
$db_host = "usingfullyqualifieddomain";
$cpuser = "myuser";
$cppass = "mypass";
$xmlapi = new xmlapi($db_host);
$xmlapi->set_port(2083);
$xmlapi->password_auth($cpuser,$cppass);
$xmlapi->set_debug(1);
//create database
print $xmlapi->api1_query($cpuser, "Mysql", "adddb", 'myDatabaseName');
//create user
print $xmlapi->api1_query($cpuser, "Mysql", "adduser", array('user' => 'myDBUser','pass'=>'myDBPwd'));
The error is probably related to the way you're making your first service call, to create the database. Here is how I do it, on CPanel 11:
$auth_user = 'XXXXXX';
$auth_pass = 'XXXXX';
$server = 'XXXXXXXX.com';
$json_client = new \xmlapi($server);
$json_client->set_output('json');
$json_client->set_port(2083);
$json_client->password_auth($auth_user, $auth_pass);
$json_client->set_debug(1);
# Create Database
$result = $json_client->api1_query( $auth_user, 'Mysql', 'adddb', array($shop->alias));
var_dump($result);
Note that the fourth parameter should be an array with the parameters, and not a string as you are doing it.
Also notice that the print on the api call result is not very useful for debugging. Try var_dump'ing it, as it will show you some more interesting information to work on.
currently, cpanel support the cpanel json api..
here you can use this code ..
this worked for me well
<?php
$cpanelusername = "cpanelusername";
$cpanelpassword = "cpanelpassword";
$domain = 'mydomain.com';
$query = "https://$domain:2083/json-api/cpanel?cpanel_jsonapi_module=Mysql&cpanel_jsonapi_func=adddb&cpanel_jsonapi_apiversion=1&arg-0=DBNAME";
$curl = curl_init(); // Create Curl Object
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0); // Allow self-signed certs
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); // Allow certs that do not match the hostname
curl_setopt($curl, CURLOPT_HEADER,0); // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // Return contents of transfer on curl_exec
$header[0] = "Authorization: Basic " . base64_encode($cpanelusername.":".$cpanelpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // set the username and password
curl_setopt($curl, CURLOPT_URL, $query); // execute the query
$result = curl_exec($curl);
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
// log error if curl exec fails
}
curl_close($curl);
print $result;
?>
I'm trying to create a bucket on GCS using API v1.0 (interoperable mode) in PHP but I'm getting a 'signature does not match' error response.
Here's what I'm doing:
$access_id = "GOOGxxxxxx";
$secret_key = "xyxyxyxyx/xyxyxyxyx";
$bucket = "random_bucket_name";
$url = 'https://'.$bucket.'commondatastorage.googleapis.com';
$timestamp = date("r");
$canonicalizedResources = "/ HTTP 1.1";
$stringToSign = utf8_encode("PUT "."\n"."\n"."\n".$canonicalizedResources);
$signature = base64_encode(hash_hmac("sha1",$stringToSign,$secret_key,true));
$authSignature = $access_id.":".$signature;
$headers = array('Host: '.$bucket.'.commondatastorage.googleapis.com',
'Date: '.$timestamp, 'x-goog-api-version: 1',
'x-goog-project-id: xxxyyyxy','Content-Length: 0',
'Authorization: GOOG1 '.$authSignature);
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c,CURLOPT_HTTPHEADER,$headers);
$xml = curl_exec($c);
And here's the response that I get:
<?xml version='1.0' encoding='UTF-8'?>
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you
provided. Check your Google secret key and signing method.</Message>
<StringToSign>
GET
Sat, 03 Mar 2012 14:56:53 -0800
x-goog-api-version:1
x-goog-project-id:xxxyyyxy
/random_bucket_name/
</StringToSign>
</Error>
Any ideas where I'm going wrong?
Here's Google's documentation on this:
https://developers.google.com/storage/docs/reference-methods#putbucket
One thing I noticed is that even though I specify "PUT" in the "stringToSign" variable ... the response says that I used "GET" ... ?
Any help would be appreciated.
There are a few problems here:
Your canonicalized resource should be "/bucket/", not "/ HTTP 1.1".
You need to include your two custom headers (x-goog-version and x-goog-project-id) in the string to sign.
The string to sign must include the timestamp sent in the Date: header.
You need to set CURLOPT_PUT so that curl knows to send a PUT request, rather than the default GET request (that's why your error response alludes to a GET request).
Here's a corrected version of your code, which I tested and used to create a new bucket:
<?php
$access_id = "REDACTED";
$secret_key = "REDACTED";
$bucket = "your-bucket";
$url = 'https://'.$bucket.'commondatastorage.googleapis.com';
$timestamp = date("r");
$version_header = "x-goog-api-version:1";
$project_header = "x-goog-project-id:REDACTED";
$canonicalizedResources = "/".$bucket."/";
$stringToSign = utf8_encode("PUT\n\n\n".$timestamp."\n".$version_header."\n".$project_header."\n".$canonicalizedResources);
$signature = base64_encode(hash_hmac("sha1",$stringToSign,$secret_key,true));
$authSignature = $access_id.":".$signature;
$headers = array('Host: '.$bucket.'.commondatastorage.googleapis.com',
'Date: '.$timestamp, $version_header,
$project_header,'Content-Length: 0',
'Authorization: GOOG1 '.$authSignature);
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c,CURLOPT_HTTPHEADER,$headers);
curl_setopt($c, CURLOPT_PUT, TRUE);
$xml = curl_exec($c);
print($xml);
?>
P.S. All the details on HMAC authentication for Google Cloud Storage are provided here: https://developers.google.com/storage/docs/reference/v1/developer-guidev1#authentication