簡體   English   中英

使用LWP :: UserAgent進行身份驗證的Perl中的POST API

[英]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::UserAgentrequest()方法,但是有一個post()便捷方法可以為您完成所有這些工作。

此處的示例使用Content參數設置帖子正文的內容,並同時設置AuthorizationContent-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM