# MEXC V2 API文档中鉴权处理(python版) **Published by:** [Outlaw_oracle](https://paragraph.com/@outlaw-oracle/) **Published on:** 2022-03-25 **URL:** https://paragraph.com/@outlaw-oracle/mexc-v2-api-python ## Content 虽说MEXC已经出了v3版的API,但截至目前合约API尚未在v3版上线。当初写代码时,由于笔者对python的hmac等库不太熟悉,写到鉴权部分的代码时,遇到一些阻碍。因此将鉴权部分的代码写在这里,方便后之来者( 通过`client = exchange_contactAPI(access_key='你的access_key字符串', secret_key='你的secret_key字符串')`调用即可。当然具体函数得自己写了。 import hmac import time import json import requests class exchange_contactAPI: def __init__(self, access_key, secret_key): self.base_url = 'https://api.mexc.com' #此为合约API的baseurl,如要使用现货API需改为'https://www.mexc.com' self.access_key = access_key self.secret_key = secret_key def get_auth(self, uri, params={}): #需要鉴权的GET请求,传入参数params为字典类型 url = self.base_url + uri header = {} header['ApiKey'] = self.access_key timestamp_s = time.time() timestamp_ms_int = int(1000 * timestamp_s) header['Request-Time'] = str(timestamp_ms_int) params_str = '&'.join(["{}={}".format(i, params[i]) for i in sorted(params.keys())]) signature_str = self.access_key + str(timestamp_ms_int) + params_str byte_key = self.secret_key.encode() byte_msg = signature_str.encode() signature = hmac.new(byte_key, byte_msg, digestmod='SHA256') #maybe exchange byte_key and | header['Signature'] = signature.hexdigest() header['Content-Type'] = 'application/json' res = requests.get(url=url, headers=header) return res.text def post_auth(self, uri, params={}): #需要鉴权的POST请求 url = self.base_url + uri header = {} header['ApiKey'] = self.access_key timestamp_s = time.time() timestamp_ms_int = int(1000 * timestamp_s) header['Request-Time'] = str(timestamp_ms_int) params_str = json.dumps('&'.join(["{}={}".format(i, params[i]) for i in sorted(params.keys())])) signature_str = self.access_key + str(timestamp_ms_int) + params_str byte_key = self.secret_key.encode() byte_msg = signature_str.encode() signature = hmac.new(byte_key, byte_msg, digestmod='SHA256') header['Signature'] = signature.hexdigest() header['Content-Type'] = 'application/json' res = requests.get(url=url, headers=header) return res.text ## Publication Information - [Outlaw_oracle](https://paragraph.com/@outlaw-oracle/): Publication homepage - [All Posts](https://paragraph.com/@outlaw-oracle/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@outlaw-oracle): Subscribe to updates - [Twitter](https://twitter.com/wcbngd): Follow on Twitter