import json, hashlib
def invoice_hash(cart):
    # Sort by UTF-16 code units to match the JavaScript helper (Python defaults to code points)
    items = sorted(cart["items"], key=lambda i: i["id"].encode("utf-16-be"))
    c = {"amount": cart["amount"], "currency": cart["currency"].upper(),
         "items": [{"id": i["id"], "name": i["name"], "price": i["price"], "qty": i["qty"]} for i in items],
         "merchantId": cart["merchantId"]}
    for k in ("taxCents", "shippingCents", "shippingMethod", "destinationPostalCode"):
        if k in cart: c[k] = cart[k]
    s = json.dumps(c, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(s.encode("utf-8")).hexdigest()
cart = {"merchantId":"merch_demo_01","currency":"USD","amount":4200,"items":[{"id":"SKU-B","name":"Glazing Fluid","price":2600,"qty":1},{"id":"SKU-A","name":"Lip Treat","price":1600,"qty":1}]}
print(invoice_hash(cart))
