A method and system for processing offline wallet transactions based on a two-way two-dimensional code handshake

By using a two-way QR code handshake protocol and a unified transaction state machine, the security and synchronization issues of offline transactions in scenarios where communication is unreachable are solved, enabling secure transfer and transaction consistency across multiple devices, making it suitable for offline wallet systems for mobile payments.

CN122492192APending Publication Date: 2026-07-31耿洋
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
耿洋
Filing Date
2026-05-09
Publication Date
2026-07-31

AI Technical Summary

Technical Problem

In scenarios where communication networks are unavailable, existing QR code payment solutions suffer from limited availability, security and synchronization issues in offline transactions, and are particularly difficult to resolve in terms of secure transfer and inconsistency in transaction status when devices are replaced.

Method used

The offline wallet transaction method based on two-way QR code handshake is adopted. Through two-way signature verification between the payer and the payee, the integrity of offline transactions is protected. The wallet card is securely transferred between new and old devices. After the network is restored, idempotent verification and on-chain synchronization are performed, and the multi-terminal transaction state machine is unified.

Benefits of technology

It enables bidirectional verifiable offline transactions even without a network, ensuring transaction security and consistency. It supports instant revocation of devices during transfer, ensuring idempotency and auditability of transactions. It is suitable for collaborative operation of multiple heterogeneous terminals and reduces hardware costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure FT_1
    Figure FT_1
  • Figure FT_2
    Figure FT_2
  • Figure FT_3
    Figure FT_3
Patent Text Reader

Abstract

This invention discloses an offline wallet transaction processing method and system based on a two-way QR code handshake. The receiving terminal constructs and signs a payment intention and generates a first QR code under offline conditions. After scanning, the paying terminal performs signature / validity / single transaction / daily cumulative / counter monotonicity verification locally, generates and signs a payment authorization, and displays a second QR code. After scanning again, the receiving terminal sets the local transaction to pendingSync and issues a receipt. After network connection is restored, the transactions are uploaded in batches to an offline transaction synchronization service. The service performs deduplication based on transaction identifier and composite idempotent key double key, double signature verification using normalized SHA-256 digests, and pre-filtering based on single transaction / daily cumulative / unsynchronized / synchronization freshness / clock offset thresholds. Wallet addition / subtraction, dual ledger entries, and audit disk write-down are completed within the same atomic transaction. Furthermore, this invention provides a wallet card device transfer and original device revocation mechanism based on a one-time transferCode and server-side atomic transactions. This mechanism revoks the offline issuance capability of the original device at the same time the new device is activated. The method shares the same state machine and protocol across iOS, Web, and STM32 terminals, exhibiting strong interoperability and low deployment costs.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of mobile payment and digital wallet technology, and in particular to an offline wallet transaction processing method and system suitable for scenarios where communication networks are unreachable. More specifically, it relates to a closed-loop wallet system based on a two-way QR code handshake protocol, a wallet card device transfer and revocation mechanism, and an offline transaction on-chain synchronization idempotent verification mechanism. Background Technology

[0002] With the widespread adoption of mobile payments, "QR code payment" has become one of the mainstream payment methods. However, most existing QR code payment solutions require at least one of the payer and payee to be connected to the internet. In subway turnstiles, tunnels, underground parking lots, ferries, post-disaster scenarios, cross-border areas without network access, and some parks with limited network access, the availability of QR code payments is severely restricted.

[0003] To address the above issues, the industry has proposed several offline payment solutions: (1) Two-way authentication based on near field communication (NFC), which requires dedicated SE / eSE security units and dedicated read / write terminals, resulting in high hardware and deployment costs; (2) A solution based on "payer unilateral code issuance + payee accounting and online entry", which, since only one party completes the signature, carries the risk that the payee cannot confirm the transaction intent (such as amount, timeliness, merchant identity) in an offline scenario, and the payer cannot obtain an electronic receipt in the offline state; (3) A solution based on hardware encryption card + terminal card reader, which is limited by the hardware supply chain and is not convenient to promote on general smartphones.

[0004] At the semantic level of wallet account and device binding, existing solutions generally have the following problems in the "device replacement / card replacement" scenario: after the original device is lost or damaged, the new device is only migrated with the server account, and the original device's local key and executable offline transaction capabilities are not revoked in the first place; the resulting offline scenario "double-spending" risk and credential abuse risk have not been systematically resolved.

