unzer 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
unzer-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 mausbrand
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
unzer-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: unzer
3
+ Version: 1.0.0
4
+ Summary: An unofficial python SDK for unzer.com
5
+ Author-email: Sven Eberth <se@mausbrand.de>
6
+ Maintainer-email: Sven Eberth <se@mausbrand.de>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2021 mausbrand
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Project-URL: Repository, https://github.com/mausbrand/unzer-python-sdk.git
30
+ Project-URL: Bug Tracker, https://github.com/mausbrand/unzer-python-sdk/issues
31
+ Project-URL: Changelog, https://github.com/mausbrand/unzer-python-sdk/releases
32
+ Keywords: unzer,payment,sdk,client
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3.10
37
+ Classifier: Programming Language :: Python :: 3.11
38
+ Classifier: Programming Language :: Python :: 3.12
39
+ Classifier: Programming Language :: Python :: 3.13
40
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
41
+ Requires-Python: >=3.10
42
+ Description-Content-Type: text/markdown
43
+ License-File: LICENSE
44
+ Requires-Dist: requests
45
+ Dynamic: license-file
46
+
47
+ <div align="center">
48
+ <h1>unzer-python-sdk</h1>
49
+ <a href="https://pypi.org/project/unzer/">
50
+ <img alt="Badge showing current PyPI version" title="PyPI" src="https://img.shields.io/pypi/v/unzer">
51
+ </a>
52
+ <a href="LICENSE">
53
+ <img src="https://img.shields.io/github/license/mausbrand/unzer-python-sdk" alt="Badge displaying the license" title="License badge">
54
+ </a>
55
+ <br>
56
+ An unofficial python SDK for the payment service <a href="https://www.unzer.com">Unzer</a>.
57
+ </div>
unzer-1.0.0/README.md ADDED
@@ -0,0 +1,11 @@
1
+ <div align="center">
2
+ <h1>unzer-python-sdk</h1>
3
+ <a href="https://pypi.org/project/unzer/">
4
+ <img alt="Badge showing current PyPI version" title="PyPI" src="https://img.shields.io/pypi/v/unzer">
5
+ </a>
6
+ <a href="LICENSE">
7
+ <img src="https://img.shields.io/github/license/mausbrand/unzer-python-sdk" alt="Badge displaying the license" title="License badge">
8
+ </a>
9
+ <br>
10
+ An unofficial python SDK for the payment service <a href="https://www.unzer.com">Unzer</a>.
11
+ </div>
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = [
3
+ "setuptools>=65",
4
+ # "wheel"
5
+ ]
6
+ build-backend = "setuptools.build_meta"
7
+
8
+ [project]
9
+ name = "unzer"
10
+ dynamic = ["version"]
11
+ dependencies = [
12
+ "requests"
13
+ ]
14
+ requires-python = ">=3.10"
15
+ authors = [
16
+ { name = "Sven Eberth", email = "se@mausbrand.de" },
17
+ ]
18
+ maintainers = [
19
+ { name = "Sven Eberth", email = "se@mausbrand.de" },
20
+ ]
21
+ description = "An unofficial python SDK for unzer.com"
22
+ readme = "README.md"
23
+ license = { file = "LICENSE" }
24
+ keywords = ["unzer", "payment", "sdk", "client"]
25
+ classifiers = [
26
+ "Intended Audience :: Developers",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3.10",
30
+ "Programming Language :: Python :: 3.11",
31
+ "Programming Language :: Python :: 3.12",
32
+ "Programming Language :: Python :: 3.13",
33
+ "Topic :: Software Development :: Libraries :: Python Modules"
34
+ ]
35
+
36
+ [tool.setuptools.dynamic]
37
+ version = { attr = "unzer.__version__" }
38
+
39
+ [tool.setuptools.packages.find]
40
+ where = ["src"]
41
+
42
+ [project.urls]
43
+ Repository = "https://github.com/mausbrand/unzer-python-sdk.git"
44
+ "Bug Tracker" = "https://github.com/mausbrand/unzer-python-sdk/issues"
45
+ Changelog = "https://github.com/mausbrand/unzer-python-sdk/releases"
unzer-1.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ __title__ = "unzer-sdk"
2
+ __author__ = "Sven Eberth"
3
+ __email__ = "se@mausbrand.de"
4
+ __version__ = "1.0.0"
5
+
6
+ from .client import UnzerClient
7
+ from .model import *
@@ -0,0 +1,540 @@
1
+ import logging
2
+ import time
3
+ from types import NoneType
4
+
5
+ import requests
6
+ from urllib3.exceptions import TimeoutError
7
+
8
+ from . import __version__
9
+ from .model import *
10
+ from .model.basket import Basket
11
+ from .model.payment import PaymentGetResponse, PaymentRequest, PaymentResponse
12
+ from .model.paymentpage import PaymentPage, PaymentPageResponse
13
+ from .model.webhook import Webhook
14
+
15
+ logger = logging.getLogger("unzer-sdk")
16
+
17
+
18
+ class UnzerClient:
19
+ endpoint = "https://api.unzer.com/v1"
20
+ retryDelays = (1, 2, 4, 8)
21
+ timeout = 5
22
+
23
+ def __init__(
24
+ self,
25
+ private_key: str,
26
+ public_key: str,
27
+ sandbox: bool = False,
28
+ language: str = "en",
29
+ ):
30
+ super(UnzerClient, self).__init__()
31
+ self.private_key = private_key
32
+ self.public_key = public_key
33
+ self.sandbox = sandbox
34
+ self.language = language
35
+
36
+ def request(self, operation, method, payload=None):
37
+ """Perform a request to the unzer-api.
38
+
39
+ This method does not really perform the request itself,
40
+ but rather prepares the request for :meth:`_request`.
41
+
42
+ :param operation: The HTTP method (e.g. POST, GET).
43
+ :param method: The method on the REST API. (path).
44
+ :param payload: The payload for this request.
45
+ Send json-encoded as body.
46
+ :return: The json-decoded response from the api.
47
+ :rtype: Any
48
+ """
49
+ url = "%s/%s" % (self.endpoint, operation)
50
+ headers = {
51
+ "user-agent": "unzer-python-sdk %s" % __version__,
52
+ "content-type": "application/json; charset=UTF-8",
53
+ "accept": "application/json",
54
+ "accept-language": self.language, # language for translation of customerMessage in errors
55
+ }
56
+ return self._request(
57
+ url,
58
+ method,
59
+ headers,
60
+ payload,
61
+ auth=(self.private_key, "")
62
+ )
63
+
64
+ def _request(self, url, method, headers, payload, auth):
65
+ """Helper method to perform the request with throttling.
66
+
67
+ :param url: The complete URL.
68
+ :type url: str
69
+ :param method: The HTTP method (e.g. POST, GET).
70
+ :type method: str
71
+ :param headers: The HTTP headers.
72
+ :type headers: list[tuple] | dict[str, str]
73
+ :param payload: The HTTP payload (will be json encoded).
74
+ :type url: Any
75
+ :param auth: The authentication for this request.
76
+ :type auth: tuple(str, str)
77
+ :return: The json decoded response
78
+ :type: Any
79
+
80
+ :raises: :exc:`ErrorResponse` in case of an client error
81
+ or after last retry failed.
82
+ """
83
+ r = None
84
+ for idx, delay in enumerate((0,) + self.retryDelays):
85
+ logger.debug("Perform try no. %d (delay: %d)", idx, delay)
86
+ time.sleep(delay)
87
+ logger.debug("%s %s", method, url)
88
+ logger.debug("payload: %r", payload)
89
+ try:
90
+ r = requests.request(
91
+ method,
92
+ url,
93
+ json=payload,
94
+ headers=headers,
95
+ auth=auth,
96
+ verify=True,
97
+ timeout=self.timeout,
98
+ )
99
+ except (TimeoutError, requests.exceptions.ReadTimeout):
100
+ logger.exception("Caught TimeoutError")
101
+ continue
102
+ if 200 <= r.status_code <= 201:
103
+ logger.debug("Response[%s %s]: %r", r.status_code, r.reason, r.json())
104
+ return r.json()
105
+ elif 500 <= r.status_code < 600:
106
+ logger.debug("Server error")
107
+ logger.debug("Response[%s %s]: %r", r.status_code, r.reason, r.text)
108
+ continue
109
+ else:
110
+ logger.debug("Client error")
111
+ logger.debug("Response[%s %s]: %r", r.status_code, r.reason, r.text)
112
+ errorResponse = ErrorResponse.fromDict(r.json())
113
+ errorResponse.statusCode = r.status_code
114
+ errorResponse.srcResponse = r
115
+ raise errorResponse
116
+
117
+ logger.error("All request attempts failed")
118
+ if r is not None:
119
+ try:
120
+ errorResponse = ErrorResponse.fromDict(r.json(), "All request attempts failed")
121
+ errorResponse.statusCode = r.status_code
122
+ errorResponse.srcResponse = r
123
+ except ValueError:
124
+ logger.exception("Failed to build an ErrorResponse from last request")
125
+ else:
126
+ raise errorResponse
127
+ raise ErrorResponse("All request attempts failed", srcResponse=r)
128
+
129
+ def getKeyPair(self):
130
+ """Provides the public key of the used private key as well as a list of the payment types available for the merchant.
131
+
132
+ :return: The fetched KeyPairResponse
133
+ :rtype: dict
134
+ """
135
+ # ToDo: implement KeyPairResponse-model
136
+ return self.request(
137
+ "keypair",
138
+ "GET",
139
+ )
140
+
141
+ def getError(self, errorId):
142
+ """Get information about an error
143
+
144
+ :param errorId: The error id (e.g. p-err-abcdefghij1234567rstuvwyxyz)
145
+ :type errorId: str
146
+ :rtype: dict
147
+ """
148
+ if not isinstance(errorId, str):
149
+ raise TypeError("Expected a errorId of type str. Got %r" % type(errorId))
150
+ return self.request(
151
+ "errors/%s" % errorId,
152
+ "GET",
153
+ )
154
+
155
+ def createCustomer(self, customer):
156
+ """Creating a customer
157
+
158
+ :param customer: Customer object
159
+ :type customer: Customer
160
+ :return: The created customer object
161
+ :rtype: Customer
162
+ """
163
+ if not isinstance(customer, Customer):
164
+ raise TypeError("Expected a Customer object. Got %r" % type(customer))
165
+ if customer.key:
166
+ raise TypeError("Customer has a id (key) set. "
167
+ "Call updateCustomer to update it or remove it to create a new one.")
168
+ data = self.request(
169
+ "customers",
170
+ "POST",
171
+ customer.serialize(),
172
+ )
173
+ # API docs wrong: we get only a dict with the id back
174
+ return self.getCustomer(data["id"])
175
+
176
+ def updateCustomer(self, customer):
177
+ """Update a customer using unique customerId or the resource id from the customers resource.
178
+ The customer MUST have customerId oder key (id)
179
+
180
+ :param customer: Customer object
181
+ :type customer: Customer
182
+ :return: The updated customer object
183
+ :rtype: Customer
184
+ """
185
+ if not isinstance(customer, Customer):
186
+ raise TypeError("Expected a Customer object. Got %r" % type(customer))
187
+ if not customer.keyOrCustomerId:
188
+ raise TypeError("Customer has no customerId oder key (id)")
189
+ data = self.request(
190
+ "customers/%s" % customer.keyOrCustomerId,
191
+ "PUT",
192
+ customer.serialize(),
193
+ )
194
+ # API docs wrong: we get only a dict with the id back
195
+ return self.getCustomer(data["id"])
196
+
197
+ def createOrUpdateCustomer(self, customer):
198
+ try:
199
+ return self.createCustomer(customer)
200
+ except ErrorResponse as er:
201
+ if er.errors and er.statusCode == 400 and er.errors[0].code == "API.410.200.010":
202
+ return self.updateCustomer(customer)
203
+ raise er
204
+
205
+ def deleteCustomer(self, customer):
206
+ """Delete a customer using unique customerId or the resource id from the customers resource.
207
+ The customer MUST have customerId oder key (id)
208
+
209
+ :param customer: Customer object, customerId or id (key)
210
+ :type customer: Customer or str
211
+ :return: The id of the customer
212
+ :rtype: str
213
+ """
214
+ if isinstance(customer, Customer):
215
+ if not customer.key and not customer.customerId:
216
+ raise TypeError("Customer has no customerId oder key (id)")
217
+ codeOrExternalId = customer.customerId or customer.key
218
+ elif isinstance(customer, str):
219
+ codeOrExternalId = customer
220
+ else:
221
+ raise TypeError("Expected a Customer object or str. Got %r" % type(customer))
222
+ data = self.request(
223
+ "customers/%s" % codeOrExternalId,
224
+ "DELETE",
225
+ )
226
+ return data["id"]
227
+
228
+ def getCustomer(self, codeOrExternalId):
229
+ """Fetch a customer using unique customerId or the resource id from the customers resource.
230
+
231
+ :param codeOrExternalId: customerId or id (key)
232
+ :type codeOrExternalId: str
233
+ :return: The fetched customer object
234
+ :rtype: Customer
235
+ """
236
+ data = self.request(
237
+ "customers/%s" % codeOrExternalId,
238
+ "GET",
239
+ )
240
+ return Customer.fromDict(data)
241
+
242
+ def createBasket(self, basket):
243
+ """Creating a basket
244
+
245
+ :param basket: Basket object
246
+ :type basket: Basket
247
+ :return: The created Basket object
248
+ :rtype: Basket
249
+ """
250
+ if not isinstance(basket, Basket):
251
+ raise TypeError("Expected a Basket object. Got %r" % type(basket))
252
+ data = self.request(
253
+ "baskets",
254
+ "POST",
255
+ basket.serialize(),
256
+ )
257
+ return self.getBasket(data["id"])
258
+
259
+ def updateBasket(self, basket):
260
+ """Update a basket.
261
+ The basket MUST have key (id)
262
+
263
+ :param basket: Basket object
264
+ :type basket: Basket
265
+ :return: The updated basket object
266
+ :rtype: Basket
267
+ """
268
+ if not isinstance(basket, Basket):
269
+ raise TypeError("Expected a Basket object. Got %r" % type(basket))
270
+ if not basket.key:
271
+ raise TypeError("Basket has no key (id)")
272
+ data = self.request(
273
+ "baskets/%s" % basket.key,
274
+ "PUT",
275
+ basket.serialize(),
276
+ )
277
+ return self.getBasket(data["id"])
278
+
279
+ def getBasket(self, basketId):
280
+ """Fetch a basket.
281
+
282
+ :param basketId: basket's id (key)
283
+ :type basketId: str
284
+ :return: The fetched basket object
285
+ :rtype: Basket
286
+ """
287
+ data = self.request(
288
+ "baskets/%s" % basketId,
289
+ "GET",
290
+ )
291
+ return Basket.fromDict(data)
292
+
293
+ def createPaymentType(self, paymentType):
294
+ """Create a new PaymentType at Unzer.
295
+
296
+ This can be any Object which inherits the abstract class PaymentType.
297
+
298
+ :param paymentType: The PaymentPage model
299
+ :type paymentType: PaymentType
300
+ :return: The paymentType response
301
+ :rtype: PaymentType
302
+ """
303
+ if not isinstance(paymentType, PaymentType):
304
+ raise TypeError("Expected a PaymentType object. Got %r" % type(paymentType))
305
+ paymentType.validateBeforeRequest()
306
+ data = self.request(
307
+ "types/%s" % paymentType.method,
308
+ "POST",
309
+ paymentType.serialize(),
310
+ )
311
+ return type(paymentType).fromDict(data)
312
+
313
+ def createPaymentPage(self, paymentPage):
314
+ """The initialize payment page call with direct charge purpose.
315
+
316
+ :param paymentPage: The PaymentPage model
317
+ :type paymentPage: PaymentPage
318
+ :return: The PaymentPageResponse
319
+ :rtype: PaymentPageResponse
320
+ """
321
+ if not isinstance(paymentPage, PaymentPage) or isinstance(paymentPage, PaymentPageResponse):
322
+ raise TypeError("Expected a PaymentPage object. Got %r" % type(paymentPage))
323
+ paymentPage.validateBeforeRequest()
324
+ data = self.request(
325
+ "paypage/%s" % paymentPage.action,
326
+ "POST",
327
+ paymentPage.serialize(),
328
+ )
329
+ return PaymentPageResponse.fromDict(data)
330
+
331
+ def getPaymentPage(self, payPageId):
332
+ """Fetch the payment resource. Provides an overview about a payment.
333
+
334
+ :param payPageId: The related payment page id.
335
+ :type payPageId: str
336
+ :return: The PaymentPage ressource
337
+ :rtype: PaymentPageResponse
338
+ """
339
+ if not isinstance(payPageId, str):
340
+ raise TypeError("Expected a payPageId of type str. Got %r" % type(payPageId))
341
+ data = self.request(
342
+ "paypage/%s" % payPageId,
343
+ "GET",
344
+ )
345
+ return PaymentPageResponse.fromDict(data)
346
+
347
+ def getPayment(self, codeOrOrderId):
348
+ """Fetch the payment resource. Provides an overview about a payment.
349
+
350
+ :param codeOrOrderId: The id of the order
351
+ :type codeOrOrderId: str
352
+ :return: Payment ressource
353
+ :rtype: PaymentGetResponse
354
+ """
355
+ if not isinstance(codeOrOrderId, str):
356
+ raise TypeError("Expected a codeOrOrderId of type str. Got %r" % type(codeOrOrderId))
357
+ data = self.request(
358
+ "payments/%s" % codeOrOrderId,
359
+ "GET",
360
+ )
361
+ return PaymentGetResponse.fromDict(data, self)
362
+
363
+ def authorize(self, payment):
364
+ """Authorize call for redirect payments.
365
+
366
+ The paymentType will be created within this method,
367
+ if not already created.
368
+
369
+ :param payment: The PaymentRequest model
370
+ :type payment: PaymentRequest
371
+ :return: The paymentType response
372
+ :rtype: PaymentResponse
373
+ """
374
+ return self._authorize_or_charge("authorize", payment)
375
+
376
+ def charge(self, payment):
377
+ """Charge call for redirect payments.
378
+
379
+ The paymentType will be created within this method,
380
+ if not already created.
381
+
382
+ :param payment: The PaymentRequest model
383
+ :type payment: PaymentRequest
384
+ :return: The paymentType response
385
+ :rtype: PaymentResponse
386
+ """
387
+ return self._authorize_or_charge("charges", payment)
388
+
389
+ def _authorize_or_charge(self, type_, payment): # type: (str, PaymentRequest) -> PaymentResponse
390
+ """Internal helper for authorize and charge calls
391
+ """
392
+ if type_ not in {"authorize", "charges"}:
393
+ raise ValueError("Invalid type %r" % type_)
394
+ if not isinstance(payment, PaymentRequest):
395
+ raise TypeError("Expected a PaymentRequest object. Got %r" % type(PaymentRequest))
396
+ if not payment.paymentType:
397
+ raise ValueError("No paymentType set")
398
+ if not payment.paymentType.key:
399
+ payment.paymentType = self.createPaymentType(payment.paymentType)
400
+ payment.validateBeforeRequest()
401
+ data = self.request(
402
+ "/".join(filter(None, ["payments", payment.paymentId, type_])),
403
+ "POST",
404
+ payment.serialize(),
405
+ )
406
+ if data.get("isError"):
407
+ raise ErrorResponse.fromDict(data)
408
+ return PaymentResponse.fromDict(data)
409
+
410
+ def getChargedTransaction(self, codeOrOrderId, txnCode):
411
+ """Fetch the corresponding charged transaction.
412
+ The first found charged transaction will be returned if the <txnCode> = null.
413
+
414
+ :param codeOrOrderId: The id of the payment
415
+ :type codeOrOrderId: str
416
+ :param txnCode: The id of the transaction
417
+ :type txnCode: str
418
+
419
+ :return: PaymentResponse ressource
420
+ :rtype: PaymentResponse
421
+ """
422
+ if not isinstance(codeOrOrderId, str):
423
+ raise TypeError("Expected a codeOrOrderId of type str. Got %r" % type(codeOrOrderId))
424
+ if not isinstance(txnCode, (str, NoneType)):
425
+ raise TypeError("Expected a txnCode of type str or None. Got %r" % type(txnCode))
426
+ data = self.request(
427
+ "payments/%s/charges/%s" % (codeOrOrderId, txnCode or ""),
428
+ "GET",
429
+ )
430
+ return PaymentResponse.fromDict(data)
431
+
432
+ def listWebhooks(self):
433
+ """Get all webhook resources.
434
+
435
+ :return: A list of Webhooks
436
+ :rtype: list[Webhook]
437
+ """
438
+ data = self.request(
439
+ "webhooks",
440
+ "GET",
441
+ )
442
+ return self._loadWebhookResponse(data)
443
+
444
+ def getWebhook(self, webhookId):
445
+ """Get one specific webhook resource.
446
+
447
+ :param webhookId: The id of the webhook.
448
+ :type webhookId: str
449
+ :return: The webhook resource.
450
+ :rtype: Webhook
451
+ """
452
+ data = self.request(
453
+ "webhooks/%s" % webhookId,
454
+ "GET",
455
+ )
456
+ return Webhook.fromDict(data)
457
+
458
+ def createWebhook(self, webhook):
459
+ """Create a new webhook.
460
+
461
+ :param webhook: The webhook mode
462
+ :return: A list of created Webhooks models (each for each event-type)
463
+ :rtype: list[Webhook]
464
+ """
465
+ if not isinstance(webhook, Webhook):
466
+ raise TypeError("Expected a Webhook object. Got %r" % type(webhook))
467
+ if webhook.webhookId:
468
+ raise TypeError("Webhook has a id set. "
469
+ "Call updateWebhook to update it or remove the id to create a new one.")
470
+ webhook.validateBeforeRequest()
471
+ data = self.request(
472
+ "webhooks",
473
+ "POST",
474
+ webhook.serialize(),
475
+ )
476
+ return self._loadWebhookResponse(data)
477
+
478
+ def updateWebhook(self, webhook):
479
+ """Update the URL for an existing webhook.
480
+ Will not change the event (not supported by unzer-api)!
481
+
482
+ :param webhook: The webhook resource to be updated
483
+ :type webhook: Webhook
484
+ :return: The updated webhook
485
+ :rtype: Webhook
486
+ """
487
+ if not isinstance(webhook, Webhook):
488
+ raise TypeError("Expected a Webhook object. Got %r" % type(webhook))
489
+ if not webhook.webhookId:
490
+ raise ValueError("Webhook to update has no id")
491
+ if not webhook.url:
492
+ raise ValueError("Webhook to update has no url")
493
+ data = self.request(
494
+ "webhooks/%s" % webhook.webhookId,
495
+ "PUT",
496
+ {"url": webhook.url},
497
+ )
498
+ return Webhook.fromDict(data)
499
+
500
+ def _loadWebhookResponse(self, data):
501
+ """Helper method load webhook responses.
502
+
503
+ :param data: The data from the request.
504
+ :type data: dict
505
+ :return: A list of Webhooks
506
+ :rtype: list[Webhook]
507
+ """
508
+ if "events" not in data:
509
+ webhooks = [data] # got exactly one webhook, data is the webhook itself
510
+ else:
511
+ webhooks = data["events"] # list of webhooks wrapped in events property
512
+ return map(Webhook.fromDict, webhooks)
513
+
514
+ def deleteWebhook(self, webhookOrId):
515
+ """Delete a specific webhook.
516
+
517
+ :param webhookOrId: A webhook id or webhook model
518
+ :type webhookOrId: str | Webhook
519
+ :return: The id of the deleted webhook
520
+ :type: str
521
+ """
522
+ if isinstance(webhookOrId, Webhook):
523
+ webhookOrId = webhookOrId.webhookId
524
+ data = self.request(
525
+ "webhooks/%s" % webhookOrId,
526
+ "DELETE",
527
+ )
528
+ return data["id"]
529
+
530
+ def deleteAllWebhooks(self):
531
+ """Delete all webhooks
532
+
533
+ :return: A list of the deleted webhooks
534
+ :rtype: list[dict]
535
+ """
536
+ data = self.request(
537
+ "webhooks",
538
+ "DELETE",
539
+ )
540
+ return data["events"]