django-redsys
Django views, URLs and signals for RedSys TPV Virtual payments over the redirect connection. Signing, verification, parameters, constants and response codes come from python-redsys; this app adds the Django side: the page that sends the cardholder to RedSys, the endpoint that receives RedSys's notification, the OK and KO pages, and signals.
Installation
pip install django-redsys
# settings.py
INSTALLED_APPS = [..., 'django_redsys']
REDSYS_CLIENT = {
'secret_key': '...',
'merchant_code': '999008881',
'terminal': 1,
'sandbox': True,
}
# urls.py
urlpatterns = [..., path('redsys/', include('django_redsys.urls'))]
Settings
| Setting | Use |
|---|---|
REDSYS_CLIENT |
Required. The account: the keyword options of python-redsys's RedirectClient. |
REDSYS_NOTIFICATION_IPS |
Optional. Addresses or networks allowed to post notifications; see Notification senders. |
The keys of REDSYS_CLIENT:
| Key | Use |
|---|---|
secret_key |
Merchant secret key. Required unless api_key is set. |
merchant_code, terminal |
Merchant code (FUC) and terminal number. |
sandbox or environment |
sandbox=True targets the test environment; environment= takes redsys.environments.TEST, PROD, INTE or DESA. Production by default. |
currency |
Default currency (redsys.currencies); the euro unless set. |
signature_version |
HMAC_SHA512_V2 by default. |
module |
Ds_Merchant_Module of every request. |
api_key |
A RedSys API key, read with RedirectClient.from_api_key(); replaces secret_key, merchant_code, terminal and the environment. |
The keys go to the constructor unchanged, so an option a later python-redsys adds works without a django-redsys release. An unknown key, an invalid value, or api_key together with the values it replaces raises ImproperlyConfigured. See the python-redsys configuration.
manage.py check validates both settings (django_redsys.E001, django_redsys.E002). manage.py check --deploy warns when REDSYS_CLIENT targets an environment other than production while DEBUG is off (django_redsys.W001); a staging server that uses the test environment on purpose silences it with SILENCED_SYSTEM_CHECKS.
Payment view
A subclass of RedsysPaymentView returns the operation fields; the view signs them and renders a form that posts itself to RedSys. It answers GET and POST. A view that stores state, as the one below, is reached through a POST form (a "Pay" button): browsers and crawlers prefetch GET links, and each prefetch would use up an order number.
from decimal import Decimal
from django.shortcuts import get_object_or_404
from django_redsys.views import RedsysPaymentView
from redsys import generate_order
class PayOrderView(RedsysPaymentView):
def get_redsys_fields(self):
order = get_object_or_404(Order, pk=self.kwargs['pk'], user=self.request.user)
order.redsys_order = generate_order()
order.save(update_fields=['redsys_order'])
return {
'order': order.redsys_order,
'amount': order.total, # Decimal, in euros unless currency= says otherwise
'merchant_data': str(order.pk),
'product_description': 'Online order',
}
| Attribute or method | Use |
|---|---|
get_redsys_fields() |
Required. The keyword fields of the operation: order, amount and any other redirect parameter. None (or Http404 raised) when there is no order to pay: the view answers 404. |
get_redsys_client() |
The client that signs, get_client() by default. A view that pays through another terminal or merchant returns its own RedirectClient; the notification and result views have the same method. |
transaction_type |
redsys.transactions.AUTHORIZATION by default; PREAUTHORIZATION, AUTHENTICATION or REFUND_WITHOUT_ORIGINAL for the other redirect operations. |
redirect_template_name |
django_redsys/redirect.html by default. |
get_redsys_request() |
Builds and signs the python-redsys Request; sends request_created. |
merchant_url, url_ok and url_ko default to the app's notification, OK and KO URLs; a value returned by get_redsys_fields() replaces them. The URLs are absolute, from request.build_absolute_uri(); behind a proxy that terminates TLS, SECURE_PROXY_SSL_HEADER makes them https.
The page is sent with Cache-Control: no-store: a cached copy would post an order number RedSys already received, which it rejects (SIS0051).
RedsysPaymentFormView is the same on top of FormView: after form_valid(), self.form holds the validated form for get_redsys_fields(). RedsysPaymentMixin holds the behavior for other view classes; redirect_to_redsys() returns the response.
Invalid fields raise python-redsys's ValueError subclasses before anything is signed (errors).
Notification and signals
RedSys posts the result of every operation to merchant_url. NotificationView (django_redsys:notification) verifies the signature, parses the result into a python-redsys Response and sends the signals; it answers 200 with an empty body. A payload that fails parsing or verification, whatever the exception, raises SuspiciousOperation chained to it: Django answers 400 and logs it on the django.security logger.
Signal (django_redsys.signals) |
Sent | Arguments |
|---|---|---|
request_created |
A payment view signed a request. | request, redsys_request, fields |
notification_received |
A notification passed verification. | request, response |
notification_authorized |
After notification_received, when response.is_authorized(). |
request, response |
notification_denied |
After notification_received, otherwise. |
request, response |
notification_invalid |
A notification failed verification or parsing, or came from an address outside REDSYS_NOTIFICATION_IPS. |
request, error |
notification_repeated |
With the notification record, a verified notification whose payload already arrived; sent instead of the three above. | request, response |
sender is the view class. The notification is the source of truth for an operation's outcome; the OK and KO pages are not, since the cardholder may never reach them.
A valid notification can arrive more than once. The signed result also reaches the cardholder's browser on the redirect to url_ok or url_ko (when the portal sends it, see below), and a copy posted to the notification URL verifies like the original. Receivers are idempotent: they act on the state of the order, not on the arrival of the signal, and check that the result matches what was asked for.
from django.db import transaction
from django.dispatch import receiver
from django_redsys.signals import notification_authorized
@receiver(notification_authorized)
def mark_paid(sender, request, response, **kwargs):
with transaction.atomic():
order = Order.objects.select_for_update().filter(redsys_order=response.order).first()
if order is None or order.is_paid or order.total != response.amount:
return
order.mark_paid(authorization_code=response.authorization_code)
response carries every result field (order, amount, response_code, authorization_code, merchant_data, card_country, ...) and response.describe(language) gives the meaning of the code; see the response parameters and response codes. An exception in a receiver propagates, and the notification gets a 500.
Notification senders
REDSYS_NOTIFICATION_IPS, off by default, limits who may post to the notification URL. A request from any other address gets 403 before its payload is parsed, and notification_invalid is sent with a PermissionDenied error.
REDSYS_NOTIFICATION_IPS = ['192.0.2.10', '198.51.100.0/24'] # RedSys's addresses, as the bank or RedSys gives them
The address compared is REMOTE_ADDR. Behind a proxy or load balancer, REMOTE_ADDR is the proxy's unless the server sets it from the forwarded header; a subclass of NotificationView can override is_allowed_sender() to read it another way. The signature check stays: the list only saves the work of parsing what does not come from RedSys.
Notification record
django_redsys.notifications, an optional app, records every verified notification and turns a repeat into notification_repeated:
INSTALLED_APPS = [..., 'django_redsys', 'django_redsys.notifications']
python manage.py migrate
- A notification is a repeat when its
Ds_MerchantParametersis identical to one already recorded (SHA-256 digest, unique). A new result for the same order is not a repeat. Idempotency per order stays with the receivers. - The record and the signals commit in one transaction on the database the model is routed to: a receiver that raises leaves nothing recorded, and the next arrival of the same notification is processed as new.
- Each record keeps the order, the response code and
SISnnnnerror code, whether it was authorized, the amount and currency, the transaction type, the authorization code, the merchant code, terminal and environment (TEST,PROD, ...), whether the payment was 3-D Secure authenticated (Ds_SecurePayment), the payment method that processed it (Ds_ProcessedPayMethod), RedSys's date and hour as sent (Ds_Date,Ds_Hour), the sender address, the first and last arrival, and the number of arrivals. Card data, stored-card tokens (Ds_Merchant_Identifier,Ds_Merchant_Cof_Txnid) andmerchant_dataare not stored: a token charges the card again, andmerchant_datais free text. Invalid notifications are not recorded. - The admin lists the records read-only (
django.contrib.admininstalled).python manage.py purge_redsys_notifications --older-than DAYSdeletes the records first received more thanDAYSdays ago, for a retention period run from cron or a scheduler. - The app label is
django_redsys_notifications.
OK and KO pages
django_redsys:ok and django_redsys:ko render django_redsys/ok.html and django_redsys/ko.html through ResultView, with the verified result as redsys_response. RedSys appends the signed result to the redirect only when the option "Enviar Parámetros en las URLs" is on in its portal. Without a result that verifies, or with an outcome that does not match the page (an authorized result on the KO page, or the reverse), the page answers 404. With the option off, url_ok and url_ko point to the project's own views. A template with the same name in the project replaces the app's.
Templates and Content Security Policy
django_redsys/redirect.html receives endpoint and fields (the three Ds_* fields) and submits the form with an inline script, with a <noscript> button as fallback. With Django's CSP middleware (Django 6.0 and later) and the django.template.context_processors.csp context processor, the script carries the request's nonce; the policy then needs CSP.NONCE in script-src and the RedSys host in form-action:
from django.utils.csp import CSP
SECURE_CSP = {
'script-src': [CSP.SELF, CSP.NONCE],
'form-action': [CSP.SELF, 'https://sis.redsys.es', 'https://sis-t.redsys.es:25443'],
}
Every template defines a title and a content block; redirect.html also defines head.
Direct operations
django_redsys.client.get_client() builds the client from REDSYS_CLIENT; it takes another client class for the direct connection (pip install "python-redsys[http]"):
from django_redsys.client import get_client
from redsys.clients import DirectClient
response = get_client(DirectClient).refund(order=order.redsys_order, amount=order.total).send()
response.is_refunded()
Compatibility
| Version | 1.0.0 |
| Django | 5.2 LTS, 6.0 and 6.1 |
| Python | 3.10 to 3.15 (Django 6.0 and later need 3.12) |
| python-redsys | 2.2 and later |
Upgrading from 0.4: docs/migration-0.4-to-1.0.md.
Development
uv sync
uv run pytest
uv run ruff check django_redsys tests && uv run ruff format --check django_redsys tests
License
Apache License 2.0, as python-redsys. See LICENSE and NOTICE. Releases up to 0.4.2 were published under the MIT License.
Metadata
Release files for django-redsys 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_redsys-1.0.0.tar.gz | 32.5 kB | With provenance | Details for django_redsys-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_redsys-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for django_redsys-1.0.0-py3-none-any.whl |
Total release size: 55.1 kB
Release files / django_redsys-1.0.0.tar.gz
| Download URL | django_redsys-1.0.0.tar.gz |
|---|---|
| Size | 32.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0a8982cdbd2f595839937654cd2f7d233f9ba570f3379f4864a0eba1d7502ccd
|
|
BLAKE2b-256 checksum How to use checksums |
11b9698c8633b139a92013f2858345158314988095ca9a58a611ed9050b7c809
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 8, 2026.
Transparency logRelease files / django_redsys-1.0.0-py3-none-any.whl
| Download URL | django_redsys-1.0.0-py3-none-any.whl |
|---|---|
| Size | 22.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
de6c9256910e60bf61c96b16bf1d5bd97cfd6a072c7ca1326dfb3193f04b28b0
|
|
BLAKE2b-256 checksum How to use checksums |
87d50e2e9f4599a5f2c438c2022146c11f76a28f50d15d444da97bf1a783eb8d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 8, 2026.
Transparency logSecurity for django-redsys 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for django_redsys-1.0.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 8, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.