In Bitstamp's API documentation, a client_id is mentioned. It is used to generate a signature.
https://www.bitstamp.net/api/
But I couldn't find how I can get that client_id.
Any hint on that? Many thanks.
Did you register for an API key via their instructions? They say:
To get an API key, go to "Account", "Security" and then "API Access". Set permissions and click "Generate key".`
Once you have the API key, you use a HMAC encoded of the API key, API secret, and your customer/client id. You should be able to get your client id by going to the "Account Balance" page, where I believe it's referred to as your "Customer ID".
Use this code to get idea. This is Ruby code
require 'open-uri'
require 'json'
require 'base64'
require 'openssl'
require 'hmac-sha2'
require 'net/http'
require 'net/https'
require 'uri'
def bitstamp_private_request(method, attrs = {})
secret = "xxx"
key = "xxx"
client_id = "xxx"
nonce = nonce_generator
message = nonce + client_id + key
signature = HMAC::SHA256.hexdigest(secret, message).upcase
url = URI.parse("https://www.bitstamp.net/api/#{method}/")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
data = {
nonce: nonce,
key: key,
signature: signature
}
data.merge!(attrs)
data = data.map { |k,v| "#{k}=#{v}"}.join('&')
headers = {
'Content-Type' => 'application/x-www-form-urlencoded'
}
resp = http.post(url.path, data, headers)
console_log "https://www.bitstamp.net/api/#{method}/"
resp.body
end
def nonce_generator
(Time.now.to_f*1000).to_i.to_s
end
The page where you change password on Bitstamp presents you your client id (contains letters and digits).
I have some probelm with bitstamp api
below is my code php
$message = $nonce.$client_id.$api_key;
$signature = strtoupper(hash_hmac('sha256', $message, $secret_key));
$post_string = 'api_key='.$api_key.'&signature='.$signature.'&nonce='.$nonce;
$url = "https://www.bitstamp.net/api/balance/";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
$tempData = json_decode($json);
print_r($tempData);<br>
Output:
stdClass Object ( [error] => Missing key, signature and nonce parameters )
Related
I am developing a PHP script to consume the Iconomi API, but I have problems with authentication.
According to the documentation, you have to create a signature and attach it in the header. However the curl_exec function returns false, which means it has failed.
These are the instructions:
Creating a request
All REST requests must contain the following headers:
ICN-API-KEY - The api key as a string.
ICN-SIGN - The base64-encoded signature (see Signing a Message).
ICN-TIMESTAMP - A timestamp for your request in epoch milliseconds.
Signing a Message
You generate the ICN-SIGN header by creating a sha512 HMAC using the base64-decoded secret key on the > prehash string timestamp + method + requestPath + body (where + represents string concatenation) and base64-encode the output, where:
the timestamp value is the same as the ICN-TIMESTAMP header.
the body is the request body string or omitted if there is no request body (typically for GET requests).
method must always be in upper case
And this is my code:
function call_iconomi_api()
{
$url = 'https://api.iconomi.com';
$api_key = get_field('iconomi_api_key', 'option');
$api_secret = get_field('iconomi_api_secret', 'option');
$timestamp = round(microtime(true) * 1000);
$request_path = '/v1/assets';
$message = $timestamp . 'GET' . $request_path;
$signature = base64_encode(hash_hmac('sha512', $message, $api_secret));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url . $request_path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'ICN-API-KEY: ' . $api_key,
'ICN-SIGN: ' . $signature,
'ICN-TIMESTAMP: ' . $timestamp
));
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
Try to use
$signature = base64_encode(hash_hmac('sha512', $message, $api_secret, true));
If you look into https://iconomi-ag.github.io/iconomi-api/#section/Introduction/Authentication under section "Signing a Message" (Example of GET with query parameters) this function with last param as true returns identical string as base64 encoded signature
I want to send btc using my account with api with php.
I tried coinbase api from github which is depreciated
https://github.com/coinbase/coinbase-php
and i am getting error when i tried this code
require_once( __DIR__ . '/requires/coinbase/vendor/autoload.php');
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
$transaction = Transaction::send([
'toBitcoinAddress' => "$bticoin_address",
'amount' => new Money($amount, CurrencyCode::USD),
'description' => 'Your first bitcoin!',
'fee' => '0.0001' // only required for transactions under BTC0.0001
]);
try {
$transaction = $client->createAccountTransaction($account, $transaction);
}
catch(Exception $e) {
echo $e->getMessage();
}
and i am getting this error
<b>Fatal error</b>: Uncaught TypeError: Argument 1 passed to Coinbase\Wallet\Exception\HttpException::exceptionClass() must be an instance of Psr\Http\Message\ResponseInterface, null given, called in /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php on line 33 and defined in /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php:98
Stack trace:
#0 /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php(33): Coinbase\Wallet\Exception\HttpException::exceptionClass(NULL)
#1 /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/HttpClient.php(137): Coinbase\Wallet\Exception\HttpException::wrap(Object(GuzzleHttp\Exception\RequestException))
#2 /home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/HttpClient.php(121): Coinbase\Wallet\HttpClient->send(Object(GuzzleHttp\Psr7\Request), Array)
#3 /home/fiberpay/public_html/owne in <b>/home/fiberpay/public_html/owner/requires/coinbase/vendor/coinbase/coinbase/src/Exception/HttpException.php</b> on line <b>98</b><br />
Is there anyway to do that ??
I spend much time to google it but still not found any solution that is i why i put that on there may be i got some good solution from there :)
Best Regars
Instead of using coinbase PHP wrapper use coinbase API itself
To send money from one coinbase account to another you can use the below code
first, get api_key and api_secret
$private_key = 'Doadlraixxxxxx'; //Coinbase Private Key
$api_key = 'ysEZjjBxxxxx'; //Coinbase API KEY
The Create a new stdClass object which contains your request method for withdrawing it will be POST, the path will be API path, and for withdrawing it will be /v2/accounts/:accountid/transactions, and then simply put private key and API key here
$json = new stdClass();
$json->method = "POST";
$json->path = "/v2/accounts/".$account_id."/transactions";
$json->secretapikey = $private_key;
$json->apikey = $api_key;
Now create another stdClass that contain your withdrawal info like email, currency, etc
$body = new stdClass();
$body->type = "send";
$body->to = $to_email;
$body->amount = $amount;
$body->currency = $currency;
then in the next step, we have to create a signature according to the timestamp for this we have to create SHA256 hash of current time, path, and the $body stdClass
$result = json_encode($json);
$body = json_encode($body);
$time= time();
$sign = $time.$json->method.$json->path.$body;
$hmac = hash_hmac("SHA256", $sign, $json->secretapikey);
Our Signature and body are ready now just need to post it
$URL = "https://api.coinbase.com/v2/accounts/".$account_id."/transactions";
$header = array(
"CB-ACCESS-KEY:".$api_key,
"CB-ACCESS-SIGN:".$hmac,
"CB-ACCESS-TIMESTAMP:".time(),
"CB-VERSION:2019-11-15",
"Content-Type:application/json"
);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
After sending a request the money will be sended successfully.
And with a little decoration code will look like this
https://gist.github.com/AdityaEXP/27408bd361d5b8fcc9ac2bf459eb5303
I've been using the coinbase php library for 4years.
When you get that error, it's highly probably due to incorrect account credentials.
Also, the default github library has an expired uploaded certificate in one of its folder.
You have to replace it.
Coinbase PHP works fine for me everytime.
i was away from Ruby for a while...now, i need to recreate a php api connection (curl) on ruby, to add it to my rails app, but all im getting is a Net::HTTPMovedPermanently message
here is the original php version:
$url = "https://marketplace.walmartapis.com/v3/token";
$uniqid = uniqid();
$authorization_key = base64_encode($client_id.":".$client_secret);
$code = "";
$ch = curl_init();
$options = array(
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: $uniqid",
"Authorization: Basic $authorization_key",
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
),
);
curl_setopt_array($ch,$options);
$response = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if($code == 201 || $code == 200)
{
$token = json_decode($response,true);
return $token['access_token'];
}
}
And this is my Ruby version so far:
require 'net/http'
require 'base64'
client_id = "id"
client_secret = "secret"
url = "https://marketplace.walmartapis.com/v3/token/"
uniqid = "1234567890abc"
uri = URI(url)
request = Net::HTTP::Post.new(uri)
request['WM_SVC.NAME'] = 'Walmart Marketplace'
request['WM_QOS.CORRELATION_ID'] = uniqid
request.basic_auth(client_id, client_secret)
request['Accept'] = 'application/json'
request['Content-Type'] = 'application/x-www-form-urlencoded'
http = Net::HTTP.new(uri.host)
response = http.request(request)
puts response
What im missing?
Update...
i've changed some things based on curl-to-ruby web, and is at follows...now im getting a 400 error
require 'net/http'
require 'uri'
client_id = "foo"
client_secret = "bar"
url = "https://marketplace.walmartapis.com/v3/token"
uniqid = "1234567890abc"
uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request["WM_SVC.NAME"] = "Walmart Marketplace"
request["WM_QOS.CORRELATION_ID"] = uniqid
request.basic_auth(client_id, client_secret)
request["Accept"] = "application/json"
request.content_type = "application/x-www-form-urlencoded"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, req_options) do |http|
http.request(request)
end
puts response.code
puts response.body
i created a new question to clear out whats working so far, and the missing fields comparing to php
It looks like the resource you are trying to access has been moved. The HTTPMovedPermanently reponse is a form of HTTPRedirection. Your code should make another request to the new location.
This is the example directly from the Net::HTTP documentation:
def fetch(uri_str, limit = 10)
# You should choose a better exception.
raise ArgumentError, 'too many HTTP redirects' if limit == 0
response = Net::HTTP.get_response(URI(uri_str))
case response
when Net::HTTPSuccess then
response
when Net::HTTPRedirection then
location = response['location']
warn "redirected to #{location}"
fetch(location, limit - 1)
else
response.value
end
end
Wink API is currently on version 2.
My Question: How can you do a simple "Hello World" with the Wink API V2 via PHP?
Notes:
Wink uses PubNub for subscriptions (devices have an event)
Uses OAuth2 standard
Website/Login is often "hokey": (& will error when you login: "Authentication failed!")
Login here: https://developer.wink.com & use Google account (or whatever)
Then change URL to this: https://developer.wink.com/clients
Sometimes you have to do this a couple times!!
You will need to request an Application API key in order to use the API. I followed up with an email to get it approved swiftly.
Once you are approved, you'll get: Client ID, Client Secret, & URLs to assist
API URL: https://api.wink.com/...
Email support: support#wink.zendesk.com (Get Application API key, etc)
OAuth 2:
Wink indicates to use "Authorization Code Grant Type"
Dox & Example: https://developer.byu.edu/docs/consume-api/use-api/choose-grant-type
Related Links:
Wink API: https://winkapiv2.docs.apiary.io/#
Stackoverflow related questions:
How to use Wink API V2 from a non-web app
Issues with Pubnub + Wink Hub and sensors
Wink API Subscriptions Stop Sending Overnight
https://community.home-assistant.io/t/wink-access-token-issue/52197/15
Github Example: https://github.com/cbulock/php-wink (This was last updated 3 years ago; might be on previous API ver)
Information regarding this is extremely limited, so I'll answer my own question hoping to help others. (It took a long time since there wasn't any good info out there.) This example has a user interface (Login required by Wink). I'm hoping someone can post a non-user-interface version (for background scripting, etc).
This will give you raw json output, for you to do with as you wish. This single php page will initially load, take you to Wink's login (you need an account with your devices if this wasn't obvious), after logging it, it will take you back to this same page with a code, call for a token, then use that token to get the device resources.
Create: //[YourServer]/wink_helloworld.php on your http/php server.
wink_helloworld.php:
//Make sure to add this exact URL to your Wink Developer Portal! (https://developer.wink.com/clients)
$redirect_uri = "http://[YourServer]/wink_helloworld.php";
// This is from Wink Developer Portal
$client_id = "abcdefg";
$wink_oauth_url = "https://api.wink.com/oauth2/token";
$client_secret = "hijklmnop";
$devices_url = "https://api.wink.com/users/me/wink_devices";
//need to create a state variable, like a session id. should actually be random tho!!
$randomstring="xyzABC123";
$state = base64_encode($randomstring);
/*_____________________________________________________________________________________________________________________________________ */
echo "<h2>Wink Hello World - Show Devices</h2>";
//If we don't have a code, then send user to login page
if($_GET['code'] == null | $_GET['code'] == ""){
echo "<a href='https://api.wink.com/oauth2/authorize?response_type=code&client_id=".$client_id."&redirect_uri=$redirect_uri&state=".$state."'>Login</a>";
return;
}
$code = $_GET['code'];
//if we dont have a token, lets get one
if($access_token == null | $access_token == ""){
$access_token = getAccessToken();
}
// lets get some data from our devices!
getResource($access_token);
/*_____________________________________________________________________________________________________________________________________ */
// Get token
function getAccessToken() {
global $wink_oauth_url, $code, $client_secret;
echo "<b>getAccessToken()</b> Using Code: $code<br>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $wink_oauth_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, "{
\"client_secret\": \"$client_secret\",
\"grant_type\": \"authorization_code\",
\"code\": \"$code\"
}");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($curl);
//var_dump($response);
formatResults($response); //debug output
curl_close($curl);
return json_decode($response)->access_token;
}
/*_____________________________________________________________________________________________________________________________________ */
// Get Resource(s) with our code & token
function getResource($access_token) {
global $devices_url;
echo "<b>getResource()</b> Using Token: $access_token<p>";
$header = array("Authorization: Bearer {$access_token}");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $devices_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($curl);
curl_close($curl);
formatResults($response); //debug output
}
/*_____________________________________________________________________________________________________________________________________ */
//debug formatted output functions
function formatResults($json){
echo "<pre>";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
I am trying to get a list of all my Twilio numbers using cURL inside of a php function. I am getting the information I need back from Twilio however it is just a string of all the information with no whitespace or anything.
This is what I am getting back. I have removed my account number and sid:
string(1621) " {{ SID }}ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX(936) 585-6544+19365856544https://demo.twilio.com/welcome/sms/reply/POSTPOSTfalseWed, 11 May 2016 14:39:22 +0000Wed, 18 May 2016 15:41:25 +0000https://demo.twilio.com/welcome/sms/reply/POSTPOSTnonefalsetruetruetruePOST2010-04-01/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PN5e0ef24464a1fbbcf4e2bd127c471892"
Here is the function I am using to cURL Twilio.
function post_incoming($POST) {
// resource url & authentication
$uri = 'https://api.twilio.com/2010-04-01/Accounts/' . $this->sid . '/IncomingPhoneNumbers';
$auth = $this->sid . ':' . $this->authtoken;
$res = curl_init();
// set cURL options
curl_setopt( $res, CURLOPT_URL, $uri );
curl_setopt( $res, CURLOPT_USERPWD, $auth ); // authenticate
curl_setopt( $res, CURLOPT_RETURNTRANSFER, true ); // don't echo
// send cURL
$result = curl_exec( $res );
var_dump($result);
return $result;
}
I need to get the information back as a json array or some kind of array that way I can parse out the Twilio phone number for later.
It is a lot easier if you use the PHP helper library. It woudl look something like this:
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$numbers_arr = array();
// Loop over the list of numbers and echo a property for each one
foreach ($client->account->incoming_phone_numbers as $number) {
$numbers_arr[] = $number->phone_number;
}
return json_encode($numbers_arr);
}
This function uses the Twilio PHP SDK to get a list of all numbers in the account then puts them into an array variable $numbers_arr and returns that variable as JSON.