Callback de cobro
The merchant server is called only after a pay-in completes successfully; the callback status is always completed.
Only final payment results are sent. Any HTTP 2xx response stops delivery immediately. After the first failure, the platform retries in 1 minute; after another failure, it makes a final retry in 5 minutes, for up to 3 attempts total. Callback business times use Beijing time in YYYY/MM/DD HH:mm:ss format.
Encabezados
| Campo | Tipo | Obligatorio | Descripción |
|---|---|---|---|
| content-type | application/json | Sí | Siempre aplicación/json. |
| x-callback-timestamp | string | Sí | Devolución de llamada timestamp en milisegundos. |
| x-callback-nonce | string | Sí | Devolución de llamada nonce. |
| x-callback-signature | string | Sí | HMAC-SHA256(apiKey, timestamp + "." + nonce + "." + rawBody)。 |
| x-callback-signature-algorithm | string | Sí | Siempre HMAC-SHA256. |
| x-callback-signature-version | string | Sí | Siempre v1. |
Parámetros
| Campo | Tipo | Obligatorio | Descripción |
|---|---|---|---|
| merchantUid | string | Sí | Merchant UID. |
| orderNo | string | Sí | Número de pedido de la plataforma. |
| merchantOrderNo | string | null | Sí | Número de pedido del comerciante. |
| bindKey | string | null | Sí | Clave vinculante para recarga de socios. Generalmente vacío para órdenes de pago compartido. |
| chainCode | string | null | Sí | Red del pedido. |
| tokenSymbol | string | null | Sí | Moneda del pedido. |
| txHash | string | null | Sí | Hash de la transacción asociada; null antes de detectarla. |
| expectedAmount | string | null | Sí | Importe del pedido. |
| paidAmount | string | Sí | Monto real pagado. |
| fromAddress | string | null | Sí | Dirección del remitente. |
| status | string | Sí | Final successful pay-in status; always completed. |
| mode | string | Sí | Modo: shared o exclusive. |
| businessType | string | Sí | Tipo de negocio del pedido. |
| serviceFeeUsd | string | No | Comisión de este cobro. |
| feeBalanceAfterUsd | string | No | Saldo de la cuenta de tarifas después del cobro. |
| payerRiskStatus | string | Sí | Estado de riesgo del pagador. |
| payerRiskLabel | string | null | Sí | Etiqueta de riesgo del pagador. |
Ejemplo de solicitud
{
"merchantUid": "880001",
"orderNo": "PI1776193200123ABCD1234",
"merchantOrderNo": "M202604150001",
"bindKey": null,
"expectedAmount": "100.000000",
"paidAmount": "100.000000",
"chainCode": "TRON",
"tokenSymbol": "USDT",
"txHash": "f7f17891f52c35d0c93170f0d12bb347ac16ab34853b4bc8dcf7fd0a8c9aa321",
"fromAddress": "TS7b7iD8G2PaPqK1TqSmLJ9nrrYH4oKX1S",
"status": "completed",
"mode": "shared",
"businessType": "fixed",
"serviceFeeUsd": "0.000000",
"feeBalanceAfterUsd": "10.000000",
"payerRiskStatus": "low_risk",
"payerRiskLabel": "低风险"
}Campos de respuesta
| Campo | Tipo | Obligatorio | Descripción |
|---|---|---|---|
| HTTP Status | 200-299 | Sí | Cualquier respuesta 2xx se considera exitosa. |
| Response Body | string | json | No | La respuesta body se puede personalizar. |
Ejemplo de respuesta
HTTP/1.1 200 OK
Content-Type: application/json
{
"ok": true
}Ejemplos de código
Ejecución: guarda Java como UUGateExample.java (UUGateCallback.java para callbacks) y usa java nombre de archivo; PHP: php example.php; Go: go run example.go; Node.js: node example.mjs. La verificación de callbacks lee el cuerpo original desde la entrada estándar.
import { createHmac, timingSafeEqual } from 'node:crypto';
function required(name) {
const value = process.env[name]?.trim();
if (!value) throw new Error(name + ' is required');
return value;
}
const key = required('UUGATE_API_KEY');
const timestamp = required('UUGATE_CALLBACK_TIMESTAMP'), nonce = required('UUGATE_CALLBACK_NONCE');
const signature = required('UUGATE_CALLBACK_SIGNATURE');
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
const rawBody = Buffer.concat(chunks);
const expected = createHmac('sha256', key).update(timestamp + '.' + nonce + '.', 'utf8').update(rawBody).digest();
const actual = Buffer.from(signature, 'hex');
if (!/^[a-fA-F0-9]{64}$/.test(signature) || actual.length !== expected.length || !timingSafeEqual(expected, actual))
throw new Error('Invalid callback signature');
console.log('VERIFIED');import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class UUGateCallback {
static String required(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) throw new IllegalArgumentException(name + " is required");
return value.trim();
}
public static void main(String[] args) throws Exception {
String key = required("UUGATE_API_KEY");
String timestamp = required("UUGATE_CALLBACK_TIMESTAMP"), nonce = required("UUGATE_CALLBACK_NONCE");
String signature = required("UUGATE_CALLBACK_SIGNATURE");
byte[] rawBody = System.in.readAllBytes();
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
mac.update((timestamp + "." + nonce + ".").getBytes(StandardCharsets.UTF_8));
byte[] expected = mac.doFinal(rawBody);
if (!signature.matches("[a-fA-F0-9]{64}") ||
!MessageDigest.isEqual(expected, HexFormat.of().parseHex(signature)))
throw new IllegalArgumentException("Invalid callback signature");
System.out.println("VERIFIED");
}
}<?php
function required(string $name): string {
$value = trim((string) getenv($name));
if ($value === '') throw new RuntimeException($name . ' is required');
return $value;
}
$key = required('UUGATE_API_KEY');
$timestamp = required('UUGATE_CALLBACK_TIMESTAMP'); $nonce = required('UUGATE_CALLBACK_NONCE');
$signature = required('UUGATE_CALLBACK_SIGNATURE');
$rawBody = file_get_contents('php://stdin');
if ($rawBody === false) throw new RuntimeException('Cannot read raw body');
$expected = hash_hmac('sha256', $timestamp . '.' . $nonce . '.' . $rawBody, $key);
if (!preg_match('/^[a-fA-F0-9]{64}$/D', $signature) || !hash_equals($expected, strtolower($signature)))
throw new RuntimeException('Invalid callback signature');
echo 'VERIFIED', PHP_EOL;package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"strings"
)
func required(name string) string {
value := strings.TrimSpace(os.Getenv(name))
if value == "" { panic(name + " is required") }
return value
}
func main() {
key := required("UUGATE_API_KEY")
timestamp, nonce := required("UUGATE_CALLBACK_TIMESTAMP"), required("UUGATE_CALLBACK_NONCE")
signature := required("UUGATE_CALLBACK_SIGNATURE")
rawBody, err := io.ReadAll(os.Stdin); if err != nil { panic(err) }
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(timestamp + "." + nonce + ".")); mac.Write(rawBody)
actual, err := hex.DecodeString(signature)
if err != nil || !hmac.Equal(mac.Sum(nil), actual) { panic("Invalid callback signature") }
fmt.Println("VERIFIED")
}Notas
- La verificación de devolución de llamada utiliza apiKey, no el encabezado de solicitud de firma x OpenAPI.
- Tras verificar, comprueba comerciante, pedido, activo, red e importe. Guarda pago y resultado en una transacción idempotente por pedido de plataforma antes de responder 2xx; los duplicados no deben repetir abonos o entregas.
- Para la recarga de miembros, utilice bindKey directamente como identificador de miembro para que no necesite una tabla de asignación adicional de orderNo a miembro.
- Este código solo verifica callbacks. Usa el cuerpo original como entrada estándar y asigna los encabezados a UUGATE_CALLBACK_TIMESTAMP, UUGATE_CALLBACK_NONCE y UUGATE_CALLBACK_SIGNATURE. UUGATE_API_KEY debe ser la clave de creación del pedido. Después valida el pedido y persiste con idempotencia transaccional antes de devolver HTTP 2xx.