Paymn

Paymn / Guides

Payment callbacks without crediting twice

For whoever writes the code that adds balance after a payment.

The buyer paid. Your server was restarting, so the callback failed, and the balance never arrived: that is a support ticket. Or the callback was retried, your code ran twice, and the buyer now has double the balance: that is money you gave away. Both come from the same place, the few lines that handle the callback.

1. Credit on the callback, never on the return page

After paying, the buyer is sent back to your return_url. That page load is not proof of anything: anyone can open the URL. Show "thank you, we are confirming your payment" there, and change the balance only when the signed callback arrives at your notify_url.

2. Check the signature before anything else

The callback carries a signature computed from its fields and your API key. Recompute it on your server and compare. If it does not match, stop. Without this check, whoever learns your callback URL can add balance to their own account.

3. Credit once per paymentId

A callback is retried until your server answers, so the same payment can reach you more than once. The retry carries the same paymentId. Store that id with a unique constraint and let the database decide:

  • Insert the paymentId and add the balance in one transaction.
  • If the insert fails because the id already exists, do nothing and still answer success.

A check of the form "look it up, then add" is not enough: two retries arriving together both pass the look-up. The unique constraint is what makes it safe.

4. Answer success only when the work is saved

Answer success after the balance is committed, not before. If your handler fails midway, return an error and let the retry do the job: the callback is sent again with growing delays, up to 20 attempts.

When a callback never arrived

  • Every attempt is recorded in the merchant portal, with what your server answered.
  • Once your endpoint is fixed, resend the callback for that order from the portal.
  • Your server can also ask: GET /api/order returns an order's status by your own order id or by paymentId.

Creating the order is idempotent too

If a buyer double-clicks "Pay" or your request times out and you send it again, use the same clientOrderId. Creating an order again with the same clientOrderId returns the existing order instead of a second one.

See it happen

In the sandbox you can create an order, mark it paid and watch the callback arrive at your own server, then resend it to confirm your handler credits only once. Field names and the signature recipe are in the API documentation.

Next: Alipay and WeChat Pay for a store outside China