Skip to content

Instantly share code, notes, and snippets.

@swenson
Created February 25, 2014 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swenson/9202339 to your computer and use it in GitHub Desktop.
Save swenson/9202339 to your computer and use it in GitHub Desktop.
Deferred payment in Python for PayPal
import json
import requests
class PaymentInfo(object):
def __init__(self, credit_card, transaction):
self.credit_card = credit_card
self.transaction = transaction
class CreditCard(object):
def __init__(self, number, type, expire_month, expire_year, cvv2, first_name, last_name, billing_address):
self.number = number
self.type = type
self.expire_month = expire_month
self.expire_year = expire_year
self.cvv2 = cvv2
self.first_name = first_name
self.last_name = last_name
self.billing_address = billing_address
class InvalidCredentials(Exception):
pass
class PayPal(object):
def __init__(self, client_id, secret):
self.client_id = client_id
self.secret = secret
def get_token(self):
r = requests.post('https://api.sandbox.paypal.com/v1/oauth2/token', {
'grant_type': 'client_credentials'
}, auth=(self.client_id, self.secret))
try:
return r.json()['access_token']
except (AttributeError,):
raise InvalidCredentials()
def authorize_payment(self, payment_info):
"""
Authorizes a payment for up to 30 days.
"""
if 'token' not in self.__dict__:
self.token = self.get_token()
data = json.dumps({
"intent": "authorize",
"payer": {
"payment_method": "credit_card",
"funding_instruments": [
{"credit_card": payment_info.credit_card.__dict__}
]
},
"transactions": [
{
"amount": payment_info.transaction
}
]
})
r = requests.post("https://api.sandbox.paypal.com/v1/payments/payment",
data=data,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer %s" % self.token
})
if (r.status_code >= 400):
print r.json()
res = r.json()['transactions'][0]['related_resources'][0]
# Not sure if we can guarantee the order here?
capture_url = [x['href'] for x in res['authorization']['links'] if x['rel'] == 'capture'][0]
auth_id = res['authorization']['id']
return auth_id, capture_url
def capture_payment(self, authorize_id, currency, total):
"""
Captures (eg cashes) an already authorized payment
"""
if 'token' not in self.__dict__:
self.token = self.get_token()
url = "https://api.sandbox.paypal.com/v1/payments/authorization/%s/capture" % authorize_id
r = requests.post(url,
data=json.dumps({
"amount": {
"currency": currency,
"total": total,
},
"is_final_capture": "true",
}),
headers={"Authorization": "Bearer %s" % self.token})
# TODO check status code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment