---
title: Alif Integration
description: Integrate Alif (alifpay) checkout into a Python project with PayTechUZ — invoices and checkout links, the fiscal receipt, refunds, the signed webhook, sandbox and a Django example.
source: https://pay-tech.uz/en/docs/integrations/alif
---

# Alif Integration

Alif (alifpay) takes card payments on its own checkout page. You raise an
invoice through Alif's API and send the payer to its page; when the payment
ends, Alif posts the invoice to your webhook. Available since PayTechUZ
0.6.0.

## Installation

```bash
pip install "paytechuz[django]>=0.6.0"
```

## Payment links

```python
from paytechuz.gateways.alif import AlifGateway

alif = AlifGateway(
    token="your_alif_token",  # sandbox and live tokens differ
    webhook_url="https://example.com/payments/webhook/alif/",
    is_test_mode=True,        # api-dev.alifpay.uz and checkout-dev.alifpay.uz
)

link = alif.create_payment(
    id="order_123",           # your order id, kept in the invoice's meta
    amount=50000,             # so'm; Alif gets tiyin
    return_url="https://example.com/payment/done/",
    description="Order #123", # the item on Alif's page
)
# https://checkout-dev.alifpay.uz/?invoice=<alif invoice id>
```

Alif takes invoices of 500 to 200 000 000 so'm. Other `/invoice` fields go as
keyword arguments under Alif's names: `timeout` (seconds the invoice stays
payable), `phone` (`998XXXXXXXXX`), `cancel_url` (`return_url` by default),
`meta` (strings only).

Alif answers its own errors with HTTP 200 and an `error` object (its code is
then in `exc.data['error']['code']`), and a wrong token with HTTP 401.
PayTechUZ raises both as `ExternalServiceError`.

### Fiscal receipt

```python
link = alif.create_payment(
    id="order_123",
    amount=50000,
    description="Order #123",
    receipt=True,
    spic="your_ikpu_code",    # the item's IKPU (MXIK)
    pin="committent_pinfl",   # or tin="committent_inn"
)
```

`spic` is required with `receipt=True`. When Alif sells as your commissioner
(komissioner), the receipt names you as the committent: pass your PINFL as
`pin` (14 digits) or your INN as `tin` (9 digits).

### Check and refund

```python
invoice = alif.check_payment("alif_invoice_id")   # getInvoice
invoice["payment"]["status"]                      # 'SUCCEEDED', 'REVERTED', ...

alif.cancel_payment("alif_invoice_id")            # refundInvoice: the whole amount
```

## Django webhook

### Settings

```python
# settings.py
INSTALLED_APPS = [
    # ...
    'paytechuz.integrations.django',
]

PAYTECHUZ = {
    'ALIF': {
        'TOKEN': 'your_alif_token',
        'SECRET_KEY': 'your_alif_secret_key',  # checks the Signature header
        'IS_SANDBOX': False,
        'ACCOUNT_MODEL': 'shop.models.Order',
        'ACCOUNT_FIELD': 'id',       # what create_payment(id=...) was given
        'AMOUNT_FIELD': 'amount',    # in so'm on your model; Alif sends tiyin
        'ONE_TIME_PAYMENT': True,
    },
}
```

Run `python manage.py migrate` (migration `0006` adds `alif` to the
`payments` table's gateways).

### View

```python
# views.py
from paytechuz.integrations.django.views import BaseAlifWebhookView
from paytechuz.integrations.django.webhooks.alif import Refused

from shop.models import Order


class AlifWebhookView(BaseAlifWebhookView):
    def before_payment(self, invoice, account):
        # An order no longer payable: Alif gives the payer the money back.
        if account.status != 'pending':
            raise Refused(f'order {account.pk} is {account.status}', 409)

    def successfully_payment(self, params, transaction):
        Order.objects.filter(id=transaction.account_id).update(status='paid')

    def cancelled_payment(self, params, transaction):
        Order.objects.filter(id=transaction.account_id).update(status='cancelled')
```

```python
# urls.py
path('payments/webhook/alif/', AlifWebhookView.as_view(), name='alif_webhook'),
```

There is no webhook address in a cabinet: each invoice carries it, from the
`webhook_url` given to `AlifGateway`.

`successfully_payment` runs in the same database transaction as the payment
row. If it raises, nothing is recorded, the webhook answers 500 and Alif posts
again.

## How the webhook decides

The webhook body is not trusted for money:

1. With `SECRET_KEY` set, the `Signature` header must be the base64
   HMAC-SHA256 of the raw body; otherwise `403`. Without `SECRET_KEY` a
   warning is logged and the next step still holds.
2. The invoice is read again from Alif with `getInvoice`, and that answer
   decides. An invoice Alif does not know answers `404`; Alif unreachable,
   `502`.
3. The account is the invoice's `meta.account_id`.

| Status at `getInvoice` | Answer |
| --- | --- |
| `SUCCEEDED` | pays the account once; `200`, and `200` again for every repeat |
| `REVERTED` | cancels the payment, `cancelled_payment` if it was paid; `200` |
| `PENDING`, `HELD`, `PENDING_REVERSAL` | `409`: not ended yet, Alif posts again |
| any other (declined, card errors) | `200`, nothing changes |

A payment is refused with `400` for a wrong amount, `404` for no or an
unknown account, `409` for an account already paid (`ONE_TIME_PAYMENT`), or
the status your `before_payment` gives `Refused(message, http)`.

:::warning Any answer but 200 is a refund
Alif retries a webhook that does not get HTTP 200 for about an hour, then
cancels the payment and gives the payer the money back. A refusal is how you
say "do not take this money". A repeated webhook for a payment you already
took always gets 200.
:::

## Sandbox

```python
PAYTECHUZ = {
    'ALIF': {
        'TOKEN': 'your_alif_sandbox_token',
        'IS_SANDBOX': True,   # getInvoice at api-dev.alifpay.uz
        # ACCOUNT_MODEL etc. as above
    },
}
```

Use `is_test_mode=True` on the gateway as well. Sandbox payments are recorded
but `sandbox_payment(params, transaction)` is called instead of
`successfully_payment`, a sandbox refund calls nothing, and sandbox rows do
not count as paid for `ONE_TIME_PAYMENT`.

## Further reading

- [Django Integration](./django)
- [Alif API documentation](https://docs.alifpay.uz)
- [PayTechUZ GitHub repository](https://github.com/PayTechUz/paytechuz)