[0005] On the other hand, the transactions to be synchronized accumulated in offline scenarios are uploaded to the server in batches after the network is restored. This requires multiple requirements such as deduplication, replay blocking, signature verification by both parties, risk control thresholds, clock skew tolerance, and atomic ledger recording under untrusted network conditions. Existing solutions such as "first entry into the warehouse and then cancellation" or "verification led by the receiving side" cannot meet all the above constraints at the system level at the same time. Especially when multiple terminals (mobile terminal, web terminal, embedded MCU terminal) are accessed together, the inconsistency of the state machines of different terminals will lead to the fragmentation of synchronization semantics.

[0006] In summary, there is an urgent need for a technology that can: (1) complete a fully verifiable payment process of "intent-authorization-receipt" in scenarios where neither party has a network connection; (2) support the secure transfer of wallet card authorization between new and old devices and forcibly revoke the original device; (3) ensure that all offline transactions are idempotent and auditable on the blockchain after network connection is restored; and (4) enable offline wallet technology to share the same transaction state machine among heterogeneous terminals such as mobile phones, browsers, and embedded MCUs. Summary of the Invention The technical problem that the invention aims to solve

[0007] The technical problems to be solved by this invention include: how to complete offline wallet transactions with mutual integrity protection and validity period constraints when neither the payer nor the payee has a usable communication network; how to achieve controllable transfer of wallet cards between old and new devices and immediately revoke the offline issuance capability of the original device; how to perform deduplication, replay prevention, dual signature verification, risk control release, and atomic accounting for multiple offline transactions accumulated over a period of time after network connection is restored; and how to unify the transaction state machine and protocol semantics in scenarios involving multiple heterogeneous terminals. Technical solution

[0008] To solve the above-mentioned technical problems, the present invention provides the following technical solution:

[0009] On one hand, the present invention provides an offline wallet transaction method based on a two-way QR code handshake, applicable to an offline wallet system that includes at least a payment terminal and a receiving terminal, the method comprising:

[0010] Step S210: The receiving terminal constructs a payment intention PaymentIntent based on the amount to be received, currency, merchant account identifier, merchant device identifier, merchant random number, merchant monotonic counter and validity period, and uses the merchant private key bound in the security unit of the receiving terminal to digitally sign the standardized signature material of the payment intention to obtain a first signature σM.

[0011] In step S220, the payment terminal encodes the payment intent and the first signature σM into a first QR code QR1 and displays it; at the same time, it saves a local transaction record with an initiated status in the local transaction log. The local transaction record includes at least a transaction identifier txId, a merchant intent identifier intentId, a merchant random number, a merchant counter, and an idempotent key generated by the merchant-side specification.

[0012] In step S230, the payment terminal scans and decodes the first QR code QR1, verifies the validity of the first signature σM, the validity period, the single transaction limit, the daily cumulative limit, and the monotonicity of the payer's monotonic counter. When all verifications pass, the payment terminal generates a payment authorization PaymentAuthorization based on the payment intention, which includes a payment random number, the payer's monotonic counter, and the local timestamp. The payment terminal then uses the payer's private key to digitally sign the standardized signature material of the payment authorization to obtain a second signature σP.

[0013] In step S240, the payment terminal encodes the payment authorization and the second signature σP into a second QR code QR2 and displays it; at the same time, it sets the status of the local transaction record to authorized and writes it into the local transaction log, and calculates and saves the composite idempotent key on the payer side, which is formed by concatenating txId and the payer authorization identifier authId according to a preset rule;

[0014] In step S250, the receiving terminal scans and decodes the second QR code QR2, and verifies whether the (txId, intentId, amount, currency) tuple carried by the payment authorization is consistent with the local transaction record in the initiated state. If consistent, the status of the local transaction record is advanced to pendingSync and the fields such as payer account / device / random number / counter / authorization identifier are completed. Based on the merchant's private key, a third signature is constructed on the receipt to generate a payment receipt (PaymentReceipt), which can optionally be displayed via the third QR code QR3 or fed back to the payment terminal through other local channels.

[0015] Step S260: When the receiving terminal regains network connectivity, it uploads multiple transactions in the pendingSync state from its local transaction log to the offline transaction synchronization service on the server in batches. The offline transaction synchronization service performs the following sequential operations on each uploaded transaction: (a) deduplication based on txId and idempotent keys; (b) verification of account and device binding relationship and activity status; (c) risk control release based on single transaction limit, daily cumulative limit, unsynchronized upper limit, synchronization freshness and clock offset threshold; (d) based on normalized hash digest SHA-256(txId|intentId|authId|amount|currency|merchantNonce|payerNonce|intentIssuedAt|authorizationIssuedAt|expiresAt). (e) Perform double signature verification of the public keys of both the merchant and the payer; if all passes, execute the following in the same atomic transaction: reduce the payer's wallet balance, increase the payee's wallet balance, add two debit / credit ledger entries, persist the transaction record, update the merchant's device's most recent synchronization time, and write it to the audit log; (f) Return three semantic results for each transaction: accepted, duplicate, or rejected.

