交易签名
为了系统安全的目的,在发送交易请求时,您需要将此参数添加到header:
标头 | 内容 |
---|---|
Content-Type | text/plain |
X-Transaction-Signature | {transaction_signature} |
所需参数
- Transaction Secret: 商户后台取得(API 对接 -> QR Ph交易密钥)
- Request Body: 交易请求内容
生成步骤
- 使用 HMAC 算法,对 Request Body 以 Transaction Secret 作为密钥进行签名(hash)
- 使用 base64 编码签名的结果。
- PHP
- Java
- Python
function transcation_signature(string $request_body, string $transaction_secret): string
{
return base64_encode(hash_hmac('sha256', $request_body, $transaction_secret, true));
}
public static String transactionSignature(String requestBody, String transactionSecret) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(transactionSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secretKey);
byte[] hashBytes = sha256_HMAC.doFinal(requestBody.getBytes(StandardCharsets.UTF_8));
String signature = Base64.getEncoder().encodeToString(hashBytes);
return signature;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
def transaction_signature(request_body, transaction_secret):
request_body_bytes = bytes(request_body, 'utf-8')
transaction_secret_bytes = bytes(transaction_secret, 'utf-8')
hash_object = hmac.new(transaction_secret_bytes, request_body_bytes, hashlib.sha256)
raw_signature = hash_object.digest()
signature = base64.b64encode(raw_signature).decode('utf-8')
return signature