import hashlib
import hmac
import json
import os
import sys
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def signature(raw, key):
return hashlib.sha256(raw + key.encode("utf-8")).hexdigest()
def call(base, path, payload, terminal, key):
raw = json.dumps(payload, ensure_ascii=False,
separators=(",", ":")).encode("utf-8")
request = urllib.request.Request(
base + path, data=raw, method="POST",
headers={
"Content-Type": "application/json",
"Authorization-Type": "sha256",
"Authorization": terminal + " " + signature(raw, key),
},
)
opener = urllib.request.build_opener(NoRedirect())
try:
response = opener.open(request, timeout=45)
except urllib.error.HTTPError as error:
response = error
# A timeout raises an exception; never automatically repeat a push.
with response:
response_raw = response.read()
http_status = response.code
auth = response.headers.get("Authorization", "").split(" ")
expected = signature(response_raw, key)
if (len(auth) != 2 or auth[0] != terminal
or not hmac.compare_digest(auth[1].lower(), expected)):
raise RuntimeError("Unverified response; keep outcome unknown")
result = json.loads(response_raw)
if not 200 <= http_status < 300 or result.get("result_code") != "200":
raise RuntimeError(
"API error: " + str(result.get("error_code", http_status))
)
return result
def main():
mode = sys.argv[1] if len(sys.argv) > 1 else "query"
if mode == "selftest":
raw = b'{"terminal_sn":"TEST_TERMINAL","client_sn":"SG_TEST_001"}'
assert signature(raw, "TEST_SECRET") == (
"3425ab126f49ea26ec607af9d2d2c90225db75a43b8fabd01e28580d2080d00f"
)
print("Signature self-test passed (no network request)")
return
if mode not in ("push", "query"):
raise SystemExit("Usage: aimt_example.py selftest|push|query")
base = os.environ["AIMT_BASE_URL"].rstrip("/")
url = urlsplit(base)
if (url.scheme != "https" or not url.netloc or url.username
or url.password or url.path or url.query or url.fragment):
raise SystemExit("AIMT_BASE_URL must be the assigned HTTPS origin")
terminal = os.environ["AIMT_TERMINAL_SN"]
key = os.environ["AIMT_TERMINAL_KEY"]
order = os.environ["AIMT_ORDER_ID"]
if not order.isascii() or not order.isalnum() or len(order) > 32:
raise SystemExit("AIMT_ORDER_ID: 1-32 ASCII letters/digits")
payload = {"terminal_sn": terminal}
if mode == "push":
if os.environ.get("AIMT_TEST_CONFIRMED") != "1":
raise SystemExit("Confirm test environment before setting AIMT_TEST_CONFIRMED=1")
payload.update({
"out_trade_no": order,
"total_amount": "100",
"trade_time": str(int(time.time() * 1000)),
"target_device_id": os.environ["AIMT_TARGET_DEVICE_ID"],
"notify_url": os.environ["AIMT_NOTIFY_URL"],
"pay_type": "1,2,6",
})
path = "/appPush/tradePush"
else:
if os.environ.get("AIMT_ORDER_SN"):
payload["sn"] = os.environ["AIMT_ORDER_SN"]
else:
payload["client_sn"] = order
if os.environ.get("AIMT_REFUND_REQUEST_NO"):
payload["refund_request_no"] = os.environ["AIMT_REFUND_REQUEST_NO"]
path = "/upay/v2/query"
result = call(base, path, payload, terminal, key)
business = result.get("biz_response") or {}
transaction = business.get("data") or {}
# Print only identifiers and states, never full customer payloads.
print(json.dumps({
"result_code": result.get("result_code"),
"biz_result": business.get("result_code"),
"error_code": business.get("error_code"),
**{k: transaction.get(k) for k in
("sn", "client_sn", "tsn", "type", "status",
"order_status", "total_amount", "net_amount")},
}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()