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.
Related
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);
?>
I'm going to rewrite this POST request in python:
<?php
// Set these variables
$networkid = ""; // In your HasOffers system at Support -> API
$apikey = ""; // In your HasOffers system at Support -> API
$offerid = "0"; // Specify an offer ID to add the creative to
$creativetype = "image banner"; // Types: file, image banner, flash banner, email creative, offer thumbnail, text ad, html ad, hidden
$filename = "banner_728x90.gif"; // File name; no spaces, and file must be in same directory as this script
$display = $filename; // Or change this to the "display name" for this creative
// Don't change anything below here
$creativetype = urlencode($creativetype);
$display = urlencode($display);
$fields[$filename] = "#{$filename}";
$url = "http://api.hasoffers.com/v3/OfferFile.json?Method=create&NetworkToken={$apikey}&NetworkId={$networkid}&data[offer_id]={$offerid}&data[type]={$creativetype}&data[display]={$display}&return_object=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$resp = curl_exec($ch);
curl_close($ch);
print_r(json_decode($resp, true)); // Final output; remove or change this if you want
?>
As I know, in pycurl the CURLOPT_POSTFIELDS attribute is absent. What can I use instead?
Thank you!
there are many python libraries that can be used:
http.client
https://docs.python.org/3.1/library/http.client.html
requests
https://pypi.python.org/pypi/requests/
the commands are pretty straightforwards:
using http.client:
import http.client
conn = http.client.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print(res.status, res.reason)
200 OK
or requests:
import requests
r = requests.get('https://github.com/timeline.json')
print r.json
Using HTTP client, a simple POST request may be done as follows:
connect = http.client.HTTPSConnection("base_url")
connect.request('POST', '/rest/api/'+ you_can_add_variables+ '/users?userEmail=' + another_variable, headers=headers)
Using requests:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
the documentation provided above should not prove difficult to understand
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 have a twitter api php script successfully spits out the last 100 of my followers
$flwrs_url = "http://api.twitter.com/1/statuses/followers/exampleuser.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $flwrs_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
....
(I used exampleuser instead of my own account)
How do I extend this to include more or all of my followers?
Thank you
According to the Twitter API Documentation for GET followers/ids the request should return up to 5000 followers.
However, if not all followers are returned by the API, there should be a next_cursor element in the response which can be used to retrieve the next batch of followers. You only have to append the value of next_cursor as cursor to the request (see also the API documentation).
Please note that you are using Version 1 of the Twitter API which has been deprecated recently. That is, it will stop working probably early next year. You should upgrade to Version 1.1 as soon as possible. There are new guidelines in place, one of them is that all requests must be authenticated with oAuth.
Thanks for the answer Florian. BTW stumbing around I think I found the correct way to do what I was looking for. Correct me if I'm wrong.
after using the:
$code=$tmhOAuth->request('GET', $tmhOAuth->url('1/followers/ids'),
array('screen_name' => $user, 'cursor' => $cursor));
technique to grab all 5000 followers (user ids). I use the following code to grab batches of 100 (user details) at a time:
$status_url = "http://api.twitter.com/1/users/lookup.json?user_id=";
$lastNum=$last; // $lastNum=100;
$i=$first; // $i=0;
while($i<$lastNum){
if ($i==($lastNum-1)){
$status_url = $status_url . "$followers[$i]";
}else{
$status_url = $status_url . "$followers[$i],";
}
$i++;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $status_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$i = 0;
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
$name = $friends['name'];
$thumb = $friends['profile_image_url'];
$url = $friends['screen_name'];
$location = $friends['location'];
$description = $friends['description'];
echo "$i) $id $screen_name $name $location $description<br />";
$i++;
}
I realize I need to put "sleep" in between each of these "batches of 100", but I'm not quite sure how much to use.
I'm trying to convert this PHP cURL function to work with my rails app. The piece of code is from an SMS payment gateway that needs to verify the POST paramters. Since I'm a big PHP noob I have no idea how to handle this problem.
$verify_url = 'http://smsgatewayadress';
$fields = '';
$d = array(
'merchant_ID' => $_POST['merchant_ID'],
'local_ID' => $_POST['local_ID'],
'total' => $_POST['total'],
'ipn_verify' => $_POST['ipn_verify'],
'timeout' => 10,
);
foreach ($d as $k => $v)
{
$fields .= $k . "=" . urlencode($v) . "&";
}
$fields = substr($fields, 0, strlen($fields)-1);
$ch = curl_init($verify_url); //this initiates a HTTP connection to $verify_url, the connection headers will be stored in $ch
curl_setopt($ch, CURLOPT_POST, 1); //sets the delivery method as POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //The data that is being sent via POST. From what I can see the cURL lib sends them as a string that is built in the foreach loop above
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This verifies if the target url sends a redirect header and if it does cURL follows that link
curl_setopt($ch, CURLOPT_HEADER, 0); //This ignores the headers from the answer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //This specifies that the curl_exec function below must return the result to the accesed URL
$result = curl_exec($ch); //It ransfers the data via POST to the URL, it gets read and returns the result
if ($result == true)
{
//confirmed
$can_download = true;
}
else
{
//failed
$can_download = false;
}
}
if (strpos($_SERVER['REQUEST_URI'], 'ipn.php'))
echo $can_download ? '1' : '0'; //we tell the sms sever that we processed the request
I've googled a cURL lib counterpart in Rails and found a ton of options but none that I could understand and use in the same way this script does.
If anyone could give me a hand with converting this script from php to ruby it would be greatly appreciated.
The most direct approach might be to use the Ruby curb library, which is the most straightforward wrapper for cURL. A lot of the options in Curl::Easy map directly to what you have here. A basis might be:
url = "http://smsgatewayadress/"
Curl::Easy.http_post(url,
Curl::PostField.content('merchant_ID', params[:merchant_ID]),
# ...
)