diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..c98efcf --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 PAY.ON AG + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..df74add --- /dev/null +++ b/README.md @@ -0,0 +1,239 @@ +# opp-python +Python wrapper for the [PAY.ON’s Open Payment Platform](https://docs.oppwa.com/) server-to-server REST API. + +## Getting started + +- We highly recommend to start with the [integration guide](https://docs.oppwa.com/) to get familiar with the OPP workflow. +- Check the server-to-server [documentation](https://docs.oppwa.com/server-to-server) and try out our code snippets. +- Install the latest release. +- Take a look at our [tests](tests/) to see the wrapper in action. + +## Installation +The recommended way for installing the package is from PyPi, executing the following line: + +``` +pip install opp +``` + +Alternatively, you can clone the project and install it locally. + +``` +git clone git@github.com:OpenPaymentPlatform/python.git +cd python +pip install . +``` +## News + +We have just released the first version of our wrapper - 1.0.0 . Feel free to share with us any feedback, bugs, feature requests or your project using our wrapper, by opening an [issue](issues). + +## Usage +The wrapper exposes two interfaces. +- The core interface is a simple http client for low level communication. It exposes only basic services, corresponding to the API endpoints. Requests and responses are dictionaries. +- The facade interface allows a higher level communication with the API. It exposes convinience services for implementing specific payment workflows. Requests are parameterized, API responses are deserialized. The interface also contains several helper functions. + +### Core +In order to use the core module, you should first import it as shown below: +```python +import opp.core +``` + +#### Initialization +Initialize a core wrapper instance by providing your credentials: +```python +api = opp.core.API(**{"authentication.userId": "YourUserId", + "authentication.password": "YourPassword", + "authentication.entityId": "YourEntityId"}) +``` + + +##### Services + +The core interface exposes several services through ``opp.core.API``, representing the different API endpoints: + +- payments() +- checkouts() +- registrations() + +Every service provides methods for the (available) CRUD functionality of the endpoint. +Note, that the services are initialized along the wrapper instance, you should not create them explicitly. + +##### Create + +To create an object, just call the ``create`` method on the service, for example: + +```python +checkout = api.checkouts().create(**{"amount": "92.00", + "currency": "EUR", + "paymentType": "PA"}) +``` +##### Retrieve + +To retrieve an object, just supply the ID as an argument to the service and call ``get()``, for example: + +```python +checkout2 = api.checkouts(checkout_id='some_id').get() +``` + +##### Delete + +To delete an object, just supply the ID as an argument to the service and call ``get()``, for example: + +```python +result = api.registrations(registration_id='some_id').delete() +``` + + +### Facade +In order to use the ``facade`` module, you should first import it as shown below: +```python +import opp.facade +``` + +#### Objects +The facade interface is exposing convenience Python objects for the Open Payment Platform [parameters](https://docs.oppwa.com/parameters#) for inputs, as well as for response parameters. Following examples show some of the these objects and how to create them. +**Convention: All object properties in the facade are in snake case notation as opposed to the OPP API reference where a camel case notation is used.** + +##### BasicPayment +```python +basic_payment = opp.facade.BasicPayment(amount='92.00', currency='EUR', payment_brand='AMEX', descriptor='Test Amex') +``` +*The ``paymentType`` parameter from the OPP API reference is not included in the BasicPayment object, because it is mapped automatically depending which of the opp.facade.API services is used.* + +##### CardAccount +```python +card_account = opp.facade.CardAccount(holder='Jane Jones', number='377777777777770', expiry_month='05', + expiry_year='2018', + cvv='1234') +``` + +##### VirtualAccount +```python +virtual_account = opp.facade.VirtualAccount(account_id="1a2b3c4d5e6f7g8h9i", password="sy6KJsT8") +``` + +##### BankAccount +```python +bank_account = opp.facade.BankAccount(holder="Jane Jones", bank_name="Deutsche Bank", number="1009534785", + iban="DE23100000001234567890", bank_code="DEUTDEMM", bic="DEUTDEFF", + country="DE", + mandate=opp.facade.Mandate(id='1a2b3c4d5e6f7g8h9i', date_of_signature='2015-07-09'), + transaction_due_date="2015-07-09") +``` + +##### Customer +```python +opp.facade.Customer(merchant_customer_id="1a2b3c4d5e6f7g8h9i", given_name="Jane", + surname="Jones", sex="F", + birth_date="1983-10-05", phone="+49 123456789", mobile="+49 987654321", + email="jane.jones@test.de", company_name="Test Company", + identification_doc_type="TAXSTATEMENT", + identification_doc_id="a1b2c3d4e5f6g7h8i9", + customer_ip="XX.XXX.XX.XXX") +``` + +#### Initialization +First, create an ``opp.facade.Authentication`` object: +```python +authentication = opp.facade.Authentication(user_id='8a8294174b7ecb28014b9699220015cc', password='sy6KJsT8', + entity_id='8a8294174b7ecb28014b9699220015ca') +``` + +Then initialize the facade interface: + +```python +api = opp.facade.API(authentication) +``` + +##### Services +The facade interface provides a more granular level of service description based on the operations and workflows you should implement. +Based on the payment type of the operation the ``opp.core.API.payments()`` service is divided into: + +- preauthorizations() +- debits() +- credits() +- refunds() +- captures() +- reversals() + +As in the ``core`` module the facade exposes its services through an object called ``opp.facade.API`` where following services are defined: + +- preauthorizations() +- debits() +- credits() +- refunds() +- captures() +- reversals() +- checkouts() +- registrations() + +As in the core module every service provides methods for the (available) CRUD functionality of the endpoint. +Note, that the services are initialized along the wrapper instance, you should not create them explicitly. + +The ``facade`` modules provides an Exception mechanism when the OPP platform returns an error response. + +##### Create + +To create an object, just call the ``create`` method on the service, for example: + +```python +try: + preauthorization = api.preauthorizations().create(basic_payment, card_account) + print(preauthorization.result.code) +except opp.facade.ApiError as e: + #handle error + print(e) +``` + +As you can see in the example above all returned properties by the OPP API can be accessed with the dot operator from the returned Python object. + +##### Retrieve + +To retrieve an object, just supply the ID as an argument to the service and call ``get()``, for example: + +```python +try: + transaction = api.debits(payment_id='some_id').get() +except opp.facade.ApiError as e: + #handle error + print(e) +``` + +##### Delete + +To delete an object, just supply the ID as an argument to the service and call ``get()``, for example: + +```python +try: + result = api.registrations(registration_id='some_id').delete() +except opp.facade.ApiError as e: + #handle error + print(e) +``` + +### Configuration +The ``config`` module provides a simple interface for configuring some HTTP related policies as shown below. + +```python +import opp.config +opp.config.configure(test_url=TEST_URL, live_url=LIVE_URL, mode=TEST_INTERNAL, request_timeout=REQUEST_TIMEOUT) +``` +The same configuration applies for the ``opp.core``, as well as for the ``opp.facade`` modules. + +### Logging +For logging the HTTP operations that are executed through the ``opp`` Python library you can use the standard ``logging`` utilityself. + +```python +import logging +logging.basicConfig(level=logging.DEBUG, filename='opp.log') +``` + +## Changelog + +### 1.0.0 +* First version + +## License + +Copyright 2015 PAY.ON AG. + +MIT License (enclosed) diff --git a/example_facade_concurrent.py b/example_facade_concurrent.py new file mode 100644 index 0000000..de8f0dc --- /dev/null +++ b/example_facade_concurrent.py @@ -0,0 +1,54 @@ +__author__ = 'PAY.ON' +import opp +import logging + +import threading +logger = logging.getLogger("example_facade_concurrent") + + +def success_worker(num, worker_api): + #success_worker creates a transaction and should succeed + + # create payment parameters + basic_payment = opp.facade.BasicPayment(amount='92.00', currency='EUR', payment_brand='AMEX', descriptor='Test Amex') + + # create card account parameters + card_account = opp.facade.CardAccount(holder='Jane Jones', number='377777777777770', expiry_month='05', + expiry_year='2018', + cvv='1234') + + try: + preauthorization = worker_api.preauthorizations().create(basic_payment, card_account) + logger.debug("Success Worker #{0} RESPONSE: {1}".format(num, preauthorization.__dict__)) + except opp.facade.ApiError as e: + #handle error + print(e) + + +def failure_worker(num, worker_api): + #failure_worker tries to create a transaction without sending any payment data and should fail with an exception, + #so output will come from except case + try: + worker_api.preauthorizations().create() + except opp.facade.ApiError as e: + #handle error + logger.debug("Failure Worker #{0} RESPONSE: {1}".format(num, e)) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG, filename='opp.log') + threads = [] + authentication = opp.facade.Authentication(user_id='8a8294174b7ecb28014b9699220015cc', password='sy6KJsT8', + entity_id='8a8294174b7ecb28014b9699220015ca') + + # initialize OPP API with authentication object + api = opp.facade.API(authentication) + #start workers with passing through the shared opp.facade.API object + for i in range(5): + t = threading.Thread(target=success_worker, args=(i, api, )) + t2 = threading.Thread(target=failure_worker, args=(i, api, )) + threads.append(t) + t2.start() + t.start() + + + diff --git a/opp/facade.py b/opp/facade.py index 36b5b04..d7140e3 100644 --- a/opp/facade.py +++ b/opp/facade.py @@ -3,7 +3,7 @@ import opp.core import opp.utils import logging - +import six logger = logging.getLogger(__name__) @@ -114,7 +114,7 @@ def from_params(params): class BankAccount(object): def __init__(self, holder=None, bank_name=None, number=None, iban=None, bank_code=None, bic=None, country=None, - mandate_id=None, mandate_date_of_signature=None, transaction_due_date=None): + mandate=None, transaction_due_date=None): """ @@ -126,8 +126,7 @@ def __init__(self, holder=None, bank_name=None, number=None, iban=None, bank_cod :param bank_code: :param bic: :param country: - :param mandate_id: - :param mandate_date_of_signature: + :param mandate: :param transaction_due_date: """ self.holder = holder @@ -137,8 +136,7 @@ def __init__(self, holder=None, bank_name=None, number=None, iban=None, bank_cod self.bank_code = bank_code self.bic = bic self.country = country - self.mandate_id = mandate_id - self.mandate_date_of_signature = mandate_date_of_signature + self.mandate = mandate self.transaction_due_date = transaction_due_date def to_params(self): @@ -149,8 +147,8 @@ def to_params(self): "bankAccount.bankCode": self.bank_code, "bankAccount.bic": self.bic, "bankAccount.country": self.country, - "bankAccount.mandate.id": self.mandate_id, - "bankAccount.mandate.dateOfSignature": self.mandate_date_of_signature, + "bankAccount.mandate.id": self.mandate.id, + "bankAccount.mandate.dateOfSignature": self.mandate.date_of_signature, "transactionDueDate": self.transaction_due_date} @staticmethod @@ -159,8 +157,7 @@ def from_params(params): return BankAccount(holder=params.get('holder'), bank_name=params.get('bankName'), number=params.get('number'), iban=params.get('iban'), bank_code=params.get('bankCode'), bic=params.get('bic'), - country=params.get('country'), mandate_id=params.get('mandate.id'), - mandate_date_of_signature=params.get('mandate.dateOfSignature'), + country=params.get('country'), mandate=Mandate.from_params(params.get('mandate')), transaction_due_date=params.get('transactionDueDate')) @@ -221,7 +218,7 @@ def from_params(params): company_name=params.get('companyName'), identification_doc_type=params.get('identificationDocType'), identification_doc_id=params.get('identificationDocId'), - customer_ip=params.get('customer.ip')) + customer_ip=params.get('ip')) class BillingAddress(object): @@ -298,7 +295,7 @@ def to_params(self): @staticmethod def from_params(params): if params is not None: - return BillingAddress(given_name=params.get('givenName'), surname=params.get('surname'), + return ShippingAddress(given_name=params.get('givenName'), surname=params.get('surname'), street1=params.get('street1'), street2=params.get('street2'), city=params.get('city'), state=params.get('state'), postcode=params.get('postcode'), country=params.get('country')) @@ -362,7 +359,7 @@ def to_params(self): params = {} count = 0 for item in self.items: - for k, v in item.to_params().iteritems(): + for k, v in six.iteritems(item.to_params()): key_str = "cart.items[{0}].{1}".format(count, k) value_str = "{0}".format(v) d = {key_str: value_str} @@ -378,7 +375,6 @@ def from_params(params): item = Item.from_params(param) if item is not None: items.append(item) - return Cart(items=items) @@ -437,13 +433,13 @@ def __init__(self, **kwargs): :rtype : object :param name: """ - for key, value in kwargs.iteritems(): - self.key = value + for key, value in six.iteritems(kwargs): + self.__dict__.update({key: value}) def to_params(self): params = {} - for key, value in self.__dict__.iteritems(): - params.update({"customParameters[{0}]".format(key): value}) + for key, value in six.iteritems(self.__dict__): + params.update({"customParameters[SHOPPER_{0}]".format(key): value}) return params @@ -485,6 +481,16 @@ def from_params(params): return Merchant(bank_account=BankAccount.from_params(params.get('bankAccount'))) +class Mandate(object): + def __init__(self, id=None, date_of_signature=None): + self.id = id + self.date_of_signature = date_of_signature + + @staticmethod + def from_params(params): + if params is not None: + return Mandate(id=params.get('id'), date_of_signature=params.get('dateOfSignature')) + class Parameter(object): def __init__(self, name, value): self.name = name @@ -510,7 +516,6 @@ def from_params(params): parameter = Parameter.from_params(param) if parameter is not None: parameters_list.append(parameter) - return Redirect(url=params.get('url'), parameters=parameters_list) @@ -534,7 +539,7 @@ def __init__(self, id=None, payment_type=None, payment_brand=None, amount=None, self.shipping_address = shipping_address self.cart = cart self.merchant = merchant - self.async_payments = redirect + self.redirect = redirect self.timestamp = timestamp self.build_number = build_number self.ndc = ndc @@ -546,7 +551,7 @@ def from_params(params): id = params.get('id') payment_type = params.get('paymentType') payment_brand = params.get('paymentBrand') - amount = params.get('paymentType') + amount = params.get('amount') currency = params.get('currency') descriptor = params.get('descriptor') # nested objects @@ -554,10 +559,13 @@ def from_params(params): card_account = CardAccount.from_params(params.get('cardAccount')) virtual_account = VirtualAccount.from_params(params.get('virtualAccount')) bank_account = BankAccount.from_params(params.get('bankAccount')) - customer = Customer.from_params(params.get('customer')), - billing_address = BillingAddress.from_params(params.get('billingAddress')) - shipping_address = ShippingAddress.from_params(params.get('shippingAddress')) - cart = Cart.from_params(params.get('cart')) + customer = Customer.from_params(params.get('customer')) + billing_address = BillingAddress.from_params(params.get('billing')) + shipping_address = ShippingAddress.from_params(params.get('shipping')) + if params.get('cart') is not None: + cart = Cart.from_params(params.get('cart').get('items')) + else: + cart = None merchant = Merchant.from_params(params.get('merchant')) redirect = Redirect.from_params(params.get('redirect')) timestamp = params.get('timestamp') diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..224a779 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description-file = README.md \ No newline at end of file diff --git a/setup.py b/setup.py index ecc84d2..556c8c9 100644 --- a/setup.py +++ b/setup.py @@ -1,17 +1,25 @@ # coding=utf-8 __author__ = 'PAY.ON' +import sys + +if sys.version_info < (3, 4): + install_requires = ['requests >= 2.5.3', 'six >= 1.9.0', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'] +else: + install_requires = ['requests >= 2.5.3', 'six >= 1.9.0'] + from setuptools import setup + setup( name='opp', version='1.0.0', description='Python wrapper for OPP', author='PAY.ON', author_email='opp@payon.com', - url='https://github.com/OpenPaymentPlatform/python.git', + url='https://github.com/OpenPaymentPlatform/python', license='MIT', packages=['opp'], classifiers=[ - 'Development Status :: 4 - Beta', + 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', @@ -21,4 +29,6 @@ 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], - install_requires=['requests >= 2.5.3', 'six >= 1.9.0', 'requests[security]']) + install_requires=install_requires, + download_url='https://github.com/OpenPaymentPlatform/python/tarball/1.0.0' +) diff --git a/test b/test deleted file mode 100644 index 8a634dd..0000000 --- a/test +++ /dev/null @@ -1 +0,0 @@ -u'merchant': {u'bankAccount': {u'iban': u'TRUE', u'holder': u'merchantName', u'number': u'15300', u'country': u'BR'}}, u'customParameters': {u'BRADESCO_cpfsacado': u'11111111111', u'SHOPPER_pluginId': u'Python'}, u'buildNumber': u'20150702-073859.r185710.opp-tags-20150702_stage', u'result': {u'code': u'000.100.112', u'description': u"Request successfully processed in 'Merchant in Connector Test Mode'"}, u'timestamp': u'2015-07-07 08:02:02+0000', u'ndc': u'8a8294174b7ecb28014b9699220015ca_e3d173abf0444fba9c8ef2d50443ea47', u'id': u'8a8294494e634488014e678937424be9'} \ No newline at end of file diff --git a/tests/facade/test_from_params.py b/tests/facade/test_from_params.py new file mode 100644 index 0000000..65cf458 --- /dev/null +++ b/tests/facade/test_from_params.py @@ -0,0 +1,409 @@ +__author__ = 'PAY.ON' +try: + import unittest2 as unittest +except ImportError: + import unittest + +import tests.test_data_utils +import opp.facade + + +class TestFromParams(unittest.TestCase): + def test_card_account_from_params(self): + card_account_with_result_parameters = opp.facade.CardAccount.from_params( + {"number": "377777777777770", "holder": "Jane Jones", + "expiryMonth": "05", "expiryYear": "2018", + "cvv": "1234" + } + ) + self.assertEqual(card_account_with_result_parameters.holder, "Jane Jones") + self.assertEqual(card_account_with_result_parameters.number, "377777777777770") + self.assertEqual(card_account_with_result_parameters.expiry_month, "05") + self.assertEqual(card_account_with_result_parameters.expiry_year, "2018") + self.assertEqual(card_account_with_result_parameters.cvv, "1234") + + def test_virtual_account_from_params(self): + virtual_account_with_result_parameters = opp.facade.VirtualAccount.from_params( + {"accountId": "1a2b3c4d5e6f7g8h9i", "password": "sy6KJsT8"} + ) + self.assertEqual(virtual_account_with_result_parameters.account_id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(virtual_account_with_result_parameters.password, "sy6KJsT8") + + def test_bank_account_from_params(self): + bank_account_with_result_parameters = opp.facade.BankAccount.from_params( + {"holder": "Jane Jones", + "bankName": "Deutsche Bank", + "number": "1009534785", + "iban": "DE23100000001234567890", + "bankCode": "DEUTDEMM", + "bic": "DEUTDEFF", + "country": "DE", + "mandate": {"id": "1a2b3c4d5e6f7g8h9i", + "dateOfSignature": "2015-07-09" + }, + "transactionDueDate": "2015-07-09" + } + ) + self.assertEqual(bank_account_with_result_parameters.holder, "Jane Jones") + self.assertEqual(bank_account_with_result_parameters.bank_name, "Deutsche Bank") + self.assertEqual(bank_account_with_result_parameters.number, "1009534785") + self.assertEqual(bank_account_with_result_parameters.iban, "DE23100000001234567890") + self.assertEqual(bank_account_with_result_parameters.bank_code, "DEUTDEMM") + self.assertEqual(bank_account_with_result_parameters.bic, "DEUTDEFF") + self.assertEqual(bank_account_with_result_parameters.country, "DE") + self.assertEqual(bank_account_with_result_parameters.mandate.id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(bank_account_with_result_parameters.mandate.date_of_signature, "2015-07-09") + self.assertEqual(bank_account_with_result_parameters.transaction_due_date, "2015-07-09") + + def test_customer_from_params(self): + customer_with_result_parameters = opp.facade.Customer.from_params( + {"merchantCustomerId": "1a2b3c4d5e6f7g8h9i", + "givenName": "Jane", + "surname": "Jones", + "sex": "F", + "birthDate": "1983-10-05", + "phone": "+49 123456789", + "mobile": "+49 987654321", + "email": "jane.jones@test.de", + "companyName": "Test Company", + "identificationDocType": "TAXSTATEMENT", + "identificationDocId": "a1b2c3d4e5f6g7h8i9", + "ip": "XX.XXX.XX.XXX" + } + ) + self.assertEqual(customer_with_result_parameters.merchant_customer_id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(customer_with_result_parameters.given_name, "Jane") + self.assertEqual(customer_with_result_parameters.surname, "Jones") + self.assertEqual(customer_with_result_parameters.sex, "F") + self.assertEqual(customer_with_result_parameters.birth_date, "1983-10-05") + self.assertEqual(customer_with_result_parameters.phone, "+49 123456789") + self.assertEqual(customer_with_result_parameters.mobile, "+49 987654321") + self.assertEqual(customer_with_result_parameters.email, "jane.jones@test.de") + self.assertEqual(customer_with_result_parameters.company_name, "Test Company") + self.assertEqual(customer_with_result_parameters.identification_doc_type, "TAXSTATEMENT") + self.assertEqual(customer_with_result_parameters.identification_doc_id, "a1b2c3d4e5f6g7h8i9") + self.assertEqual(customer_with_result_parameters.customer_ip, "XX.XXX.XX.XXX") + + def test_billing_address_from_params(self): + billing_address_with_result_parameters = opp.facade.BillingAddress.from_params( + {"street1": "Street 1", + "street2": "Street 2", + "city": "Test city", + "state": "Test state", + "postcode": "12345", + "country": "DE" + } + ) + self.assertEqual(billing_address_with_result_parameters.street1, "Street 1") + self.assertEqual(billing_address_with_result_parameters.street2, "Street 2") + self.assertEqual(billing_address_with_result_parameters.city, "Test city") + self.assertEqual(billing_address_with_result_parameters.state, "Test state") + self.assertEqual(billing_address_with_result_parameters.postcode, "12345") + self.assertEqual(billing_address_with_result_parameters.country, "DE") + + def test_shipping_address_from_params(self): + shipping_address_with_result_parameters = opp.facade.ShippingAddress.from_params( + {"givenName": "Jane", + "surname": "Jones", + "street1": "Street 1", + "street2": "Street 2", + "city": "Test city", + "state": "Test state", + "postcode": "12345", + "country": "DE" + } + ) + self.assertEqual(shipping_address_with_result_parameters.given_name, "Jane") + self.assertEqual(shipping_address_with_result_parameters.surname, "Jones") + self.assertEqual(shipping_address_with_result_parameters.street1, "Street 1") + self.assertEqual(shipping_address_with_result_parameters.street2, "Street 2") + self.assertEqual(shipping_address_with_result_parameters.city, "Test city") + self.assertEqual(shipping_address_with_result_parameters.state, "Test state") + self.assertEqual(shipping_address_with_result_parameters.postcode, "12345") + self.assertEqual(shipping_address_with_result_parameters.country, "DE") + + def test_cart_from_params(self): + item = {"name": "T-shirt", + "merchantItemId": "1a2b3c4d5e6f7g8h9i", + "quantity": "1", + "type": "XL", + "price": "5", + "currency": "EUR", + "description": "Summer", + "tax": "0.25", + "shipping": "1", + "discount": "5" + } + second_item = {"name": "FIFA16", + "merchantItemId": "2b3c4d5e6f7g8h9i1a", + "quantity": "1", + "type": "PS4", + "price": "55", + "currency": "EUR", + "description": "New", + "tax": "0.25", + "shipping": "1", + "discount": "5" + } + list_of_items = [item, second_item] + cart = opp.facade.Cart.from_params(list_of_items) + + self.assertEqual(cart.items[0].name, "T-shirt") + self.assertEqual(cart.items[0].merchant_item_id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(cart.items[0].quantity, "1") + self.assertEqual(cart.items[0].type, "XL") + self.assertEqual(cart.items[0].price, "5") + self.assertEqual(cart.items[0].currency, "EUR") + self.assertEqual(cart.items[0].description, "Summer") + self.assertEqual(cart.items[0].tax, "0.25") + self.assertEqual(cart.items[0].shipping, "1") + self.assertEqual(cart.items[0].discount, "5") + self.assertEqual(cart.items[1].name, "FIFA16") + self.assertEqual(cart.items[1].merchant_item_id, "2b3c4d5e6f7g8h9i1a") + self.assertEqual(cart.items[1].quantity, "1") + self.assertEqual(cart.items[1].type, "PS4") + self.assertEqual(cart.items[1].price, "55") + self.assertEqual(cart.items[1].currency, "EUR") + self.assertEqual(cart.items[1].description, "New") + self.assertEqual(cart.items[1].tax, "0.25") + self.assertEqual(cart.items[1].shipping, "1") + self.assertEqual(cart.items[1].discount, "5") + + def test_result_from_params(self): + result_with_result_parameters = opp.facade.Result.from_params( + {"code": "000.100.110", + "description": "Request successfully processed" + } + ) + self.assertEqual(result_with_result_parameters.code, "000.100.110") + self.assertEqual(result_with_result_parameters.description, "Request successfully processed") + + def test_merchant_from_params(self): + bank_account_parameters = {"bankAccount": {"holder": "Jane Jones", + "number": "1009534785", + "iban": "DE23100000001234567890", + "country": "DE" + } + } + merchant = opp.facade.Merchant.from_params(bank_account_parameters) + self.assertEqual(merchant.bank_account.holder, "Jane Jones") + self.assertEqual(merchant.bank_account.number, "1009534785") + self.assertEqual(merchant.bank_account.iban, "DE23100000001234567890") + self.assertEqual(merchant.bank_account.country, "DE") + + def test_mandate_from_params(self): + mandate_with_result_parameters = opp.facade.Mandate.from_params( + {"id": "1a2b3c4d5e6f7g8h9i", + "dateOfSignature": "2015-07-09" + } + ) + self.assertEqual(mandate_with_result_parameters.id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(mandate_with_result_parameters.date_of_signature, "2015-07-09") + + def test_parameter_from_params(self): + parameter_with_result_parameters = opp.facade.Parameter.from_params( + {"name": "test_parameter", + "value": "test" + } + ) + self.assertEqual(parameter_with_result_parameters.name, "test_parameter") + self.assertEqual(parameter_with_result_parameters.value, "test") + + def test_redirect_from_params(self): + redirect_parameters = {"url": "http://mupteste.comercioeletronico.com.br/sepsBoletoRet/15300/prepara_pagto.asp", + "parameters": [ + {"name": "cdk10", + "value": "0AWe9qIp0v8pXrJtFrxF+w==" + }, + {"name": "cdk6", + "value": "lxJCnzrEzeM=" + } + ] + } + redirect = opp.facade.Redirect.from_params(redirect_parameters) + self.assertEqual(redirect.url, "http://mupteste.comercioeletronico.com.br/sepsBoletoRet/15300/prepara_pagto.asp") + self.assertEqual(redirect.parameters[0].name, "cdk10") + self.assertEqual(redirect.parameters[0].value, "0AWe9qIp0v8pXrJtFrxF+w==") + self.assertEqual(redirect.parameters[1].name, "cdk6") + self.assertEqual(redirect.parameters[1].value, "lxJCnzrEzeM=") + + def test_response_parameters_from_params(self): + response_parameters = {"id": "8a8294494e735cfa014e763863a80add", + "paymentType": "PA", + "paymentBrand": "BOLETO", + "amount": "1.03", + "currency": "BRL", + "descriptor": "2203.5434.7682 OPP_Channel", + "result": { + "code": "000.100.112", + "description": "Request successfully processed in 'Merchant in Connector Test Mode'" + }, + "cardAccount": { + "number": "377777777777770", + "holder": "Jane Jones", + "expiryMonth": "05", + "expiryYear": "2018", + "cvv": "1234" + }, + "virtualAccount": { + "accountId": "1a2b3c4d5e6f7g8h9i", + "password": "sy6KJsT8" + }, + "bankAccount": { + "holder": "Jane Jones", + "bankName": "Deutsche Bank", + "number": "1009534785", + "iban": "DE23100000001234567890", + "bankCode": "DEUTDEMM", + "bic": "DEUTDEFF", + "country": "DE", + "mandate": {"id": "1a2b3c4d5e6f7g8h9i", + "dateOfSignature": "2015-07-09" + }, + "transactionDueDate": "2015-07-09" + }, + "merchant": { + "bankAccount": { + "holder": "merchantName", + "number": "15300", + "iban": "DE23100000001234567890", + "country": "BR" + } + }, + "customer": { + "givenName": "Braziliano", + "surname": "Babtiste" + }, + "billing": { + "street1": "Amazonstda", + "city": "Brasilia", + "state": "DE", + "postcode": "12345678", + "country": "BR" + }, + "shipping": { + "givenName": "Jane", + "surname": "Jones", + "street1": "Riostda", + "city": "Rio de Janeiro", + "state": "FE", + "postcode": "12345698", + "country": "BR" + }, + "cart": { + "items": [ + { + "name": "T-shirt", + "merchantItemId": "1a2b3c4d5e6f7g8h9i", + "quantity": "1", + "type": "XL", + "price": "5", + "currency": "EUR", + "description": "Summer", + "tax": "0.25", + "shipping": "1", + "discount": "5" + }, + { + "name": "FIFA16", + "merchantItemId": "2b3c4d5e6f7g8h9i1a", + "quantity": "1", + "type": "PS4", + "price": "55", + "currency": "EUR", + "description": "New", + "tax": "0.25", + "shipping": "1", + "discount": "5" + } + ] + }, + "customParameters": { + "BRADESCO_cpfsacado": "11111111111" + }, + "redirect": { + "url": "http://mupteste.comercioeletronico.com.br/sepsBoletoRet/15300/prepara_pagto.asp", + "parameters": [ + { + "name": "cdk10", + "value": "0AWe9qIp0v8pXrJtFrxF+w==" + }, + { + "name": "cdk6", + "value": "lxJCnzrEzeM=" + } + ] + }, + "buildNumber": "20150707-105209.r185912.opp-tags-20150709_lr", + "timestamp": "2015-07-10 04:28:03+0000", + "ndc": "8a8294174b7ecb28014b9699220015ca_8a102b3e46974c83bbeb0bfc62a9518e" + } + response = opp.facade.ResponseParameters.from_params(response_parameters) + self.assertEqual(response.id, "8a8294494e735cfa014e763863a80add") + self.assertEqual(response.payment_type, "PA") + self.assertEqual(response.payment_brand, "BOLETO") + self.assertEqual(response.amount, "1.03") + self.assertEqual(response.descriptor, "2203.5434.7682 OPP_Channel") + self.assertEqual(response.result.code, "000.100.112") + self.assertEqual(response.result.description, "Request successfully processed in 'Merchant in Connector Test Mode'") + self.assertEqual(response.card_account.number, "377777777777770") + self.assertEqual(response.card_account.holder, "Jane Jones") + self.assertEqual(response.card_account.expiry_month, "05") + self.assertEqual(response.card_account.expiry_year, "2018") + self.assertEqual(response.card_account.cvv, "1234") + self.assertEqual(response.virtual_account.account_id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(response.virtual_account.password, "sy6KJsT8") + self.assertEqual(response.bank_account.holder, "Jane Jones") + self.assertEqual(response.bank_account.bank_name, "Deutsche Bank") + self.assertEqual(response.bank_account.iban, "DE23100000001234567890") + self.assertEqual(response.bank_account.bank_code, "DEUTDEMM") + self.assertEqual(response.bank_account.bic, "DEUTDEFF") + self.assertEqual(response.bank_account.country, "DE") + self.assertEqual(response.bank_account.mandate.id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(response.bank_account.mandate.date_of_signature, "2015-07-09") + self.assertEqual(response.bank_account.transaction_due_date, "2015-07-09") + self.assertEqual(response.customer.given_name, "Braziliano") + self.assertEqual(response.customer.surname, "Babtiste") + self.assertEqual(response.billing_address.street1, "Amazonstda") + self.assertEqual(response.billing_address.city, "Brasilia") + self.assertEqual(response.billing_address.state, "DE") + self.assertEqual(response.billing_address.postcode, "12345678") + self.assertEqual(response.billing_address.country, "BR") + self.assertEqual(response.shipping_address.given_name, "Jane") + self.assertEqual(response.shipping_address.surname, "Jones") + self.assertEqual(response.shipping_address.street1, "Riostda") + self.assertEqual(response.shipping_address.city, "Rio de Janeiro") + self.assertEqual(response.shipping_address.state, "FE") + self.assertEqual(response.shipping_address.postcode, "12345698") + self.assertEqual(response.shipping_address.country, "BR") + self.assertEqual(response.cart.items[0].name, "T-shirt") + self.assertEqual(response.cart.items[0].merchant_item_id, "1a2b3c4d5e6f7g8h9i") + self.assertEqual(response.cart.items[0].quantity, "1") + self.assertEqual(response.cart.items[0].type, "XL") + self.assertEqual(response.cart.items[0].price, "5") + self.assertEqual(response.cart.items[0].currency, "EUR") + self.assertEqual(response.cart.items[0].description, "Summer") + self.assertEqual(response.cart.items[0].tax, "0.25") + self.assertEqual(response.cart.items[0].shipping, "1") + self.assertEqual(response.cart.items[0].discount, "5") + self.assertEqual(response.cart.items[1].name, "FIFA16") + self.assertEqual(response.cart.items[1].merchant_item_id, "2b3c4d5e6f7g8h9i1a") + self.assertEqual(response.cart.items[1].quantity, "1") + self.assertEqual(response.cart.items[1].type, "PS4") + self.assertEqual(response.cart.items[1].price, "55") + self.assertEqual(response.cart.items[1].currency, "EUR") + self.assertEqual(response.cart.items[1].description, "New") + self.assertEqual(response.cart.items[1].tax, "0.25") + self.assertEqual(response.cart.items[1].shipping, "1") + self.assertEqual(response.cart.items[1].discount, "5") + self.assertEqual(response.merchant.bank_account.holder, "merchantName") + self.assertEqual(response.merchant.bank_account.number, "15300") + self.assertEqual(response.merchant.bank_account.iban, "DE23100000001234567890") + self.assertEqual(response.merchant.bank_account.country, "BR") + self.assertEqual(response.redirect.parameters[0].name, "cdk10") + self.assertEqual(response.redirect.parameters[0].value, "0AWe9qIp0v8pXrJtFrxF+w==") + self.assertEqual(response.redirect.parameters[1].name, "cdk6") + self.assertEqual(response.redirect.parameters[1].value, "lxJCnzrEzeM=") + self.assertEqual(response.build_number, "20150707-105209.r185912.opp-tags-20150709_lr") + self.assertEqual(response.timestamp, "2015-07-10 04:28:03+0000") + self.assertEqual(response.ndc, "8a8294174b7ecb28014b9699220015ca_8a102b3e46974c83bbeb0bfc62a9518e") \ No newline at end of file diff --git a/tests/facade/tests_facade.py b/tests/facade/test_to_params.py similarity index 79% rename from tests/facade/tests_facade.py rename to tests/facade/test_to_params.py index 8ef62f3..7008b9c 100644 --- a/tests/facade/tests_facade.py +++ b/tests/facade/test_to_params.py @@ -8,7 +8,7 @@ import opp.facade -class TestsFacade(unittest.TestCase): +class TestToParams(unittest.TestCase): def test_authentication_to_params(self): expected_parameters = tests.test_data_utils.authentication result_parameters = opp.facade.Authentication(user_id="8a8294174b7ecb28014b9699220015cc", password="sy6KJsT8", @@ -63,8 +63,7 @@ def test_bank_account_to_params(self): result_parameters = opp.facade.BankAccount(holder="Jane Jones", bank_name="Deutsche Bank", number="1009534785", iban="DE23100000001234567890", bank_code="DEUTDEMM", bic="DEUTDEFF", country="DE", - mandate_id="1a2b3c4d5e6f7g8h9i", - mandate_date_of_signature="2015-07-09", + mandate=opp.facade.Mandate(id='1a2b3c4d5e6f7g8h9i', date_of_signature='2015-07-09'), transaction_due_date="2015-07-09").to_params() self.assertEqual(expected_parameters, result_parameters) @@ -118,11 +117,6 @@ def test_shipping_address_to_params(self): self.assertEqual(expected_parameters, result_parameters) def test_cart_to_params(self): - item_object = opp.facade.Item(name="T-shirt", merchant_item_id="1a2b3c4d5e6f7g8h9i", quantity="1", - type="XL", - price="5", currency="EUR", - description="Summer", tax="0.25", shipping="1", - discount="5") expected_parameters = {"cart.items[0].name": "T-shirt", "cart.items[0].merchantItemId": "1a2b3c4d5e6f7g8h9i", "cart.items[0].quantity": "1", @@ -133,7 +127,43 @@ def test_cart_to_params(self): "cart.items[0].tax": "0.25", "cart.items[0].shipping": "1", "cart.items[0].discount": "5"} + item_object = opp.facade.Item(name="T-shirt", merchant_item_id="1a2b3c4d5e6f7g8h9i", quantity="1", + type="XL", + price="5", currency="EUR", + description="Summer", tax="0.25", shipping="1", + discount="5") list_of_items = [item_object] result_parameters = opp.facade.Cart(list_of_items).to_params() + self.assertEqual(expected_parameters, result_parameters) + def test_tokenization_and_registration_to_params(self): + expected_parameters = {"createRegistration": "true"} + result_parameters = opp.facade.TokenizationAndRegistration(create_registration="true").to_params() self.assertEqual(expected_parameters, result_parameters) + + def test_recurring_to_params(self): + expected_parameters = {"recurringType": "INITIAL"} + result_parameters = opp.facade.Recurring(type="INITIAL").to_params() + self.assertEqual(expected_parameters, result_parameters) + + def test_threed_secure_to_params(self): + expected_parameters = {"threeDSecure.eci": "07", + "threeDSecure.verificationId": "dGVzdF92ZXJpZmljYXRpb25faWQ=", + "threeDSecure.xid": "dGVzdF94aWQ=" + } + result_parameters = opp.facade.ThreeDSecure(eci="07", verification_id="dGVzdF92ZXJpZmljYXRpb25faWQ=", xid="dGVzdF94aWQ=").to_params() + self.assertEqual(expected_parameters, result_parameters) + + def test_custom_parameters_to_params(self): + expected_parameters = {"customParameters[SHOPPER_number_of_installments]": "3", + "customParameters[SHOPPER_trial_period_days]": "10" + } + result_parameters = opp.facade.CustomParameters(number_of_installments='3', trial_period_days='10').to_params() + self.assertEqual(expected_parameters, result_parameters) + + def test_asynchronous_payments_to_params(self): + expected_parameters = {"shopperResultUrl": "http://shopperurl.com", + "notificationUrl": "http://notificationurl.com" + } + result_parameters = opp.facade.AsynchronousPayments(shopper_result_url="http://shopperurl.com", notification_url="http://notificationurl.com").to_params() + self.assertEqual(expected_parameters, result_parameters) \ No newline at end of file diff --git a/tox.ini b/tox.ini index 6967f86..6614500 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py28, py3 +envlist = py27,py34 [testenv] deps= nose