← All articles

Inside a Click payment: Prepare and Complete

Why one payment takes two requests, what the signature protects against and where a server can get it wrong — with a step-by-step diagram.

Taking payments through Click, one of Uzbekistan’s payment systems, looks simple from the outside: the customer presses a button and the money arrives. Inside, Click calls your server twice and expects a precise answer each time. Most cases of “the money was taken, but the order is still unpaid” start with a misreading of these two requests.

This article walks through the Click Shop API flow from start to finish. First, watch the whole path in the diagram: press “Play” or move through the steps yourself.

  1. The customer confirms the payment in the Click app or on the payment page. Your server does not know about it yet.

  2. Click sends your server a Prepare request (action=0): the order number merchant_trans_id, the amount and the signature sign_string. It asks one thing: may money be taken for this order?

  3. The server verifies the signature, finds the order, compares the amount and saves a payment record in the “preparing” state. No money has moved yet.

  4. The reply carries error: 0 and merchant_prepare_id, the number of the record just saved. Click remembers it.

  5. Only now does Click debit the customer’s card. This step is entirely on Click’s side, and it may fail.

  6. Click reports the outcome with a Complete request (action=1). It carries the same merchant_prepare_id and an error: 0 means the money was taken, a negative number means the payment failed.

  7. The server finds the record by merchant_prepare_id and marks the order as paid. If the same request arrives again, it changes nothing the second time.

  8. The reply carries error: 0 and merchant_confirm_id. For Click, the payment is finished.

  9. The customer sees that the payment went through, and you ship the goods or open the service.

Click Shop API: the path of one payment

Why two stages

Imagine that Click took the money first and told you afterwards. If the order does not exist, the amount is wrong or the order has already been paid, the money is gone and you cannot accept it — it has to be refunded.

So Click asks first and charges second:

  • Prepare — “can you accept this payment?” The money is still on the customer’s card. If you refuse, nobody loses anything.
  • Complete — “the money was taken, or it was not; record the outcome.”

The idea resembles a two-phase commit: in the first stage the parties say they are ready, in the second the result is written down.

Both requests arrive as POST with an application/x-www-form-urlencoded body. You answer in JSON.

The signature: did the request really come from Click

The Prepare and Complete addresses are open to the internet. Anyone can try sending your server a request that says “the order is paid”. The signature is what stops that.

Click adds a sign_string to every request: an md5 of the request fields and the SECRET_KEY issued to you when you connect.

Prepare:  md5(click_trans_id + service_id + SECRET_KEY + merchant_trans_id
              + amount + action + sign_time)

Complete: md5(click_trans_id + service_id + SECRET_KEY + merchant_trans_id
              + merchant_prepare_id + amount + action + sign_time)

The SECRET_KEY itself is not in the request: only you and Click know it. The server computes the same formula and compares the result with sign_string. If they differ, it returns -1 and does nothing else.

Three details matter here:

  1. amount is text. The signature is computed from the exact string Click sent. Turn it into a number and back into text, get 1000 instead of 1000.00, and the signature no longer matches.
  2. The two formulas differ. Complete adds merchant_prepare_id between merchant_trans_id and amount.
  3. Compare in constant time. A plain == stops at the first character that differs, and the difference in response time can help someone guess the signature character by character. .NET has CryptographicOperations.FixedTimeEquals for this.

Prepare: before the money moves

At Prepare the server answers three questions:

  • does the order exist (by merchant_trans_id)? If not, -5;
  • has it been paid already? If so, -4;
  • is the amount right? If not, -2.

If everything is in order, the server saves a payment record in the “preparing” state and returns its number as merchant_prepare_id. Online shops reserve the goods at this point so that they are not sold to someone else.

{
  "click_trans_id": 123456789,
  "merchant_trans_id": "order-42",
  "merchant_prepare_id": 7001,
  "error": 0,
  "error_note": "Success"
}

The main point: Prepare is not a payment. You must not mark the order as paid or hand over the goods at this stage: the money has not been taken and may never be.

Complete: recording the outcome

At Complete everything depends on the error field of the request.

error is negative — the payment failed on Click’s side. The server marks the record as cancelled, releases the reserved goods and returns -9.

error is zero — the money was taken. The server finds the record by merchant_prepare_id, checks that it belongs to this order and marks the order as paid.

What gets forgotten most often here is idempotency. Click may send Complete more than once, for example when your answer never reached it. The second request must not hand over the goods a second time: if the record is already paid, the server changes nothing.

One more rule: once Prepare was accepted and the money was taken, Complete must not be answered with an error. Click’s documentation names only two exceptions: the payment was confirmed earlier (-4) or cancelled earlier (-9). If errors keep coming back after several attempts, the payment may be handed to Click’s technical support for manual investigation.

And if you cannot deliver after the money was taken? You still answer Complete as successful and return the money through the payment/reversal method of the Merchant API.

Common mistakes

  • Treating Prepare as the payment. The order becomes “paid” at Prepare while no money has been taken.
  • Reformatting amount. Use the exact string Click sent when computing the signature.
  • A Complete that is not idempotent. A repeated request leads to a second delivery.
  • Ignoring a negative error. “Complete arrived, so the money is in” is a wrong assumption.
  • Not tying merchant_prepare_id to the order. The record was found, but it may belong to another order: check both identifiers together.

Response codes

The codes your server returns to Click:

Code error_note When
0 Success Everything is in order
-1 SIGN CHECK FAILED! The signature does not match
-2 Incorrect parameter amount The amount is wrong
-3 Action not found Unknown action
-4 Already paid The payment was confirmed earlier
-5 User does not exist The order or user was not found
-6 Transaction does not exist No record for this merchant_prepare_id
-7 Failed to update user The data could not be updated
-8 Error in request from click The request itself is malformed
-9 Transaction cancelled The payment was cancelled earlier

A ready-made solution for .NET

So as not to write these rules again in every project, I moved them into an open-source library: Click .NET SDK. It parses the request, checks service_id and the signature, and builds the response in the right format. Two methods are left for you.

Wiring it up:

builder.Services.AddClick<OrderClickHandler>(builder.Configuration);

var app = builder.Build();

// POST /click/shop: both Prepare and Complete arrive here
app.MapClickShopApi();

The business logic:

public sealed class OrderClickHandler(AppDbContext db) : IClickShopHandler
{
    public async Task<ClickPrepareResult> OnPrepareAsync(
        ClickShopRequest r, CancellationToken ct)
    {
        var order = await db.Orders
            .FirstOrDefaultAsync(o => o.Id == r.MerchantTransId, ct);

        if (order is null)
            return ClickPrepareResult.Fail(ClickError.UserNotFound);     // -5
        if (order.IsPaid)
            return ClickPrepareResult.Fail(ClickError.AlreadyPaid);      // -4
        if (order.Amount != r.AmountValue)
            return ClickPrepareResult.Fail(ClickError.IncorrectAmount);  // -2

        var payment = new Payment
        {
            OrderId = order.Id,
            ClickTransId = r.ClickTransId,
            Amount = r.AmountValue,
            State = PaymentState.Preparing,
        };
        db.Payments.Add(payment);
        await db.SaveChangesAsync(ct);

        return ClickPrepareResult.Ok(payment.Id); // merchant_prepare_id
    }

    public async Task<ClickCompleteResult> OnCompleteAsync(
        ClickShopRequest r, CancellationToken ct)
    {
        var payment = await db.Payments
            .FirstOrDefaultAsync(p => p.Id == r.MerchantPrepareId, ct);

        if (payment is null || payment.OrderId != r.MerchantTransId)
            return ClickCompleteResult.Fail(ClickError.TransactionNotFound);   // -6

        // The payment failed on Click's side.
        if (r.Error < 0)
        {
            payment.State = PaymentState.Cancelled;
            await db.SaveChangesAsync(ct);
            return ClickCompleteResult.Fail(ClickError.TransactionCancelled);  // -9
        }

        if (payment.State == PaymentState.Cancelled)
            return ClickCompleteResult.Fail(ClickError.TransactionCancelled);  // -9

        // A repeated request skips this block: the record is already paid.
        if (payment.State != PaymentState.Paid)
        {
            var order = await db.Orders.FirstAsync(o => o.Id == payment.OrderId, ct);
            payment.State = PaymentState.Paid;
            order.IsPaid = true;
            await db.SaveChangesAsync(ct); // both changes, one transaction
        }

        return ClickCompleteResult.Ok(payment.Id); // merchant_confirm_id
    }
}

r.Amount is the very string Click signed; r.AmountValue is the same value as a decimal. The signature is computed from the first, and the second is handier for comparing amounts.

The SDK compares the signature in constant time, keeps amount as a string and does not call the handler at all when the signature does not match. In other words, the details above are handled inside the library. The code is open on GitHub.

In short

  • Prepare asks, Complete records. The money moves between the two.
  • The signature is the only proof that a request came from Click. Check it every time, before any business logic.
  • Make Complete idempotent: even if the same request arrives twice, there is one result.

Source: Click Shop API documentation.

Read next

  1. RAM va .NET xotirasi: yacheykadan GC gachaRAM ichida nima bor, CPU baytni qanday o‘qiydi, OS xotirani jarayonga qanday beradi va .NET uni qanday boshqaradi — o‘lchovlar va qadamma-qadam chizmalar bilan.