Last active
October 30, 2015 07:10
-
-
Save DiKorsch/6017205221500fc4956a to your computer and use it in GitHub Desktop.
Coinbase API in python 2.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib, hmac, urllib2, time, json, requests | |
COINBASE_ENDPOINT = "https://coinbase.com/api/v1" | |
FORMAT = "json" | |
# store these in a secure place... this is only for demo purpose | |
KEY = "KEY" | |
SECRET = "SECRET" | |
def __request(url, params = None): | |
body = json.dumps(params) if isinstance(params, dict) else None | |
if params is not None: | |
url = url.format(params) | |
opener = urllib2.build_opener() | |
nonce = int(time.time() * 1e6) | |
message = str(nonce) + url + (body or '') | |
signature = hmac.new(SECRET, message, hashlib.sha256).hexdigest() | |
headers = {'ACCESS_KEY' : KEY, | |
'ACCESS_SIGNATURE': signature, | |
'ACCESS_NONCE': nonce, | |
'Accept': 'application/json'} | |
# If body is nil, a GET request is made. | |
if body is None: | |
req = urllib2.Request(url, headers=headers) | |
# If we are passing data, a POST request is made. Note that content_type is specified as json. | |
else: | |
headers.update({'Content-Type': 'application/json'}) | |
req = urllib2.Request(url, data=body, headers=headers) | |
try: | |
return opener.open(req) | |
except urllib2.HTTPError as e: | |
raise e | |
def request_to(path_str): | |
""" | |
This decorator works in the following way: | |
- POST request: return a dict with needed key value pairs (see 'send' and 'get' implementation) | |
- simple GET request: return nothing or None (see 'balance' implementation) | |
- GET request with a parameter in the URL (like /api/v1/transactions/:id_or_idem_field): return the parameter (see 'transaction' and 'order' implementation) | |
For all possible API-requests check the coinbase API-Reference: https://coinbase.com/api/doc | |
""" | |
def wrapper(func): | |
def inner(*args, **kw): | |
params = func(*args, **kw) | |
url = COINBASE_ENDPOINT + path_str | |
result = json.loads(__request(url, params).read()) | |
if "success" in result and not result["success"]: | |
if "errors" in result: | |
err_msgs = " - ".join(result.get("errors", ["Unknown Error"])) | |
elif "error" in result: | |
err_msgs = result.get("error") | |
raise Exception(err_msgs) | |
return result | |
return inner | |
return wrapper | |
# | |
# Some API calls follow | |
# | |
@request_to("/account/balance") | |
def balance(): | |
return None | |
# creates an order, so user can payin to your account | |
@request_to("/orders") | |
def get(amount, currency = "BTC"): | |
return { | |
"button": { | |
"name": "Payin notes", | |
"price_string": amount, | |
"price_currency_iso": currency | |
} | |
} | |
#creates an payout transaction, so user can payout from your account | |
@request_to("/transactions/send_money") | |
def send(to, amount, currency = "BTC"): | |
return { | |
"transaction": { | |
"notes": "Payout notes", | |
"to": to, | |
"amount": amount, | |
"amount_currency_iso": currency | |
} | |
} | |
@request_to("/transactions/{0}") | |
def transaction(trans_id): | |
return trans_id | |
@request_to("/orders/{0}") | |
def order(order_id): | |
return order_id | |
if __name__ == "__main__": | |
print balance() | |
get_resp = get("0.001") | |
print json.dumps(get_resp, indent = 2) | |
print json.dumps(order(get_resp["order"]["id"]), indent = 2) | |
# you can create an iframe with get_resp["order"]["button"]["id"] as it shown here: https://coinbase.com/docs/merchant_tools/payment_iframes | |
send_resp = send("bitcoin-address here", "0.001") | |
print json.dumps(send_resp, indent = 2) | |
print transaction(send_resp["transaction"]["id"]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment