A method and system for cross-system e-commerce order and blockchain digital asset linkage processing
By employing an OpenAPI security gateway, local order storage, and asynchronous chain operation queues during refunds on e-commerce platforms, the problem of untimely recovery of blockchain digital assets during refunds has been solved. This achieves lock-free idempotency and channel isolation, improves system performance and data consistency, and eliminates the practice of 'freeloading' refunds.
Patent Information
- Application Number
- CN202611348605.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-02
- Publication Date
- 2026-11-10
AI Technical Summary
When returning goods and requesting refunds on e-commerce platforms, existing technologies cannot effectively recover or freeze the bound blockchain digital assets. This allows consumers to continue holding and reselling NFT digital collectibles, resulting in a "freebie" behavior of "refund without digital asset return". Furthermore, cross-system distributed calls lack idempotency guarantees, sales through multiple channels pose a risk of accidental removal from the platform, on-chain reversal operations block the main business thread, cross-database query performance is poor, and consistency cannot be guaranteed.
By employing an OpenAPI security gateway, an order local storage engine, a channel-sensitive filtering module, and an asynchronous chain operation exclusive queue, we achieve local storage of all order fields, refund final state detection and linkage state machine, channel-sensitive filtering, and asynchronous chain operation exclusive queue. Through idempotent control of database condition updates and asynchronous task queue processing, we ensure the automated linkage and lock-free idempotency of digital assets.
Completely eliminate the practice of 'free-riding' with refunds, achieve extremely simple and efficient lock-free idempotent control, accurately isolate channels to prevent accidental damage, provide high-performance asynchronous on-chain reversal protection, eliminate cross-database query performance bottlenecks, and ensure system throughput and data consistency.
Smart Images

Figure FT_1 
Figure FT_2 
Figure FT_3
Abstract
Description
Technical Field
[0001] This invention belongs to the cross-technical field of distributed e-commerce and blockchain asset management. Specifically, it relates to a technical solution for the automated, idempotent linkage of e-commerce order lifecycle and blockchain digital assets and digital time capsules for delisting and disposal in a cross-system distributed environment. More specifically, this invention relates to the cross-application of the following technical fields: (1) distributed e-commerce system technology, especially cross-system order status synchronization and localized mirror storage methods; (2) blockchain digital asset management technology, especially digital asset logical ownership management and revocation mechanism based on ERC721 tokens and notarization contracts; (3) distributed system data consistency technology, especially lock-free idempotent control method based on the number of affected rows; (4) multi-channel sales isolation technology, especially anti-false positive filtering mechanism based on channel identifiers; (5) asynchronous task queue technology, especially on-chain operation retry mechanism based on distributed exclusive locks and dual exception classification. Background Technology
[0002] With the booming development of e-commerce and the maturity of blockchain digital collectibles (NFT) technology, more and more brands are linking the sale of physical goods with blockchain digital assets—after purchasing physical goods, consumers can obtain corresponding on-chain NFT digital collectibles and digital commemorative content (such as time capsules). However, when consumers initiate returns and refunds on e-commerce platforms, how to promptly recover or freeze the linked blockchain digital assets across systems has become a pressing technical challenge. Existing technologies have the following significant drawbacks:
[0003] Flaw 1: Post-sale refunds lead to the problem of "freeloading" digital assets. After purchasing goods on e-commerce platforms, consumers bind irreversible blockchain NFT digital assets by scanning a QR code and create commemorative content such as digital time capsules. If consumers subsequently initiate a return and refund on the e-commerce platform, traditional systems, lacking cross-system linkage mechanisms, cannot promptly recover or freeze the bound digital assets. Consumers can continue to hold and distribute NFT digital collectibles after receiving a refund, and even resell them on the secondary market for profit, resulting in the "freeloading" behavior of "refund without digital asset return." This not only causes economic losses for brands but also undermines the scarcity and credibility of digital assets. Existing technologies lack an automated linkage link from the e-commerce order refund status to the revocation of blockchain digital assets. Even some solutions attempt to manually process digital assets after a refund, facing problems such as processing delays, human error, and inconsistencies in operation.
[0004] Defect 2: Lack of idempotency guarantee in cross-system distributed calls. When third-party e-commerce malls push order status change notifications, the following abnormal situations may occur due to network instability, message middleware retry mechanisms, or system failure recovery: (1) Refund notifications for the same order are pushed repeatedly; (2) Order status change notifications arrive out of order (e.g., receiving a refund notification first, then receiving a shipping notification); (3) Network timeouts during the push process cause the caller to retry due to uncertainty about success. These situations are extremely common in distributed system environments. Existing technologies usually use distributed locks or distributed transactions to ensure idempotency, but distributed locks introduce lock contention and deadlock risks, while distributed transactions (such as two-phase commit and Saga patterns) are complex to implement and have high performance overhead. In cross-system e-commerce scenarios, the cost and complexity of these solutions are often unacceptable.
[0005] Defect 3: Lack of isolation in multi-channel sales strategies poses a risk of accidental delisting. Enterprises often sell their products simultaneously through multiple channels: e-commerce self-operated channels (channel=0, consumers order from the official online store), marketing gift channels (channel=1, distributed as promotional gifts), and enterprise bulk purchasing channels (channel=2, bulk purchases by the enterprise). Products from different channels may use the same order number string—especially since the "order number" for marketing and bulk purchasing channels is actually an arbitrary third-party number entered during shipment, which may accidentally overlap with the official order number from the e-commerce channel. In existing technology, if digital assets are simply associated with the order number and delisted, when the order number of a gift from the marketing channel overlaps with the refund order number from the e-commerce channel, legitimate digital assets from the marketing channel may be mistakenly delisted, causing business losses. This cross-channel number collision problem is common in enterprises selling through multiple channels, but existing technology lacks an effective isolation mechanism.
[0006] Defect 4: On-chain reversal operations block the main business thread. Confirmation of blockchain transactions requires a block packaging process, which typically takes several seconds to minutes. If the refund-linked processing synchronously waits for on-chain reversal transaction confirmation, it will cause API requests to be blocked for a long time, severely impacting system throughput. When the blockchain network is congested, synchronous waiting may lead to HTTP request timeouts and thread pool exhaustion. Furthermore, blockchain notarization contracts typically only provide the function of appending event logs (logEvent), not token burning or token transfer functions. This means that "reversing digital assets" cannot be achieved by burning tokens on-chain; it can only be done by setting the logical ownership to zero off-chain and appending a refund event on-chain as a reversal notarization. Existing technology lacks a systematic solution to this constraint. In traditional solutions, the system's digital assets and digital capsules are stored in a local database, while order data is stored in an external e-commerce system's database. Refund-related processing requires querying the associated digital capsules and digital assets based on the order number, a process that necessitates cross-database queries. Cross-database queries not only suffer from poor performance (network latency, inability to use indexes for optimization) but can also lead to connection pool exhaustion when database connection resources are limited. More seriously, cross-database queries cannot use database transactions to guarantee consistency; a time window exists between queries and updates, potentially resulting in data inconsistencies. Summary of the Invention
[0007] Technical solution To achieve the above-mentioned objectives, this invention provides a method and system for cross-system e-commerce order and blockchain digital asset linkage processing, the overall technical solution of which is as follows:
[0008] This system comprises five core components: an OpenAPI security gateway, a fully localized, lock-free, idempotent Upsert engine, an atomic linked state machine for affected rows, channel-sensitive filtering, and an asynchronous chain operation exclusive queue, forming a complete technical closed loop. OpenAPI Security Gateway: Deployed under the ` / open / **` URL prefix and protected by an independent Spring Security security chain. The security gateway performs dual authentication—API key verification and IP whitelist verification. API key verification uses the `MessageDigest.isEqual` constant time comparison algorithm to prevent side-channel attacks based on response time. It supports multiple independent API keys (clientId→apiKey mapping) for multiple third-party callers, which can be individually assigned and revoked. The IP whitelist supports extracting the real client IP from the X-Forwarded-For header.
[0009] The order localization storage engine stores a full-field snapshot of orders pushed by third-party e-commerce systems in a local order mirror table (biz_order). This mirror table redundantly stores all fields, including buyer's WeChat ID (wx_openid / wx_unionid), SKU code (sku_code), product name, customer name / phone / address, total order amount, status, order attributes, and order time, ensuring zero cross-database joins for subsequent order read operations. The order number (order_no) serves as a unique index and idempotent key, with database unique constraints guaranteeing concurrency safety.
[0010] Refund final state detection and linked state machine: After the order is synchronized and entered into the database, check whether the status field belongs to the preset refund final state set {after_sale_completed (after-sale completed), cancelled (cancelled)}. If so, call the takedownByOrder method of the capsule service across modules to perform linked removal processing.
[0011] Channel-Sensitive Filtering Module: Before removing items from shelves, a channel validity check is performed on each associated digital capsule record. The judgment rule is as follows: only capsules with an empty product identifier (capsules not bound to a product are created based on the e-commerce synchronized order number) or whose associated product channel identifier is an e-commerce channel (channel=0) are retained and removed from shelves; capsules from marketing channels (channel=1) and centralized procurement channels (channel=2) are filtered and not removed from shelves.
[0012] Asynchronous chain operation exclusive queue: On-chain reversal operations are written to the chain operation queue list (nft_chain_op) as task records, initially in a pending state. Background scheduled tasks asynchronously execute on-chain transaction submissions, receipt waiting, and exception retries under the protection of a Redis distributed exclusive lock.
[0013] (1) When the order status changes (payment successful, shipment, completion, refund, cancellation, etc.), the third-party e-commerce system sends a POST request to the OpenAPI gateway of this system. The request body is a JSON snapshot message containing all fields of the order.
[0014] (2) The OpenApiAuthFilter performs dual authentication: IP whitelist verification: Obtain the client IP from the X-Forwarded-For header or RemoteAddr and compare it with the pre-configured IP whitelist. If the whitelist is empty, the source IP is not restricted.
[0015] API key verification: Extract the key value from the request header (header name is configurable, default is X-Api-Key) and compare it one by one with the pre-configured clientId→apiKey mapping table. The comparison uses the MessageDigest.isEqual method to perform a constant time comparison to prevent side-channel attacks. If a match is found, the clientId is written to the thread context; otherwise, a 401 Unauthorized response is returned.
[0016] (3) After successful authentication, the system requests access to the order synchronization service. The order synchronization service verifies the following required fields: orderNo (order number) must be non-empty and all leading and trailing whitespace removed; status (status) must be non-empty and belong to the predefined valid status enumeration set {pending_pay, pending_ship, shipped, delivered, cancelled, after_sale_completed}. If the verification fails, a business exception is thrown, and an error response is returned.
[0017] (4) Query the local order mirror table using order_no as the unique index: If it does not exist, insert a new record (source is set to "miniapp_shop_admin" to identify the source); if it already exists, perform a full field overwrite update using the primary key ID. Regardless of whether it is an insertion or an update, the synced_at field is refreshed to the current timestamp. Since there is a unique index (uk_order_no) on the order_no field, the database will reject the second insertion when inserting the same order_no concurrently, ensuring idempotency.
[0018] (1) After the order is synchronized and put into storage, check whether the order status after this storage / update belongs to the preset refund final state set REFUND_TRIGGER={after_sale_completed, cancelled}.
[0019] (2) The after_sale_completed state corresponds to the "after-sale completed" final state in the e-commerce system, indicating that the consumer has initiated a return / refund and the after-sales process has been completed (the refund amount has been returned to the consumer's account). The cancelled state corresponds to the "order cancelled" final state, indicating that the order was cancelled before shipment.
[0020] (3) If the status matches the refund final state set, call the CapsuleService.takedownByOrder(orderNo, "order_refund") method on the order_no to trigger the linked delisting process. If the status does not match the refund final state set (such as shipped, delivered, or other normal fulfillment statuses), the synchronization process ends normally without triggering any linkage.
[0021] (4) Since only e-commerce channel orders enter the order mirror table, marketing / bulk purchase channel order numbers will never trigger this linkage process, fundamentally eliminating the possibility of non-e-commerce channels triggering refund linkage.
[0022] The takedownByOrder method performs the following operations: (1) Query the list of digital capsule records associated with order_no that are in the sealed (status=1) or unsealed (status=2) state.
[0023] (2) Filter the retrieved capsule records using the channel validity filter (filterEcommerceCapsules method): Collect a list of non-empty goods_item_ids (item identifiers) from all capsule records; Batch query the channel field of these product records and construct the itemId→channel mapping; For each capsule record, the following criteria are applied: If goods_item_id is empty (capsules not bound to a single item are created according to the e-commerce synchronized order number), it is determined to belong to the e-commerce channel and is retained; if goods_item_id is not empty and the corresponding single item channel=0 (e-commerce), it is retained; if goods_item_id is not empty and the corresponding single item channel=1 (marketing) or channel=2 (bulk purchase), it is filtered out.
[0024] (3) For sealed / unsealed capsules filtered through the channel, remove them from the shelves one by one: update the status to 3 (removed from the shelves), and set update_by to "order_refund". After removal from the shelves, call the revokeCapsuleNft method to reclaim the ownership of the associated NFT.
[0025] (4) Query the list of digital capsule records associated with order_no that are in draft state (status=0), perform channel filtering, and then perform logical deletion on each record (automatically set del_flag to 1 via the @TableLogic annotation). Capsules in draft state have not yet been minted as NFTs, so there is no need to reclaim NFT ownership.
[0026] The `revokeAssetOwnership` method performs the following operations: (1) Query the NftAsset record of the specified asset type (goods NFT or capsule NFT) and asset ID, and the current_owner_id is not empty (i.e., there is still an owner and it needs to be reclaimed).
[0027] (2) Execute conditional update: UPDATE nft_asset SET current_owner_id=NULL, update_by='order_refund' WHERE id=? AND current_owner_id IS NOT NULL. Note the "current_owner_id IS NOT NULL" constraint attached to the WHERE condition—this is the key to idempotency control: if the current owner of the asset has already been set to NULL (the previous refund push has been processed), then the number of rows affected by this update is 0.
[0028] (3) Determine the number of affected rows: If updated > 0, it means that the ownership recovery operation was indeed performed this time, and continue to create on-chain revocation certificate; if updated = 0, it means that the ownership of the asset has been recovered (may be a duplicate push), skip the subsequent steps, and do not create any on-chain operation tasks.
[0029] (4) When updated > 0 and the asset has a tokenId, create an NftAssetEvent record (event_type="refund", from_member_id=original owner ID) and at the same time create an NftChainOp task record (operation_type=2, i.e. LogEvent, event_type="refund", from_member_id=original owner ID, status=0, i.e. pending execution, retry_count=0).
[0030] (5) For repeated refund pushes for the same order: When the NFT owner is not null during the first push, the number of rows affected by the nulling operation is 1, and an on-chain reversal task is created; when the NFT owner is null during the second push, the number of rows affected by the nulling operation is 0, and no on-chain reversal task is created. The entire process does not require distributed locks, idempotent tokens, or pre-query judgments, and achieves lock-free idempotency purely by counting the number of rows affected by database condition updates.
[0031] (1) The Chain Operation Queue Consumption Engine (ChainWorkerService) scans the nft_chain_op table every 60 seconds for task records with status=0 (to be executed), retry_count<3, and allow_execute_time empty or already completed. Each batch can process up to 10 records.
[0032] (2) Before executing each task, perform an idempotency check: check whether the task has carried txHash. If it has, it means that the transaction has been submitted in the previous round. Call WenchangChainClient.getReceipt(txHash) to query the on-chain receipt. If the receipt is successful (status=0x1), mark the task as successful and fill in the blockNumber. If the receipt fails (revert), mark it as permanently failed. If the receipt is not on the chain, postpone the retry and do not resubmit the transaction.
[0033] (3) For LogEvent type tasks, first check if the chain_status of the corresponding NftAsset is 1 (minting confirmed). If the NFT has not yet been minted and confirmed, postpone execution (throw a TransientChainException) and wait for the Mint operation to complete before retrying. This is because the logEvent method of the notarization contract requires the TokenID to already exist on the chain; otherwise, the contract will revert.
[0034] (4) Call the logEvent method of the notarization contract to submit a refund revocation event. The parameters are (tokenId, "refund", original owner member ID, 0, from_proof, "", contentHash, verifyUrl). The verifyUrl is dynamically generated as baseUrl + tokenId. After the transaction is submitted, the txHash is persisted to the task record immediately, and then polling waits for the receipt confirmation (querying once every 2 seconds, up to 15 times).
[0035] (5) After the receipt is confirmed, txHash and blockNumber are filled back into the NftChainOp task record and NftAssetEvent event record, and the task status is set to 1 (success).
[0036] (6) Anomaly classification and handling: PermanentChainException: This includes unrecoverable errors such as contract execution revert, TokenID already minted, invalid parameters, and insufficient balance. The task is directly marked with status=2 (permanent failure), and the alert log "[CHAIN_OP_ALERT] permanently failed, manual intervention required" is output.
[0037] Transient ChainException: Includes recoverable errors such as RPC timeouts, network fluctuations, failed receipt polling, and NFTs not yet minted and confirmed. Increment `retry_count` by 1, set `allow_execute_time` to the current time plus the backoff interval (`retry_count` × 5 minutes), and keep `status` = 0 to wait for the next retry round. When `retry_count` reaches its maximum of 3 times, it is upgraded to permanent failure.
[0038] (7) Management intervention: Administrators can manually re-dump (reset status to 0, retry_count to zero, and trigger asynchronous processing immediately) or abandon (set status to 2 and specify the reason) the chain operation task through the management backend. Administrators can also manually trigger the "process one round immediately" operation, which is asynchronously dispatched to a dedicated thread pool for execution and does not block HTTP requests.
[0039] (1) When the system is deployed and launched for the first time, it is necessary to backfill the existing historical orders in the third-party e-commerce system to the local order mirror table in one go. The backfill service (OrderBackfillService) switches to the e-commerce system database data source through the @DS("shop") annotation, reads all e-commerce order records (500 records per page) in the primary key cursor pagination mode, and performs a join query on the customer table (wx_openid / wx_unionid) and the SKU table (sku_code).
[0040] (2) Perform field mapping on each historical order record, convert it to OrderSyncRequest format, and write it to the local order mirror table through the OrderSyncService.sync method, following the same upsert path as incremental synchronization. Due to the idempotency of upsert, historical backfilling can be safely rerun, and repeated execution will not generate duplicate records.
[0041] (3) During the historical backfilling process, if a historical refund order with a status of after_sale_completed or canceled is encountered, the linked processing steps S2 to S5 will also be triggered, so that the digital capsule associated with the historical refund order is also in a delisted state and the ownership of the associated NFT is also reclaimed. This ensures that after the system goes online, the digital asset status of all historical refund orders is consistent with the current order status.
[0042] (4) The backfilling trigger method is the controlled administrator endpoint (POST / admin / v1 / order / backfill), which can only be called by the administrator. After the call, the total number of backfilled entries is returned.
[0043] This system includes the following functional modules: Open Interface Gateway Module: Deployed under the / open / ** path, it uses OpenApiAuthFilter to perform dual authentication of IP whitelist and API key, supports independent key management for multiple callers and constant time comparison to prevent side-channel attacks.
[0044] Order local storage module: Receives authenticated order synchronization requests, verifies field validity, performs idempotent upsert with order_no as the unique index, and redundantly stores all order fields.
[0045] Refund final status detection module: After the order is synchronized and entered into the warehouse, it checks whether the status belongs to {after_sale_completed, cancelled}. If it matches, it triggers a linked removal from the shelves.
[0046] Channel-sensitive filtering module: Performs channel validity checks on associated digital capsule records, retains e-commerce channels (goods_item_id is empty or channel=0), and filters marketing / bulk purchasing channels.
[0047] Atomic Linkage Processing Module: Performs status shelving (1 / 2→3) and draft logic deletion (0→del_flag=1) on capsules filtered by the channel, and sets the ownership condition to null on associated NFTs.
[0048] Idempotency determination module: Determines whether to create an on-chain reversal task based on the number of rows affected by the ownership nulling operation, achieving lock-free idempotency.
[0049] Asynchronous chain operation queue module: creation, scanning, distributed exclusive lock, transaction submission, receipt waiting, exception classification retry and management intervention of on-chain reversal tasks.
[0050] The history backfill module reads all historical orders from an external e-commerce database by primary key cursor, writes them to the local mirror library via the same upsert path, and is idempotent and can be rerun. Beneficial effects
[0051] Compared with the prior art, the present invention has the following significant advantages: (1) Completely eliminate the practice of "free-riding" on digital assets through refunds. When a consumer initiates a refund on an e-commerce platform and the after-sales service is completed, the system automatically removes the sealed / unsealed digital capsules associated with the order (status→3), logically deletes the draft capsules (del_flag→1), and reclaims the logical ownership of the associated NFTs (current_owner_id→NULL). After receiving the refund, the consumer no longer holds the corresponding digital assets in their account and cannot continue to display, transfer, or resell them, fundamentally eliminating the risk of economic loss from "refunds without digital assets".
[0052] (2) Extremely simple and efficient lock-free idempotent control. By adding the "current_owner_id IS NOT NULL" constraint to the WHERE condition of the ownership reset operation, the number of affected rows in the database condition update is used as the idempotency criterion. No distributed locks, idempotent tokens, or pre-query judgment are required. The return value of a single UPDATE statement is sufficient to determine whether it is a duplicate push. In the case of a duplicate push, the number of affected rows is 0, and no on-chain operation tasks are created. This solution is extremely simple (only one WHERE condition is required), extremely high-performance (single UPDATE), and extremely reliable (database atomic guarantee), completely solving the idempotency problem of cross-system distributed calls.
[0053] (3) Precise channel isolation mechanism to prevent accidental removal. Through channel-sensitive filtering, the channel affiliation of each capsule record is determined before delisting: capsules not bound to a single product (goods_item_id is empty) are created according to the e-commerce synchronized order number and belong to the e-commerce channel; capsules bound to a single product are determined according to the single product channel field. When the order number of the marketing / bulk purchase channel happens to be the same as the refund order number of the e-commerce channel, due to the channel restriction condition (goods_item_id is empty OR channel=0), the capsule of the non-e-commerce channel will not be mistakenly delisted. This mechanism allows enterprises to safely operate e-commerce, marketing and bulk purchase channels at the same time without worrying about business losses caused by cross-channel number collisions.
[0054] (4) High-performance asynchronous on-chain reversal guarantee. Off-chain processing (removal from shelves, ownership reset) linked to refunds is completed synchronously in database transactions, with millisecond-level response. On-chain reversal operations are executed in the background through an asynchronous task queue, without blocking API request threads. A dual exception classification mechanism ensures that permanent exceptions are terminated immediately and alerted (avoiding ineffective retries that waste resources), while transient exceptions are exponentially backed up to avoid retries (upgrading to the final state after a maximum of 3 times), ensuring the eventual consistency of on-chain reversals. Administrators can manually re-submit or abandon failed tasks, providing operational intervention capabilities.
[0055] (5) Eliminate the performance bottleneck of cross-database queries. By storing all order fields locally in a mirrored format, buyer identifiers, SKU codes, customer information, etc., are all redundantly stored in the local order mirrored table. This ensures that all read operations in the refund linkage process, such as order queries, purchased product lists, and order number associations, are performed without cross-database queries. The order number is used as an invariant in the shared string space—the local mirrored table only contains e-commerce orders, and if it cannot be found, it is considered a non-e-commerce / external order number—so that all read operations can be completed uniformly through the local table, completely eliminating the network latency, connection pool exhaustion, and consistency time window issues of cross-database queries.
[0056] (6) Unified path for one-time and incremental synchronization of historical data. The historical backfill service reuses the same upsert path for incremental synchronization, eliminating the need to write special migration logic for historical data. Due to the idempotent nature of upsert, backfilling can be safely rerun. During the backfilling process, historical refund orders also trigger linked processing, ensuring that the digital asset status of all historical data is consistent with the order status after the system goes live.
[0057] (7) Securely isolated open interfaces for multiple callers. The OpenAPI gateway supports independent API keys (clientId→apiKey mapping) for multiple third-party callers, which can be individually assigned and revoked. A constant time comparison algorithm prevents side-channel attacks. IP whitelists provide network layer isolation. This design allows enterprises to securely expose order synchronization interfaces to multiple external systems without affecting each other. Attached Figure Description
[0058] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the embodiments will be briefly described below. Obviously, the drawings described below are merely some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without any creative effort.
[0059] Figure 1 This is a diagram illustrating the interactive architecture of the cross-system order incremental synchronization and refund asset linkage system of the present invention, showing the interaction between the third-party e-commerce system, OpenAPI gateway, order mirror library, linkage processing engine and blockchain network; Figure 2 This invention presents a flowchart of the refund atomic delisting state machine based on the number of affected rows, illustrating the complete process from refund detection, channel filtering, capsule delisting, NFT ownership reset to on-chain revocation task creation; Figure 3 This is a logic diagram for multi-channel sensitive filtering in this invention, showing the differentiated processing paths for e-commerce channels, marketing channels, and centralized procurement channels; Figure 4This is a sequence diagram of the asynchronous chain operation queue exception classification, consumption, and retry in this invention, showing the timing relationship between task scanning, idempotency verification, transaction submission, receipt waiting, permanent / transient exception classification, and backoff retry. Figure 5 This is a schematic diagram illustrating the order localization mirror storage and shared string space invariant of the present invention, showing the relationship between the order mirror table and the order_no field in the capsule / single item table; Figure 6 This is a flowchart illustrating the unified path for historical order backfilling and incremental synchronization in this invention, showcasing the architecture design of the backfilling service's reuse and synchronization path. Explanation of reference numerals in the attached figures
[0060] 100: Third-party e-commerce platform / external online store; 101: Online store business system; 102: Online store after-sales / refund module; 103: External online store main database; 200: Open Security Gateway; 201: OpenApiAuthFilter authentication filter; 202: API Key constant time comparison module; 203: IP whitelist filtering and matching module; 300: Core Business Service Layer; 301: Order Synchronization and Localization Service; 302: Refund Final State Detection Module; 303: Channel-Sensitive Filtering Engine; 304: Capsule and Asset Atomic Linkage Disposal Service; 305: Asynchronous Chain Operation Scheduling and Retry Service; 306: Historical Order Cursor Backfilling Service; 400: Local data storage layer (MySQL); 401: Local order mirror table (biz_order); 402: Multimedia capsule table (biz_capsule); 403: Product item table (biz_goods_item); 404: Digital asset table (nft_asset); 405: Traceability event table (nft_asset_event); 406: Chain operation queue list (nft_chain_op); 500: Blockchain Evidence Storage Layer (Wenchang Chain Alliance Network); 501: Platform Trustee Main Wallet; 502: Evidence Storage Smart Contract (TimeCapsuleProvenanceContract). Detailed Implementation
[0061] The technical solution of the present invention will be described in detail below with reference to the accompanying drawings and specific embodiments.
[0062] Consumer Wang purchased a silk scarf (order number ORD-20260601-001) from the official online store. He bound it to his Moqi NFT (tokenId=5001) via QR code and sealed a "Shiguang Youjian" (capsuleId=100, corresponding to capsuleNFT tokenId=5002). Later, due to product quality issues, Wang initiated a return and refund request through the online store. After the online store completed its after-sales process, the order status was updated to "after_sale_completed".
[0063] (1) The e-commerce system (MiniApp_Shop_Admin) sends a POST / open / v1 / order / sync request to the OpenAPI gateway of this system. The request body contains a complete snapshot of the orders: {"orderNo":"ORD-20260601-001","status":"after_sale_completed","wxOpenid":"o_demo_openid_001","skuCode":"SCARF-90-BLUE","goodsName":"Yunshuiyao·90cm Blue Silk Scarf","customerName":"Wang Mou","customerPhone":"13800138000","totalAmount":1280.00,"orderCreatedAt":"2026-06-01T10:30:00"} (2) OpenApiAuthFilter performs authentication: it verifies that the value of the request header X-Api-Key matches the pre-configured key (using the MessageDigest.isEqual constant for time comparison) and verifies that the source IP is in the whitelist. Authentication passes.
[0064] (3) The OrderSyncService.sync method verifies that orderNo is not empty and status="after_sale_completed" is a valid status enumeration. Query the local order mirror table with order_no="ORD-20260601-001" and find that there is already a record (the shipped status was previously synchronized). Perform a full field overwrite update, update status to "after_sale_completed", and refresh synced_at to the current time.
[0065] (4) If the status is detected to belong to the REFUND_TRIGGER set {after_sale_completed,cancelled}, call CapsuleService.takedownByOrder("ORD-20260601-001", "order_refund").
[0066] (5) Use takedownByOrder to query the capsule record with order_no="ORD-20260601-001" and status IN (1,2), and find capsuleId=100 (status=1, sealed, goods_item_id=200).
[0067] (6) Channel filtering: if capsuleId=100 and goods_item_id=200 is not empty, query the channel field of the product single item record id=200 and get channel=0 (e-commerce channel), it is determined to belong to the e-commerce channel and is retained.
[0068] (7) Execute the removal from the shelves: UPDATE biz_capsule SET status=3, update_by='order_refund'WHERE id=100. The capsule status changes from sealed (1) to removed from the shelves (3).
[0069] (8) Reclaim NFT ownership: Call revokeCapsuleNft(cap, "order_refund") to revokeAssetOwnership for the goods NFT with goods_item_id=200 and the capsule NFT with capsuleId=100 respectively.
[0070] (9) For the product NFT (asset_type='goods', asset_id=200): Query the NftAsset record, current_owner_id=Wang's member ID (not null). Execute UPDATE nft_asset SET current_owner_id=NULL, update_by='order_refund' WHERE id=asset ID AND current_owner_id IS NOTNULL. The number of affected rows = 1 (greater than 0), create an NftAssetEvent (event_type="refund", from_member_id=Wang's ID) and an NftChainOp task (operation_type=2, event_type="refund", status=0).
[0071] (10) For capsule NFT (asset_type='capsule', asset_id=100): also perform ownership reset, number of affected rows=1, create refund event and chain operation task.
[0072] (11) ChainWorkerService periodically scans for two refund chain operation tasks and submits logEvent transactions to the notarization contract under the protection of Redis exclusive locks, appending refund events to the notarization chains of product TokenID=5001 and capsule TokenID=5002. After the transaction is confirmed, txHash and blockNumber are filled back.
[0073] The e-commerce system was unsure whether the first refund synchronization was successful due to a network timeout, so it resent the same order snapshot (orderNo="ORD-20260601-001", status="after_sale_completed") to the OpenAPI gateway.
[0074] (1) OpenApiAuthFilter authentication is successful. OrderSyncService.sync queries the local mirror table with order_no, finds that there is already a record, performs a full field overwrite update (status is still "after_sale_completed", field values remain unchanged), and refreshes synced_at.
[0075] (2) If the status is detected to be REFUND_TRIGGER, call takedownByOrder("ORD-20260601-001", "order_refund").
[0076] (3) The `takedownByOrder` query retrieves capsule records with `order_no="ORD-20260601-001"` and `status IN (1,2)`. Since Example 1 updated the status of capsuleId=100 to 3 (removed from shelves), the `status IN (1,2)` query no longer finds this record, resulting in an empty list. No capsules need to be removed from shelves.
[0077] (4) Query the draft (status=0) capsule record, which is also empty (no draft or the draft was logically deleted in the first push).
[0078] (5) The entire takedownByOrder method has no side effects and returns normally. It will not create NftAssetEvent or NftChainOp tasks repeatedly. Even if the marketplace pushes the same refund notification 100 times, only one actual NFT ownership recovery and on-chain revocation operation will be performed.
[0079] The company sells goods through both e-commerce and marketing channels. A batch of promotional scarves was shipped from the marketing channel, and the "order number" entered by the administrator upon shipment was "MKT-20260601-001," which coincidentally matched a refund order number from an e-commerce platform.
[0080] (1) E-commerce refund: Consumer Zhang initiated a refund for his e-commerce order "MKT-20260601-001", and the mall synchronized the status "after_sale_completed". takedownByOrder found two capsule records associated with this order_no: capsuleId=201: Sealed; goods_item_id=301: Corresponding marketing channel gift (channel=1).
[0081] capsuleId=202: already sealed, goods_item_id=null, created according to the e-commerce synchronized order number (channel=e-commerce affiliation).
[0082] (2) Channel filtering: For capsuleId=201, goods_item_id=301 which are not empty, and querying a single product channel=1 (marketing), it is determined to be a non-e-commerce channel and is filtered out. For capsuleId=202, goods_item_id is empty, it is determined to belong to an e-commerce channel and is retained.
[0083] (3) Execution result: Only capsuleId=202 was removed from the platform, and the NFT ownership was reclaimed. capsuleId=201 (the capsule given away as a gift through the marketing channel) was unaffected and continued to be used normally. Consumers in the marketing channel will not have their digital assets mistakenly removed from the platform due to refunds from the e-commerce channel.
[0084] Consumer Zhao purchased the product and linked it to the Moqi NFT (tokenId=5003), but had not yet created a Shiguang Youjian account. At this point, a refund was requested.
[0085] (1) The `takedownByOrder` query returned empty records for sealed / unsealed capsules associated with `order_no` (Zhao did not create any capsules). The query for draft capsules also returned empty records.
[0086] (2) There are no operations in the capsule removal and draft deletion steps of takedownByOrder. However, if the product associated with the order has an NFT and the owner is not empty, takedownByOrder will find the product ID through capsule.getGoodsItemId() when executing revokeCapsuleNft, and then reclaim the ownership of the product NFT.
[0087] (3) If the capsule list is empty, revokeCapsuleNft will not be triggered. In this case, the recovery of NFT ownership depends on the fact that the NFT owner of the item in the order is still Zhao after the refund. Since the main entry point of takedownByOrder is associated with the item through capsules, if there are no capsules at all, an additional mechanism is needed to handle the recovery of pure NFTs.
[0088] (4) In the actual implementation of this system, takedownByOrder only processes NFTs associated with capsules. For refund scenarios where consumers have bound Moqi but have not created capsules, NFT ownership is not automatically reclaimed at the order synchronization level—this is consistent with business logic: when consumers only bind Moqi but have not sealed Youjian, the disposal of Moqi NFTs after a refund can be manually handled by the administrator through the Admin backend. However, if there are sealed capsules, the ownership of both the capsule NFT and the associated product NFT will be reclaimed when the capsule is removed from the shelves.
[0089] In Example 1, two refund chain operation tasks (tasks #201 and #202) were created. It is assumed that during the waiting period for the receipt after task #201 submitted the transaction, the blockchain network experienced a brief congestion.
[0090] (1) ChainWorkerService scans task #201 (status=0, txHash="0xdef456...", retry_count=0). It checks that there is already a txHash and calls getReceipt("0xdef456...") to query the on-chain receipt.
[0091] (2) The receipt query returns "Transaction not found" (blockchain network congestion, transaction has not yet been packaged). The system determines this as a transient anomaly, increases retry_count from 0 to 1, sets allow_execute_time to the current time + 5 minutes (1×5=5 minutes), and keeps status=0 to wait for the next round of retry. Transaction is not submitted repeatedly.
[0092] (3) Five minutes later, the scheduled task scans for task #201 again. The receipt is checked again, and the transaction has now been packaged and its status is successful (0x1). The markSuccess method is called to populate the blockNumber and mark the task as successful with status=1. At the same time, the txHash and blockNumber fields of NftAssetEvent are populated.
[0093] (4) Suppose that when task #202 submits the transaction, the notarization contract returns a revert (e.g., the tokenId does not exist), and the system determines it as a permanent exception (PermanentChainException). Directly mark the task status=2 (permanent failure) and output the alarm log "[CHAIN_OP_ALERT] permanently failed, manual intervention required: opId=202, nftAssetId=..., operationType=2, eventType=refund, err=Transactionreverted".
[0094] (5) After receiving the alarm, the administrator checks the chain operation queue details through the management backend (GET / admin / v1 / nft / chain-ops / 202) to confirm the cause of failure. After investigation, it was found that the minting operation (Mint) of the NFT had not yet succeeded, which caused the tokenId to not exist on the chain when logEvent was called. The administrator first resubmits the Mint task, and after the Mint succeeds, resubmits the refund task (POST / admin / v1 / nft / chain-ops / retry, passing in
[202] ). The system resets the status to 0, sets the retry_count to zero, and immediately triggers asynchronous processing.
[0095] When the system is deployed and launched for the first time, it is necessary to populate the local order mirror table with the 10,000 existing historical orders from the mall.
[0096] (1) The administrator calls the POST / admin / v1 / order / backfill endpoint (admin JWT authentication required).
[0097] (2) The OrderBackfillService.backfillAll method switches to the e-commerce database data source via @DS("shop") and executes a paginated query: SELECT o.id, o.order_no, o.status, ... FROM hxh_shop.orders_order o LEFT JOIN hxh_shop.customer_customer c ON o.customer_id=c.id LEFT JOIN hxh_shop.goods_goodssku gs ON o.sku_id=gs.id WHERE o.id > #{lastId} ORDER BY o.id ASC LIMIT 500. The first query returns lastId=0.
[0098] (3) Perform field mapping (toReq method) on each order record, convert it to OrderSyncRequest format, and call OrderSyncService.sync method to write it to the local mirror table using the same upsert path as incremental synchronization.
[0099] (4) If the status of a historical order is "after_sale_completed" or "cancelled", the sync method will trigger takedownByOrder linkage disposal after upsert is completed. The capsule associated with the historical refund order will be removed from the shelves and NFT ownership will be reclaimed—if these assets were previously active. Due to the idempotency mechanism, even if the refund order has been manually processed before upsert, duplicate disposal will not have any side effects (the number of affected rows is 0).
[0100] (5) After each page is processed, update lastId to the out_order_id value of the last record, and continue querying the next page until the query result is empty. Finally, return the total number of records to be filled (e.g., 10,000 records).
[0101] (6) If the backfilling process is interrupted due to network abnormalities or other reasons, the administrator can call the backfill endpoint again. Due to the idempotency of upsert, backfilled orders will not be inserted again; only unfilled orders will be processed from the breakpoint. The entire backfilling process is safe and can be rerun.
Claims
1. A method for cross-system e-commerce order and blockchain digital asset linkage and disposal, characterized in that, Includes the following steps: S1: The open interface gateway receives order status snapshot messages from third-party e-commerce systems, performs API key verification and source IP whitelist verification on the messages, and stores the order status snapshot locally with the order number as the unique index to the order mirror library. The order mirror library redundantly stores all fields of buyer identifier, SKU code, customer information and fulfillment status to eliminate cross-database association queries. S2: Monitor changes in the status field in the order status snapshot. When the status field is detected to belong to a preset refund final state set, trigger the digital asset linkage disposal process. S3: Query the associated target digital capsule record and target digital asset record based on the order number, and perform channel validity verification on each digital capsule record found: when the digital capsule record is not associated with a single product, it is determined to belong to the e-commerce channel; when the digital capsule record is associated with a single product, the channel identifier of the single product is read; only when the channel identifier is an e-commerce channel is it determined to belong to the e-commerce channel, and digital capsule records that are not e-commerce channels are filtered out. S4: Perform a single atomic update operation on the digital capsule records that have passed the validity verification through the channel: set the digital capsules that are in the sealed or unsealed state to the delisted state, perform logical deletion on the digital capsules that are in the draft state, and at the same time perform a logical ownership reset operation on the associated target digital assets, the reset operation is subject to the condition constraint that the current owner is not empty; S5: Based on the actual number of affected rows returned by the atomic update operation and the null operation, perform idempotency determination. Only when the actual number of affected rows is greater than zero, submit a blockchain evidence revocation task to the asynchronous chain operation queue. The blockchain evidence revocation task includes the refund event type and the original owner identifier. S6: Obtain the blockchain evidence revocation task from the asynchronous chain operation queue through the distributed task consumption engine, and add a refund revocation event to the blockchain evidence contract under the protection of a distributed exclusive lock. The refund revocation event records the original owner's identifier, refund time, and verification link.
2. The method according to claim 1, characterized in that, The API key verification uses a constant-time comparison algorithm, including: Extract the API key field value from the HTTP request header; The API key field value is compared byte by byte with at least one pre-configured caller key. The comparison is performed using the MessageDigest.isEqual method to perform a constant time comparison to prevent side-channel attacks based on response time. It supports independent API key configuration for multiple callers, with each caller having a corresponding clientId, and keys can be assigned and revoked individually; The IP whitelist verification supports extracting the client's real IP address from the X-Forwarded-For request header, and does not restrict the source IP when the whitelist is empty.
3. The method according to claim 1, characterized in that, The localized idempotent storage method for the order status snapshot is as follows: Verify the non-emptiness and validity of the order number and status fields. The status field must belong to a predefined set of valid status enumerations. Use the order number as the unique index to query whether an existing record exists in the order mirror database; If the record does not exist, insert a new record and set the source identifier to the third-party system identifier; If it already exists, perform a full-field update using the order number as the primary key and refresh the most recently synchronized timestamp; The unique index of the order mirror table is the order number field, and the idempotency of concurrent insertion is guaranteed by the database unique constraint; The order number in the order mirror library only includes orders from e-commerce channels. Order numbers from marketing channels and centralized procurement channels are not included in the order mirror library. The order number exists as a shared string space for e-commerce channel orders, marketing channel orders, and centralized procurement channel orders.
4. The method according to claim 1, characterized in that, The specific rules for determining the validity of the channel are as follows: When the product identifier field of the digital capsule is empty, the digital capsule is an unbound product capsule created according to the e-commerce synchronized order number, which is determined to belong to the e-commerce channel and is retained; When the product identifier field of the digital capsule record is not empty, the channel field of the product record is queried based on the product identifier. When the channel field value is 0, it is determined to be an e-commerce channel and is retained. When the channel field value is 1, it is determined to be a marketing channel and filtered out; when the channel field value is 2, it is determined to be a centralized procurement channel and filtered out. The channel restriction conditions can be described as follows: the product identifier is empty or the associated product channel = e-commerce channel; When order numbers from marketing channels or centralized procurement channels happen to be the same as order numbers from e-commerce channels, digital capsules from non-e-commerce channels will not be mistakenly removed from the shelves due to the existence of channel restrictions.
5. The method according to claim 1, characterized in that, The idempotency determination and on-chain reversal task submission mechanism based on the number of affected rows is as follows: The logical ownership null operation uses a conditional update statement, with the "current owner identifier ISNOT NULL" constraint added to the WHERE condition. When the asset owner has been nulled, the number of rows affected by the update is zero. When the number of affected rows is zero, it is determined that the process has been completed, and no blockchain evidence revocation task is submitted; the process is returned directly. When the number of affected rows is greater than zero, a record of evidence storage event is created, the event type is refund, the original owner's identifier is recorded, and a task to be executed is inserted into the asynchronous chain operation queue, the task status is pending execution, and the operation type is evidence storage event write. For repeated pushes of the same order, since the owner has been set to null in the first push, the nulling operation in subsequent pushes affects the number of rows to zero. The evidence storage event and chain operation task are not created repeatedly, achieving lock-free idempotency that relies solely on the database to affect the row count.
6. The method according to claim 1, characterized in that, The distributed exclusive lock and exception classification retry mechanism of the asynchronous chain operation queue are as follows: The distributed exclusive lock uses NFT asset identifiers as the granularity, with the lock key format being "nft:chain:lock:{asset ID}", and implements distributed mutual exclusion through Redis; Before executing a chain operation task, first check whether the task has carried a transaction hash. If it has, perform idempotency verification by querying the on-chain receipt: if the receipt is successful, mark the task as successful; if the receipt fails, mark it as permanently failed; if the receipt is not on the chain, postpone the retry. For new tasks, the transaction hash is persisted to the task record immediately after the transaction is submitted, and then the confirmation receipt is awaited. On-chain operation anomalies are divided into permanent anomalies and transient anomalies: Permanent anomalies include unrecoverable errors such as contract execution rollback and TokenID minted, which are directly marked as final state failure and output alarm logs; Transient anomalies include recoverable errors such as RPC timeout and network fluctuations, which are retried using an exponential backoff strategy, with a maximum of 3 retries and a backoff interval of the number of retries multiplied by a preset base interval. Administrators can manually resubmit failed tasks or mark them as permanently abandoned.
7. The method according to claim 1, characterized in that, The method also includes a one-time backfilling step for historical orders: Read all e-commerce order records from the order database of a third-party e-commerce system by pagination using the primary key cursor, with a preset number of records read per page; Perform field mapping on each order record, convert it into an order synchronization request format, and write it to the order mirror library through the same idempotent storage path as in step S1; Due to its idempotent storage properties, historical backfilling can be safely rerun, and repeated execution will not generate duplicate records. During the historical backfilling process, if a historical order in the final state of refund is encountered, the linkage processing procedure of steps S2 to S6 will also be triggered, so that the digital assets associated with the historical refund order are also in the state of being delisted or recovered.
8. A cross-system e-commerce order and blockchain digital asset linkage and disposal system, characterized in that, include: The open interface gateway module is used to receive order status snapshot messages from third-party e-commerce systems and perform API key verification and IP whitelist verification. The order localization storage module is used to store all fields of an order idempotently in the local order mirror library using the order number as a unique index; The refund final state detection module is used to monitor order status changes and determine whether they belong to a preset refund final state set. The channel-sensitive filtering module is used to perform e-commerce channel validity verification on digital capsule records based on the channel identifier of each product. The atomic linkage processing module is used to perform digital capsule delisting, draft logic deletion, and digital asset ownership reset to zero through a single atomic update operation; The idempotency determination module is used to determine whether to submit an on-chain reversal task based on the number of affected rows returned by the atomic update operation. The asynchronous chain operation queue module is used to asynchronously execute on-chain submission, receipt waiting, and exception retries for blockchain evidence revocation events in the form of a task queue.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the method of any one of claims 1 to 7.
