Skip to content
This repository was archived by the owner on May 21, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@ The official Amazon Pay Python SDK.

## Requirements

Python >= 3.2<br/>
pyOpenSSL >= 0.11<br/>
Requests >= 2.6.0<br/>
- Python >= 3.2<br/>

Install dependencies using requirements.txt

```shell
pip install -r requirements.txt
```


## Documentation

Expand Down
103 changes: 51 additions & 52 deletions amazon_pay/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from amazon_pay.payment_request import PaymentRequest
from fileinput import filename


class AmazonPayClient:

logger = logging.getLogger('__amazon_pay_sdk__')
Expand All @@ -34,9 +35,7 @@ def __init__(
log_enabled=False,
log_file_name=None,
log_level=None
):


):
"""
Parameters
----------
Expand Down Expand Up @@ -143,30 +142,31 @@ def __init__(
ch = logging.StreamHandler(sys.stdout)
self.logger.addHandler(ch)
ch.setLevel(numeric_level)

app_name_and_ver = ''

if application_name not in ['', None]:
app_name_and_ver = app_name_and_ver + str(application_name)
if application_version not in ['', None]:
app_name_and_ver = app_name_and_ver + '/' + str(application_version)
app_name_and_ver = app_name_and_ver + \
'/' + str(application_version)

elif application_version not in ['', None]:
app_name_and_ver = app_name_and_ver + str(application_version)

if ((application_name not in ['', None]) | (application_version not in ['', None])):
app_name_and_ver = app_name_and_ver + '; '

current_py_ver = ".".join(map(str, sys.version_info[:3]))

self._user_agent = 'amazon-pay-sdk-python/{0} ({1}Python/{2}; {3}/{4})'.format(
str(self._application_library_version),
str(app_name_and_ver),
str(current_py_ver),
str(platform.system()),
str(platform.release())
)

self.logger.debug('user agent: %s', self._user_agent)

self._headers = {
Expand Down Expand Up @@ -205,13 +205,13 @@ def get_login_profile(self, access_token, client_id):
sandbox=self._sandbox)
response = lwa_client.get_login_profile(access_token=access_token)
return response

def get_merchant_account_status(
self,
merchant_id=None,
mws_auth_token=None):
""" Check the account status of the merchant

Parameters
----------
merchant_id : string, optional
Expand All @@ -220,18 +220,18 @@ def get_merchant_account_status(

mws_auth_token: string, optional
Your marketplace web service auth token. Default: None

"""
parameters = {
'Action': 'GetMerchantAccountStatus'
}
}

optionals = {
'SellerId': merchant_id,
'MWSAuthToken': mws_auth_token}

return self._operation(params=parameters, options=optionals)

def create_order_reference_for_id(
self,
object_id,
Expand Down Expand Up @@ -683,22 +683,22 @@ def set_order_reference_details(
return self._operation(params=parameters, options=optionals)

def set_order_attributes(
self,
amazon_order_reference_id,
currency_code=None,
amount=None,
seller_order_id=None,
payment_service_provider_id=None,
payment_service_provider_order_id=None,
platform_id=None,
seller_note=None,
request_payment_authorization=None,
store_name=None,
list_order_item_categories=None,
custom_information=None,
merchant_id=None,
mws_auth_token=None,
supplementary_data=None):
self,
amazon_order_reference_id,
currency_code=None,
amount=None,
seller_order_id=None,
payment_service_provider_id=None,
payment_service_provider_order_id=None,
platform_id=None,
seller_note=None,
request_payment_authorization=None,
store_name=None,
list_order_item_categories=None,
custom_information=None,
merchant_id=None,
mws_auth_token=None,
supplementary_data=None):
'''
Return and update the information of an order with missing
or updated information
Expand Down Expand Up @@ -806,7 +806,6 @@ def set_order_attributes(

return self._operation(params=parameters, options=optionals)


def get_order_reference_details(
self,
amazon_order_reference_id,
Expand All @@ -823,7 +822,7 @@ def get_order_reference_details(
The order reference identifier. This value is retrieved from the
amazon pay Button widget after the buyer has successfully authenticated
with Amazon.

access_token : string, optional
The access token. This value is retrieved from the
amazon pay Button widget after the buyer has successfully authenticated
Expand Down Expand Up @@ -901,8 +900,8 @@ def confirm_order_reference(
'SuccessUrl': success_url,
'FailureUrl': failure_url,
'AuthorizationAmount.Amount': authorization_amount,
'AuthorizationAmount.CurrencyCode': self.currency_code if currency_code is None else currency_code }
'AuthorizationAmount.CurrencyCode': self.currency_code if currency_code is None else currency_code}

if authorization_amount == "0" or authorization_amount is None:
del optionals['AuthorizationAmount.Amount']
del optionals['AuthorizationAmount.CurrencyCode']
Expand Down Expand Up @@ -988,7 +987,6 @@ def list_order_reference(
order_reference_status_list_filter=None,
merchant_id=None,
mws_auth_token=None):

"""
Allows the search of any Amazon Pay order made using secondary
seller order IDs generated manually, a solution provider, or a custom
Expand All @@ -1004,7 +1002,7 @@ def list_order_reference(
The type of query the id is referencing.
Note: At this time, you can only use the query type (SellerOrderId).
More options will be available in the future. Default: SellerOrderId

payment_domain: string, optional
The region and currency that will be set to authorize and collect
payments from your customers. You can leave this blank for the
Expand Down Expand Up @@ -1048,28 +1046,29 @@ def list_order_reference(
of the orders on file. You can search for any valid status for orders
on file. Filters MUST be written out in English.
Example: "Open", "Closed", "Suspended", "Canceled"
Default: None
Default: None
"""

if self.region is not None:
region_code = self.region.lower()
if region_code == 'na':
payment_domain = 'NA_USD'
elif region_code in ('uk', 'gb'):
payment_domain = 'EU_GBP'
elif region_code in ('jp', 'fe'):
payment_domain = 'FE_JPY'
payment_domain = 'FE_JPY'
elif region_code in ('eu', 'de', 'fr', 'it', 'es', 'cy'):
payment_domain = 'EU_EUR'
else:
raise ValueError("Error. The current region code does not match our records")
raise ValueError(
"Error. The current region code does not match our records")

parameters = {
'Action': 'ListOrderReference',
'QueryId': query_id,
'QueryIdType': query_id_type,
'PaymentDomain': payment_domain
}
}
optionals = {
'CreatedTimeRange.StartTime': created_time_range_start,
'CreatedTimeRange.EndTime': created_time_range_end,
Expand Down Expand Up @@ -1120,7 +1119,6 @@ def get_payment_details(
amazon_order_reference_id,
merchant_id=None,
mws_auth_token=None):

'''
This is a convenience function that will return every authorization,
charge, and refund call of an Amazon Pay order ID.
Expand Down Expand Up @@ -1176,7 +1174,8 @@ def get_payment_details(
answer.append(response)
queryID = json.loads(response.to_json())
chargeID = queryID['GetAuthorizationDetailsResponse']\
['GetAuthorizationDetailsResult']['AuthorizationDetails']['IdList']
['GetAuthorizationDetailsResult'][
'AuthorizationDetails']['IdList']

if chargeID is not None:
chargeID = chargeID['member']
Expand All @@ -1194,7 +1193,7 @@ def get_payment_details(
if type(refundID['member']) is not list:
refundID = [refundID['member']]
else:
refundID = refundID['member']
refundID = refundID['member']

for id in refundID:
parameters = {
Expand Down Expand Up @@ -1721,12 +1720,12 @@ def _operation(self, params, options=None):

request.send_post()
return request.response

def _enumerate(
self,
category,
filter_types,
optionals):
self,
category,
filter_types,
optionals):

def enumerate_param(param, values):
"""
Expand Down Expand Up @@ -1758,7 +1757,7 @@ def enumerate_param(param, values):
optionals.update(enumerate_param(category, filter_types))
else:
if ',' in filter_types:
filter_types = filter_types.replace(' ','')
filter_types = filter_types.replace(' ', '')
filter_types = filter_types.split(',')
optionals.update(enumerate_param(category, filter_types))
else:
Expand Down
18 changes: 10 additions & 8 deletions amazon_pay/ipn_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ def __init__(self, body, headers):
self._xml = self._notification_data.replace(
'<?xml version="1.0" encoding="UTF-8"?>\n',
'')
self.logger.debug('IPN Response: %s',
self._sanitize_response_data(self._xml))
self.logger.debug('IPN Response: %s',
self._sanitize_response_data(self._xml))

def authenticate(self):
"""Attempt to validate a SNS message received from Amazon
Expand Down Expand Up @@ -171,23 +171,25 @@ def _validate_signature(self):
return True

def to_json(self):
"""Retuns notification message as JSON"""
"""Retuns notification message as JSON"""
return PaymentResponse(self._xml).to_json()

def to_xml(self):
"""Retuns notification message as XML"""
return PaymentResponse(self._xml).to_xml()

def _sanitize_response_data(self, text):
editText = text
patterns = []
patterns.append(r'(?s)(<SellerNote>).*(<\/SellerNote>)')
patterns.append(r'(?s)(<AuthorizationBillingAddress>).*(<\/AuthorizationBillingAddress>)')
patterns.append(r'(?s)(<SellerAuthorizationNote>).*(<\/SellerAuthorizationNote>)')
patterns.append(
r'(?s)(<AuthorizationBillingAddress>).*(<\/AuthorizationBillingAddress>)')
patterns.append(
r'(?s)(<SellerAuthorizationNote>).*(<\/SellerAuthorizationNote>)')
patterns.append(r'(?s)(<SellerCaptureNote>).*(<\/SellerCaptureNote>)')
patterns.append(r'(?s)(<SellerRefundNote>).*(<\/SellerRefundNote>)')
replacement = r'\1 REMOVED \2'

for pattern in patterns:
editText = re.sub(pattern, replacement, editText)
return editText
return editText
Loading