如何解决请求在Coinbase API上传输/发送时出错
我正在尝试将从一个加密帐户到coinbase api的转移过帐,但似乎无法实现。当我尝试两次传输时,错误发生在代码的底部。第一次,它返回“ {}”,第二次,它返回回溯错误。
这是我的代码:
import hmac,hashlib,time,requests,os
from requests.auth import AuthBase
from coinbase.wallet.client import Client
API_KEY = os.environ.get('API_KEY')
API_SECRET = os.environ.get('API_SECRET')
xrp_acct_id = os.environ.get('XRP_ID')
usdc_acct_id = os.environ.get('USDC_ID')
xrp_destination_tag = os.environ.get('xrp_destination_tag')
xtz_acct_id = os.environ.get('XTZ_ID')
user_id = os.environ.get('Coinbase_User_Id')
# Create custom authentication for Coinbase API
class CoinbaseWalletAuth(AuthBase):
def __init__(self,api_key,secret_key):
self.api_key = api_key
self.secret_key = secret_key
def __call__(self,request):
timestamp = str(int(time.time()))
message = timestamp + request.method + request.path_url + (request.body or b'').decode()
signature = hmac.new(bytes(self.secret_key,'utf-8'),message.encode('utf-8'),hashlib.sha256).hexdigest()
request.headers.update({
'CB-ACCESS-SIGN': signature,'CB-ACCESS-TIMESTAMP': timestamp,'CB-ACCESS-KEY': self.api_key,'CB-VERSION': '2020-01-18'
})
return request
api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY,API_SECRET)
client = Client(API_KEY,API_SECRET)
# Get current user:
# r_user = requests.get(api_url + 'user',auth=auth)
# print(r_user.json())
# Get transactions:
# xrp_txs = client.get_transactions(xrp_acct_id)
# Get accounts:
r = requests.get(api_url + 'accounts',auth=auth)
# Get price (XRP-USD):
price = client.get_spot_price(currency_pair='XRP-USD')
# To parse the JSON
accounts_json = r.json()
#
# # Variable to figure out wallet balances
XRP_balance = 0.0
# Dictionary used to store balances and wallet name's
accounts = {}
# Loop to get balances
for i in range(0,len(accounts_json["data"])):
wallet = accounts_json["data"][i]["name"]
amount = accounts_json["data"][i]["balance"]["amount"]
# Switch statement to figure out which index which wallet is
if wallet == "XRP Wallet":
XRP_balance = float(amount) * float(price["amount"])
accounts["XRP_USD"] = XRP_balance
elif wallet == "USDC Wallet":
USDC_amount = amount
accounts["USDC"] = USDC_amount
else:
print()
print(accounts)
txs = {
'type': 'transfer','account_id': usdc_acct_id,'to': xrp_acct_id,'amount': '10','currency': 'USDC'
}
r = requests.post(api_url + 'accounts/' + usdc_acct_id + '/transactions',json=txs,auth=auth)
print(r.json())
###### OUTPUT FROM THIS IS "{}" ##############
tx = client.transfer_money(account_id=usdc_acct_id,to=xtz_acct_id,amount='10',fee='0.99',currency='USDC')
###### OUTPUT FROM THIS IS "Traceback error" See Below ##############
txs = {
'type': 'send','to': xrp_address["address"],'destination_tag': xrp_destination_tag,'currency': 'XRP'
}
r = requests.post(api_url + 'accounts/' + xtz_acct_id + '/transactions',auth=auth)
print(r)
print(r.json())
########## THIS OUTPUT IS FROM AFTER TRACEBACK ERROR ################
这是整个输出:
{'USDC': '100.000000','XRP_USD': 571.5256683544001}
{}
Traceback (most recent call last):
File "/Users/mattaertker/Documents/CryptoExchangeProgram/exchangeMyCurrency.py",line 97,in <module>
tx = client.transfer_money(account_id=usdc_acct_id,File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py",line 339,in transfer_money
response = self._post('accounts',account_id,'transactions',data=params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py",line 132,in _post
return self._request('post',*args,**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py",line 116,in _request
return self._handle_response(response)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/client.py",line 125,in _handle_response
raise build_api_error(response)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/coinbase/wallet/error.py",line 49,in build_api_error
blob = blob or response.json()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py",line 898,in json
return complexjson.loads(self.text,**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py",line 357,in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py",line 337,in decode
obj,end = self.raw_decode(s,idx=_w(s,0).end())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py",line 355,in raw_decode
raise JSONDecodeError("Expecting value",s,err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
<Response [400]>
{'errors': [{'id': 'validation_error','message': 'Please enter a valid email or Tezos address','field': 'base'}]}
但是,至少我可以从我的tezos帐户向我的tezos帐户汇款:
txs = {
'type': 'send','to': xtz_address["address"],auth=auth)
print(r)
输出:
<Response [201]>
我检查了我的tezos帐户,当然,因为响应为201,所以确实将其发送给自己。我最近发现,当您未指定destination_tag时,它仍然无法执行此操作!
解决方法
如果您想将加密货币从一种货币转换为另一种货币,则不必使用 transfer_money。从 webapp 观看 Coinbase API,这是您需要调用的端点:
-
必须知道您想出售的加密的 base_id 和想要购买的加密的 base_id。您可以通过从响应中调用
GET "https://api.coinbase.com/v2/ /assets/prices?base=USD&filter=holdable&resolution=latest" and get
来了解您的货币的“base_id”。 -
通过使用 json 中的请求正文调用
POST "https://api.coinbase.com/v2/trade"
来下订单,如下所示:{ 'amount': [amount that you want to convert],'amount_asset': [currency of amount that you want to convert],'amount_from': 'input','source_asset': ["base_id" of crypto that you want to sell],'target_asset': ["base_id" of crypto that you want to buy] }
-
如果之前的 POST "/trade" 响应代码是 201,你必须得到 响应的 json 的“id”值并通过以下方式提交您的订单 呼叫
POST "https://api.coinbase.com/v2/trades/[id of json response of previous https://api.coinbase.com/v2/trade POST"]/commit
。如果 此 POST 提交的响应代码是 201,您的交换是 开始,如果coinbase没有错误,你的转换是 完成!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。