Skip to content

Instantly share code, notes, and snippets.

@mattijevi
Last active April 4, 2017 01:00
Show Gist options
  • Save mattijevi/d403152f6bbca384bb89e69dcf8d94da to your computer and use it in GitHub Desktop.
Save mattijevi/d403152f6bbca384bb89e69dcf8d94da to your computer and use it in GitHub Desktop.
import uuid
import hmac
import hashlib
import base64
import random
import time
import json
import requests
import logging
# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
# https://github.com/SagePayments/Direct-API/blob/master/php/sale.php
SAGE_CLIENT_ID = ''
SAGE_CLIENT_SECRET = ''
SAGE_MERCHANT_KEY = ''
SAGE_MERCHANT_ID = ''
SAGE_API_ENDPOINT = 'https://api-cert.sagepayments.com/'
# the nonce can be any unique identifier -- guids and timestamps work well
nonce = int(time.time()) # uuid.uuid4()
# a standard unix timestamp. a request must be received within 60s
# of its timestamp header.
timestamp = int(time.time())
# setting up the request data itself
verb = "POST"
url = "https://api-cert.sagepayments.com/bankcard/v1/charges?type=Sale"
requestData = {
# this is a pretty minimalistic example...
# complete reference material is available on the dev portal.
"Ecommerce": {
"orderNumber": "Invoice{id}".format(
id=random.randint(
100,
10000
)
),
"amounts": {
"tip": "4.24",
"total": "42.42",
"tax": "2.12",
"shipping": "1.06"
},
"cardData": {
"number": "4111111111111111",
"expiration": "0617",
"cvv": "123"
}
}
}
# convert to json for transport
payload = json.dumps(requestData)
# the request is authorized via an HMAC header that we generate by
# concatenating certain info, and then hashing it using our client key
toBeHashed = "{verb}{url}{payload}{SAGE_MERCHANT_ID}{nonce}{timestamp}".format(
verb=verb,
url=url,
payload=payload,
SAGE_MERCHANT_ID=SAGE_MERCHANT_ID,
nonce=nonce,
timestamp=timestamp,
)
signature = base64.b64encode(
hmac.new(
SAGE_CLIENT_SECRET.encode('ascii'),
toBeHashed.encode('ascii'),
digestmod=hashlib.sha512
).hexdigest().encode('utf-8')
)
r = requests.post(
url,
headers={
'clientId': SAGE_CLIENT_ID,
'merchantId': SAGE_MERCHANT_ID,
'merchantKey': SAGE_MERCHANT_KEY,
'nonce': str(nonce),
'timestamp': str(timestamp),
'Authorization': signature,
'Content-Type': "application/json",
},
data=payload
)
print(r.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment