跳到主要内容

Python 签名示例

import hmac
import hashlib
import base64
import time
import uuid


def sign_hmac_sha256(message: str, secret: str) -> str:
signature = hmac.new(
secret.encode("utf-8"),
message.encode("utf-8"),
hashlib.sha256
).digest()
return base64.b64encode(signature).decode("utf-8")


def build_sign_string(method: str, uri: str, timestamp: str,
nonce: str, body: str) -> str:
return "{}\n{}\n{}\n{}\n{}\n".format(
method, uri, timestamp, nonce, body or ""
)


def build_authorization(mchid: str, serial: str, nonce: str,
timestamp: str, signature: str) -> str:
return 'KP-CASHIER-HMAC-SHA256 mchid="{}", serial="{}", nonce="{}", timestamp="{}", signature="{}"'.format(
mchid, serial, nonce, timestamp, signature
)


def build_client_header(sn: str, name: str, ip: str,
app: str, version: str, session: str = "") -> str:
parts = [
'sn="{}"'.format(sn),
'name="{}"'.format(name),
'ip="{}"'.format(ip),
'app="{}"'.format(app),
'version="{}"'.format(version),
]
if session:
parts.append('session="{}"'.format(session))
return ", ".join(parts)


if __name__ == "__main__":
method = "POST"
uri = "/open/cashier/trans/micropay"
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
body = '{"amount":100,"out_trade_no":"TS20260507000001","auth_code":"134567890123456789"}'
secret = "your_secret_key"

sign_string = build_sign_string(method, uri, timestamp, nonce, body)
signature = sign_hmac_sha256(sign_string, secret)
authorization = build_authorization("100001", "KEY001", nonce, timestamp, signature)
client_header = build_client_header("SN-DEVICE-001", "收银台A01", "192.168.1.100", "cashier-pos", "2.0.0", "abc123")

print("Authorization: " + authorization)
print("Ikudot-Cashier-Client: " + client_header)

AES 加解密

部分敏感字段(如支付密码)需使用 AES-256-CBC 加密后传输。

import base64
import os

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


def aes_encrypt(plaintext: str, base64_key: str) -> dict:
key = base64.b64decode(base64_key)
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext.encode("utf-8"), AES.block_size))
return {
"algorithm": "AES_256_CBC",
"ciphertext": base64.b64encode(ciphertext).decode("utf-8"),
"iv": base64.b64encode(iv).decode("utf-8"),
}


def aes_decrypt(base64_ciphertext: str, base64_iv: str, base64_key: str) -> str:
key = base64.b64decode(base64_key)
iv = base64.b64decode(base64_iv)
ciphertext = base64.b64decode(base64_ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode("utf-8")


if __name__ == "__main__":
aes_key = "Base64EncodedAesKey=="
plaintext = "123456"

encrypted = aes_encrypt(plaintext, aes_key)
print("加密结果:", encrypted)

decrypted = aes_decrypt(encrypted["ciphertext"], encrypted["iv"], aes_key)
print("解密结果:", decrypted)