Created
November 24, 2016 03:58
-
-
Save chenchiyuan/9b64c9918e3c1878fee2487ee1b485ca to your computer and use it in GitHub Desktop.
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
class AlipaySDK(object): | |
def __init__(self, app_id, debug=False, version="2.0"): | |
self.app_id = app_id | |
self.debug = debug | |
self.gateway = "https://openapi.alipay.com/gateway.do" | |
self.version = version | |
self.sign_type = "RSA" | |
self.charset = "utf-8" | |
self.oauth_url = "https://openauth.alipay.com/oauth2/appToAppAuth.htm" | |
def sign(self, params): | |
items = sorted(params.items()) | |
s = '&'.join(map(lambda (key, value): "%s=%s" % (key, value), items)) | |
origin_sign = rsa_sign(s) | |
sign = base64.b64encode(origin_sign) | |
return sign | |
def post(self, method, app_auth_token="", **params): | |
now = datetime_now() | |
timestamp = datetime_to_str(now, '%Y-%m-%d %H:%M:%S') | |
request_params = { | |
"app_id": self.app_id, | |
"method": method, | |
"charset": self.charset, | |
"sign_type": self.sign_type, | |
"timestamp": timestamp, | |
"version": self.version, | |
"biz_content": json.dumps(params), | |
"format": "json", | |
} | |
if app_auth_token: | |
request_params['app_auth_token'] = app_auth_token | |
sign = self.sign(request_params) | |
request_params['sign'] = sign | |
response = requests.post(self.gateway, params=request_params) | |
json_data = json.loads(response.content) | |
return json_data | |
def create_photo(self, app_auth_token, content, suffix="jpg"): | |
method = "alipay.offline.material.image.upload" | |
name = md5(content) | |
now = datetime_now() | |
timestamp = datetime_to_str(now, '%Y-%m-%d %H:%M:%S') | |
request_params = { | |
"app_id": self.app_id, | |
"method": method, | |
"charset": self.charset, | |
"sign_type": self.sign_type, | |
"timestamp": timestamp, | |
"version": "1.0", | |
"format": "json", | |
"image_type": suffix, | |
"image_name": name, | |
} | |
if app_auth_token: | |
request_params['app_auth_token'] = app_auth_token | |
sign = self.sign(request_params) | |
request_params['sign'] = sign | |
files = { | |
"image_content": ("%s.%s" % (name, suffix), content, 'text/plain') | |
} | |
response = requests.post(self.gateway, params=request_params, files=files) | |
return json.loads(response.content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment