pretix-eupago 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,8 @@
1
+ try:
2
+ from pretix.base.plugins import PluginConfig # NOQA
3
+ except ImportError:
4
+ raise RuntimeError("Please, don't run pip install directly. Use pip install -e .")
5
+
6
+ __version__ = "1.0.0"
7
+
8
+ from .apps import PluginApp # NOQA isort:skip
pretix_eupago/apps.py ADDED
@@ -0,0 +1,24 @@
1
+ from django.utils.translation import gettext_lazy as _
2
+
3
+ from pretix.base.plugins import PluginConfig
4
+
5
+ from . import __version__
6
+
7
+
8
+ class PluginApp(PluginConfig):
9
+ name = "pretix_eupago"
10
+ verbose_name = "euPago"
11
+ default = True
12
+
13
+ class PretixPluginMeta:
14
+ name = _("euPago Payments")
15
+ author = "Afonso Santos"
16
+ description = _("Accept Multibanco and MB WAY payments via euPago")
17
+ visible = True
18
+ experimental = True
19
+ version = __version__
20
+ category = "PAYMENT"
21
+ compatibility = "pretix>=4.0.0"
22
+
23
+ def ready(self):
24
+ from . import signals # NOQA
@@ -0,0 +1,304 @@
1
+ import json
2
+ import logging
3
+ from collections import OrderedDict
4
+ from datetime import date, timedelta
5
+
6
+ import requests
7
+ from django import forms
8
+ from django.http import HttpRequest
9
+ from django.template.loader import get_template
10
+ from django.utils.translation import gettext_lazy as _
11
+
12
+ from pretix.base.models import OrderPayment
13
+ from pretix.base.payment import BasePaymentProvider, PaymentException
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ MULTIBANCO_URL = {
18
+ "production": "https://clientes.eupago.pt/clientes/rest_api/multibanco/create",
19
+ "sandbox": "https://sandbox.eupago.pt/clientes/rest_api/multibanco/create",
20
+ }
21
+ MBWAY_URL = {
22
+ "production": "https://clientes.eupago.pt/api/v1.02/mbway/create",
23
+ "sandbox": "https://sandbox.eupago.pt/api/v1.02/mbway/create",
24
+ }
25
+
26
+ # Default Multibanco reference validity in days
27
+ MULTIBANCO_EXPIRY_DAYS = 7
28
+
29
+
30
+ class EupagoSettingsMixin:
31
+ @property
32
+ def settings_form_fields(self):
33
+ fields = OrderedDict(
34
+ [
35
+ (
36
+ "api_key",
37
+ forms.CharField(
38
+ label=_("API Key"),
39
+ help_text=_(
40
+ "Your euPago API key, found in Backoffice → Channels → Channel Listing."
41
+ ),
42
+ ),
43
+ ),
44
+ (
45
+ "sandbox",
46
+ forms.BooleanField(
47
+ label=_("Sandbox / Test mode"),
48
+ required=False,
49
+ initial=False,
50
+ help_text=_("Use the euPago sandbox environment for testing."),
51
+ ),
52
+ ),
53
+ (
54
+ "multibanco_expiry_days",
55
+ forms.IntegerField(
56
+ label=_("Multibanco reference validity (days)"),
57
+ min_value=1,
58
+ max_value=365,
59
+ initial=MULTIBANCO_EXPIRY_DAYS,
60
+ required=False,
61
+ help_text=_("How many days the Multibanco reference remains valid."),
62
+ ),
63
+ ),
64
+ ]
65
+ )
66
+ return OrderedDict(list(super().settings_form_fields.items()) + list(fields.items()))
67
+
68
+ @property
69
+ def _is_sandbox(self):
70
+ return self.settings.get("sandbox", as_type=bool, default=False)
71
+
72
+ @property
73
+ def _api_key(self):
74
+ return self.settings.get("api_key", default="")
75
+
76
+ def _env(self):
77
+ return "sandbox" if self._is_sandbox else "production"
78
+
79
+ @property
80
+ def test_mode_message(self):
81
+ if self._is_sandbox:
82
+ return _("euPago sandbox mode is active. No real payments will be processed.")
83
+ return None
84
+
85
+
86
+ class EupagoMultibanco(EupagoSettingsMixin, BasePaymentProvider):
87
+ identifier = "eupago_multibanco"
88
+ verbose_name = _("Multibanco (euPago)")
89
+ public_name = _("Multibanco")
90
+
91
+ # No form fields needed — Multibanco references are generated server-side.
92
+ @property
93
+ def payment_form_fields(self):
94
+ return OrderedDict()
95
+
96
+ def payment_is_valid_session(self, request):
97
+ return True
98
+
99
+ def checkout_confirm_render(self, request) -> str:
100
+ template = get_template("pretix_eupago/checkout_multibanco.html")
101
+ return template.render({"request": request})
102
+
103
+ def execute_payment(self, request: HttpRequest, payment: OrderPayment):
104
+ expiry_days = self.settings.get("multibanco_expiry_days", as_type=int, default=MULTIBANCO_EXPIRY_DAYS)
105
+ expiry = (date.today() + timedelta(days=expiry_days)).strftime("%Y-%m-%d")
106
+ identifier = f"{payment.order.code}-{payment.pk}"
107
+
108
+ payload = {
109
+ "chave": self._api_key,
110
+ "valor": float(payment.amount),
111
+ "id": identifier,
112
+ "per_dup": 0,
113
+ "data_fim": expiry,
114
+ }
115
+
116
+ try:
117
+ resp = requests.post(
118
+ MULTIBANCO_URL[self._env()],
119
+ json=payload,
120
+ timeout=30,
121
+ headers={"ApiKey": self._api_key},
122
+ )
123
+ resp.raise_for_status()
124
+ data = resp.json()
125
+ except requests.RequestException:
126
+ logger.exception("euPago Multibanco: HTTP error for payment %s", payment.pk)
127
+ raise PaymentException(
128
+ _("Could not reach the payment provider. Please try again later.")
129
+ )
130
+
131
+ if str(data.get("estado")) != "0":
132
+ logger.error(
133
+ "euPago Multibanco: API error for payment %s: %s",
134
+ payment.pk,
135
+ data,
136
+ )
137
+ raise PaymentException(
138
+ _("The payment provider returned an error. Please try a different payment method.")
139
+ )
140
+
141
+ payment.info = json.dumps(
142
+ {
143
+ "referencia": data["referencia"],
144
+ "entidade": data["entidade"],
145
+ "valor": str(data.get("valor", payment.amount)),
146
+ "identifier": identifier,
147
+ "expiry": expiry,
148
+ }
149
+ )
150
+ payment.save(update_fields=["info"])
151
+ # Payment is pending — confirmed via webhook when customer pays.
152
+
153
+ def payment_pending_render(self, request, payment) -> str:
154
+ template = get_template("pretix_eupago/pending_multibanco.html")
155
+ return template.render({"info": payment.info_data, "payment": payment})
156
+
157
+ def payment_control_render(self, request, payment) -> str:
158
+ template = get_template("pretix_eupago/control_multibanco.html")
159
+ return template.render({"info": payment.info_data, "payment": payment})
160
+
161
+ def order_pending_mail_render(self, order, payment) -> str:
162
+ info = payment.info_data or {}
163
+ if not info.get("referencia"):
164
+ return ""
165
+ template = get_template("pretix_eupago/mail_multibanco.txt")
166
+ return template.render({"info": info, "payment": payment})
167
+
168
+ def shred_payment_info(self, obj):
169
+ # Multibanco references are not personal data; nothing to shred.
170
+ pass
171
+
172
+ def api_payment_details(self, payment):
173
+ info = payment.info_data or {}
174
+ return {
175
+ "entidade": info.get("entidade"),
176
+ "referencia": info.get("referencia"),
177
+ "expiry": info.get("expiry"),
178
+ }
179
+
180
+ def matching_id(self, payment):
181
+ info = payment.info_data or {}
182
+ return info.get("referencia")
183
+
184
+
185
+ class EupagoMBWAY(EupagoSettingsMixin, BasePaymentProvider):
186
+ identifier = "eupago_mbway"
187
+ verbose_name = _("MB WAY (euPago)")
188
+ public_name = _("MB WAY")
189
+
190
+ @property
191
+ def payment_form_fields(self):
192
+ return OrderedDict(
193
+ [
194
+ (
195
+ "phone",
196
+ forms.CharField(
197
+ label=_("MB WAY phone number"),
198
+ help_text=_(
199
+ "Portuguese mobile number registered with MB WAY (e.g. 912 345 678). "
200
+ "You have 5 minutes to approve the payment in the MB WAY app."
201
+ ),
202
+ max_length=20,
203
+ ),
204
+ )
205
+ ]
206
+ )
207
+
208
+ def payment_is_valid_session(self, request):
209
+ return bool(
210
+ request.session.get("payment_%s_phone" % self.identifier)
211
+ )
212
+
213
+ def checkout_confirm_render(self, request) -> str:
214
+ template = get_template("pretix_eupago/checkout_mbway.html")
215
+ return template.render(
216
+ {
217
+ "phone": request.session.get("payment_%s_phone" % self.identifier, ""),
218
+ "request": request,
219
+ }
220
+ )
221
+
222
+ def payment_prepare(self, request: HttpRequest, payment: OrderPayment):
223
+ """Called when adding/retrying payment on the order detail page."""
224
+ form = self.payment_form(request)
225
+ if form.is_valid():
226
+ payment.info = json.dumps({"phone": form.cleaned_data["phone"]})
227
+ payment.save(update_fields=["info"])
228
+ return True
229
+ return False
230
+
231
+ def execute_payment(self, request: HttpRequest, payment: OrderPayment):
232
+ # Phone may come from payment.info (payment_prepare flow) or session (checkout flow).
233
+ info = payment.info_data or {}
234
+ phone = info.get("phone") or request.session.get(
235
+ "payment_%s_phone" % self.identifier, ""
236
+ )
237
+
238
+ if not phone:
239
+ raise PaymentException(_("No MB WAY phone number was provided."))
240
+
241
+ # Normalise: strip whitespace, leading +351 or 351, then prefix "351#"
242
+ phone = phone.strip().replace(" ", "")
243
+ for prefix in ("+351", "351"):
244
+ if phone.startswith(prefix):
245
+ phone = phone[len(prefix):]
246
+ break
247
+ phone = "351#" + phone
248
+
249
+ identifier = f"{payment.order.code}-{payment.pk}"
250
+
251
+ payload = {
252
+ "payment": {
253
+ "amount": {"value": float(payment.amount), "currency": "EUR"},
254
+ "identifier": identifier,
255
+ },
256
+ "customer": {"phone": phone},
257
+ }
258
+
259
+ try:
260
+ resp = requests.post(
261
+ MBWAY_URL[self._env()],
262
+ json=payload,
263
+ timeout=30,
264
+ headers={"Authorization": f"ApiKey {self._api_key}"},
265
+ )
266
+ resp.raise_for_status()
267
+ data = resp.json()
268
+ except requests.RequestException:
269
+ logger.exception("euPago MBWAY: HTTP error for payment %s", payment.pk)
270
+ raise PaymentException(
271
+ _("Could not reach the payment provider. Please try again later.")
272
+ )
273
+
274
+ payment.info = json.dumps(
275
+ {
276
+ "phone": phone,
277
+ "transactionID": data.get("transactionID", ""),
278
+ "identifier": identifier,
279
+ }
280
+ )
281
+ payment.save(update_fields=["info"])
282
+ # Payment is pending — confirmed via webhook when customer approves in app.
283
+
284
+ def payment_pending_render(self, request, payment) -> str:
285
+ template = get_template("pretix_eupago/pending_mbway.html")
286
+ return template.render({"info": payment.info_data, "payment": payment})
287
+
288
+ def payment_control_render(self, request, payment) -> str:
289
+ template = get_template("pretix_eupago/control_mbway.html")
290
+ return template.render({"info": payment.info_data, "payment": payment})
291
+
292
+ def shred_payment_info(self, obj):
293
+ d = obj.info_data or {}
294
+ d["phone"] = "*** redacted ***"
295
+ obj.info = json.dumps(d)
296
+ obj.save(update_fields=["info"])
297
+
298
+ def api_payment_details(self, payment):
299
+ info = payment.info_data or {}
300
+ return {"transaction_id": info.get("transactionID")}
301
+
302
+ def matching_id(self, payment):
303
+ info = payment.info_data or {}
304
+ return info.get("transactionID")
@@ -0,0 +1,10 @@
1
+ from django.dispatch import receiver
2
+
3
+ from pretix.base.signals import register_payment_providers
4
+
5
+
6
+ @receiver(register_payment_providers, dispatch_uid="payment_eupago")
7
+ def register_payment_provider(sender, **kwargs):
8
+ from .payment import EupagoMBWAY, EupagoMultibanco
9
+
10
+ return [EupagoMultibanco, EupagoMBWAY]
@@ -0,0 +1,21 @@
1
+ {% load i18n %}
2
+ <div class="eupago-checkout eupago-mbway">
3
+ <p>
4
+ {% blocktrans trimmed %}
5
+ You will receive a payment request in the <strong>MB WAY app</strong> on your phone.
6
+ You have <strong>5 minutes</strong> to approve it after placing your order.
7
+ {% endblocktrans %}
8
+ </p>
9
+ {% if phone %}
10
+ <p>
11
+ {% blocktrans trimmed with phone=phone %}
12
+ Payment request will be sent to: <strong>{{ phone }}</strong>
13
+ {% endblocktrans %}
14
+ </p>
15
+ {% endif %}
16
+ <p class="text-muted">
17
+ {% blocktrans trimmed %}
18
+ Make sure your phone is on and the MB WAY app is active before confirming.
19
+ {% endblocktrans %}
20
+ </p>
21
+ </div>
@@ -0,0 +1,14 @@
1
+ {% load i18n %}
2
+ <div class="eupago-checkout eupago-multibanco">
3
+ <p>
4
+ {% blocktrans trimmed %}
5
+ After placing your order you will receive a <strong>Multibanco entity and reference number</strong>
6
+ that you can use to pay at any ATM or through your bank's online portal.
7
+ {% endblocktrans %}
8
+ </p>
9
+ <p class="text-muted">
10
+ {% blocktrans trimmed %}
11
+ The reference will be valid for a limited time. Please complete your payment before it expires.
12
+ {% endblocktrans %}
13
+ </p>
14
+ </div>
@@ -0,0 +1,19 @@
1
+ {% load i18n %}
2
+ <div class="eupago-control eupago-mbway">
3
+ {% if info.transactionID %}
4
+ <dl class="dl-horizontal">
5
+ <dt>{% trans "Transaction ID" %}</dt>
6
+ <dd>{{ info.transactionID }}</dd>
7
+ {% if info.phone %}
8
+ <dt>{% trans "Phone" %}</dt>
9
+ <dd>{{ info.phone }}</dd>
10
+ {% endif %}
11
+ {% if info.identifier %}
12
+ <dt>{% trans "Identifier" %}</dt>
13
+ <dd>{{ info.identifier }}</dd>
14
+ {% endif %}
15
+ </dl>
16
+ {% else %}
17
+ <p class="text-muted">{% trans "No MB WAY transaction on record." %}</p>
18
+ {% endif %}
19
+ </div>
@@ -0,0 +1,24 @@
1
+ {% load i18n %}
2
+ {% load money %}
3
+ <div class="eupago-control eupago-multibanco">
4
+ {% if info.referencia %}
5
+ <dl class="dl-horizontal">
6
+ <dt>{% trans "Entity" %}</dt>
7
+ <dd>{{ info.entidade }}</dd>
8
+ <dt>{% trans "Reference" %}</dt>
9
+ <dd>{{ info.referencia }}</dd>
10
+ <dt>{% trans "Amount" %}</dt>
11
+ <dd>{{ payment.amount|money:payment.order.event.currency }}</dd>
12
+ {% if info.expiry %}
13
+ <dt>{% trans "Valid until" %}</dt>
14
+ <dd>{{ info.expiry }}</dd>
15
+ {% endif %}
16
+ {% if info.identifier %}
17
+ <dt>{% trans "Identifier" %}</dt>
18
+ <dd>{{ info.identifier }}</dd>
19
+ {% endif %}
20
+ </dl>
21
+ {% else %}
22
+ <p class="text-muted">{% trans "No Multibanco reference on record." %}</p>
23
+ {% endif %}
24
+ </div>
@@ -0,0 +1,10 @@
1
+ {% load i18n %}
2
+ {% load money %}
3
+ {% blocktrans trimmed %}To complete your payment, use the following Multibanco details:{% endblocktrans %}
4
+
5
+ {% trans "Entity" %}: {{ info.entidade }}
6
+ {% trans "Reference" %}: {{ info.referencia|slice:":3" }} {{ info.referencia|slice:"3:6" }} {{ info.referencia|slice:"6:" }}
7
+ {% trans "Amount" %}: {{ payment.amount|money:payment.order.event.currency }}
8
+ {% if info.expiry %}{% trans "Valid until" %}: {{ info.expiry }}{% endif %}
9
+
10
+ {% blocktrans trimmed %}Pay at any ATM or through your bank's online portal (homebanking). Your order will be confirmed automatically once the payment is received.{% endblocktrans %}
@@ -0,0 +1,22 @@
1
+ {% load i18n %}
2
+ <div class="eupago-pending eupago-mbway">
3
+ <p>
4
+ {% blocktrans trimmed %}
5
+ A payment request has been sent to your MB WAY app.
6
+ Please open the app and approve the payment within <strong>5 minutes</strong>.
7
+ {% endblocktrans %}
8
+ </p>
9
+ {% if info.phone %}
10
+ <p class="text-muted">
11
+ {% blocktrans trimmed with phone=info.phone %}
12
+ Sent to: {{ phone }}
13
+ {% endblocktrans %}
14
+ </p>
15
+ {% endif %}
16
+ <p class="text-muted">
17
+ {% blocktrans trimmed %}
18
+ Your order will be confirmed automatically once the payment is approved.
19
+ If the request expires, you can retry the payment from your order page.
20
+ {% endblocktrans %}
21
+ </p>
22
+ </div>
@@ -0,0 +1,36 @@
1
+ {% load i18n %}
2
+ {% load money %}
3
+ <div class="eupago-pending eupago-multibanco">
4
+ {% if info.referencia %}
5
+ <table class="table">
6
+ <tbody>
7
+ <tr>
8
+ <th>{% trans "Entity" %}</th>
9
+ <td><strong>{{ info.entidade }}</strong></td>
10
+ </tr>
11
+ <tr>
12
+ <th>{% trans "Reference" %}</th>
13
+ <td><strong>{{ info.referencia|slice:":3" }} {{ info.referencia|slice:"3:6" }} {{ info.referencia|slice:"6:" }}</strong></td>
14
+ </tr>
15
+ <tr>
16
+ <th>{% trans "Amount" %}</th>
17
+ <td><strong>{{ payment.amount|money:payment.order.event.currency }}</strong></td>
18
+ </tr>
19
+ {% if info.expiry %}
20
+ <tr>
21
+ <th>{% trans "Valid until" %}</th>
22
+ <td>{{ info.expiry }}</td>
23
+ </tr>
24
+ {% endif %}
25
+ </tbody>
26
+ </table>
27
+ <p class="text-muted">
28
+ {% blocktrans trimmed %}
29
+ Pay at any ATM (Caixa Automático) or through your bank's online portal (homebanking).
30
+ Your order will be confirmed automatically once the payment is received.
31
+ {% endblocktrans %}
32
+ </p>
33
+ {% else %}
34
+ <p>{% trans "Payment reference is being generated. Please refresh this page in a moment." %}</p>
35
+ {% endif %}
36
+ </div>
pretix_eupago/urls.py ADDED
@@ -0,0 +1,10 @@
1
+ from django.urls import path
2
+
3
+ from .views import EupagoWebhookView
4
+
5
+ # Global URL patterns (not event-scoped).
6
+ # Pretix includes these at / so the final URL is:
7
+ # https://<domain>/eupago/webhook/
8
+ urlpatterns = [
9
+ path("eupago/webhook/", EupagoWebhookView.as_view(), name="eupago-webhook"),
10
+ ]
pretix_eupago/views.py ADDED
@@ -0,0 +1,127 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import logging
5
+
6
+ from django.http import HttpResponse, HttpResponseBadRequest
7
+ from django.utils.decorators import method_decorator
8
+ from django.views import View
9
+ from django.views.decorators.csrf import csrf_exempt
10
+
11
+ from pretix.base.models import OrderPayment
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ @method_decorator(csrf_exempt, name="dispatch")
17
+ class EupagoWebhookView(View):
18
+ """
19
+ Handles both euPago webhook formats:
20
+ v1.0 — GET request with query-string parameters
21
+ v2.0 — POST request with JSON body (preferred; supports HMAC verification)
22
+
23
+ Configure one URL per euPago channel in Backoffice → Channels → Channel Listing
24
+ → "Receive notification for a URL":
25
+ https://<your-pretix-domain>/eupago/webhook/
26
+ """
27
+
28
+ def get(self, request, *args, **kwargs):
29
+ """Webhook v1.0: payment data arrives as query-string parameters."""
30
+ params = request.GET
31
+ identifier = params.get("identificador", "")
32
+ mp = params.get("mp", "") # PC:PT = Multibanco, MW:PT = MBWAY
33
+
34
+ if not identifier:
35
+ logger.warning("euPago webhook v1.0: missing 'identificador' param")
36
+ return HttpResponseBadRequest("missing identifier")
37
+
38
+ logger.info("euPago webhook v1.0: mp=%s identifier=%s", mp, identifier)
39
+ self._confirm_payment(identifier)
40
+ return HttpResponse("OK", content_type="text/plain")
41
+
42
+ def post(self, request, *args, **kwargs):
43
+ """Webhook v2.0: JSON body with optional HMAC-SHA256 signature header."""
44
+ try:
45
+ body = request.body
46
+ data = json.loads(body)
47
+ except (json.JSONDecodeError, ValueError):
48
+ logger.warning("euPago webhook v2.0: invalid JSON body")
49
+ return HttpResponseBadRequest("invalid JSON")
50
+
51
+ transactions = data.get("transactions", {})
52
+ status = transactions.get("status", "")
53
+ identifier = transactions.get("identifier", "")
54
+ method = transactions.get("method", "")
55
+
56
+ logger.info(
57
+ "euPago webhook v2.0: method=%s status=%s identifier=%s",
58
+ method,
59
+ status,
60
+ identifier,
61
+ )
62
+
63
+ if status == "Paid":
64
+ if not identifier:
65
+ logger.warning("euPago webhook v2.0: missing identifier in payload")
66
+ return HttpResponseBadRequest("missing identifier")
67
+ self._confirm_payment(identifier)
68
+
69
+ return HttpResponse("OK", content_type="text/plain")
70
+
71
+ def _confirm_payment(self, identifier: str):
72
+ """
73
+ Locate an OrderPayment by our stored identifier (format: ORDERCODE-PK)
74
+ and confirm it if still pending.
75
+ """
76
+ try:
77
+ # identifier format: "ORDERCODE-PK", e.g. "SPMC2024-42"
78
+ # rsplit to handle order codes that might contain hyphens
79
+ parts = identifier.rsplit("-", 1)
80
+ if len(parts) != 2:
81
+ logger.warning("euPago webhook: unexpected identifier format: %s", identifier)
82
+ return
83
+
84
+ payment_pk = int(parts[1])
85
+ payment = OrderPayment.objects.select_related("order").get(pk=payment_pk)
86
+
87
+ except (ValueError, OrderPayment.DoesNotExist):
88
+ logger.warning("euPago webhook: payment not found for identifier=%s", identifier)
89
+ return
90
+ except Exception:
91
+ logger.exception("euPago webhook: error looking up identifier=%s", identifier)
92
+ return
93
+
94
+ # Guard against identifier spoofing: verify stored identifier matches
95
+ stored = (payment.info_data or {}).get("identifier", "")
96
+ if stored != identifier:
97
+ logger.warning(
98
+ "euPago webhook: identifier mismatch for payment %s (stored=%s received=%s)",
99
+ payment_pk,
100
+ stored,
101
+ identifier,
102
+ )
103
+ return
104
+
105
+ if payment.state in (
106
+ OrderPayment.PAYMENT_STATE_CONFIRMED,
107
+ OrderPayment.PAYMENT_STATE_CANCELED,
108
+ OrderPayment.PAYMENT_STATE_REFUNDED,
109
+ ):
110
+ logger.info(
111
+ "euPago webhook: payment %s already in terminal state %s, skipping",
112
+ payment_pk,
113
+ payment.state,
114
+ )
115
+ return
116
+
117
+ try:
118
+ payment.confirm()
119
+ logger.info("euPago webhook: confirmed payment %s for order %s", payment_pk, payment.order.code)
120
+ except Exception:
121
+ logger.exception("euPago webhook: error confirming payment %s", payment_pk)
122
+
123
+
124
+ def _verify_hmac(body: bytes, signature: str, secret: str) -> bool:
125
+ """Verify euPago webhook v2.0 X-Signature header (HMAC-SHA256)."""
126
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
127
+ return hmac.compare_digest(expected, signature)
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: pretix-eupago
3
+ Version: 1.0.0
4
+ Summary: Accept Multibanco and MB WAY payments via euPago in pretix
5
+ Author: Afonso Santos
6
+ License: Apache Software License
7
+ Project-URL: Homepage, https://github.com/afonsosantos/pretix-eupago
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Django :: 4.2
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/x-rst
17
+ License-File: LICENSE
18
+ Requires-Dist: requests
19
+ Dynamic: license-file
20
+
21
+ pretix-eupago
22
+ ==============
23
+
24
+ This is a plugin for `pretix`_ that integrates `euPago`_, a Portuguese payment
25
+ gateway, to accept **Multibanco** references and **MB WAY** push payments.
26
+
27
+ Development setup
28
+ ------------------
29
+
30
+ 1. Make sure that you have a working `pretix development setup`_.
31
+
32
+ 2. Clone this repository.
33
+
34
+ 3. Activate the virtual environment you use for pretix development.
35
+
36
+ 4. Execute ``python setup.py develop`` (or ``pip install -e .``) within this directory to register this
37
+ application with pretix's plugin registry.
38
+
39
+ 5. Execute ``make`` within this directory to compile translations.
40
+
41
+ 6. Restart your local pretix server. You can now use the plugin from this repository for your events by
42
+ enabling it in the 'plugins' tab in the settings.
43
+
44
+ Configuration
45
+ -------------
46
+
47
+ Enable the plugin for an event, then go to the event's payment settings and configure the desired
48
+ provider(s) (Multibanco and/or MB WAY):
49
+
50
+ * **API Key** — your euPago API key, found in Backoffice → Channels → Channel Listing.
51
+ * **Sandbox / Test mode** — use the euPago sandbox environment for testing.
52
+ * **Multibanco reference validity (days)** — how many days a generated Multibanco reference stays valid.
53
+
54
+ Finally, configure a single webhook URL in euPago's Backoffice (Channels → Channel Listing → "Receive
55
+ notification for a URL"), for every channel you use::
56
+
57
+ https://<your-pretix-domain>/eupago/webhook/
58
+
59
+ This URL is global (not event-scoped) and handles both euPago webhook formats (v1.0 GET and v2.0 POST).
60
+
61
+ License
62
+ -------
63
+
64
+ Copyright 2026 Afonso Santos
65
+
66
+ Released under the terms of the Apache License 2.0, see the LICENSE file for details.
67
+
68
+ .. _pretix: https://github.com/pretix/pretix
69
+ .. _euPago: https://eupago.pt
70
+ .. _pretix development setup: https://docs.pretix.eu/en/latest/development/setup.html
@@ -0,0 +1,19 @@
1
+ pretix_eupago/__init__.py,sha256=oVdcIYniV7tmHlDEUmLLFIAfwER8zuR9SWcdA_CZ7Z8,240
2
+ pretix_eupago/apps.py,sha256=8h8_LzPu99Nh4EodCoBa3Bpm1nUNjDsE2uH5NgNSHJ8,619
3
+ pretix_eupago/payment.py,sha256=KTq2AOKauJfTQUYVeWMnxjk56jRWf4f5aJrXCZBpLNw,10849
4
+ pretix_eupago/signals.py,sha256=wq9Icby9Prq1YYAVTqlmQ9FgNEZWNFU_-fAHuBNlbpw,316
5
+ pretix_eupago/urls.py,sha256=t8nH8uX8VxLloPMqxs1JA7pKox2vwIG8yig9567YOok,296
6
+ pretix_eupago/views.py,sha256=Zum0_0Qf8X8_vZN0Z9SW7ISp0auXDctue_-tlVtDHng,4822
7
+ pretix_eupago/templates/pretix_eupago/checkout_mbway.html,sha256=mjpPVUZawfYNHMXEG2X14MZeFG1jAEyiUaPyKKDKkNs,717
8
+ pretix_eupago/templates/pretix_eupago/checkout_multibanco.html,sha256=Bf2-mdX189eGWE6gNKEbZixPoXeiupzdyIgpiH3iZOk,551
9
+ pretix_eupago/templates/pretix_eupago/control_mbway.html,sha256=390qK4u2BND3LV26hDjC7rMMGGpvnqJ_Ih_GAyzvZQA,587
10
+ pretix_eupago/templates/pretix_eupago/control_multibanco.html,sha256=iBsE9yCAqHeVRuH_X230SlJrsTihwmXku2QnJVbBSqk,794
11
+ pretix_eupago/templates/pretix_eupago/mail_multibanco.txt,sha256=9XCO12n-zUTk1ww6185xM4c_qQ95Yr1ClEGb16HMV6g,646
12
+ pretix_eupago/templates/pretix_eupago/pending_mbway.html,sha256=7FjceNjql6p1UZbbtSfekAdS27HeIs1Wde1YgV4vkNQ,756
13
+ pretix_eupago/templates/pretix_eupago/pending_multibanco.html,sha256=08wV4Umu_BuSGKacswpIYVbyNlq6PCRwmFb7EqcU0-0,1335
14
+ pretix_eupago-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
15
+ pretix_eupago-1.0.0.dist-info/METADATA,sha256=8p8HJgIFDA0TfEMNKf9xiebSlo0uWhbrssyejQXptHk,2515
16
+ pretix_eupago-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
17
+ pretix_eupago-1.0.0.dist-info/entry_points.txt,sha256=6q_2eSfrYG1KWzBnVCr5QmKWjVR2xJO4KxLCLZha75M,56
18
+ pretix_eupago-1.0.0.dist-info/top_level.txt,sha256=E1HbwjV6CPgnEkpk0C2oEHaGqAIj41BDbQ8vNUT-EgU,14
19
+ pretix_eupago-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pretix.plugin]
2
+ pretix_eupago = pretix_eupago:PluginApp
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ pretix_eupago