![](/img/trans.png)
[英]How to make the post request in BOX API using LWP::UserAgent?
[英]POST API in Perl using LWP::UserAgent with authentication
我正在嘗試在perl中使用POST方法將信息發送到API。
我想調用以下需要以下輸入的api:URI: https : //www.cryptopia.co.nz/api/SubmitTrade
輸入參數為:
市場:交易的市場符號,例如“ DOT / BTC”(如果提供了“ TradePairId”,則不需要)
TradePairId:交易的Cryptopia交易對標識符,例如“ 100”(如果提供“ Market”,則不需要)
類型:交易類型,例如“買入”或“賣出”
費率:要支付的硬幣的費率或價格,例如0.00000034
數量:要購買的硬幣數量,例如123.00000000
請您告訴我如何從Perl調用此api嗎? 請求結構:
REQUEST_SIGNATURE:API_KEY +“ POST” + URI + NONCE + HASHED_POST_PARAMS
API_KEY:您的Cryptopia api密鑰
URI:請求uri。 例如https://www.cryptopia.co.nz/Api/SubmitTrade
HASHED_POST_PARAMS:post參數的Base64編碼MD5哈希
NONCE:每個請求的唯一指示符。
所以問題是我如何加入此api https://www.cryptopia.co.nz/api/SubmitTrade並通過身份驗證將其傳遞給它,並檢查返回的結果是否成功?
結果示例:
{
"Success":true,
"Error":null,
"Data":
{
"OrderId": 23467,
"FilledOrders": [44310,44311]
}
}
我沒有Cryptopia帳戶可以對此進行測試,但這至少可以使您更接近可行的原型。
加載所需的模塊並創建LWP::UserAgent
對象。
use strict;
use warnings;
use LWP::UserAgent;
use JSON;
use Digest::MD5 qw(md5);
use Digest::SHA qw(hmac_sha256);
use MIME::Base64;
use URI::Encode qw(uri_encode);
my $api_key = 'PUBLIC KEY';
my $api_private_key = 'PRIVATE KEY';
my $ua = LWP::UserAgent->new;
棘手的部分是生成授權標頭。 您帳戶的API密鑰將進行base64編碼-因此,在使用該API密鑰簽署請求時將調用該decode_base64()
。
my $url = "https://www.cryptopia.co.nz/api/GetTradeHistory";
my %req = (
Market => 'DOT/BTC',
);
my $nonce = int(rand(1000000));
my $post_data = encode_json(\%req);
my $post_data_enc = encode_base64(md5($post_data), "");
my $encoded_url = lc(uri_encode($url, encode_reserved => 1));
my $req_signature = sprintf("%sPOST%s%s%s", $api_key, $encoded_url, $nonce, $post_data_enc);
# Sign request signature with private key.
my $req_signature_hmac = encode_base64(hmac_sha256($req_signature, decode_base64($api_private_key)));
# Generate value for 'Authorization' header field.
my $auth_header_value = sprintf("amx %s:%s:%s", $api_key, $req_signature_hmac, $nonce);
注意事項...
encode_base64()
-防止它在輸出中添加換行符。 URI::Encode
模塊中的uri_encode()
用於對URL進行編碼。 您可以顯式創建一個HTTP::Request
對象,並將其傳遞給LWP::UserAgent
的request()
方法,但是有一個post()
便捷方法可以為您完成所有這些工作。
此處的示例使用Content
參數設置帖子正文的內容,並同時設置Authorization
和Content-Type
標頭。
my $response = $ua->post($url,
Content => $post_data,
'Content-Type' => 'application/json',
Authorization => $auth_header_value
);
die "Request failed: ", $response->content unless $response->is_success();
print $response->content, $/;
通過調用$response->is_success()
方法,檢查上述LWP Response對象可能就足夠了。 但是,如果要顯式檢查是否成功,則只需解碼JSON響應-使用$resp = decode_json($response->decoded_content)
。 然后檢查結果哈希中的相關鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.