Skip to main content

PayU payments provider for django-payments

Project description

https://badge.fury.io/py/django-payments-payu.svg https://travis-ci.org/PetrDlouhy/django-payments-payu.svg?branch=master https://codecov.io/gh/PetrDlouhy/django-payments-payu/branch/master/graph/badge.svg

NOTE: This project is still in development, so use with extreme caution.

PayU payments provider for django-payments. Uses the new PayU REST API. Supports normal, express and recurring payments.

Documentation

The full documentation is at https://django-payments-payu.readthedocs.io.

Quickstart

Install django-payments and set up PayU payment provider backend according to django-payments documentation:

This backend implements payments using PayU.com.

Set up the payment provider:

Example:

# use sandbox
PAYMENT_VARIANTS = {
    'payu': ('payments_payu.provider.PayuProvider', {
        'pos_id': '123456',
        'second_key': 'iseedeadpeople',
        'client_secret': 'peopleiseedead',
        'sandbox': True,
        'capture': False,
        'get_refund_description': lambda payment, amount: 'My refund',
        'get_refund_ext_id': lambda payment, amount: str(uuid.uuid4()),
        'get_buyer_language': lambda payment: 'cs',
    }),
}
Here are valid parameters for the provider:
client_secret:

PayU OAuth protocol client secret

pos_id:

PayU POS ID

second_key:

PayU second key (MD5)

shop_name:

Name of the shop send to the API

sandbox:

if True, set the endpoint to sandbox

endpoint:

endpoint URL, if not set, the will be automatically set based on sandbox settings

recurring_payments:

enable recurring payments, only valid with express_payments=True, see bellow for additional setup, that is needed

express_payments:

use PayU express form

widget_branding:

tell express form to show PayU branding

store_card:

(default: False) whether PayU should store the card

google_pay:

(default: None) a dict that enables a Google Pay button next to the express form, only valid with express_payments=True, see below

get_refund_description:

An optional callable that is called with two keyword arguments payment and amount in order to get the string description of the particular refund whenever provider.refund(payment, amount) is called. The callable is optional because of backwards compatibility. However, if it is not set, an attempt to refund raises an exception. A default value of get_refund_description is deprecated.

get_refund_ext_id:

An optional callable that is called with two keyword arguments payment and amount in order to get the External string refund ID of the particular refund whenever provider.refund(payment, amount) is called. If None is returned, no External refund ID is set. An External refund ID is not necessary if partial refunds won’t be performed more than once per second. Otherwise, a unique ID is recommended since PayuProvider.refund is idempotent and if exactly same data will be provided, it will return the result of the already previously performed refund instead of performing a new refund. Defaults to a random UUID version 4 in the standard form.

get_buyer_language:

An optional callable that is called with with the keyword argument payment in order to get the language for the hosted payment page and e-mail messages sent from PayU to the payer. Consult the documentation for an up-to-date list of supported language codes and their capabilities. When not set, a default value of en will be used.

NOTE: notifications about the payment status from PayU are requested to be sent to django-payments process_payment url. The request from PayU can fail for several reasons (i.e. it can be blocked by proxy). Use “Show reports” page in PayU administration to get more information about the requests.

Google Pay:

With express_payments=True the provider can render a Google Pay button above the PayU card widget. The button uses the Google Pay API with PayU as the gateway (gateway: payu); the returned token is charged through the standard PayU order with an ap pay-by-link method. With recurring_payments=True the first Google Pay order is sent with recurring=FIRST so PayU issues a multi-use card token that is stored via Payment.set_renew_token() and used for later server-initiated renewals exactly like card payments.

NOTE: Google Pay needs to be enabled on your PayU POS. For the production environment you also need a merchant ID from the Google Pay & Wallet Console. If your site sends a Content-Security-Policy, allow the Google Pay script (script-src https://pay.google.com, frames from https://pay.google.com).

Valid keys of the google_pay dict:

merchant_id:

Google Pay merchant ID (required for the production environment)

merchant_name:

(optional) merchant name shown in the Google Pay sheet

environment:

(default: "TEST" if sandbox else "PRODUCTION") Google Pay environment

gateway_merchant_id:

(default: pos_id) gateway merchant ID passed to the Google Pay tokenization specification

allowed_auth_methods:

(default: ["PAN_ONLY", "CRYPTOGRAM_3DS"])

allowed_card_networks:

(default: ["MASTERCARD", "VISA"])

button_radius:

(optional) corner radius in px passed to the Google Pay button (buttonRadius)

button_color:

(optional) "black", "white" or "default" (buttonColor); use "white" on dark backgrounds per Google’s brand guidelines

Example:

PAYMENT_VARIANTS = {
    'payu': ('payments_payu.provider.PayuProvider', {
        # ...
        'express_payments': True,
        'google_pay': {
            'merchant_id': 'BCR2DN4T26O5PZZZ',
            'merchant_name': 'My shop',
        },
    }),
}
Apple Pay:

With express_payments=True the provider can render an Apple Pay button above the PayU card widget. The button appears only in Safari on a device that can make Apple Pay payments. The returned token is charged through the standard PayU order with a jp pay-by-link method; recurring works like Google Pay (first order recurring=FIRST -> multi-use token stored via Payment.set_renew_token() -> server-initiated renewals).

Apple Pay for the Web additionally requires merchant validation: when the payment sheet opens, the browser calls onvalidatemerchant and the provider POSTs to Apple using your Merchant Identity certificate to obtain a merchant session. This means, unlike Google Pay, you must have that certificate available to the server.

Setup checklist:

  • Enable Apple Pay on your PayU POS and send PayU your Payment Processing certificate (PayU decrypts the token).

  • Create an Apple Merchant ID and a Merchant Identity certificate; make it available to the app.

  • Register and verify every domain that shows the button (serve /.well-known/apple-developer-merchantid-domain-association.txt).

  • If your site sends a Content-Security-Policy, allow the Apple Pay JS API (it is a browser API, no external script, but the button uses the -apple-pay-button appearance).

Valid keys of the apple_pay dict:

merchant_id:

Apple Merchant ID, e.g. merchant.com.example (required)

merchant_name:

merchant/display name shown in the sheet (defaults to shop_name)

country_code:

(default: "US") merchant country code

certificate:

the Merchant Identity certificate, passed as-is to requests’s cert= for merchant validation (a path to a combined PEM, or a (cert, key) tuple of paths)

supported_networks:

(default: ["masterCard", "visa"])

merchant_capabilities:

(default: ["supports3DS"])

Example:

PAYMENT_VARIANTS = {
    'payu': ('payments_payu.provider.PayuProvider', {
        # ...
        'express_payments': True,
        'apple_pay': {
            'merchant_id': 'merchant.com.example',
            'merchant_name': 'My shop',
            'country_code': 'CZ',
            'certificate': '/path/to/merchant_identity.pem',
        },
    }),
}
Recurring payments:

If recurring payments are enabled, the PayU card token needs to be stored in your application for usage in next payments. The next payments can be either initiated by user through (user will be prompted only for payment confirmation by the express form) or by server. To enable recurring payments, you will need to set additional things:

NOTE: Recurring payments are not enabled by default even in Sandbox, you sould consult their helpdesk to enable this.

  • In order to make payments recurring, the card token needs to be stored for the Payment’s user (not just the payment itself). Implement the Payment.set_renew_token() and Payment.get_renew_token().

  • Implement Payment.get_payment_url().

  • For the server initiated recurring payments you will need to create the new payment and then call payment.autocomplete_with_wallet().
    • The method returns either string ‘success’ or url where the user can provide his CVV2 or 3D secure information.

    • The 'success' string means, that the payment is waiting for notification from PayU, but no further user action is required.

Example of triggering recurring payment:

payment = Payment.objects.create(...)
redirect_url = payment.autocomplete_with_wallet()
if redirect_url != 'success':
    send_mail(
        'Recurring payment - action required',
        'Please renew your CVV2/3DS at %s' % redirect_url,
        'noreply@test.com',
        [user.email],
        fail_silently=False,
    )

Running Tests

Does the code actually work?

source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ tox

Credits

Tools used in rendering this package:

History

2.6.0 (2026-07-23)

  • permanent token errors (PayU INVALID_TOKEN) now invalidate the stored renew token via the host’s optional payment.invalidate_renew_token() hook - renewal tasks stop retrying a token that can never work again and interactive users get a fresh card widget instead of a guaranteed failure. Retryable declines (insufficient funds etc.) are unaffected.

  • rejected payments store the PayU transaction detail (paymentFlow + card response codes, e.g. “114 - 3ds authentication error”) in extra_data["rejection_transaction"] - the CANCELED notification itself carries no reason, so this is the only durable record of why a payment was declined.

2.5.0 (2026-07-21)

  • replace the stray debug print in the refund notification path and the bare Exception("Refund was not finelized") with a proper PayuApiError("Refund was not finalized").

  • test suite: 100% line and branch coverage of the provider, and third-party warnings (e.g. mock’s DeprecationWarning on Python 3.14) no longer break the no-warnings assertions.

  • process_notification: never demote a CONFIRMED payment. PayU can deliver duplicate/out-of-order notifications (e.g. a stale CANCELED after COMPLETED); applying one used to clobber a real capture, moving the payment to REJECTED/ERROR while it had actually been paid. The spurious callback is now acked (200 ok, so PayU stops retrying) and the CONFIRMED status is kept. Legitimate refunds are unaffected (they are handled by the dedicated refund branch). Mirrors the existing create_order guard added in 2.1.2.

  • wallet tokens (Google Pay / Apple Pay) are validated before creating the PayU order: a token missing its cryptographic parts now fails the payment immediately with ERROR_WALLET_TOKEN_MALFORMED in extra_data instead of PayU’s vague APPLE_PAY_CLIENT_ERROR, and each accepted token logs its non-sensitive metadata (the Apple Pay publicKeyHash, which identifies the payment-processing certificate the token was encrypted for, and the Google Pay protocolVersion) for diagnostics.

  • add optional Apple Pay button to the express payment form (apple_pay provider parameter). The Apple Pay token.paymentData (which carries the data/signature/header/version PayU decrypts) is charged through a standard PayU order (pay-by-link method jp with base64 authorizationCode); with recurring_payments=True the first order is sent with recurring=FIRST and the returned multi-use card token is stored for renewals. Merchant validation (onvalidatemerchant) is handled by the provider using the configured Merchant Identity certificate.

2.4.0 (2026-07-15)

  • Google Pay: add an optional button_color key in the google_pay config passed to the button as buttonColor ("black" / "white" / "default"). Google’s brand guidelines require the white button on dark backgrounds.

2.3.0 (2026-07-04)

  • survive malformed PayU error responses: an integer status ({"status": 500}) no longer crashes post_request with TypeError, a missing codeLiteral no longer crashes the error log with KeyError, and a non-JSON body (e.g. an HTML 502 page from a proxy) raises PayuApiError instead of a raw JSONDecodeError. The payment now fails cleanly (ERROR status + redirect to the failure page) in the first two cases.

  • Google Pay: re-initialization guards for hosts that inject the express form dynamically (skip double init, initialize when pay.js is already loaded), and an optional button_radius key in the google_pay config passed to the button as buttonRadius.

2.2.0 (2026-07-03)

  • add optional Google Pay button to the express payment form (google_pay provider parameter). The Google Pay token is charged through a standard PayU order (pay-by-link method ap with base64 authorizationCode); with recurring_payments=True the first order is sent with recurring=FIRST and the returned multi-use card token is stored for server-initiated renewals.

  • create_order: don’t overwrite the stored renew token when the order response echoes a pay method without card data (e.g. a wallet pay-by-link method), which is not a reusable card token.

  • fix HtmlOutputField rendering its html autoescaped on Django 5.x - the “This payment is already being processed” error form showed literal “<br/><strong>…” markup to the user.

2.1.1 (2026-05-07)

  • fix create_order demoting an already CONFIRMED payment to ERROR when PayU rejects a duplicate request (e.g. the user’s browser POSTs to the process URL again after 3DS while a parallel webhook has already confirmed the payment). The existing narrow guard for ERROR_ORDER_NOT_UNIQUE is generalised to keep CONFIRMED state regardless of PayU’s rejection reason.

2.1.0 (2026-01-24)

  • add optional get_buyer_language argument to PayuProvider

2.0.0 (2025-05-29)

  • implement the wallet logic

  • change extra_data with atomic operations to reduce concurrent problems

  • support Django 5.2

  • drop support for Python 3.7

  • log error if the payment is switching status out from confirmed

  • fix log warning if the payment is switching status out from confirmed

1.5.0 (2024-08-16)

  • log warning when status changes out from confirmed

  • fix problem with form in Django 5.0

  • support Django 5.1

1.4.6 (2024-07-23)

  • remove debug code committed by mistake

1.4.5 (2024-07-23)

  • fix safestring in Django 5.0

1.4.4 (2024-06-27)

  • fix PayuApiError: invalid response to refund

1.4.3 (2024-05-15)

  • fix “AttributeError: Manager isn’t accessible via Payment instances” introduced in 1.4.1

1.4.2 (2024-05-14)

  • fix multiple deduction of the refund amount from payment.captured_amount

  • change statuses of payments refunded with an amount greater than payment.captured_amount to REFUNDED instead of just deducing captured_amount

1.4.1 (2024-05-14)

  • fix captured_amount not being saved when processing data

1.4.0 (2024-04-12)

  • fix backward compatibility by making PayuProvider’s get_refund_description argument optional

  • add renewal_triggered_by parameter to payment.set_renew_token

  • make PayuProvider.refund fail if get_refund_description is not provided

  • make PayuProvider.refund raise PayuApiError if an unexpected response is received

  • deprecate the default value of get_refund_description; set it to a callable instead

  • deprecate automatic_renewal parameter of payment.set_renew_token; use renewal_triggered_by parameter instead

  • deprecate None value of renewal_triggered_by parameter of payment.set_renew_token; set “user”/”task”/”other” instead

1.3.1 (2024-03-19)

  • Fix description on PyPI

1.3.0 (2024-03-19)

  • add get_refund_description and get_refund_ext_id arguments to PayuProvider

  • add PayuProvider.refund

  • update payment.captured_amount only when order is completed

  • subtract refunds from payment.captured_amount rather than from payment.total

  • rename PayuProvider.payu_api_order_url to payu_api_orders_url

  • tests for Django 2.2-5.0 Python 3.7-3.12

1.2.4 (2022-03-17)

  • treat partial refunds

  • tests for Django 2.2-4.0 Python 3.7-3.10

1.2.3 (2022-01-25)

  • better distinct PayU API errors

1.2.2 (2021-11-30)

  • solve the duplicate order case that errored already confirmed payment

1.2.1 (2021-10-29)

  • set fraud status if PayU anti-froud error

  • store PayU error on payment

1.2.0 (2021-10-11)

  • user Payment.billing_* correctly - the functions like get_user or get_user_email, get_user_first_name and get_user_last_name were redundant and are not called anymore.

  • Shop name is taken from provider configuration variable shop_name

1.1.0 (2021-10-05)

  • redirect to payment.get_failure_url() after API error, log the error

1.0.0 (2020-10-21)

  • first major release

  • many fixes

  • recurring payments working

  • proved by production environment

0.3.0 (2020-05-30)

  • fix amount quantization

  • add store_card parameter

  • fix base url parameter for express form

0.2.0 (2020-04-13)

  • Second release

  • Fixed testing matrix

0.1.0 (2020-04-06)

  • First release on PyPI.

  • Still in development.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_payments_payu-2.6.0.tar.gz (44.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_payments_payu-2.6.0-py2.py3-none-any.whl (23.6 kB view details)

Uploaded Python 2Python 3

File details

Details for the file django_payments_payu-2.6.0.tar.gz.

File metadata

  • Download URL: django_payments_payu-2.6.0.tar.gz
  • Upload date:
  • Size: 44.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for django_payments_payu-2.6.0.tar.gz
Algorithm Hash digest
SHA256 ee5458a7a964c4652140475541a3af979611e715bc3b7ad1bd668b5c5fb09670
MD5 f4f2fac2a64600c5a6ede51e7b56af16
BLAKE2b-256 ee13eb6a5a5f0165e99ae8b6ebb3c4be6f8b3521369da56710aec6424be77074

See more details on using hashes here.

File details

Details for the file django_payments_payu-2.6.0-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for django_payments_payu-2.6.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 3d3eb6dd7e6529ed12680cb49581c0c93c01c60c41f8f95166603b5ced919b8f
MD5 dc5e12d6c634e1ab69afb0b8a78f150a
BLAKE2b-256 ca007d6a3c2c00c673da52c8445c4d702722db916055f7e21fb7be8089a19333

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page