Metadata-Version: 2.5
Name: django-htpayway
Version: 1.1.0
Summary: A Django integration for HT PayWay payment gateway.
Author-email: Sasha Matijasic <sasha@selectnull.com>
License-File: LICENSE
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# django-htpayway

Accept payments through [HT PayWay](https://poslovni.ht.hr/payway) in a Django shop. The app creates a local `Transaction`, sends the customer's browser to PayWay with a signed payment form, and verifies the result before calling your shop's payment hook.

## Install

In an existing Django project running Python 3.12 or newer:

```sh
python -m pip install django-htpayway
# Or, with uv:
uv add django-htpayway
```

Add `"htpayway"` to `INSTALLED_APPS` (the import name differs from the distribution name) and create the transaction table:

```sh
python manage.py migrate htpayway
```

The app uses Django's auth user model and `request.user`, including for anonymous checkout. Keep Django's session and authentication middleware enabled. To use the bundled payment pages, enable app template discovery (`APP_DIRS: True` in the Django template backend, or use the app-directories loader).

## Configure

### 1. Set the merchant credentials and payment endpoint

Use the shop ID, signing secret, and payment form URL supplied by PayWay for the **same environment**. The app reads Django settings; this example loads their values from environment variables so the secret stays out of source control.

```python
# settings.py
import os

HTPAYWAY_SHOP_ID = os.environ["HTPAYWAY_SHOP_ID"]
HTPAYWAY_SECRET_KEY = os.environ["HTPAYWAY_SECRET_KEY"]
HTPAYWAY_FORM_URL = os.environ["HTPAYWAY_FORM_URL"]  # PayWay endpoint, not your callback URL
HTPAYWAY_CLASS = "shop.payments.ShopPayWay"
```

### 2. Connect payment results to your shop

Subclass `PayWay` and implement both hooks. In this example, `PaymentAttempt` is **your own model**, not part of this package. Replace the lookup and methods with your shop's order logic. The `pgw_order_id` you send at checkout is the reference you get back here.

```python
# shop/payments.py
from htpayway import PayWay
from shop.models import PaymentAttempt


class ShopPayWay(PayWay):
    def on_success(self, transaction):
        attempt = PaymentAttempt.objects.get(pk=transaction.pgw_order_id)
        attempt.mark_paid()

    def on_failure(self, transaction):
        attempt = PaymentAttempt.objects.get(pk=transaction.pgw_order_id)
        attempt.mark_failed()
```

Return `None` to show the bundled `htpayway/success.html` or `htpayway/failure.html` page, or return a Django `HttpResponse` (such as a redirect). You can also override those templates in your project.

### 3. Mount the payment URLs

```python
# urls.py — add this entry to your existing urlpatterns
from django.urls import include, path

urlpatterns = [
    path("payway/", include("htpayway.urls", namespace="htpayway")),
]
```

With this prefix, the return URLs are `/payway/success/` and `/payway/failure/`. The app builds their absolute URLs from the incoming checkout request. In production, make sure Django sees the public HTTPS scheme and hostname, including when it runs behind a reverse proxy.

## Start a payment

Once your checkout has created a payment attempt, use its unique reference and the amount calculated **on the server**. Pass the amount in major currency units (for example, `Decimal("10.99")`, not `1099`); the app formats it for PayWay.

```python
from django.shortcuts import redirect
from htpayway.utils import begin_transaction


def start_payment(request, attempt):
    tx = begin_transaction(request, {
        "pgw_order_id": str(attempt.pk),
        "amount": attempt.amount,
    })
    return redirect("htpayway:begin", transaction_id=tx.pk)
```

Call this helper from your checkout view. The `begin` page submits the signed form to PayWay. Use a distinct `pgw_order_id` for each new payment attempt, even if a customer retries payment for the same order.

## Development: run the tests

From the root of your `django-htpayway` clone, use [uv](https://docs.astral.sh/uv/) to install the locked development dependencies and run the package tests with the bundled Django project:

```sh
uv sync --locked
uv run python test_project/manage.py test htpayway
```

To run just the callback tests and see each test name:

```sh
uv run python test_project/manage.py test htpayway.test_callbacks --verbosity 2
```

No PayWay account, merchant credentials, or manual migrations are needed. Django creates and discards a test database. The bundled project uses SQLite, so the concurrent callback test is skipped: it requires row-level locking. To exercise that test, run the same suite with Django settings pointing to a development PostgreSQL database and a role allowed to create test databases.

## Callback behavior

A verified first return records the result and runs the hook in one database transaction. If the hook raises, database changes roll back. Schedule side effects such as confirmation emails with `django.db.transaction.on_commit()`. On databases that support row locks, concurrent returns for the same attempt are serialized.

An exact signed repeat renders the standard result page without running the hook again, even if the first response was a redirect. Malformed returns (400), invalid signatures (403), unknown order references (404), and conflicting or ambiguous results (409) leave payment state unchanged.
