forked from glim/rest-api-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
207 lines (172 loc) · 7.55 KB
/
api.py
File metadata and controls
207 lines (172 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
from __future__ import division
import base64
import datetime
import httplib2
import json
import logging
import os
import platform
import paypalrestsdk.util as util
from paypalrestsdk.exceptions import *
from paypalrestsdk.version import __version__
class Api:
# User-Agent for HTTP request
library_details = "httplib2 %s; python %s" % (httplib2.__version__, platform.python_version())
user_agent = "PayPalSDK/rest-sdk-python %s (%s)" % (__version__, library_details)
# Create API object
# == Example
# import paypalrestsdk
# api = paypalrestsdk.Api( mode="sandbox",
# client_id='CLIENT_ID', client_secret='CLIENT_SECRET', ssl_options={} )
def __init__(self, options={}, **args):
args = util.merge_dict(options, args)
self.mode = args.get("mode", "sandbox")
self.endpoint = args.get("endpoint", self.default_endpoint())
self.token_endpoint = args.get("token_endpoint", self.endpoint)
self.client_id = args.get("client_id")
self.client_secret = args.get("client_secret")
self.ssl_options = args.get("ssl_options", {})
self.token_hash = None
self.token_request_at = None
if args.get("token"):
self.token_hash = {"access_token": args.get("token"), "token_type": "Bearer"}
self.options = args
# Default endpoint
def default_endpoint(self):
if self.mode == "live":
return "https://api.paypal.com"
else:
return "https://api.sandbox.paypal.com"
# Find basic auth
def basic_auth(self):
credentials = "%s:%s" % (self.client_id, self.client_secret)
return base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
# Generate token_hash
def get_token_hash(self):
self.validate_token_hash()
if self.token_hash is None:
self.token_request_at = datetime.datetime.now()
self.token_hash = self.http_call(util.join_url(self.token_endpoint, "/v1/oauth2/token"), "POST",
body="grant_type=client_credentials",
headers={
"Authorization": ("Basic %s" % self.basic_auth()),
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json", "User-Agent": self.user_agent
})
return self.token_hash
# Validate expires_in
def validate_token_hash(self):
if self.token_request_at and self.token_hash and self.token_hash.get("expires_in") is not None:
delta = datetime.datetime.now() - self.token_request_at
duration = (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6
if duration > self.token_hash.get("expires_in"):
self.token_hash = None
# Get access token
def get_token(self):
return self.get_token_hash()["access_token"]
# Get token type
def get_token_type(self):
return self.get_token_hash()["token_type"]
# Make HTTP call and Format Response
# == Example
# api.request("https://api.sandbox.paypal.com/v1/payments/payment?count=10", "GET", {})
# api.request("https://api.sandbox.paypal.com/v1/payments/payment", "POST", "{}", {} )
def request(self, url, method, body=None, headers={}):
http_headers = util.merge_dict(self.headers(), headers)
if http_headers.get('PayPal-Request-Id'):
logging.info('PayPal-Request-Id: %s' % (http_headers['PayPal-Request-Id']))
try:
return self.http_call(url, method, body=body, headers=http_headers)
# Format Error message for bad request
except BadRequest as error:
return {"error": json.loads(error.content)}
# Handle Exipre token
except UnauthorizedAccess as error:
if(self.token_hash and self.client_id):
self.token_hash = None
return self.request(url, method, body, headers)
else:
raise error
# Make http Call
def http_call(self, url, method, **args):
logging.info('Request[%s]: %s' % (method, url))
http = httplib2.Http(**self.ssl_options)
start_time = datetime.datetime.now()
response, content = http.request(url, method, **args)
duration = datetime.datetime.now() - start_time
logging.info('Response[%d]: %s, Duration: %s.%ss' % (response.status, response.reason, duration.seconds, duration.microseconds))
return self.handle_response(response, content.decode('utf-8'))
# Validate HTTP response
def handle_response(self, response, content):
status = response.status
if status in (301, 302, 303, 307):
raise Redirection(response, content)
elif 200 <= status <= 299:
if content:
return json.loads(content)
else:
return {}
elif status == 400:
raise BadRequest(response, content)
elif status == 401:
raise UnauthorizedAccess(response, content)
elif status == 403:
raise ForbiddenAccess(response, content)
elif status == 404:
raise ResourceNotFound(response, content)
elif status == 405:
raise MethodNotAllowed(response, content)
elif status == 409:
raise ResourceConflict(response, content)
elif status == 410:
raise ResourceGone(response, content)
elif status == 422:
raise ResourceInvalid(response, content)
elif status >= 401 and status <= 499:
raise ClientError(response, content)
elif status >= 500 and status <= 599:
raise ServerError(response, content)
else:
raise ConnectionError(response, content, "Unknown response code: #{response.code}")
# Default HTTP headers
def headers(self):
return {
"Authorization": ("%s %s" % (self.get_token_type(), self.get_token())),
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": self.user_agent
}
# Make GET request
# == Example
# api.get("v1/payments/payment?count=1")
# api.get("v1/payments/payment/PAY-1234")
def get(self, action, headers={}):
return self.request(util.join_url(self.endpoint, action), 'GET', headers=headers)
# Make POST request
# == Example
# api.post("v1/payments/payment", { 'indent': 'sale' })
# api.post("v1/payments/payment/PAY-1234/execute", { 'payer_id': '1234' })
def post(self, action, params={}, headers={}):
return self.request(util.join_url(self.endpoint, action), 'POST', body=json.dumps(params), headers=headers)
# Make DELETE request
def delete(self, action, headers={}):
return self.request(util.join_url(self.endpoint, action), 'DELETE', headers=headers)
global __api__
__api__ = None
# Get default api
def default():
global __api__
if __api__ is None:
try:
client_id = os.environ["PAYPAL_CLIENT_ID"]
client_secret = os.environ["PAYPAL_CLIENT_SECRET"]
except KeyError:
raise MissingConfig("Required PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET. Refer https://github.com/paypal/rest-api-sdk-python#configuration")
__api__ = Api(mode=os.environ.get("PAYPAL_MODE", "sandbox"), client_id=client_id, client_secret=client_secret)
return __api__
# Create new default api object with given configuration
def set_config(options={}, **config):
global __api__
__api__ = Api(options, **config)
return __api__
configure = set_config