[0016] In step S270, the receiving terminal advances the status of the corresponding record in its local transaction log to synced or rejected based on the returned transaction-by-transaction results.

[0017] On the other hand, the present invention also provides a method for transferring wallet cards between devices, applied to the server side of the aforementioned offline wallet system. The method includes: a management terminal initiating a startTransfer request and submitting an account identifier and the original device identifier; the server verifying whether the initiator is an account owner or has an admin role, and after verifying that the original device is in an active state, generating a one-time transferCode with provable entropy, setting a pending transfer session with an expiration date, and writing it to disk; transmitting the transferCode to the new device through a controlled out-of-band channel; the new device generating a new key pair in its local security unit, initiating a completeTransfer request to the server, and submitting the transferCode, the new device's public key, and the key version; the server executing the following within the same atomic transaction: setting the original device's status to revoked and writing freezeReason=card_transferred:tid, creating a new device and binding it to the same account identifier and original role, setting the transfer session to completed, and writing it to the audit log; thereafter, the original device will be forcibly revoked and exit the session in any synchronization action, thereby eliminating the possibility of it continuing to participate in offline issuance.

[0018] On another front, the present invention also provides an offline wallet system based on the above method. The system includes: a payment terminal, a receiving terminal, a management terminal, and server-side services for account and device activation, wallet ledger service, offline transaction synchronization service, risk control and strategy service, wallet card transfer service, clearing and reconciliation service, and auditing and historical services. The payment terminal, receiving terminal, and management terminal share the same offline wallet transaction state machine through a shared core module. This shared core module includes a QR code encoding / decoding module, a two-way handshake coordination module, a risk control strategy engine, a local transaction log module, a device identity / key module, and a synchronization queue module. This shared core module is implemented on iOS operating system terminals, Web console terminals, and embedded terminals based on STM32 series microcontrollers using a common protocol, common state fields, and common signature materials, enabling payers and payees from different terminal types to interoperate without relying on any backend connection.

[0019] Furthermore, the present invention also provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements any of the methods described above. And an electronic device including a processor, a memory, and a communication device, wherein the memory stores instructions executable by the processor, which, when executed, implement any of the methods described above. Beneficial effects

[0020] Compared with the prior art, the present invention has the following significant advantages:

[0021] (1) Two-way verifiability: Through the three-stage two-way QR code handshake of "merchant issuing code (Intent) - payer issuing code (Authorization) - merchant receipt (Receipt), even when neither party has a network, the two-way verification and signature solidification of amount, currency, validity period, random number and monotonic counter can be completed locally by both parties, eliminating the risks of "amount tampering / replay / order misuse" under the one-way code issuing scheme;

[0022] (2) Immediate revocation of the original device: By combining "start / complete two-stage card transfer + one-time transferCode + server-side atomic transaction", the original device's issuance capability is revoked at the same time as the new device is activated, fundamentally eliminating the possibility of "double spending / credential abuse" in offline scenarios;

[0023] (3) Idempotent auditable on-chain: Through double signature verification based on normalized digest, deduplication of (txId, idempotencyKey) double key, risk control threshold pre-filtering and atomic accounting of "loan entry + wallet balance", even if the receiving terminal repeatedly uploads in the weak network / breakdown resume scenario, it will not lead to duplicate entries or omissions. All transactions can be traced end-to-end in the audit log.

[0024] (4) Multi-terminal collaboration: iOS smartphones, web browsers and embedded terminals based on STM32 microcontrollers share the same offline transaction state machine and signature material specifications. This means that different types of terminals, such as wearable hardware wallets, smartphone payers, and web console operation terminals, can be combined in any role (payment ↔ receipt), which greatly expands the applicability of this invention in scenarios such as turnstiles, ferries, emergency disaster relief and cross-border restricted networks.

[0025] (5) Low deployment cost: This solution does not rely on NFC, SE / eSE security chips or dedicated read / write hardware. It can complete all offline interactions using only the camera / screen of a general smartphone. It has extremely low hardware threshold and deployment cost, making it easy to promote on a large scale. Attached Figure Description

[0026] Figure 1 is an overall architecture diagram of the offline QR code wallet system provided in an embodiment of the present invention;

[0027] Figure 2 is a timing diagram of the handshake for two-way QR code offline payment provided in an embodiment of the present invention;

[0028] Figure 3 is a timing diagram of wallet card transfer between devices and old device cancellation provided in an embodiment of the present invention;

[0029] Figure 4 is a flowchart of offline transaction on-chain synchronization and idempotency verification provided in an embodiment of the present invention;

[0030] Figure 5 is a schematic diagram of the offline wallet transaction state machine shared by multiple terminals provided in an embodiment of the present invention. Detailed Implementation

[0031] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the embodiments described herein are merely illustrative and not intended to limit the invention. All other embodiments obtained by those skilled in the art based on the embodiments of this invention without inventive effort are within the scope of protection of this invention. I. System Overall Architecture (See Figure 1)

[0032] [Offline QR Code Wallet System Overall Architecture]

[0033] The system described in this embodiment includes a client domain and a server domain. The client domain includes: a payment terminal 110, a receiving terminal 120, a management terminal 130, and a shared core module 140. The payment terminal 110 and the receiving terminal 120 can be respectively implemented as an iOS smartphone or an embedded hardware wallet based on an STM32 series microcontroller; the management terminal 130 can be implemented as an iOS smartphone or a web console in browser form.

[0034] The shared core module 140 further includes: a QR code encoding / decoding module 141, used to encode the JSON model of payment intent, payment authorization, and payment receipt into displayable QR code strings and perform reverse decoding; a two-way handshake coordination module 142, used to control the handshake process according to the "intent-authorization-receipt" three-stage control of the present invention; a risk control strategy engine 143, used to perform local verification of single transaction amount, daily accumulation, counter monotonicity, clock offset, and validity period; a local transaction log module 144, used as a local "unsynchronized queue" to persist all transactions not on the chain; a device identity and key module 145, which encapsulates the signature abstraction of security units (such as iOS Secure Enclave, STM32 onboard TRNG, and secure flash memory); and a pending synchronization queue module 146, which accepts transactions in the pendingSync state and pushes them in batches when the network connection is restored.

[0035] The server-side domain includes: account and device activation service 210, wallet ledger service 220, offline transaction synchronization service 230, risk control and strategy service 240, wallet card transfer service 250, clearing and reconciliation service 260, and audit and history service 270. The offline transaction synchronization service 230 is the core module of this invention on the server side, which works with the risk control and strategy service 240 to complete the idempotency verification, dual signature verification, and risk control release of transactions uploaded by the client. II. Two-way QR code offline payment handshake protocol (see Figure 2)

[0036] [Handshake Sequence for Two-Way QR Code Offline Payment]

[0037] This embodiment provides the following complete offline handshake process:

[0038] In step S210, after receiving the payment instruction, the payment terminal 120 is invoked by the two-way handshake coordination module 142 in its local core module 140 to assemble the PaymentIntent data structure, which includes at least the following fields: transaction identifier txId (UUID v4 or v7 is recommended), merchant intent identifier intentId, merchant account identifier merchantAccountId, merchant device identifier merchantDeviceId, amountCents (integer in the smallest currency unit to avoid floating-point precision issues), currency, merchantNonce (a random number of ≥ 16 bytes is recommended), merchantCounter (device-level monotonically increasing counter), issuedAt and expiresAt (expires time is recommended to be ≤ 30 seconds).

[0039] In step S220, the payment terminal 120 uses its device identity and key module 145 to call the merchant's private key to perform ECDSA-P256 (or SM2) signature on the standardized signature material "txId|intentId|amount|currency|nonce|counter|expiresAt" to obtain σM; then the QR code encoding and decoding module 141 serializes the PaymentIntent and σM into JSON, and then wraps them into two envelopes using Base64 (envelope.type = paymentIntent, envelope.payload = base64(JSON(model))) to generate and display the first QR code QR1; at the same time, the local transaction log module 144 persists the local transaction record in the initiated state.

[0040] In step S230, the payment terminal 110 scans and decodes QR1 using a camera: first, it decodes the Base64 envelope, then decodes the JSON to obtain the PaymentIntent; then, it calls the local risk control strategy engine 143 to perform the evaluateIntent judgment, sequentially verifying the signature verification result of σM, whether the current time is within the range of (issuedAt - clock offset tolerance, expiresAt), the local maxPerTransactionCents single transaction limit, the local maxPerDayPerPayerCents daily cumulative limit, and the monotonicity of the payer-side counter, etc.

[0041] In step S240, after the payment terminal 110 passes the local verification, it assembles the PaymentAuthorization: inheriting the same (txId, intentId, amount, currency), and appending its own generated payerAuthorizationId, payerAccountId, payerDeviceId, payerNonce, payerCounter, and authorizedAt; it uses the payer's private key to sign the normalized signature material "txId|intentId|amount|currency|payerNonce|payerCounter|authorizedAt" to obtain σP; the QR code encoding / decoding module 141 serializes the PaymentAuthorization and σP into a QR code QR2 with envelope.type = paymentAuthorization and displays it; at the same time, the local transaction log module 144 writes or updates the local transaction record, sets the status to authorized, and generates a composite idempotent key in the form of "payer:txId:authId".

[0042] In step S250, after scanning and decoding QR2, the receiving terminal 120 first queries the local transaction log for the initiated record pre-stored in step S220 using PaymentAuthorization.txId. If it does not exist, the authorization is discarded. If it exists, the (txId, intentId, amount, currency) tuple is strictly verified to be consistent with the local record. If the verification passes, the status of the local record is advanced to pendingSync and payerAuthorizationId, payerAccountId, payerDeviceId, payerNonce, and payerCounter are completed. Then, a PaymentReceipt is constructed and the merchant's private key is used to sign the receipt signature material "txId|payerAuthorizationId|pending_sync" to obtain the third signature σR. Optionally, it can be displayed via the third QR code QR3, or it can be directly fed back to the payment terminal 110 via Bluetooth, sound waves, or other local short-range communication channels.

[0043] At this point, the three-phase two-way handshake concludes without network connectivity for either party. It is important to note that in each phase, the participating parties make local decisions solely based on the QR code content provided by the other party, without relying on any external services. Furthermore, the changes to the local transaction log status and the generation of signature materials for each phase strictly follow the order described in this invention. III. Transfer of wallet cards between devices and cancellation of old devices (see Figure 3)

[0044] [Timeline of Wallet Card Transfer Between Devices and Revocation of Old Devices]

[0045] In this embodiment, the original device D_old needs to transfer its wallet "card authorization" under a certain account to the new device D_new due to reasons such as loss, damage, warranty replacement, cancellation and reissue. The wallet card transfer service 250 provides two endpoints, startTransfer and completeTransfer, and works together in the following sequence:

[0046] Step S410: The account owner or an operator with the admin role initiates a startTransfer request through the management terminal 130, submitting accountId and fromDeviceId; Step S420: The wallet card transfer service 250 authenticates and confirms actor.accountId === ownerAccountId or actor.roles.includes("admin"), and verifies that the source device is active; a 16-bit hexadecimal transferCode (≥ 64-bit entropy) is generated using randomBytes(8), and a CardTransferSession{transferId, transferCode,accountId, fromDeviceId, role, status:"pending", expiresAt: now+15min} is constructed, written to disk, and audited; Step S430: The transferCode is returned to the management terminal; Step S440: The operator transmits the transferCode to D_new through a controlled out-of-band channel; Step S450: D_new generates a new asymmetric key pair (pub_new, priv_new); Step S460, D_new submits completeTransfer(transferCode,pub_new, keyVersion); Step S470, wallet card transfer service 250 verifies that the session exists, the status is pending, not expired, and the source device is still active; Execute in the same database transaction: (a) Set D_old.status to revoked and write freezeReason to "card_transferred:transferId"; (b) Create D_new device entity, bind accountId and original role, and write (publicKey=pub_new, keyVersion,status:"active", registeredAt=now); (c) Set session.status to completed, session.completedAt=now, session.newDeviceId=D_new.id; (d) Append card_transfer.Completed audit event; Step S480, return newDeviceId to D_new; Step S490, the original device D_old is forcibly revoked during the next synchronization handshake or server-side push for offline status. Any offline transactions subsequently issued by the original device will be rejected by the server in subsequent synchronizations due to payer_device_inactive / merchant_device_mismatch.

[0047] To enhance security, this embodiment also implements any or a combination of the following additional constraints: (i) transferCode is one-time and non-replayable; (ii) only one session with status=pending is allowed for the same account at any given time; (iii) completeTransfer must be initiated by a client with liveness or local PIN verification; (iv) transferCode is only allowed to be submitted after a short-term session key is derived from PBKDF2 / HKDF on the D_new end to avoid packet capture and replay; (v) the original device retains a 30-day read-only mode after the transfer is completed so that users can view the history across accounts. IV. Offline Transaction Synchronization and Idempotency Verification (See Figure 4)

[0048] [Offline Transaction Synchronization and Idempotency Verification Process]

[0049] In this embodiment, after receiving the batch of transactions to be synchronized uploaded by the payment terminal 120 through the synchronization queue module 146, the offline transaction synchronization service 230 processes each transaction sequentially according to the process shown in Figure 4:

[0050] Step S510: Parse the batch submissions into OfflineSyncInput, which includes merchantDeviceId, submittedAt, and several OfflineTransactionInputs; Step S520: Verify whether the merchantDevice is currently active and whether the number of unsynced transactions in this batch is ≤ maxUnsyncedPerMerchant; if either condition is not met, mark all transactions in the batch as rejected with a reason (merchant_device_inactive / unsynced_limit_exceeded); Step S530: Start looping through each transaction; Step S540: Idempotent deduplication: For the current transaction, query the transaction repository for existing records using txId and idempotencyKey in turn; if a match is found, return "duplicate"; Step S550: Identity relationship verification: Merchant / payer account exists and is active, payer device exists and is active, merchant device binding relationship is consistent; otherwise, reject; Step S560: Risk control in advance: amountCents In (0, maxPerTransactionCents], the merchant device's lastSyncAt is ≤ maxSyncAgeHours, |submittedAt - authorizationIssuedAt| ≤ maxClockSkewSeconds, submittedAt ≤ expiresAt; Step S570, Normalize the digest: digest = SHA-256(txId|intentId|authId|amount|currency|merchantNonce|payerNonce|intentIssuedAt|authorizationIssuedAt|expiresAt); Step S580, Double signature verification: Verify the signatures of σM and σP using the merchant device's public key and the payer's device's public key respectively. If either fails, it is rejected (signature_invalid); Step S590, Daily accumulation: Accumulate the historical accepted signatures using (payerAccountId, authorizationIssuedAt[YYYY-MM-DD]) as the key. Check if the transaction amount, after adding this transaction, is still less than or equal to maxPerDayPerPayerCents; also check payerWallet.If availableCents ≥ amount, otherwise rejected (daily_limit_exceeded / insufficient_funds); Step S600, atomic accounting: within the same transaction, decrease payerWallet and increase merchantWallet; persist OfflineTransaction to status=accepted; write audit log; Step S610, after all transactions are processed, update merchantDevice.lastSyncAt=submittedAt and return the result for each transaction.

[0051] The above process also has the following characteristics: (i) it is idempotent for scenarios where the same upload request is sent repeatedly; (ii) failure at any step will not pollute the wallet balance or ledger; (iii) each failure returns a clear reason code; and (iv) the throughput of the overall process scales linearly with the client batch size. V. Offline wallet transaction state machine shared across multiple devices (see Figure 5)

[0052] [Offline wallet transaction state machine shared across multiple devices]

[0053] In this embodiment, payment terminal 110, receiving terminal 120, and management terminal 130 share the same set of offline transaction states: initiated → authorized → pendingSync → synced is the normal path; at any stage, if the user actively cancels, the transaction enters canceled; if PaymentIntent.expiresAt is exceeded, the transaction enters expired; if the server fails due to risk control or double signature failure, the corresponding record will be set as rejected.

[0054] (a) iOS smartphone: Implemented in Swift using the LocalTransactionState enumeration and the TwoWayQRHandshakeCoordinator, with signatures completed via Secure Enclave; (b) Web browser: Implemented in TypeScript using an equivalent TransactionState dictionary and a unified API client, with signature capabilities provided by the browser's WebCrypto or trusted hardware tokens; (c) Embedded terminal based on STM32 series microcontrollers: Implemented in C++ using the enum class TransactionState and the OfflineEngine class, with signatures completed via STM32's onboard TRNG, secure flash memory, and optional SE; The handshake protocol, signature material string concatenation order, idempotent key construction rules, status name, and QR code envelope format are strictly consistent across the three types of terminals, enabling interoperability between any two ends as payers / payees. VI. Other embodiments and variations

[0055] In another embodiment, the validity period, single transaction limit, and other fields in PaymentIntent / PaymentAuthorization / PaymentReceipt are replaced with a policy pointer based on PolicyVersion, and the latest policy is retrieved when the terminal is first started or after a transfer is completed. Thus, this invention can support operational adjustments such as "reducing the single transaction limit from 200 yuan to 100 yuan" and "dynamically adjusting the daily cumulative threshold across holidays" on the operation side.

[0056] In another embodiment, the above-mentioned ECDSA-P256 is replaced with the national cryptographic SM2 + SM3 + SM4 system, the hash digest is replaced with SM3, and the symmetric envelope is replaced with SM4-GCM, so that the present invention can be implemented in compliant scenarios in China.

[0057] In another embodiment, replacing the bidirectional QR1 / QR2 of the present invention with a bidirectional short-range carrier based on near-field screen color code, sound wave encoding, or equivalent visual / audible channels is still an equivalent alternative implementation of the present invention.

[0058] In another embodiment, the above-mentioned in-memory store-based warehousing is replaced with an implementation based on a relational database (such as PostgreSQL) or an append-only log (such as Kafka + materialized views), and the server-side wallet ledger is replaced with a strongly consistent ledger database based on double-entry bookkeeping; the above replacements do not change the core of the method of the present invention and are still within the protection scope of the present invention.

[0059] The above embodiments are preferred embodiments of the present invention and are not intended to limit the present invention. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A method for processing offline wallet transaction based on two-way two-dimensional code handshake, characterized in that, The method is applied to an offline wallet system that includes at least a payment terminal and a receiving terminal. The method includes: When the receiving terminal has no local network connection, it constructs a payment intention based on the amount to be received, currency, merchant account identifier, merchant device identifier, merchant random number, merchant monotonic counter, and validity period; it digitally signs the standardized signature material of the payment intention using the merchant's private key to obtain a first signature; it encodes the payment intention and the first signature into a first QR code and displays it; simultaneously, it saves the code in the local transaction log with the status "initiated". The local transaction record is processed as follows: The payment terminal scans and decodes the first QR code when there is no network connection on its end. It performs local verification on the first signature, the validity period, the local single transaction limit, the local daily cumulative limit, and the monotonicity of the local payer's monotonic counter. Upon successful verification, it generates a payment authorization based on the payment intent, containing a payment random number, the payer's monotonic counter, and the payer's timestamp. It then digitally signs the standardized signature material of the payment authorization using the payer's private key to obtain a second signature. The payment authorization and the second signature are encoded into a second QR code and displayed. Simultaneously, the status of the local transaction record is set to authorized, and a composite idempotent key is generated according to preset rules, concatenating the transaction identifier and the payer's authorization identifier. The receiving terminal scans and decodes the second QR code when there is no network connection on its end. It verifies whether the transaction identifier, merchant intent identifier, amount, and currency quadruple carried by the payment authorization are consistent with the local transaction record in the initiated state. If consistent, the status of the local transaction record is advanced to pendingSync. The system completes the payer's account, device, payment random number, monotonic counter, and authorization identifier. It also constructs a third signature on the receipt based on the merchant's private key to generate a payment receipt. When the receiving terminal reconnects to the network, it uploads multiple transactions in the pendingSync state from its local transaction log to the offline transaction synchronization service on the server. The offline transaction synchronization service sequentially performs the following for each uploaded transaction: deduplication based on the transaction identifier and the composite idempotent key; verification of account and device binding relationship and activity status; risk control release based on single transaction limit, daily cumulative limit, unsynchronized upper limit, synchronization freshness, and clock offset threshold; merchant and payer dual signature verification based on normalized hash digest; and within the same atomic transaction, it performs payer wallet deduction, payee wallet increase, appending two debit / credit ledger entries, persisting transaction records, updating the merchant device's most recent synchronization time and writing it to the audit log, and returns one of the following as the result: accepted, duplicate, or rejected.

2. The method of claim 1, wherein, The normalized hash digest is generated according to the following rules: the transaction identifier, the merchant intent identifier, the payer authorization identifier, the amount, the currency, the merchant random number, the payment random number, the merchant intent issuance time, the payer authorization issuance time, and the validity period are concatenated in the above order with a preset separator to obtain a signature string. Then, SHA-256 or SM3 hash conforming to the national commercial cryptography standard is applied to the signature string to obtain the normalized hash digest.

3. The method of claim 1, wherein, The standardized signature material for the payment intent is composed of the transaction identifier, the merchant intent identifier, the amount, the currency, the merchant random number, the merchant monotonic counter, and the validity period, arranged in a preset order. The standardized signature material for payment authorization is composed of the transaction identifier, the merchant intent identifier, the amount, the currency, the payment random number, the payer monotonic counter, and the payer timestamp in a preset order.

4. The method of claim 1, wherein, The local verification of the payment terminal further includes: performing an incremental verification on the merchant's monotonic counter that is not less than the maximum counter value recorded on the local terminal under that merchant / device; checking whether the current time of the validity period falls within the allowed range determined by the issuance time to the expiration time; and checking whether the amount is between 0 and the local terminal's maxPerTransactionCents.

5. The method of claim 1, wherein, The first QR code and the second QR code are carried in the form of two envelopes. The outer envelope contains at least a payload type field and an inner payload field based on Base64 encoding. The inner payload field corresponds to the JSON serialization result of the payment intention, payment authorization or payment receipt, which is then Base64 encoded into a string.

6. The method of claim 1, wherein, The risk control release further includes: when the number of transactions to be synchronized in this batch is greater than maxUnsyncedPerMerchant, the entire batch is rejected; when the merchant device's lastSyncAt is greater than submittedAt than maxSyncAgeHours, the transaction is rejected; when |submittedAt −authorizationIssuedAt| is greater than maxClockSkewSeconds, the transaction is rejected; when submittedAt is later than expiresAt, the transaction is rejected.

7. The method of claim 1, wherein, The method further includes the steps of transferring wallet cards between devices and revoking the original device: the management terminal initiates a startTransfer request and submits the account identifier and the original device identifier; the server verifies whether the initiator is the account owner or has the admin role, and verifies whether the original device is in an active state; the server generates a one-time transferCode with provable entropy, constructs a pending transfer session with a validity period and persists it; the transferCode is transmitted to the new device through a controlled out-of-band channel; The new device generates a new key pair in its local security unit, initiates a completeTransfer request to the server, and submits the transferCode, the new device's public key, and the key version. After verifying that the session exists, is in a pending state, has not expired, and the source device is still active, the server executes the following within the same atomic transaction: sets the original device's status to revoked and writes the revocation reason pointing to the current transfer session identifier; creates and binds the new device to the original account and original role; sets the session to completed and attaches the new device identifier, and writes it to the audit log. Subsequently, offline transactions issued by the original device are rejected in the offline transaction synchronization service on a transaction-by-transaction basis for "payer device inactive" or "merchant device binding inconsistent".

8. The method of claim 7, wherein, The method further implements at least one of the following additional constraints: the transferCode is one-time and non-replayable; only one transfer session with a pending status is allowed for the same account at any given time; the completeTransfer must be initiated by a client with local liveness or PIN verification; the new device derives a short-term session key from the transferCode before submitting it; and the original device retains a read-only mode for a preset duration after the transfer is completed.

9. The method of claim 1, wherein, The local transaction log transitions between initiated, authorized, pendingSync, synced, rejected, expired, and canceled states according to the following rules: The receiving terminal's state is initiated after constructing a payment intent; the paying terminal sets its local state to authorized after completing local verification and issuing a payment authorization; the receiving terminal sets its local state to pendingSync after verifying that the payment authorization matches the local initiated record; the state is set to synced after the server returns accepted for the transaction; the state is set to rejected when the server returns rejected or when risk control / dual signature fails; the state is set to expired by the local terminal when the current time is later than expiresAt; and the state is canceled if the user actively cancels.

10. The method of claim 1, wherein, The payment terminal, the receiving terminal, and the management terminal are implemented on iOS operating system terminals, web browser terminals, and embedded terminals based on STM32 series microcontrollers using the same source protocol, the same source status field, the same source signature material, and the same source QR code envelope, enabling payers and payees from different terminal types to complete the bidirectional QR code handshake without relying on any backend connection.

11. An offline wallet transaction processing system based on two-way two-dimensional code handshake, characterized by, The system includes a payment terminal, a receiving terminal, a management terminal, and a server. The payment terminal, receiving terminal, and management terminal share a common core module for the offline wallet. This common core module includes a QR code encoding / decoding module, a two-way handshake coordination module, a risk control strategy engine, a local transaction log module, a device identity and key module, and a synchronization queue module. The server includes account and device activation services, wallet ledger services, offline transaction synchronization services, risk control and strategy services, wallet card transfer services, clearing and reconciliation services, and auditing and historical services. The system is configured to execute the method as described in any one of claims 1 to 10.

12. The system of claim 11, wherein, The payment terminal and the receiving terminal each include a processor, a memory, a camera, a display screen, and a trusted security element. The security element is any one of iOS SecureEnclave, Android StrongBox, Trusted Execution Environment (TEE), SIM Card Security Element (SE), Embedded Security Element (eSE), or STM32 onboard secure flash memory.

13. The system of claim 11, wherein, The offline transaction synchronization service is deployed in a stateless manner in a multi-instance cluster. The wallet ledger service updates the payer's wallet, the payee's wallet, and the ledger entries simultaneously using atomic transactions. The audit and history service records all state changes and rejection reasons in an append-only manner.

14. A computer-readable storage medium having stored thereon a computer program, characterized in that, When the computer program is executed by a processor, it implements the method as described in any one of claims 1 to 10.

15. An electronic device, comprising: The electronic device includes a processor, a memory, and a communication device. The memory stores instructions that can be executed by the processor, which, when executed, cause the processor to perform the method as described in any one of claims 1 to 10.