Projet

Général

Profil

0002-add-keyware-payment-method-39377.patch

Valentin Deniaud, 04 mars 2020 11:58

Télécharger (15,1 ko)

Voir les différences:

Subject: [PATCH 2/2] add keyware payment method (#39377)

 eopayment/__init__.py |   8 +-
 eopayment/keyware.py  | 137 +++++++++++++++++++++++++
 tests/test_keyware.py | 225 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 369 insertions(+), 1 deletion(-)
 create mode 100644 eopayment/keyware.py
 create mode 100644 tests/test_keyware.py
eopayment/__init__.py
5 5
import logging
6 6
import pytz
7 7

  
8
import six
9

  
8 10

  
9 11
from .common import (URL, HTML, FORM, RECEIVED, ACCEPTED, PAID, DENIED,
10 12
                     CANCELED, CANCELLED, ERROR, WAITING, ResponseError, force_text,
......
14 16
'SYSTEMPAY', 'SPPLUS', 'TIPI', 'DUMMY', 'get_backend', 'RECEIVED', 'ACCEPTED',
15 17
'PAID', 'DENIED', 'CANCELED', 'CANCELLED', 'ERROR', 'WAITING', 'get_backends', 'PAYFIP_WS']
16 18

  
19
if six.PY3:
20
    __all__.append('KEYWARE')
21

  
17 22
SIPS = 'sips'
18 23
SIPS2 = 'sips2'
19 24
SYSTEMPAY = 'systempayv2'
......
24 29
PAYBOX = 'paybox'
25 30
PAYZEN = 'payzen'
26 31
PAYFIP_WS = 'payfip_ws'
32
KEYWARE = 'keyware'
27 33

  
28 34
logger = logging.getLogger(__name__)
29 35

  
......
32 38
    module = importlib.import_module('.' + kind, package='eopayment')
33 39
    return module.Payment
34 40

  
35
__BACKENDS = [ DUMMY, SIPS, SIPS2, SYSTEMPAY, SPPLUS, OGONE, PAYBOX, PAYZEN, TIPI, PAYFIP_WS ]
41
__BACKENDS = [ DUMMY, SIPS, SIPS2, SYSTEMPAY, SPPLUS, OGONE, PAYBOX, PAYZEN, TIPI, PAYFIP_WS, KEYWARE ]
36 42

  
37 43
def get_backends():
38 44
    '''Return a dictionnary mapping existing eopayment backends name to their
eopayment/keyware.py
1
# eopayment - online payment library
2
# Copyright (C) 2011-2020 Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
from gettext import gettext as _
18

  
19
import requests
20
from six.moves.urllib.parse import parse_qs, urljoin
21

  
22
from .common import (CANCELLED, ERROR, PAID, URL, WAITING, PaymentCommon,
23
                     PaymentException, PaymentResponse, ResponseError)
24

  
25
__all__ = ['Payment']
26

  
27

  
28
class Payment(PaymentCommon):
29
    '''Implements EMS API, see https://dev.online.emspay.eu/.'''
30
    service_url = 'https://api.online.emspay.eu/v1/'
31

  
32
    description = {
33
        'caption': 'Keyware payment backend',
34
        'parameters': [
35
            {
36
                'name': 'normal_return_url',
37
                'caption': _('Normal return URL'),
38
                'required': True,
39
            },
40
            {
41
                'name': 'automatic_return_url',
42
                'caption': _('Asychronous return URL'),
43
                'required': True,
44
            },
45
            {
46
                'name': 'service_url',
47
                'caption': _('URL of the payment service'),
48
                'default': service_url,
49
                'type': str,
50
                'validation': lambda x: x.startswith('https'),
51
            },
52
            {
53
                'name': 'api_key',
54
                'caption': _('API key'),
55
                'required': True,
56
            },
57
            {
58
                'name': 'payment_methods',
59
                'caption': _('Allowed payment methods'),
60
                'type': list,
61
            },
62
        ],
63
    }
64

  
65
    def request(self, amount, email=None, first_name=None, last_name=None, **kwargs):
66
        amount = int(self.clean_amount(amount, min_amount=0.01))
67

  
68
        body = {
69
            'currency': 'EUR',
70
            'amount': amount,
71
            'return_url': self.normal_return_url,
72
            'webhook_url': self.automatic_return_url,
73
            'customer': {
74
                'email_address': email,
75
                'first_name': first_name,
76
                'last_name': last_name,
77
            }
78
        }
79
        if self.payment_methods:
80
            body['payment_methods'] = self.payment_methods
81

  
82
        resp = self.call_endpoint('POST', 'orders', data=body)
83
        return resp['id'], URL, resp['order_url']
84

  
85
    def response(self, query_string, **kwargs):
86
        fields = parse_qs(query_string, keep_blank_values=True)
87
        order_id = fields['order_id'][0]
88
        resp = self.call_endpoint('GET', 'orders/' + order_id)
89

  
90
        status = resp['status']
91
        if status == 'completed':
92
            result = PAID
93
        elif status == 'processing':
94
            result = WAITING
95
        elif status == 'cancelled':
96
            result = CANCELLED
97
        else:
98
            result = ERROR
99

  
100
        response = PaymentResponse(
101
            result=result,
102
            signed=True,
103
            bank_data=resp,
104
            order_id=order_id,
105
            transaction_id=order_id,
106
            bank_status=status,
107
            test=bool('is-test' in resp.get('flags', []))
108
        )
109
        return response
110

  
111
    def cancel(self, amount, bank_data, **kwargs):
112
        order_id = bank_data['id']
113
        resp = self.call_endpoint('DELETE', 'orders/' + order_id)
114
        status = resp['status']
115
        if not status == 'cancelled':
116
            raise ResponseError('expected "cancelled" status, got "%s" instead' % status)
117
        return resp
118

  
119
    def call_endpoint(self, method, endpoint, data=None):
120
        url = urljoin(self.service_url, endpoint)
121
        try:
122
            response = requests.request(method, url, auth=(self.api_key, ''), json=data)
123
        except requests.exceptions.RequestException as e:
124
            raise PaymentException('%s error on endpoint "%s": %s' % (method, endpoint, e))
125
        try:
126
            result = response.json()
127
        except ValueError:
128
            self.logger.debug('received invalid json %r', response.text)
129
            raise PaymentException('%s on endpoint "%s" returned invalid JSON: %s' %
130
                                   (method, endpoint, response.text))
131
        self.logger.debug('received "%s" with status %s', result, response.status_code)
132
        try:
133
            response.raise_for_status()
134
        except requests.exceptions.HTTPError as e:
135
            raise PaymentException(
136
                '%s error on endpoint "%s": %s "%s"' % (method, endpoint, e, result))
137
        return result
tests/test_keyware.py
1
# eopayment - online payment library
2
# Copyright (C) 2011-2020 Entr'ouvert
3
#
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License as published
6
# by the Free Software Foundation, either version 3 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU Affero General Public License for more details.
13
#
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

  
17
import json
18

  
19
import pytest
20
import requests
21
import six
22
from httmock import response, urlmatch, HTTMock, with_httmock, all_requests, remember_called
23

  
24
import eopayment
25
from eopayment.keyware import Payment
26

  
27
pytestmark = pytest.mark.skipif(six.PY2, reason='this payment module only supports python3')
28

  
29
WEBHOOK_URL = 'https://callback.example.com'
30
RETURN_URL = 'https://return.example.com'
31
API_KEY = 'test'
32

  
33
ORDER_ID = "1c969951-f5f1-4290-ae41-6177961fb3cb"
34
QUERY_STRING = 'order_id=' + ORDER_ID
35

  
36

  
37
POST_ORDER_RESPONSE = {
38
    "amount": 995,
39
    "client": {
40
        "user_agent": "Testing API"
41
    },
42
    "created": "2016-07-04T11:41:57.121017+00:00",
43
    "currency": "EUR",
44
    "description": "Example description",
45
    "id": ORDER_ID,
46
    "merchant_id": "7131b462-1b7d-489f-aba9-de2f0eadc9dc",
47
    "modified": "2016-07-04T11:41:57.183822+00:00",
48
    "order_url": "https://api.online.emspay.eu/pay/1c969951-f5f1-4290-ae41-6177961fb3cb/",
49
    "project_id": "1ef558ed-d77d-470d-b43b-c0f4a131bcef",
50
    "status": "new"
51
}
52

  
53
GET_ORDER_RESPONSE = {
54
    "amount": 995,
55
    "client": {
56
        "user_agent": "Testing API"
57
    },
58
    "created": "2016-07-04T11:41:55.635115+00:00",
59
    "currency": "EUR",
60
    "description": "Example order #1",
61
    "id": ORDER_ID,
62
    "last_transaction_added": "2016-07-04T11:41:55.831655+00:00",
63
    "merchant_id": "7131b462-1b7d-489f-aba9-de2f0eadc9dc",
64
    "merchant_order_id": "EXAMPLE001",
65
    "modified": "2016-07-04T11:41:56.215543+00:00",
66
    "project_id": "1ef558ed-d77d-470d-b43b-c0f4a131bcef",
67
    "return_url": "http://www.example.com/",
68
    "status": "completed",
69
    "transactions": [
70
        {
71
            "amount": 995,
72
            "balance": "internal",
73
            "created": "2016-07-04T11:41:55.831655+00:00",
74
            "credit_debit": "credit",
75
            "currency": "EUR",
76
            "description": "Example order #1",
77
            "events": [
78
                {
79
                    "event": "new",
80
                    "id": "0c4bd0cd-f197-446b-b218-39cbeb028290",
81
                    "noticed": "2016-07-04T11:41:55.987468+00:00",
82
                    "occurred": "2016-07-04T11:41:55.831655+00:00",
83
                    "source": "set_status"
84
                }
85
            ],
86
            "expiration_period": "PT60M",
87
            "id": "6c81499c-14e4-4974-99e5-fe72ce019411",
88
            "merchant_id": "7131b462-1b7d-489f-aba9-de2f0eadc9dc",
89
            "modified": "2016-07-04T11:41:56.065147+00:00",
90
            "order_id": ORDER_ID,
91
            "payment_method": "ideal",
92
            "payment_method_details": {
93
                "issuer_id": "INGBNL2A",
94
            },
95
            "payment_url": "https://api.online.emspay.eu/redirect/6c81499c-14e4-4974-99e5-fe72ce019411/to/payment/",
96
            "project_id": "1ef558ed-d77d-470d-b43b-c0f4a131bcef",
97
            "status": "completed"
98
        }
99
    ]
100
}
101

  
102

  
103
@remember_called
104
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path='/v1/orders', method='POST')
105
def add_order(url, request):
106
    return response(200, POST_ORDER_RESPONSE, request=request)
107

  
108
@remember_called
109
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path='/v1/orders', method='GET')
110
def successful_order(url, request):
111
    return response(200, GET_ORDER_RESPONSE, request=request)
112

  
113
@remember_called
114
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path=r'/v1/orders', method='DELETE')
115
def cancelled_order(url, request):
116
    resp = GET_ORDER_RESPONSE.copy()
117
    resp['status'] = 'cancelled'
118
    return response(200, resp, request=request)
119

  
120
@remember_called
121
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path='/v1/orders')
122
def error_order(url, request):
123
    resp = GET_ORDER_RESPONSE.copy()
124
    resp['status'] = 'error'
125
    return response(200, resp, request=request)
126

  
127
@remember_called
128
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path='/v1/orders', method='GET')
129
def connection_error(url, request):
130
    raise requests.ConnectionError('test msg')
131

  
132
@remember_called
133
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path='/v1/orders', method='GET')
134
def http_error(url, request):
135
    error_payload = {'error': {'status': 400, 'type': 'Bad request', 'value': 'error'}}
136
    return response(400, error_payload, request=request)
137

  
138
@remember_called
139
@urlmatch(scheme='https', netloc='api.online.emspay.eu', path='/v1/orders', method='GET')
140
def invalid_json(url, request):
141
    return response(200, '{', request=request)
142

  
143
@pytest.fixture
144
def keyware():
145
    return Payment({
146
        'normal_return_url': RETURN_URL,
147
        'automatic_return_url': WEBHOOK_URL,
148
        'api_key': API_KEY,
149
        'payment_methods': ['ideal'],
150
    })
151

  
152

  
153
@with_httmock(add_order)
154
def test_keyware_request(keyware):
155
    email = 'test@test.com'
156
    order_id, kind, url = keyware.request(2.5, email=email)
157

  
158
    assert order_id == ORDER_ID
159
    assert kind == eopayment.URL
160
    assert 'api.online.emspay.eu/pay/' in url
161

  
162
    body = json.loads(add_order.call['requests'][0].body.decode())
163
    assert body['currency'] == 'EUR'
164
    assert body['customer']['email_address'] == email
165
    assert isinstance(body['amount'], int)
166
    assert body['amount'] == 250
167
    assert body['webhook_url'] == WEBHOOK_URL
168
    assert body['return_url'] == RETURN_URL
169

  
170

  
171
@with_httmock(successful_order)
172
def test_keyware_response(keyware):
173
    payment_response = keyware.response(QUERY_STRING)
174

  
175
    assert payment_response.result == eopayment.PAID
176
    assert payment_response.signed is True
177
    assert payment_response.bank_data == GET_ORDER_RESPONSE
178
    assert payment_response.order_id == ORDER_ID
179
    assert payment_response.transaction_id == ORDER_ID
180
    assert payment_response.bank_status == 'completed'
181
    assert payment_response.test is False
182

  
183
    request = successful_order.call['requests'][0]
184
    assert ORDER_ID in request.url
185

  
186

  
187
@with_httmock(error_order)
188
def test_keyware_response_error(keyware):
189
    payment_response = keyware.response(QUERY_STRING)
190
    assert payment_response.result == eopayment.ERROR
191

  
192

  
193
@with_httmock(cancelled_order)
194
def test_keyware_cancel(keyware):
195
    resp = keyware.cancel(amount=995, bank_data=POST_ORDER_RESPONSE)
196
    request = cancelled_order.call['requests'][0]
197
    assert ORDER_ID in request.url
198

  
199

  
200
@with_httmock(error_order)
201
def test_keyware_cancel_error(keyware):
202
    with pytest.raises(eopayment.ResponseError) as excinfo:
203
        keyware.cancel(amount=995, bank_data=POST_ORDER_RESPONSE)
204
        assert 'expected "cancelled" status, got "error" instead' in str(excinfo.value)
205

  
206

  
207
@with_httmock(connection_error)
208
def test_keyware_endpoint_connection_error(keyware):
209
    with pytest.raises(eopayment.PaymentException) as excinfo:
210
        keyware.call_endpoint('GET', 'orders')
211
        assert 'test msg' in str(excinfo.value)
212

  
213

  
214
@with_httmock(http_error)
215
def test_keyware_endpoint_http_error(keyware):
216
    with pytest.raises(eopayment.PaymentException) as excinfo:
217
        keyware.call_endpoint('GET', 'orders')
218
        assert 'Bad request' in str(excinfo.value)
219

  
220

  
221
@with_httmock(invalid_json)
222
def test_keyware_endpoint_json_error(keyware):
223
    with pytest.raises(eopayment.PaymentException) as excinfo:
224
        keyware.call_endpoint('GET', 'orders')
225
        assert 'JSON' in str(excinfo.value)
0
-