Callback de recebimento
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.
Cabeçalhos
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
| content-type | application/json | Sim | Sempre aplicação/json. |
| x-callback-timestamp | string | Sim | Retorno de chamada timestamp em milissegundos. |
| x-callback-nonce | string | Sim | Retorno de chamada nonce. |
| x-callback-signature | string | Sim | HMAC-SHA256(apiKey, timestamp + "." + nonce + "." + rawBody)。 |
| x-callback-signature-algorithm | string | Sim | Sempre HMAC-SHA256. |
| x-callback-signature-version | string | Sim | Sempre v1. |
Parâmetros
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
| merchantUid | string | Sim | Merchant UID. |
| orderNo | string | Sim | Número de pedido da plataforma. |
| merchantOrderNo | string | null | Sim | Número do pedido do comerciante. |
| bindKey | string | null | Sim | Chave vinculativa para recarga de associado. Geralmente vazio para ordens de pagamento compartilhadas. |
| chainCode | string | null | Sim | Rede do pedido. |
| tokenSymbol | string | null | Sim | Moeda do pedido. |
| txHash | string | null | Sim | Hash da transação correspondente; null antes da detecção. |
| expectedAmount | string | null | Sim | Valor do pedido. |
| paidAmount | string | Sim | Valor real pago. |
| fromAddress | string | null | Sim | Endereço do remetente. |
| status | string | Sim | Final successful pay-in status; always completed. |
| mode | string | Sim | Modo: shared ou exclusive. |
| businessType | string | Sim | Tipo de negócio do pedido. |
| serviceFeeUsd | string | Não | Taxa de serviço deste recebimento. |
| feeBalanceAfterUsd | string | Não | Saldo da conta de taxas após a cobrança. |
| payerRiskStatus | string | Sim | Status de risco do pagador. |
| payerRiskLabel | string | null | Sim | Rótulo de risco do pagador. |
Exemplo de requisição
{
"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 da resposta
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
| HTTP Status | 200-299 | Sim | Qualquer resposta 2xx é tratada como sucesso. |
| Response Body | string | json | Não | A resposta body pode ser customizada. |
Exemplo de resposta
HTTP/1.1 200 OK
Content-Type: application/json
{
"ok": true
}Exemplos de código
Execução: salve Java como UUGateExample.java (UUGateCallback.java para callbacks) e use java nome do arquivo; PHP: php example.php; Go: go run example.go; Node.js: node example.mjs. A verificação de callbacks lê o corpo original da entrada padrão.
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
- A verificação de retorno de chamada usa apiKey, não o cabeçalho de solicitação de assinatura x OpenAPI.
- Após verificar, confira comerciante, pedido, ativo, rede e valor. Salve pagamento e resultado em transação idempotente por pedido da plataforma antes de responder 2xx; duplicatas não podem repetir créditos ou entregas.
- Para recarga de membro, use bindKey diretamente como identificador de membro para que você não precise de uma tabela extra de mapeamento de orderNo para membro.
- Este código apenas verifica callbacks. Envie o corpo original à entrada padrão e mapeie os cabeçalhos para UUGATE_CALLBACK_TIMESTAMP, UUGATE_CALLBACK_NONCE e UUGATE_CALLBACK_SIGNATURE. UUGATE_API_KEY deve ser a chave usada na criação. Valide o pedido e persista com idempotência em uma transação antes de retornar HTTP 2xx.