A method and system for real-time issuance of digital invoices based on hybrid payment
By generating a unique payment serial number for each order and processing mixed payments synchronously, combined with asynchronous methods to achieve real-time issuance of digital invoices, the problems of invoice generation delay and data mismatch in mixed payment scenarios are solved, improving transaction efficiency and user experience.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-11
- Publication Date
- 2026-03-13
AI Technical Summary
In mixed payment scenarios, existing technologies cannot achieve efficient and accurate issuance of digital invoices, resulting in fragmented processes, asynchronous data, complex user operations, and delayed invoice generation, which affects user experience and merchant efficiency.
By generating a unique payment serial number for each order, the payment platform is synchronously invoked to complete the settlement of funds in public and private accounts. Self-paid payments are processed asynchronously, and payment data is aggregated and invoices are triggered immediately after all payment channels are successful. The digital invoice platform is used to generate and send access links in real time.
It enables real-time issuance of digital invoices in mixed payment scenarios, ensuring accurate correlation between payment data and invoice data, improving transaction efficiency and user experience, and reducing merchant operating costs and financial verification difficulties.
Smart Images

Figure CN121304265B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of invoice issuance technology, and in particular to a method and system for real-time issuance of digital invoices based on hybrid payment. Background Technology
[0002] In the modern commerce and service delivery sector, with the deepening of digital transformation, various transaction activities are becoming increasingly frequent and complex. Consumers or service recipients (hereinafter collectively referred to as "users") often face multiple payment options when acquiring goods or services. These payment methods not only include traditional cash or personal bank card payments, but may also involve financial support provided by third-party institutions, collective funds, or specific welfare programs. For example, in certain service consumption scenarios, users may need to simultaneously use funds in a public account managed by specific rules or agreements, as well as funds in their personal dedicated account, to complete a transaction. The emergence of this hybrid payment model aims to provide users with more flexible and inclusive payment options, while also bringing broader business expansion opportunities to service providers (hereinafter collectively referred to as "merchants").
[0003] Meanwhile, with the rapid development of information technology, the demand for digitized and real-time transaction vouchers is also growing. Traditional paper invoices, due to their physical limitations in printing, storage, distribution, and verification, are gradually becoming unsuitable for the high-efficiency, low-cost modern business environment. Digital electronic invoices, as an innovative solution, are gradually replacing traditional paper invoices and becoming the mainstream form of transaction voucher, thanks to their advantages such as paperless operation, easy storage, easy transmission, and traceability. The promotion of digital electronic invoices not only significantly reduces merchants' operating costs but also greatly facilitates users' voucher management and subsequent financial processing procedures.
[0004] However, seamlessly integrating this increasingly complex hybrid payment model with an efficient, real-time digital invoice issuance process is no easy task. This requires a high degree of collaboration and data interoperability between the payment system, the merchant's internal management system, and the invoice issuance system to ensure that users can obtain a digital invoice matching their transaction details instantly and accurately upon completing the payment.
[0005] Currently, in transaction scenarios involving mixed payments, merchants and users generally face problems such as fragmented processes, low efficiency, and poor user experience. Specifically, when a transaction requires settlement through both public account funds and personal dedicated account funds, the existing processing flow often exhibits the following typical characteristics: 1. In existing systems, the allocation of public account funds and the deduction of personal dedicated account funds are usually handled by different payment platforms or interfaces. This means that users need to complete the payment operation in stages, first settling the public account portion on one interface or through one system, and then switching to another interface or system to pay the personal self-payment portion. This multi-step, multi-interface operation mode not only increases the user's operational burden and prolongs the overall transaction time, but also easily leads to confusion or operational errors when switching between different systems. For merchants, it also increases the operational complexity of cashiers or service personnel and reduces service efficiency. 2. In the above-mentioned fragmented payment process, the various systems involved (e.g., the merchant's internal management system, public account payment settlement platform, personal dedicated account payment platform, and the final transaction voucher issuance system) often operate independently, with limited data interaction capabilities. After payment results (including payments from public accounts and personal accounts) are returned from their respective payment platforms, they undergo complex aggregation and verification before being synchronized to the merchant's accounting system and ultimately triggering the issuance of digital invoices. This data flow delay and non-real-time nature means that users often cannot immediately obtain digital invoices after completing all payments. Invoice generation may require waiting for payment data to be synchronized and processed between backend systems, which contradicts the "real-time issuance" concept of digital invoices and reduces their immediate convenience. Furthermore, due to time differences in data synchronization between different systems, or the need for manual verification, discrepancies between payment and invoice information can easily occur, increasing the difficulty and risk of errors in financial verification. Once data inconsistencies arise, significant manpower and resources are required for investigation and correction, impacting the smoothness of the entire business process.
[0006] In summary, in complex transaction scenarios involving multiple payment sources, existing technologies cannot achieve efficient and accurate issuance of power transmission invoices. Summary of the Invention
[0007] This application provides a method and system for real-time issuance of digital invoices based on hybrid payment, which can improve service efficiency and accuracy of invoice issuance in hybrid payment scenarios.
[0008] To achieve the above objectives, the embodiments of this application adopt the following technical solutions:
[0009] Firstly, a method for real-time issuance of digital invoices based on hybrid payment is provided, the method comprising:
[0010] In response to receiving a pending payment order sent by a user through a user terminal, the system obtains the user's identity information and generates a unique payment transaction number for the pending payment order.
[0011] The payment transaction number is bound to the order to be paid, and a payment request is simultaneously initiated to the payment platform through the payment settlement interface. The payment request carries the payment transaction number and payment details. The payment platform is used to complete the transfer of funds from the public account and the deduction of funds from the personal account, and returns the payment result.
[0012] If the payment result is successful, an asynchronous self-payment request is initiated through the multi-payment channel SDK, and the self-payment result is received.
[0013] If both the payment result and the self-funded payment result are successful, the payment result and the self-funded payment result are aggregated to generate a payment success status, and a digital invoice is issued in real time through the digital invoice platform. The digital invoice platform interface carries the payment serial number, the payment amount of the public account, the payment amount of the personal special account, the cash payment amount, and the user identity information.
[0014] In response to receiving the digital invoice access link returned by the digital invoice platform, the digital invoice access link is bound to the order to be paid, and the payment success status and the digital invoice access link are sent to the user terminal.
[0015] In one possible implementation of the first aspect, the method further includes:
[0016] If the payment result is successful and the self-paid payment result is unsuccessful, a reverse transaction request is initiated to the payment platform, and the reverse transaction request is used to cancel the payment;
[0017] In response to receiving the reverse transaction success information returned by the payment platform, the status of the order to be paid is updated to a payment failure status, and the payment failure status is sent to the user terminal.
[0018] In another possible implementation of the first aspect, the real-time issuance of digital invoices through the digital invoice platform includes:
[0019] Based on the payment transaction number, the payment amount from the public account, the payment amount from the personal account, the cash payment amount, and the user identity information, generate digital invoice issuance request data;
[0020] The request data for issuing the digital invoice is sent to the digital invoice platform, which verifies the request data and generates a digital invoice upon successful verification.
[0021] In another possible implementation of the first aspect, after generating a unique payment serial number for the order to be paid, the method further includes:
[0022] Create a transaction state machine instance for the payment serial number, and set the initial state of the transaction state machine instance to the pending state, with an initial version number of 1;
[0023] Before synchronously initiating a payment request to the payment platform through the payment settlement interface, a payment compensation instruction is constructed. The payment compensation instruction includes the payment transaction number, the reversal interface address, the reversal amount, the version number, and the pending execution status identifier.
[0024] The payment compensation instruction is written to the compensation instruction ledger using a write-ahead log method and awaits disk flushing confirmation. The compensation instruction ledger is implemented by appending log files and stored on the disk.
[0025] Upon receiving the disk flush confirmation signal, the step of synchronously initiating a payment request to the payment platform through the payment settlement interface is executed, and the status of the transaction state machine instance is updated to the processing state.
[0026] In another possible implementation of the first aspect, the step of writing the payment compensation instruction to the compensation instruction ledger using a write-ahead log method and waiting for disk confirmation includes:
[0027] The payment compensation instruction is serialized into a log record, and the log record is appended to the end of the append-only log file corresponding to the compensation instruction ledger.
[0028] Call the file system synchronization interface to force the log records in the append-only log file to be flushed from the memory buffer to the persistent storage medium on the disk;
[0029] After the flashing process is complete, a flash confirmation signal is generated.
[0030] Regularly create checkpoints, scan the append-only log files corresponding to the compensation instruction ledger, apply the compensation instructions with the status of "completed" to the main status database, and mark the corresponding log records in the main status database as "cleanable".
[0031] In another possible implementation of the first aspect, before initiating a reverse transaction request to the payment platform in the case that the payment result is successful and the self-paid payment result is unsuccessful, the method further includes:
[0032] Update the state of the transaction state machine instance to a cash failure pending compensation state;
[0033] Retrieve the payment compensation instruction with the pending execution status from the compensation instruction ledger based on the payment transaction number;
[0034] Determine the fuse status corresponding to the positive interface address;
[0035] If the fuse is in the open state, the payment compensation instruction is placed in the delay queue and the current compensation execution is terminated.
[0036] When the circuit breaker is in a closed or semi-open state, the step of initiating a reverse transaction request to the payment platform is executed.
[0037] In another possible implementation of the first aspect, initiating a reverse transaction request to the payment platform includes:
[0038] Extract the version number from the payment compensation instruction;
[0039] Construct a reverse transaction request, the reverse transaction request including the payment transaction number, the reversal amount, and the version number;
[0040] The reverse transaction request is sent to the payment platform, which maintains a compensation status vector for each transaction. The compensation status vector records the compensation version number that has been successfully executed.
[0041] Wherein, if the version number in the reversal request is greater than the compensation version number recorded in the compensation status vector, the payment platform performs a reversal operation and updates the compensation version number in the compensation status vector after the reversal is successful; if the version number in the reversal request is less than or equal to the compensation version number recorded in the compensation status vector, the payment platform directly returns a reversal success response.
[0042] In another possible implementation of the first aspect, after initiating the reverse transaction request to the payment platform, it further includes:
[0043] Upon receiving a successful reversal response from the payment platform, the status of the payment compensation instruction in the compensation instruction ledger is updated to the completed status, and the status of the transaction state machine instance is updated to the revoked status.
[0044] Upon receiving a reversal failure response from the payment platform, the number of compensation failures is recorded, and the failure counter of the circuit breaker is updated.
[0045] Calculate the next retry interval based on the number of compensation failures;
[0046] When the failure counter reaches a preset failure threshold, the fuse state is set to the open state, and the fuse duration is set.
[0047] After the duration of the fuse interruption ends, the fuse state is set to the half-open state.
[0048] Secondly, this application provides a real-time digital invoice issuance system based on hybrid payment, comprising:
[0049] Communication devices are used to establish communication connections with user terminals, payment platforms, multiple payment channels, and digital invoice platforms.
[0050] The processor is configured as follows:
[0051] In response to receiving a pending payment order sent by a user through a user terminal, the system obtains the user's identity information and generates a unique payment transaction number for the pending payment order.
[0052] The payment transaction number is bound to the order to be paid, and a payment request is simultaneously initiated to the payment platform through the payment settlement interface. The payment request carries the payment transaction number and payment details. The payment platform is used to complete the transfer of funds from the public account and the deduction of funds from the personal account, and returns the payment result.
[0053] If the payment result is successful, an asynchronous self-payment request is initiated through the multi-payment channel SDK, and the self-payment result is received.
[0054] If both the payment result and the self-funded payment result are successful, the payment result and the self-funded payment result are aggregated to generate a payment success status, and a digital invoice is issued in real time through the digital invoice platform. The digital invoice platform interface carries the payment serial number, the payment amount of the public account, the payment amount of the personal special account, the cash payment amount, and the user identity information.
[0055] In response to receiving the digital invoice access link returned by the digital invoice platform, the digital invoice access link is bound to the order to be paid, and the payment success status and the digital invoice access link are sent to the user terminal.
[0056] Thirdly, this application provides a machine-readable storage medium storing instructions that cause a machine to execute the above-described method for real-time issuance of digital invoices based on hybrid payment.
[0057] The above technical solution enables real-time issuance of digital invoices in mixed payment scenarios. By generating a unique payment serial number for each order and maintaining its consistency throughout the transaction process, the precise correlation between payment data and invoice data is ensured, effectively avoiding information mismatch issues caused by data flow delays in traditional methods. Synchronous calls to the payment platform are used to complete fund settlement for public and personal accounts, combined with asynchronous processing of self-paid payments, ensuring the reliability of the core payment process and improving overall transaction efficiency. Payment data is aggregated and invoice issuance is triggered immediately after all payment channels are successful, achieving seamless integration of payment and invoicing. Users receive a digital invoice access link immediately upon completing payment, without waiting for backend data synchronization or manual processing. This real-time invoicing mechanism significantly improves user experience and reduces merchants' operating costs and financial reconciliation difficulties. Compared to traditional phased payment and delayed invoicing methods, this solution effectively solves problems such as process fragmentation, data asynchrony, and complex user operations, providing an efficient, accurate, and convenient solution for digital transactions in mixed payment scenarios.
[0058] Other features and advantages of the embodiments of this application will be described in detail in the following detailed description section. Attached Figure Description
[0059] Figure 1 A flowchart illustrating a real-time digital invoice issuance method based on hybrid payment, provided for an embodiment of this application;
[0060] Figure 2 A schematic diagram illustrating a process for writing a payment compensation instruction into a compensation instruction ledger and waiting for confirmation by data swiping, provided as an embodiment of this application;
[0061] Figure 3 This is a schematic diagram illustrating a process for initiating a reverse transaction request to a payment platform, as provided in an embodiment of this application. Detailed Implementation
[0062] To make the objectives, technical solutions, and advantages of the embodiments of this application clearer, the technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. It should be understood that the specific embodiments described herein are only for illustration and explanation of the embodiments of this application and are not intended to limit the embodiments of this application. All other embodiments obtained by those skilled in the art based on the embodiments of this application without creative effort are within the scope of protection of this application.
[0063] It should be noted that if the embodiments of this application involve directional indicators (such as up, down, left, right, front, back, etc.), the directional indicators are only used to explain the relative positional relationship and movement of each component in a certain specific posture (as shown in the figure). If the specific posture changes, the directional indicators will also change accordingly.
[0064] Furthermore, if the embodiments of this application involve descriptions such as "first" or "second," these descriptions are for descriptive purposes only and should not be construed as indicating or implying their relative importance or implicitly specifying the number of technical features indicated. Therefore, features defined with "first" or "second" may explicitly or implicitly include at least one of those features. Additionally, the technical solutions of various embodiments can be combined with each other, but this must be based on the ability of those skilled in the art to implement them. If the combination of technical solutions is contradictory or impossible to implement, it should be considered that such a combination of technical solutions does not exist and is not within the scope of protection claimed in this application.
[0065] Figure 1 This illustration schematically shows a flowchart of a method for real-time issuance of digital invoices based on hybrid payment, according to an embodiment of this application. Figure 1 As shown in the figure, this application provides a method for real-time issuance of digital invoices based on hybrid payment, which may include the following steps.
[0066] S110. In response to receiving a pending payment order sent by the user through the user terminal, obtain the user's identity information and generate a unique payment transaction number for the pending payment order;
[0067] S120. Bind the payment transaction number to the order to be paid, and initiate a payment request to the payment platform through the payment settlement interface. The payment request carries the payment transaction number and payment details. The payment platform is used to complete the transfer of funds from the public account and the deduction of funds from the personal account, and returns the payment result.
[0068] S130. If the payment result is successful, initiate a self-payment request asynchronously through the multi-payment channel SDK and receive the self-payment result.
[0069] S140. If both the payment result and the self-funded payment result are successful, aggregate the payment result and the self-funded payment result, generate a payment success status, and issue a digital invoice in real time through the digital invoice platform. The digital invoice platform interface carries the payment serial number, the payment amount of the public account, the payment amount of the personal special account, the cash payment amount, and the user's identity information.
[0070] S150. In response to receiving the digital invoice access link returned by the digital invoice platform, bind the digital invoice access link to the order to be paid, and send the payment success status and the digital invoice access link to the user terminal.
[0071] When a user sends an order to be paid through a user terminal, the user's identity must first be verified and information extracted. The user terminal can be a smartphone, tablet, or other device with network communication capabilities. Upon receiving the order, the user's identity information is immediately extracted from the order data. This information may include the user's unique identifier, name, contact information, and other key data.
[0072] User identity information can be obtained in various ways, such as reading authenticated credentials from a user's login session or parsing the user identifier field from an order data packet. After confirming the validity of the user's identity information, a unique payment transaction number is generated for each order to be paid. This number is generated using specific encoding rules and typically includes components such as a timestamp, a random number, and a business identifier, ensuring global uniqueness throughout the system. The payment transaction number can be generated using the Snowflake algorithm or the UUID algorithm, which guarantees that the generated identifier will not be duplicated in a distributed environment. The generated payment transaction number will serve as a key index for all subsequent payment and invoice issuance operations, persisting throughout the entire transaction process. In this way, even in high-concurrency scenarios, the complete lifecycle of each transaction can be accurately tracked, providing a reliable data association basis for subsequent data aggregation and invoice issuance.
[0073] After generating the payment transaction number, it is immediately strongly bound to the order to be paid, establishing a one-to-one mapping relationship. This binding relationship is persistently stored in the database, ensuring that the corresponding order information can be accurately found through the payment transaction number even in the event of system anomalies. Next, a payment request data packet is constructed, which carries detailed payment information such as the payment transaction number, total order amount, amount payable to the public account, and amount payable to the personal account.
[0074] The construction of payment details requires accurately calculating the respective proportions of the amount to be borne by the public account and the personal dedicated account based on the type of goods or services in the order and according to preset cost-sharing rules. A payment request is synchronously initiated to the payment platform through the payment settlement interface. This synchronous call means that after initiating the request, the platform will wait for a response and will not return immediately. Upon receiving the request, the payment platform first verifies the validity and uniqueness of the payment transaction number, and then, based on the amount information in the payment details, sequentially completes the transfer of funds from the public account and the deduction from the personal dedicated account.
[0075] Fund transfers from public accounts typically involve interaction with specific fund management institutions, requiring verification of account balances, freezing of funds, and transfers. Deductions from personal accounts, on the other hand, require verification of the user's account status and available balance, and execution of the corresponding deduction record. After completing all fund operations, the payment platform generates and returns a payment result, which includes key information such as a status indicator of payment success, the actual deduction amount, and the transaction time.
[0076] Upon receiving the payment result from the payment platform and confirming its success, the self-payment process is immediately triggered. Self-payment refers to a portion of the payment made by the user using cash, bank cards, or other personal payment methods; this amount does not fall under the category of public or personal accounts. The self-payment request is initiated asynchronously through the multi-payment channel SDK. This asynchronous approach means that after initiating the request, the system will not block and wait for the result but will continue to execute subsequent logic, receiving the payment result through a callback mechanism.
[0077] In this embodiment, the multi-payment channel SDK integrates interfaces for various mainstream payment methods, enabling dynamic invocation of the corresponding payment interface based on the user's selected payment method. When initiating a self-paid payment request, request data containing parameters such as order information, payment amount, and payment transaction number needs to be constructed and sent to the corresponding payment channel through the standard interface provided by the SDK. After receiving the request, the payment channel guides the user to complete the payment operation, such as scanning a QR code and entering a payment password. After the user completes the payment, the payment channel returns the payment result through a callback interface.
[0078] When receiving self-funded payment results, it is necessary to verify the authenticity and integrity of the callback data. This is typically done by verifying digital signatures or encrypted parameters to ensure that the data has not been tampered with. The self-funded payment result includes information such as payment status, actual payment amount, and transaction serial number of the payment channel. This information will be used for subsequent data aggregation and invoice issuance.
[0079] After confirming that both the payment result and the self-funded payment result are successful, the data aggregation and invoice issuance process begins. Specifically, firstly, the payment results returned by the payment platform and the self-funded payment results are aggregated, and key payment information is extracted, including the actual payment amount to the public account, the actual payment amount to the personal dedicated account, and the cash payment amount. The aggregation process requires summarizing and verifying the amount data returned by each payment channel to ensure that the total payment amount matches the order amount, avoiding financial problems caused by discrepancies.
[0080] After data aggregation is complete, a payment success status identifier is generated and stored in association with the payment transaction number. Next, a digital invoice issuance request is constructed, which requires complete payment information and user identity information. Specifically, this includes the payment transaction number as the unique identifier for the invoice, the public account payment amount used for detailed expense breakdowns on the invoice, the personal account payment amount and cash payment amount clearly indicating different payment sources, and the user identity information used to determine the invoice header and recipient information. The invoice issuance request is initiated in real-time through the digital invoice platform interface. Upon receiving the request, the platform first verifies the completeness and compliance of the request data, including verifying the uniqueness of the payment transaction number, the accuracy of the amount data, and the validity of the user identity information. After successful verification, the platform generates a digital invoice in a standard format according to relevant regulations. The invoice details the transaction time, goods or services, the amount distribution across payment channels, and tax information. After the digital invoice is generated, the platform assigns a unique invoice code and invoice number and uploads the invoice data to the invoice management system for record-keeping.
[0081] After completing invoice generation and filing, the digital invoice platform will return a digital invoice access link. This link points to the electronic storage location of the invoice, allowing users to view, download, or print it online. Upon receiving the digital invoice access link, the platform immediately binds it to the pending payment order, establishing a link between the order and the invoice. This binding relationship is persistently stored, ensuring that users can quickly retrieve the corresponding invoice using their order information at any time.
[0082] Simultaneously, the payment success status and a link to access the digital invoice will be sent to the user's terminal. This sending can be achieved through various methods, such as in-app push notifications, SMS notifications, or email. Upon receiving the payment success status, the user's terminal will display a payment success message on the interface and provide an entry point to view the invoice.
[0083] After clicking the invoice viewing entry, the terminal will automatically open the digital invoice access link, displaying the complete electronic invoice content. The electronic invoice page typically includes all legally required elements of the invoice, such as the invoice code, invoice number, invoice date, buyer information, seller information, details of goods or services, amount, and tax amount. Users can verify the accuracy of the invoice information online. Furthermore, users can choose to download and save the invoice to their local device or send it to their finance department via email for reimbursement processing. This method automates and real-times the entire process from payment completion to invoice retrieval. Users receive a formal digital invoice the instant payment is successful without waiting or additional steps, greatly improving user experience and business processing efficiency.
[0084] This embodiment enables real-time issuance of digital invoices in a hybrid payment scenario. By generating a unique payment serial number for each order and maintaining its consistency throughout the transaction process, the precise correlation between payment data and invoice data is ensured, effectively avoiding information mismatch issues caused by data flow delays in traditional methods. Synchronous calls to the payment platform are used to complete fund settlement for public and personal accounts, combined with asynchronous processing of self-paid payments, ensuring the reliability of the core payment process and improving overall transaction efficiency. Payment data is aggregated and invoice issuance is triggered immediately after all payment channels are successful, achieving seamless integration of payment and invoicing. Users receive a digital invoice access link immediately upon completing payment, without waiting for backend data synchronization or manual processing. This real-time invoicing mechanism significantly improves user experience and reduces merchants' operating costs and financial reconciliation difficulties. Compared to traditional phased payment and delayed invoicing methods, this solution effectively solves problems such as process fragmentation, data asynchrony, and complex user operations, providing an efficient, accurate, and convenient solution for digital transactions in hybrid payment scenarios.
[0085] In one embodiment of this invention, the method further includes the following steps:
[0086] S210. If the payment result is successful and the self-paid payment result is unsuccessful, initiate a reverse transaction request to the payment platform. The reverse transaction request is used to cancel the payment.
[0087] S220. In response to receiving the reverse transaction success information returned by the payment platform, update the status of the order to be paid to the payment failure status and send the payment failure status to the user terminal.
[0088] In hybrid payment scenarios, after the payment platform completes the transfer of funds from the public account and deducts funds from the personal account and returns a success result, it needs to wait for the completion of the self-payment before confirming the final status of the entire transaction. However, in actual business scenarios, there may be situations where the payment platform's payment operation has been successful, but the user's self-payment fails for various reasons. These reasons may include the user canceling the payment operation, payment channel network abnormalities, insufficient user account balance, or the user's account being locked due to too many incorrect password attempts.
[0089] In this situation, failing to process the successful payment through the payment platform would result in funds being deducted from the user's public and personal accounts, even though the order was not actually completed, leading to fund ties and business process disruptions. To resolve this issue, a reverse transaction request needs to be initiated with the payment platform to cancel the completed payment operation.
[0090] The construction of a reverse transaction request requires key information such as the original payment transaction number, the details of the amount to be revoked, and the reason for revocation. The payment transaction number is used to accurately locate the transaction record to be revoked in the payment platform. The amount details include the amount transferred from the public account and the amount deducted from the personal account, ensuring that the revocation operation can accurately restore the fund status of each account. The reason for revocation field is used to record the basis for revocation at the business level, facilitating subsequent auditing and problem tracing.
[0091] When initiating a reverse transaction request, it must be called through a dedicated reversal interface provided by the payment platform. This interface has strict access control and data verification mechanisms to ensure that only legitimate reversal requests can be executed. After receiving a reverse transaction request, the payment platform will first verify the legitimacy of the request, including verifying whether the payment transaction number exists, whether the original transaction is in a reversible state, and whether the requester has reversal authority.
[0092] Once verification is successful, the payment platform will execute a fund reversal operation, returning the allocated public account funds to the original account and restoring the deducted personal account funds to the user's account, while generating a corresponding reversal transaction record. The entire reverse transaction process must ensure atomicity, meaning either all funds are successfully reversed or all funds fail, avoiding inconsistencies where some accounts receive reversals while others do not, in order to prevent such situations.
[0093] Once the payment platform completes the reverse transaction, it will return a successful reverse transaction message. This message includes detailed data such as the reverse transaction serial number, refund amount details, and transaction completion time. Upon receiving the successful reverse transaction message, the status of the pending payment order needs to be updated immediately, marking it as a payment failure. This order status update operation needs to be persistently stored in the database to ensure that order status changes are accurately recorded.
[0094] Simultaneously, detailed status change logs must be recorded, including the status change time, reason for the change, relevant payment transaction number, and reversal transaction number. This log data is invaluable for subsequent business analysis and troubleshooting. While updating the order status, all business resources related to the order need to be released. For example, if the order involves inventory reservation, the reserved inventory needs to be released back to the available inventory pool; if the order involves coupons or points redemption, used coupons need to be restored to available status, and deducted points need to be refunded to the user's account. These resource release operations must be completed within the same transaction as the order status update to ensure data consistency.
[0095] After completing the order status update and resource release, the user needs to be notified of the payment failure status in a timely manner. Notification methods can include displaying a payment failure message on the user's application interface, sending a failure notification via push message, or informing the user of the payment failure and its reason via SMS.
[0096] Specifically, the payment failure status information sent to the user's terminal should include not only a failure status indicator but also a detailed explanation of the reason for the failure, such as "Self-paid payment failed; deductions from both the public account and personal account have been cancelled," to help users understand why the transaction failed. Furthermore, an entry point or guidance for re-payment should be provided so that users can quickly re-initiate the payment operation after resolving the payment issue.
[0097] When a user terminal receives a payment failure status, it will display an error message on the interface and provide corresponding operation options, such as re-paying, viewing order details, or contacting customer service, thereby improving the user experience in abnormal scenarios.
[0098] This implementation method effectively solves the problem of fund inconsistency caused by partial payment success and partial payment failure in mixed payment scenarios by introducing a reverse transaction mechanism. When the payment platform's payment operation succeeds but the self-payment fails, the reverse transaction process is automatically triggered to promptly cancel the completed payment operation, ensuring user fund security and the integrity of the business process. This mechanism avoids situations where user funds are mistakenly deducted without order completion, reducing user complaints and customer service processing costs.
[0099] By promptly updating order status and notifying users, the accuracy of business data and the consistency of user experience are ensured. Users can clearly understand the reasons for transaction failures and can re-initiate payments based on prompts, avoiding user confusion and dissatisfaction caused by a lack of transparency. Compared to traditional manual refund processing, the automated reverse transaction mechanism significantly improves the efficiency of anomaly handling, shortening the refund process from what might have taken hours or even days to seconds, significantly enhancing business processing capabilities. Furthermore, a complete status change log and resource release mechanism ensure the consistency and traceability of system data in abnormal scenarios, providing reliable data support for subsequent business analysis, problem investigation, and auditing, effectively reducing the complexity and risk of system operation and maintenance.
[0100] In one embodiment of this invention, issuing digital invoices in real time through a digital invoice platform includes the following steps:
[0101] S310. Generate digital invoice issuance request data based on payment transaction number, public account payment amount, personal special account payment amount, cash payment amount and user identity information;
[0102] S320. Send the digital invoice issuance request data to the digital invoice platform. The digital invoice platform is used to verify the digital invoice issuance request data and generates a digital invoice after successful verification.
[0103] After all payment channels return successful results, the scattered payment data needs to be integrated into standardized request data that meets the requirements of the digital invoice platform. Generating digital invoice issuance request data is a process of data aggregation and format conversion, which must strictly adhere to relevant digital invoice data specifications.
[0104] First, the payment transaction number is used as the core identifier. This number remains unique and consistent throughout the entire transaction process, accurately linking order information, payment information, and invoice information to ensure data traceability. Next, the amount data from each payment channel needs to be meticulously organized, extracting and labeling the payment source attributes of public account payments, personal dedicated account payments, and cash payments.
[0105] This categorization is crucial for invoice compliance, as different payment sources may involve different financial processing rules and tax reporting requirements. For example, payments from public accounts may correspond to medical insurance payments or corporate welfare payments, requiring clear identification on the invoice for subsequent financial accounting and reimbursement approval. During the data processing, precise amount verification is also necessary to ensure the sum of amounts from all payment channels equals the total order amount, preventing invoice issuance failures due to discrepancies.
[0106] Processing user identity information is equally crucial. It's necessary to extract the essential fields required for invoice issuance from the raw user data, including user name, taxpayer identification number, contact number, and email address. For corporate users, complete invoicing information is also required, such as the company's full name, tax identification number, bank and account number, and company address.
[0107] When generating the request data, a list of invoice items conforming to tax regulations needs to be constructed based on the details of goods or services in the order. Each item must include detailed information such as item name, specifications, unit, quantity, unit price, amount, tax rate, and tax amount. The tax rate needs to be automatically matched according to the tax classification code of the goods or services to ensure the accuracy of tax processing. In addition, auxiliary fields such as invoice date, seller information, and remarks need to be added to form a complete digital invoice issuance request data structure.
[0108] The entire data generation process requires multi-level data verification, including verification of the completeness of required fields, verification of data format standardization, and verification of the consistency of amount logic, to ensure that the generated request data can pass the verification rules of the digital invoice platform.
[0109] Sending the generated digital invoice issuance request data to the digital invoice platform is a crucial step in the invoice issuance process, requiring secure and reliable data transmission. Before sending the request, the request data must be encrypted using a recognized encryption algorithm to ensure its security and integrity during transmission. Simultaneously, a digital signature must be added, using the company's digital certificate to sign the request data, proving the authenticity of the request's origin and the immutability of the data.
[0110] Upon receiving a request, the digital invoice platform first performs identity authentication and authorization verification to confirm whether the requester has the legal qualifications and authority to issue invoices. After successful verification, the platform conducts a comprehensive compliance check on the requested data, including verifying the uniqueness of the payment transaction number to prevent duplicate invoicing; verifying the accuracy of the amount data, checking whether each amount conforms to logical relationships, and whether the tax calculation is correct; verifying the completeness and validity of the user's identity information, and for enterprise users, verifying the authenticity of the tax number; and verifying the standardization of the goods or services details, checking whether the tax classification code is correct and whether the item description meets the requirements.
[0111] After all verification items pass, the digital invoice platform begins generating digital invoices. First, it applies to the invoice management system for an invoice code and invoice number, which are the unique legal identifiers for an invoice. After obtaining the invoice number, the platform generates a complete digital invoice file based on the requested data and the prescribed invoice format standards.
[0112] Specifically, digital invoices use a structured data format, containing complete information such as basic invoice information, seller information, buyer information, details of goods or services, amount and tax information, and remarks. An electronic signature is attached to ensure the legal validity of the invoice. The generated digital invoices are simultaneously uploaded to an invoice verification platform for record-keeping, ensuring the authenticity and verifiability of the invoices.
[0113] After invoice generation and filing are completed, the platform will generate a unique access link and QR code for the invoice. Users can view the invoice details online through the link and quickly verify the invoice's authenticity through the QR code. The entire verification and generation process is usually completed within seconds, achieving true real-time invoicing. Compared to the traditional invoice issuance cycle that requires waiting for hours or even days, the efficiency is significantly improved.
[0114] This implementation method achieves seamless integration and automated processing from payment data to invoice generation through a standardized digital invoice issuance process. Precise data aggregation and format conversion ensure the accuracy and completeness of invoice information, avoiding errors and omissions that could occur with manual data entry. The payment transaction number, as a unique identifier throughout the entire process, establishes a strong correlation between payment data and invoice data, providing a reliable basis for subsequent financial verification and audit traceability.
[0115] The categorization and labeling of amounts from different payment sources meets the financial management needs of complex payment scenarios, enabling invoices to clearly reflect the capital composition of each payment channel. This facilitates refined financial management and tax declaration for businesses and individuals. Real-time interaction with the digital invoice platform and a rigorous data verification mechanism ensure that every invoice issued complies with tax regulations and has full legal validity. The multi-level verification mechanism of the digital invoice platform effectively prevents violations such as fake invoices and duplicate invoicing, safeguarding the seriousness of tax collection and administration.
[0116] The real-time invoicing capability allows users to receive official invoices instantly upon completing payment, without waiting or additional steps, significantly improving user experience and business processing efficiency. Compared to traditional invoicing methods, this solution reduces the invoicing cycle from hours to seconds, while also lowering merchants' labor and management costs, providing an efficient, accurate, and compliant solution for invoice management in digital transaction scenarios.
[0117] In one embodiment of this example, after generating a unique payment transaction number for the order to be paid, the following steps are also included:
[0118] S410. Create a transaction state machine instance for the payment serial number, and set the initial state of the transaction state machine instance to the pending state, with the initial version number set to 1.
[0119] S420. Before synchronously initiating a payment request to the payment platform through the payment settlement interface, construct a payment compensation instruction. The payment compensation instruction includes a payment transaction number, a reversal interface address, a reversal amount, a version number, and a pending execution status identifier.
[0120] S430. The payment compensation instruction is written to the compensation instruction ledger using a write-ahead log method and waits for disk flushing confirmation. The compensation instruction ledger is implemented by appending log files and stored on the disk.
[0121] S440. After receiving the disk flush confirmation signal, execute the step of synchronously initiating a payment request to the payment platform through the payment settlement interface, and update the status of the transaction state machine instance to the processing status.
[0122] In this embodiment, the following steps are also included:
[0123] Run a scheduled inspection task, which is used to periodically scan all transaction state machine instances.
[0124] Identify transaction state machine instances whose status is "processing" and whose dwell time exceeds a preset timeout threshold;
[0125] Identify transaction state machine instances whose status is successful and whose dwell time exceeds a preset self-payment timeout threshold;
[0126] For each identified transaction state machine instance, an asynchronous compensation process is triggered. The asynchronous compensation process includes retrieving a compensation instruction from the compensation instruction ledger based on the corresponding payment transaction number and executing the compensation operation.
[0127] After generating a unique payment transaction number for an order awaiting payment, a dedicated transaction state machine instance is immediately created for that transaction number to track and manage state changes throughout the entire transaction lifecycle. A transaction state machine is a design pattern based on finite state machine theory, which clearly defines the states of a transaction at different stages and the rules for transitions between states.
[0128] Each transaction state machine instance contains several key attributes, including a payment transaction number as a unique identifier, the current state identifier, the state entry time, the version number, and historical state change records. When a state machine instance is created, its initial state is set to "Pending," indicating that the transaction has been received by the system but the actual payment processing has not yet begun. The "Pending" state marks the beginning of the transaction lifecycle. In this state, all preparatory work related to the transaction has been completed, including order verification, amount calculation, and user identity confirmation, but no actual fund transfer has been initiated to any payment channel.
[0129] Meanwhile, the initial version number is 1. The version number mechanism is a key technical means to achieve idempotency control in a distributed environment. The version number increments with each compensation operation to prevent duplicate refunds caused by the same compensation instruction being executed repeatedly. For example, when the version number is 1, it indicates that this is the first possible compensation operation. If the compensation is executed successfully, the version number will be updated to 2. Even if a compensation request with version number 1 is received again due to network retransmission or other reasons, the system can recognize it as a duplicate request and refuse to execute it.
[0130] The creation of a transaction state machine instance needs to be persistently stored in a database to ensure that even if the system fails and restarts, the state information of all transactions can be recovered from the database to continue subsequent processing. The state machine instance also includes a state entry timestamp, recording the precise time when a transaction enters the current state. This timestamp is used for subsequent timeout detection and anomaly handling, which can identify abnormal transactions that remain in a certain state for a long time and trigger the corresponding processing mechanism.
[0131] Before actually initiating a payment request to the payment platform, a payment compensation instruction needs to be pre-constructed and persistently stored. This is the core mechanism for achieving eventual consistency in distributed transactions. The payment compensation instruction is essentially a contingency plan, used to automatically roll back the completed payment operation if the payment operation succeeds but subsequent processes fail.
[0132] The compensation instruction must contain all the information required to execute the compensation operation. First is the payment transaction number, which serves as a unique identifier for locating the original transaction. This number allows for precise identification of the transaction record to be revoked within the payment platform. Second is the reversal interface address, the interface provided by the payment platform for executing fund return operations. Different payment platforms may have different reversal interface specifications, therefore this address needs to be dynamically configured according to the specific payment platform being used.
[0133] The reversal amount field records the specific amount to be refunded, including details of amounts transferred from public accounts and deducted from personal accounts, ensuring that the compensation operation accurately restores the fund status of each account. The version number field has an initial value of 1, consistent with the version number in the transaction state machine instance, used to implement idempotency control for the compensation operation. The pending execution status indicator indicates that the compensation instruction is currently in a pending execution state and has not yet been actually triggered for execution.
[0134] The compensation instruction can also include other auxiliary information, such as the compensation instruction creation time, maximum number of retries, and retry interval strategy, to guide the behavior of the compensation execution engine. The timing of constructing the compensation instruction is crucial; it must be completed before initiating a payment request to the payment platform. This ensures that even if a system failure occurs immediately after the payment request is sent, the compensation instruction has already been securely and persistently stored, guaranteeing that funds can be refunded later and preventing serious problems such as funds being deducted but untraceable and unrecoverable.
[0135] Writing payment compensation instructions to the compensation instruction ledger using a write-ahead log (WAP) approach is a key technology for ensuring the reliability of the compensation mechanism. The core idea of WAP is to write the operation intent into persistent storage in log form before executing the actual business operation, ensuring that even if a failure occurs during the operation, recovery or rollback can be achieved through the log.
[0136] The compensation instruction ledger is implemented using an append-only log file, a design with several advantages. First, append-only operations avoid the disk seek overhead of random writes, fully utilizing the sequential write performance of the disk and maintaining high write throughput even in high-concurrency scenarios. Second, append-only mode inherently supports data immutability; each compensation instruction, once written, becomes part of the historical record, providing a reliable basis for auditing and problem tracing.
[0137] When writing compensation instructions to the ledger, the instruction object must first be serialized into a byte stream. Various serialization formats can be used, requiring a trade-off between readability and storage efficiency. The serialized data is appended to the end of the log file, recording the offset and length of the log entry for easy subsequent retrieval.
[0138] After a write operation is complete, the data may still reside in the operating system's file buffer and not yet actually written to the persistent storage medium on the disk. Therefore, it's necessary to call the file system's synchronization interface to force the data in the buffer to be flushed to the disk; this process is called disk flushing. The disk flushing operation waits for the disk controller to confirm that the data has been written to the physical medium before returning a flush confirmation signal. Only after receiving the flush confirmation signal can it be ensured that the compensation instructions have been safely and persistently stored, so that even if a power outage or system crash occurs at this point, the compensation instructions will not be lost. This pattern of writing logs first and then executing business operations ensures that recovery can be achieved through logs under any abnormal circumstances, which is a crucial guarantee for the reliability of distributed systems.
[0139] Upon receiving the confirmation signal for the data flush, it indicates that the compensation instruction has been securely and persistently stored. Only then can the actual payment request operation be executed with confidence. This order of persisting the compensation instruction first and then executing the business operation ensures that even if any anomalies occur during the payment request process, funds can be refunded through the persisted compensation instruction.
[0140] The step of synchronously initiating a payment request to the payment platform through the payment settlement interface is described in detail in step S120, including constructing payment request data, calling the payment interface, and waiting for the payment result to return. Simultaneously with initiating the payment request, the state of the transaction state machine instance needs to be immediately updated from the pending state to the processing state, indicating that the transaction has entered the actual payment processing stage.
[0141] State update operations must be completed atomically, updating both the state identifier and the state entry timestamp simultaneously to ensure the accuracy and traceability of state changes. The "processing" state is a critical state in the transaction lifecycle. In this state, the payment request has been sent to the payment platform and is awaiting the platform's completion of the fund transfer and return of the result. Transactions in the "processing" state require special attention because delays in obtaining a clear result may occur due to network timeouts, payment platform response delays, or other reasons. Therefore, monitoring and handling through timeout detection mechanisms are necessary.
[0142] To address potential anomalies in a distributed environment, a scheduled inspection task is needed to continuously monitor all transaction state machine instances. This task is a background, timed program that executes periodically at preset intervals, such as scanning every 30 seconds or 1 minute. The core responsibility of this task is to identify transactions in abnormal or timeout states and trigger appropriate compensation or recovery processes.
[0143] First, the inspection task scans all transaction state machine instances, identifying those in the "processing" state whose dwell time exceeds a preset timeout threshold. The normal duration of the "processing" state should be between several seconds and tens of seconds. If a transaction remains in the "processing" state for longer than the preset threshold, such as more than 5 minutes, it is likely due to a payment platform response timeout or network communication anomalies. For such transactions, it is necessary to proactively query the payment platform to obtain the actual payment result, or directly trigger a compensation process to refund funds, preventing the transaction from remaining in an uncertain state for an extended period.
[0144] Secondly, the inspection task will also identify instances where the transaction status is successful but the dwell time exceeds a preset self-payment timeout threshold. When the payment platform's payment operation is successful, the transaction status will be updated to successful, and the self-payment process should be triggered immediately. However, if a system anomaly or process interruption prevents the self-payment from being initiated in a timely manner, the transaction will remain in the successful state for an extended period and cannot proceed. By setting a self-payment timeout threshold, such as 2 minutes, the inspection task can identify these abnormal transactions and re-trigger the self-payment process or execute compensation operations.
[0145] For all identified abnormal transactions, the inspection task triggers an asynchronous compensation process. Based on the payment transaction number, the corresponding compensation instruction is retrieved from the compensation instruction ledger and submitted to the compensation execution engine for processing. The compensation execution engine then initiates a fund return request to the payment platform based on the reversal interface address and reversal amount in the compensation instruction, completing the compensation operation. This entire inspection and compensation mechanism forms an automated closed-loop anomaly handling system, ensuring that transactions ultimately reach a consistent state even under various abnormal circumstances, effectively safeguarding fund security and business continuity.
[0146] This implementation method constructs a complete distributed transaction guarantee system by introducing a transaction state machine, write-ahead logs, and a periodic inspection mechanism. The transaction state machine clearly defines the state and transition rules of a transaction at different stages, making the management of the transaction process more standardized and controllable. The version number mechanism effectively solves the idempotency problem in a distributed environment, preventing duplicate fund refunds caused by repeated execution of compensation operations.
[0147] The write-ahead logging method ensures the reliable persistence of compensation instructions, preventing the loss of critical compensation information even in the event of system failure and providing a reliable basis for subsequent recovery operations. The order of persisting compensation instructions first and then executing business operations guarantees fund refunds under any abnormal circumstances, effectively avoiding the risk of funds being deducted without traceability.
[0148] Scheduled inspection tasks provide proactive anomaly detection and handling capabilities, enabling timely identification of transactions that remain in an abnormal state for extended periods and automatically triggering compensation processes. Anomaly handling can be completed without manual intervention, significantly improving the system's self-healing capabilities and reliability. Compared to traditional methods relying on manual monitoring and anomaly handling, this solution automates and intelligently handles anomalies, significantly reducing operational costs and the risk of human error, and providing highly reliable technical support for distributed transaction processing in hybrid payment scenarios.
[0149] like Figure 2 As shown, in one embodiment of this example, the payment compensation instruction is written to the compensation instruction ledger using a write-ahead log method, and then awaits confirmation by disk flushing. This includes the following steps:
[0150] S510. Serialize the payment compensation instruction into a log record, and append the log record to the end of the append-only log file corresponding to the compensation instruction ledger.
[0151] S520: Call the file system synchronization interface to force the log records in the append-only log file to be flushed from the memory buffer to the persistent storage medium on the disk.
[0152] S530: After the flashing process is complete, a flash confirmation signal is generated.
[0153] S540. Periodically create checkpoints, scan the append-only log files corresponding to the compensation instruction ledger, apply the compensation instructions with the status of "completed" to the main status database, and mark the corresponding log records in the main status database as cleanable.
[0154] Serializing payment compensation instructions into log records is the first step in a write-ahead logging mechanism. This requires converting the compensation instruction objects in memory into a persistent byte sequence. The serialization process necessitates choosing a suitable serialization format, with various data representation methods being common. Different formats offer advantages and disadvantages in terms of readability and performance. Formats with good readability facilitate debugging and troubleshooting but have relatively lower storage efficiency; while binary formats, although less readable, produce smaller serialized data and faster parsing speeds, making them suitable for high-performance scenarios. In practice, a trade-off between readability and performance can be struck based on business requirements.
[0155] In addition to the data from the compensation instructions themselves, the serialized log records also need to include metadata information, such as the unique identifier of the log record, creation timestamp, and data checksum. The data checksum is calculated using an appropriate algorithm and is used to verify the integrity of the data when reading the log, preventing data inconsistencies caused by disk errors or data corruption.
[0156] The serialized log records are appended to the end of the append-only log file corresponding to the compensation instruction ledger. Appending is a sequential I / O operation, fully leveraging the sequential read / write performance of the disk. In high-concurrency scenarios, multiple threads may attempt to write to the log file simultaneously, requiring file locks or write queue mechanisms to ensure the atomicity and order of write operations. After the write operation is complete, the data first enters the operating system's file buffer. At this point, the data is still in memory and has not yet been actually written to disk; therefore, subsequent flush operations are needed to ensure data persistence.
[0157] Calling the file system synchronization interface is a crucial step in ensuring data is truly persisted to disk. To improve I / O performance, operating systems typically cache file write operations in memory's page cache before flushing them to disk in batches at appropriate times. However, this delayed write mechanism can lead to data loss in the event of a system crash or power outage, as data in memory is volatile.
[0158] To ensure reliable data persistence, it is necessary to actively call the synchronization interface provided by the file system to force the data in the memory buffer to be immediately flushed to the persistent storage medium on disk. Common synchronization interfaces will block the current thread until the data has been completely written to disk and confirmed by the disk controller before returning. These interfaces not only flush file data, but may also flush file metadata, such as file size and modification time, to ensure the integrity of the file state.
[0159] The execution time of a flush operation depends on the performance characteristics of the disk. For mechanical hard drives, due to seek time and rotational latency, flush latency is typically between several milliseconds and tens of milliseconds. Solid-state drives (SSDs), using flash memory, can reduce flush latency to the hundreds of microseconds level. In high-concurrency scenarios, frequent flush operations can become a performance bottleneck. A batch flush strategy can be used, accumulating multiple log records and flushing them all at once, achieving a balance between reliability and performance.
[0160] After the write operation is complete, the file system synchronization interface will return a success status, at which point a disk flush confirmation signal will be generated to notify the upper-layer business logic. The disk flush confirmation signal indicates that the compensation instructions have been safely persisted to the disk. Even if a system failure or power outage occurs at this time, the data will not be lost and can be read from the log file and processed again after the system recovers.
[0161] The disk flush confirmation signal can be generated by setting a flag, triggering an event, or calling a callback function; the specific implementation depends on the system architecture. Upon receiving the disk flush confirmation signal, as described in step S440, the operation of initiating a payment request to the payment platform will continue, and the transaction state machine will be updated. This order of persistence followed by execution ensures the recoverability of the operation and is the core mechanism for achieving the reliability of a distributed system.
[0162] As the system continues to run, the append-only log file corresponding to the compensation instruction ledger will grow continuously. Without regular cleanup, this log file will consume a significant amount of disk space and also affect log retrieval efficiency. Therefore, it is necessary to periodically create checkpoints to organize and clean the log files. The checkpoint mechanism is a widely used technique in database systems. It achieves safe log truncation by periodically synchronizing the state in memory to persistent storage and marking processed log records.
[0163] The process of creating a checkpoint first requires scanning the append-only log file corresponding to the compensation instruction ledger, reading all log records, and identifying compensation instructions with a completed status. A completed status indicates that the compensation operation corresponding to the instruction has been successfully executed, or the corresponding transaction has been completed normally and does not require compensation. The lifecycle of these compensation instructions has ended and they can be removed from the activity log.
[0164] The identified completed compensation instructions are applied to the main state database, which updates the final state of the corresponding transaction and records information such as the execution result and completion time of the compensation operation. The main state database is the core data storage of the system, containing complete state information for all transactions. By applying state changes from the logs to the main state database, consistency between log data and state data is achieved.
[0165] Mark the corresponding log records as cleanable in the master state database. This indicates that these log records have been safely applied to the master state database and no longer need to be retained in the log files. Log records marked as cleanable can be physically deleted during the next log truncation operation, freeing up disk space. Log truncation operations need to be performed carefully to ensure that only log records that have been applied to the master state database and are no longer needed are deleted, avoiding data loss due to accidental deletion.
[0166] The frequency of checkpoint creation needs to be adjusted based on system load and disk space capacity. Creating checkpoints too frequently will increase system overhead, while creating them too sparsely will result in excessively large log files. By creating checkpoints regularly, the manageability of log files is ensured, and the system can resume recovery from the most recent checkpoint during fault recovery, thus shortening recovery time.
[0167] This implementation method ensures reliable persistence and efficient management of compensation instructions through a detailed write-ahead log mechanism. The serialization and append-only mechanisms fully utilize the sequential I / O performance of the disk, maintaining high write throughput even under high concurrency scenarios. Forced disk flushing ensures true data persistence, preventing the loss of critical compensation information even in extreme system failure scenarios, providing a solid guarantee for the reliability of distributed transactions.
[0168] The disk flush confirmation signal mechanism enables precise coordination between persistent operations and business operations, ensuring that the actual payment operation is only executed after the data has been securely written to disk, thus avoiding the risk of data inconsistency caused by incorrect operation sequence. The checkpoint mechanism effectively solves the problem of infinite log file growth. By periodically applying completed compensation instructions to the master state database and cleaning up the logs, it ensures reasonable utilization of disk space and improves the efficiency of log retrieval and recovery.
[0169] The entire write-ahead log mechanism achieves a good balance between reliability, performance, and maintainability, providing industrial-grade reliability assurance for distributed transaction processing in hybrid payment scenarios and significantly reducing financial risks and business interruption risks caused by system failures.
[0170] In one embodiment of this example, before initiating a reverse transaction request to the payment platform when the payment result is successful and the self-paid payment result is unsuccessful, the following steps are also included:
[0171] S610. Update the state of the transaction state machine instance to the cash failure pending compensation state.
[0172] S620. Retrieve payment compensation instructions with a pending execution status from the compensation instruction ledger based on the payment transaction number;
[0173] S630. Determine the status of the fuse corresponding to the positive interface address;
[0174] S640. If the fuse is in the open state, put the payment compensation instruction into the delay queue and terminate the current compensation execution.
[0175] S650. When the circuit breaker is in a closed or semi-open state, execute the step of initiating a reverse transaction request to the payment platform.
[0176] When a payment platform's payment result is successful but the user's cash payment result is unsuccessful, the transaction state machine instance needs to be updated immediately, changing its state from "processing" or "successful" to "cash failure pending compensation." The "cash failure pending compensation" state is a special intermediate state that clearly indicates an anomaly in the current transaction: funds in the public and personal accounts have been successfully deducted, but the user's cash payment portion failed to complete, requiring a compensation operation to revert the deducted funds.
[0177] The status update operation needs to be completed atomically, updating fields such as the status identifier, status entry timestamp, and status change reason. The status entry timestamp records the precise time when the transaction entered the cash failure pending compensation status, which is crucial for subsequent timeout monitoring and audit traceability. The status change reason field records in detail the specific reasons that led to the status change, such as "self-payment channel returned payment failure" or "user canceled self-payment operation," which helps with subsequent problem analysis and business optimization.
[0178] Status update operations also need to be recorded in the transaction's historical status change log to form a complete status transition chain, facilitating the tracing of the transaction's entire lifecycle. By accurately identifying the transaction status as a cash failure pending compensation state, various components in the system can clearly identify transactions that require compensation operations, providing clear triggering conditions for subsequent automated compensation processes.
[0179] After confirming that a compensation operation is required for the transaction, the corresponding payment compensation instruction needs to be retrieved from the compensation instruction ledger. As mentioned above, before initiating a payment request to the payment platform, the payment compensation instruction has been pre-constructed and persistently stored in the compensation instruction ledger. The retrieval operation uses the payment transaction number as the query condition, because the payment transaction number is a unique identifier throughout the entire transaction process and can accurately locate the corresponding compensation instruction record.
[0180] The compensation instruction ledger is stored in an append-only log file format. Retrieval requires reading records from the log file and performing matching. To improve retrieval efficiency, an index mapping table of payment transaction numbers to log file offsets can be maintained in memory. This index allows for quick location of the target record within the log file, avoiding the performance overhead of a full file scan.
[0181] The search criteria also require specifying the status of the compensation instruction as "pending execution," because the same payment transaction number may correspond to multiple compensation instruction records, including different statuses such as executed, executing, and pending execution. Only compensation instructions with the status of "pending execution" are valid instructions that need to be executed. The retrieved payment compensation instructions contain all the information required to execute the compensation operation, including key fields such as the reversal interface address, reversal amount, and version number. This information will be used in the subsequent compensation execution process.
[0182] Before performing the compensation operation, it is necessary to determine the circuit breaker status corresponding to the reversing interface address. A circuit breaker is a protection mechanism used to prevent the propagation of faults and is widely used in distributed systems. When an external service or interface experiences frequent failures, the circuit breaker automatically switches to the open state, temporarily blocking calls to that service and preventing a large number of failed requests from consuming system resources and increasing the burden on the external service.
[0183] Each callback interface address corresponds to an independent circuit breaker instance. The circuit breaker maintains call statistics for that interface, including metrics such as the number of successful requests, the number of failed requests, and the average response time. The circuit breaker has three states: closed, open, and half-open. In the closed state, all requests pass normally, and the circuit breaker tracks the success and failure of requests. When the failure rate exceeds a preset threshold, for example, more than 50 out of the most recent 100 requests fail, the circuit breaker switches to the open state.
[0184] In the open state, all requests are directly rejected and not actually sent to the external service, avoiding unnecessary waiting and resource consumption. The open state lasts for a period of time, called the circuit breaker duration, such as 30 seconds or 1 minute. After the circuit breaker duration ends, the circuit breaker switches to a half-open state, allowing a small number of requests to pass through to probe whether the external service has returned to normal. If these probe requests succeed, the circuit breaker switches back to the closed state and resumes normal calls; if the probe requests still fail, the circuit breaker switches back to the open state and continues to wait for the next circuit breaker duration. Determining the circuit breaker state requires querying the circuit breaker manager to obtain the current state of the circuit breaker corresponding to the current interface.
[0185] When the fuse is determined to be in the open state, it indicates that the reversing interface is currently unavailable or in a high-failure-rate state. In this case, compensation operations should not be performed immediately, as this is likely to fail, wasting system resources and increasing the burden on external services. Instead, the compensation instruction should be placed in a delayed queue, and the current compensation execution should be terminated.
[0186] A delayed queue is a special type of message queue where messages are not consumed immediately but become consumable only after a specified delay. When placing a compensation instruction into the delayed queue, an appropriate delay time needs to be set. This delay time should be slightly longer than the circuit breaker's tripping duration. For example, if the tripping duration is 1 minute, the delay time can be set to 90 seconds to ensure that when the compensation instruction is retrieved and executed again, the circuit breaker has entered a semi-open or closed state, meeting the conditions for execution.
[0187] While the compensation instruction is waiting in the delay queue, it does not consume resources of the compensation execution thread, nor does it put pressure on external services. After the delay time expires, the compensation instruction is automatically retrieved from the delay queue and re-enters the compensation execution process. At this point, the circuit breaker status is checked again. If it is still open, it is added back to the delay queue; if it has switched to a closed or semi-open state, the actual compensation operation is executed. Terminating the current compensation execution means that the current compensation process ends here, and the subsequent step of initiating a reverse transaction request to the payment platform will not continue, avoiding invalid calls while the circuit breaker is open.
[0188] When the circuit breaker is determined to be in a closed or partially open state, it indicates that the fault-correcting interface is currently available or in the process of recovery, and a compensation operation can be attempted. In the closed state, the fault-correcting interface is functioning normally, and compensation requests have a high probability of success. In the partially open state, the fault-correcting interface may be recovering from a failure, allowing a small number of requests to pass through to verify whether the service has returned to normal. Performing a compensation operation in this case is both a business necessity and a probe of the health status of external services.
[0189] The step of initiating a reverse transaction request to the payment platform is described in detail in step S210, including constructing the reverse transaction request, calling the reversal interface, and waiting for the reversal result to return. During execution, the circuit breaker's statistics need to be updated synchronously. If the reverse transaction request succeeds, the circuit breaker's success count is increased to reduce the failure rate; if the reverse transaction request fails, the circuit breaker's failure count is increased. When the failure rate exceeds a threshold, the circuit breaker's state may be triggered to change. By combining the circuit breaker mechanism with the compensation execution process, adaptive protection and automatic recovery are achieved in the event of external service failures. This ensures the final execution of the compensation operation while avoiding invalid calls and resource waste during the failure period.
[0190] This implementation method constructs an intelligent compensation execution process by introducing precise status identification, circuit breaker protection, and a delayed queuing mechanism. Accurately updating the transaction status to a cash failure pending compensation state allows the system to clearly identify transactions requiring compensation, providing clear triggering conditions for automated processing. Retrieving compensation instructions from the compensation instruction ledger ensures the completeness and accuracy of the information required for compensation operations.
[0191] The introduction of the circuit breaker mechanism effectively prevents the cascading failure effect when external services fail. When the faulty interface experiences a high failure rate, the circuit breaker automatically blocks the sending of compensation requests, avoiding the consumption of system resources and further impact on external services by a large number of failed requests. The delayed queue mechanism enables intelligent delayed execution of compensation operations. Compensation instructions are temporarily stored while the circuit breaker is open, and automatically retried after the service is restored. This ensures the final execution of the compensation operation while avoiding unnecessary retry overhead.
[0192] Compared to a simple immediate retry mechanism, this scheme significantly improves the success rate of compensation operations and the overall stability of the system. When external services experience temporary failures, it can automatically wait and complete compensation after the service is restored without manual intervention, greatly enhancing the system's self-healing ability and reliability.
[0193] Reference Figure 3 In one embodiment of this example, initiating a reverse transaction request to the payment platform includes the following steps:
[0194] S710, Extract the version number from the payment compensation instruction;
[0195] S720. Construct a reverse transaction request, which includes a payment serial number, a reversal amount, and a version number;
[0196] S730. Send the reverse transaction request to the payment platform. The payment platform is used to maintain a compensation status vector for each transaction. The compensation status vector is used to record the compensation version number that has been successfully executed.
[0197] Specifically, if the version number in the reversal request is greater than the compensation version number recorded in the compensation status vector, the payment platform will perform a reversal operation and update the compensation version number in the compensation status vector after the reversal is successful; if the version number in the reversal request is less than or equal to the compensation version number recorded in the compensation status vector, the payment platform will directly return a successful reversal response.
[0198] Extract the version number from the payment compensation instruction. As mentioned above, the version number is initialized to 1 when the transaction state machine instance is created, and this version number is included in the compensation instruction when it is constructed. The version number is a monotonically increasing integer used to identify the number of times the compensation operation has been executed or attempted.
[0199] In distributed systems, due to network instability, service timeouts, message retransmissions, and other reasons, the same compensation instruction may be executed or sent to the payment platform multiple times. Without a version number mechanism, duplicate compensation requests could lead to funds being returned multiple times, causing serious financial errors and business chaos. A version number mechanism, by assigning a unique version identifier to each compensation operation, enables the payment platform to identify and filter duplicate compensation requests, ensuring that the compensation operation for the same transaction is actually executed only once, even if multiple identical compensation requests are received.
[0200] Extracting the version number from the compensation instruction is very simple; it only requires reading the version number field from the compensation instruction object. The extracted version number will be included in the reverse transaction request in subsequent steps, serving as a crucial basis for the payment platform to determine whether to execute the actual reversal operation. The version number extraction operation must ensure accuracy to avoid version number mismatches caused by reading errors.
[0201] Constructing a reverse transaction request requires organizing the key information needed for the compensation operation into a request data structure that conforms to the payment platform's interface specifications. A reverse transaction request is an instruction to the payment platform to initiate a fund return operation; it must contain sufficient information so that the payment platform can accurately locate the original transaction and execute the corresponding reversal operation.
[0202] First, the reverse transaction request must include a payment transaction number, which is a unique identifier for the original payment transaction. As mentioned above, the payment transaction number is generated at the start of the transaction and persists throughout the entire transaction process. The payment platform can use the payment transaction number to accurately locate the original transaction record that needs to be reversed in its transaction record database, including complete transaction details such as transaction amount, transaction time, and account information.
[0203] Secondly, the reverse transaction request must include a reversal amount, which is the total amount of funds to be refunded. The reversal amount should equal the sum of the amount transferred from the public account and the amount deducted from the personal account in the original transaction, ensuring that all deducted funds are fully refunded. When constructing the reversal amount, it needs to be accurate to the cent to avoid incomplete refunds due to issues with monetary precision.
[0204] Secondly, the reverse transaction request must include a version number extracted from the compensation instruction; this version number is a core parameter for implementing idempotency control. In addition to these three core fields, the reverse transaction request can also include other auxiliary information, such as a description of the reversal reason, a request timestamp, and the requester's identifier. This information helps the payment platform with auditing and problem tracing. The completed reverse transaction request needs to undergo data format validation to ensure that all required fields are filled in and formatted correctly, avoiding request rejection due to incomplete or incorrectly formatted data.
[0205] Sending the reverse transaction request to the payment platform is the execution phase of the compensation operation. This requires transmitting the request data to the payment platform's reversal interface via network communication. The transmission process must adhere to the communication protocols and security standards stipulated by the payment platform, typically employing encrypted transmission to ensure the security of the request data during transmission.
[0206] Before sending a request, the request data needs to be signed. The request content is digitally signed using a pre-configured key or certificate. After receiving the request, the payment platform will verify the validity of the signature, confirm the authenticity of the request source and the integrity of the data, and prevent the request from being tampered with or forged.
[0207] Upon receiving a reverse transaction request, the payment platform executes a series of verification and processing steps. First, the platform verifies the request's legitimacy, including verifying the signature, checking the requester's permissions, and validating the payment transaction number. After successful verification, the platform uses the payment transaction number to query the original transaction record to confirm whether the transaction exists and is in a reversible state.
[0208] The payment platform maintains a compensation status vector for each transaction. This vector is a data structure used to record information about the compensation operations that have been successfully executed for that transaction. The most crucial field in the compensation status vector is the executed compensation version number, which records the version number of the most recently successfully executed compensation operation. When the payment platform receives a new reversal request, it compares the version number in the request with the compensation version number recorded in the compensation status vector, and decides whether to execute the actual reversal operation based on the comparison result.
[0209] Specifically, the payment platform's processing logic falls into two categories. In the first category, if the version number in the reversal request is greater than the compensation version number recorded in the compensation status vector, it indicates that this is a new compensation request that has not yet been executed. For example, if the version number recorded in the compensation status vector is 0, it means that no compensation operation has been performed on the transaction, while the version number in the reversal request is 1, thus satisfying the greater than condition.
[0210] In this situation, the payment platform will perform the actual reversal operation, which includes returning funds transferred from the public account to the original public account, restoring the amount deducted from the personal account to the user's account, and generating the corresponding reversal transaction record. The reversal operation needs to ensure atomicity, that is, either all accounts' funds are successfully returned, or all fail, to avoid an inconsistent state where some accounts are returned while others are not.
[0211] After a successful reversal, the payment platform updates the compensation status vector for that transaction, replacing the recorded compensation version number with the version number from the reversal request. For example, updating it to 1 indicates that the compensation operation with version number 1 has been successfully executed. Simultaneously, the payment platform returns a successful reversal response, which includes detailed information such as the reversal transaction serial number, refund amount details, and operation completion time.
[0212] In the second scenario, if the version number in the reversal request is less than or equal to the compensation version number recorded in the compensation state vector, it indicates that this is a duplicate compensation request, and a compensation operation with the same version number has already been successfully executed. For example, if the version number recorded in the compensation state vector is 1, and the version number in the received reversal request is also 1, then the equality condition is met, meaning that a compensation operation with version number 1 has already been executed.
[0213] In this situation, the payment platform will not perform an actual reversal operation because the funds have already been returned in the previous compensation operation. Performing it again would result in a duplicate refund. Instead, the payment platform will directly return a successful reversal response, with the same content as the response returned during the first execution, including the same reversal transaction number and refund amount. This approach ensures the idempotency of the compensation operation; that is, no matter how many times the same compensation request is sent, the final effect is equivalent to executing it only once, and the funds will only be refunded once, preventing duplicate refunds.
[0214] By combining version number mechanisms and compensation state vectors, the payment platform can accurately identify and filter duplicate compensation requests, ensuring business correctness while also improving the system's robustness and fault tolerance.
[0215] In practice, the design of the compensation state vector can include more information, such as the initial compensation execution time, the number of compensation executions, and the reception time of each compensation request. This information helps in more granular monitoring and auditing. Version number comparison operations need to be performed within a database transaction to ensure the atomicity of comparison and update operations and avoid race conditions caused by concurrent requests. The payment platform can also set a maximum allowed version number to prevent abnormal version number growth due to system errors. The entire reverse transaction request processing flow requires comprehensive logging, including detailed information such as request reception time, version number comparison results, whether an actual reversal was performed, and operation results, providing a basis for subsequent troubleshooting and auditing.
[0216] This implementation combines a version number mechanism and a compensation state vector to achieve precise idempotency control of compensation operations in a distributed environment. The version number provides a unique identifier for each compensation operation, enabling the payment platform to accurately distinguish between new and duplicate compensation requests. The compensation state vector, serving as a state record on the payment platform side, persistently stores the compensation execution history of each transaction, providing a reliable basis for idempotency judgment.
[0217] Through a version number comparison mechanism, the payment platform can intelligently decide whether to execute the actual reversal operation. For new compensation requests, funds are returned; for duplicate compensation requests, a success response is returned directly, avoiding the serious error of duplicate fund returns. This design effectively solves the risk of duplicate operation execution caused by common problems in distributed systems such as network retransmission, timeout retries, and message duplication. It ensures that, regardless of any abnormal circumstances, the compensation operation for the same transaction will only be executed once, thus reliably guaranteeing fund security.
[0218] Compared to traditional idempotency implementations based on distributed locks or unique constraints, the version number mechanism is more lightweight and efficient. It requires no additional lock contention or database constraint checks, and idempotency can be determined through simple numerical comparisons, maintaining good performance even in high-concurrency scenarios. Furthermore, this mechanism offers excellent traceability. By recording version numbers and compensation state vectors, the compensation history of each transaction can be clearly traced, providing comprehensive data support for auditing and troubleshooting, significantly improving the system's maintainability and reliability.
[0219] In one embodiment of this example, after initiating a reverse transaction request to the payment platform, the following steps are also included:
[0220] S810. Upon receiving a successful reversal response from the payment platform, update the status of the payment compensation instruction in the compensation instruction ledger to the completed status and update the status of the transaction state machine instance to the revoked status.
[0221] S820. Upon receiving a reversal failure response from the payment platform, record the number of compensation failures and update the failure counter of the circuit breaker.
[0222] S830. Calculate the next retry interval based on the number of compensation failures;
[0223] S840. When the failure counter reaches the preset failure threshold, set the fuse state to the open state and set the fuse duration.
[0224] S850. After the fuse duration ends, set the fuse state to a semi-open state.
[0225] The calculation of the next retry interval based on the number of compensation failures includes:
[0226] Number of times compensation was not obtained;
[0227] According to the formula T=T0×2 n Calculate the next retry interval, where T is the next retry interval, T0 is the base interval, and n is the number of compensation failures;
[0228] If the next retry interval exceeds the preset maximum interval, the next retry interval will be set to the preset maximum interval.
[0229] After the next retry interval arrives, the step of initiating a reverse transaction request to the payment platform through the payment settlement interface will be executed again.
[0230] When a successful reversal response is received from the payment platform, it indicates that the compensation operation has been successfully completed and the funds have been correctly returned to the corresponding account. At this point, the relevant status information in the system needs to be updated to mark the completion of the compensation process.
[0231] First, the status of the corresponding payment compensation instruction in the compensation instruction ledger needs to be updated to "completed". When a compensation instruction is created, its status is "pending execution". After the compensation operation is successfully executed, its status needs to be updated to "completed", indicating that the lifecycle of the compensation instruction has ended and it no longer needs to be executed repeatedly.
[0232] The status update operation requires appending a status change record to the log file corresponding to the compensation instruction ledger. This record includes the unique identifier of the compensation instruction, the new status, the status change time, and the reverse transaction serial number. Since the compensation instruction ledger only appends to the log file and cannot directly modify already written records, status updates are implemented by appending a new record containing the updated status information. When reading a compensation instruction, all relevant records are read in chronological order, with the latest record used to determine the current status of the compensation instruction.
[0233] Simultaneously, the transaction state machine instance needs to be updated to the revoked state, indicating that the transaction has completed the full compensation process, all deducted funds have been refunded, and the transaction has ultimately ended in revocation. The revoked state is a final state in the transaction lifecycle, and transactions in this state no longer require any further processing. The state update operation needs to be persistently stored in the database and recorded in the transaction's historical state change log, forming a complete state transition chain. The updated state information will be used in scenarios such as business statistics, financial reconciliation, and audit traceability to ensure the integrity and accuracy of transaction data.
[0234] When a reversal failure response is received from the payment platform, it indicates that the compensation operation failed to execute successfully. This may be due to reasons such as a temporary malfunction of the payment platform, abnormal network communication, or the original transaction status not allowing for reversal. In this case, it is necessary to record relevant information about the compensation failure to provide a basis for subsequent retry and circuit breaker decisions.
[0235] First, it's necessary to record the number of compensation failures. This count represents the cumulative number of failed compensation operations for the current transaction. The number of failures can be stored in the transaction state machine instance and persisted as part of the transaction state. Each time a compensation operation fails, this counter is incremented, and details such as the time of failure, the reason for failure, the error code returned by the payment platform, and the error message are recorded. This information is crucial for subsequent problem analysis and troubleshooting, helping to pinpoint the root cause of the compensation failures.
[0236] Simultaneously, the circuit breaker's failure counter needs to be updated. This counter is a global statistical indicator for the compensation interface, recording the number of failures of that interface within a certain time window. As mentioned above, the circuit breaker is used to monitor the health status of external services, triggering circuit breaker protection when the failure rate exceeds a threshold. The update operation of the failure counter needs to be thread-safe because in high-concurrency scenarios, multiple compensation operations may fail simultaneously and update the counter. Circuit breakers typically employ a sliding time window mechanism, only counting the number of failures within a recent period, such as the last minute or the last 100 requests. Expired failure records are automatically cleared to avoid the impact of historical failures on the current circuit breaker decision.
[0237] Calculating the next retry interval based on the number of compensation failures is a crucial step in implementing an intelligent retry strategy. First, the number of compensation failures for the current transaction is obtained; this number has already been recorded and updated in the preceding steps. Then, the next retry interval is calculated using the exponential backoff algorithm, with the formula T = T0 × 2. n .
[0238] The base time interval T0 is a preset constant, such as 1 second or 2 seconds, representing the waiting time for the first retry. The core idea of the exponential backoff algorithm is that the retry interval increases exponentially with the number of failures, avoiding frequent invalid retries during service failures and allowing sufficient time for external service recovery.
[0239] For example, if the base time interval T0 is 2 seconds, when n = 1, the retry interval T = 2 × 2 1 = 4 seconds; when n = 2, the retry interval T = 2 × 2 2= 8 seconds. This exponentially increasing retry interval effectively reduces the pressure on the system to external services, and also conforms to the recovery characteristics of most transient failures.
[0240] However, exponential backoff algorithms can lead to retry intervals growing indefinitely, potentially resulting in wait times of hours or even days when there are many failures. This is unacceptable for business scenarios requiring timely compensation. Therefore, a preset maximum time interval needs to be set as an upper limit, such as 5 minutes or 10 minutes. If the calculated retry interval exceeds the preset maximum time interval, the next retry interval should be forcibly set to the preset maximum time interval to avoid excessively long waiting times.
[0241] For example, if the maximum time interval is preset to 300 seconds, and the calculated retry interval is 512 seconds, the actual retry interval used will be limited to 300 seconds. This capped exponential backoff strategy achieves a good balance between fast retries and avoiding overload, enabling rapid recovery from temporary failures while avoiding resource waste during persistent failures.
[0242] After calculation, the compensation instruction is placed back into the delay queue, with the delay time set to the calculated retry interval. Upon the next retry interval, the compensation instruction is automatically retrieved from the delay queue, and the steps to initiate a reverse transaction request to the payment platform are repeated, starting a new round of compensation attempts. The retry process continues until compensation is successful or the maximum number of retry attempts is reached.
[0243] After each compensation failure and updating the circuit breaker's failure counter, it is necessary to check whether the failure counter has reached a preset failure threshold. The preset failure threshold is the condition that triggers the circuit breaker to open, and is usually defined in the form of a failure rate or an absolute number of failures. For example, it can be set to "more than 50 failures in the last 100 requests" or "more than 30 failures in the last minute".
[0244] The failure threshold setting needs to be adjusted according to the business characteristics and the stability of external services. If the threshold is too low, the circuit breaker may be too sensitive and trigger the circuit breaker in the event of an occasional failure, affecting normal business. If the threshold is too high, the circuit breaker may be slow to respond and continue to send requests when the service is already seriously faulty, increasing the system load.
[0245] When the failure counter reaches the preset failure threshold, it indicates that the reversal interface is currently in a high failure rate state, and continuing to send requests is likely to result in continuous failures. At this point, the circuit breaker protection mechanism needs to be triggered. Setting the circuit breaker to the open state means that all new compensation requests will be directly rejected and will not actually be sent to the payment platform, thus avoiding the consumption of system resources by invalid requests and further impact on external services.
[0246] Additionally, the circuit breaker duration needs to be set, which defines how long the circuit breaker remains open. This can be set to 30 seconds, 1 minute, or longer. The circuit breaker duration setting needs to consider the typical recovery time of external services, allowing sufficient time for service recovery. Changes to the circuit breaker state need to be logged, including the time the circuit breaker was triggered, the value of the failure counter, and the circuit breaker duration, for subsequent monitoring and analysis.
[0247] The circuit breaker duration is a timer that starts counting when the circuit breaker enters the open state. After the circuit breaker duration ends, it indicates that sufficient recovery time has been given to the external service, at which point it is necessary to probe whether the service has returned to normal. Setting the circuit breaker to a half-open state allows a small number of requests to pass through; these requests are called probe requests and are used to test the current health status of the external service.
[0248] The number of probe requests is typically limited to one or a few to avoid overloading the service again by sending a large number of requests before the service has fully recovered. If the probe request is successful, indicating that the external service has returned to normal, the circuit breaker will switch its state from half-open to closed, resuming normal request processing, while resetting the failure counter and clearing previously accumulated failure records.
[0249] If the probe request fails, indicating that the external service is still in a faulty state, the circuit breaker will immediately switch its state from the half-open state back to the open state, restarting a waiting cycle for the duration of the circuit breaker's interruption, continuing to protect the system from the impact of the faulty service. The half-open state is the key mechanism for the circuit breaker to achieve automatic recovery. Through periodic probes and state transitions, the circuit breaker can automatically deactivate after the external service recovers, without manual intervention, achieving the system's self-healing capability. The entire state transition process of the circuit breaker forms a complete closed loop: closed state, open state, half-open state, closed state or open state, ensuring that the system can respond appropriately under various fault scenarios.
[0250] This implementation method constructs a highly reliable distributed compensation system through sophisticated compensation result processing and an intelligent retry mechanism. Upon successful compensation, the compensation instructions and transaction status are updated promptly to ensure the accuracy and consistency of the system status, providing a reliable basis for subsequent business processing and data analysis. Upon compensation failure, real-time monitoring and intelligent protection of the external service health status are achieved by recording the number of failures and updating the circuit breaker status.
[0251] The exponential backoff retry strategy strikes a good balance between rapid recovery and avoiding overload. It can eventually compensate for temporary failures through multiple retries, while also preventing continuous impact on the failed service by gradually increasing the retry interval. The upper limit design of the retry interval ensures that the compensation operation can be completed within a reasonable time frame, avoiding business delays caused by infinite waiting.
[0252] The circuit breaker mechanism provides system-level protection, automatically triggering to prevent invalid requests from being sent and protecting system resources and external services when a persistent failure occurs in an external service. The semi-open design enables automatic circuit breaker recovery; periodic probing allows for timely circuit breaking after service recovery, resuming normal business processing without manual intervention. Compared to traditional fixed-interval or infinite retries, this solution significantly improves the success rate of compensation operations and the overall stability of the system. It provides intelligent responses in various abnormal scenarios, effectively reducing operational costs and the scope of fault impact, and providing industrial-grade reliability assurance for distributed transaction processing in hybrid payment scenarios.
[0253] This application also provides a real-time digital invoice issuance system based on hybrid payment, including:
[0254] Communication devices are used to establish communication connections with user terminals, payment platforms, multiple payment channels, and digital invoice platforms.
[0255] The processor is configured as follows:
[0256] In response to receiving a pending payment order sent by the user through the user terminal, the system obtains the user's identity information and generates a unique payment transaction number for the pending payment order;
[0257] The payment transaction number is linked to the order to be paid, and a payment request is initiated to the payment platform through the payment settlement interface. The payment request carries the payment transaction number and payment details. The payment platform is used to complete the transfer of funds from the public account and the deduction of funds from the personal account, and returns the payment result.
[0258] If the payment result is successful, initiate a self-payment request asynchronously through the multi-payment channel SDK and receive the self-payment result;
[0259] If both the payment result and the self-funded payment result are successful, the payment result and the self-funded payment result are aggregated to generate a payment success status, and a digital invoice is issued in real time through the digital invoice platform. The digital invoice platform interface carries the payment serial number, the payment amount of the public account, the payment amount of the personal special account, the cash payment amount, and the user's identity information.
[0260] Upon receiving the digital invoice access link from the digital invoice platform, the system binds the digital invoice access link to the order to be paid and sends the payment success status and the digital invoice access link to the user terminal.
[0261] This application also provides a machine-readable storage medium storing instructions that cause a machine to execute the above-described method for real-time issuance of digital invoices based on hybrid payment.
[0262] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this application can take the form of a computer program product embodied on one or more computer-usable storage media (including but not limited to disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0263] This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, as well as combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, create a machine for implementing the flowchart illustrations. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0264] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0265] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0266] In a typical configuration, a computing device includes one or more processors (CPU), input / output interfaces, network interfaces, and memory.
[0267] Memory may include non-persistent memory in computer-readable media, such as random access memory (RAM) and / or non-volatile memory, such as read-only memory (ROM) or flash RAM. Memory is an example of computer-readable media.
[0268] Computer-readable media includes both permanent and non-permanent, removable and non-removable media that can store information using any method or technology. Information can be computer-readable instructions, data structures, modules of programs, or other data. Examples of computer storage media include, but are not limited to, phase-change memory (PRAM), static random access memory (SRAM), dynamic random access memory (DRAM), other types of random access memory (RAM), read-only memory (ROM), electrically erasable programmable read-only memory (EEPROM), flash memory or other memory technologies, CD-ROM, digital versatile optical disc (DVD) or other optical storage, magnetic tape, magnetic disk storage or other magnetic storage devices, or any other non-transferable medium that can be used to store information accessible by a computing device. As defined herein, computer-readable media does not include transient computer-readable media, such as modulated data signals and carrier waves.
[0269] It should also be noted that the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such process, method, article, or apparatus. Unless otherwise specified, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes that element.
[0270] The above are merely embodiments of this application and are not intended to limit the scope of this application. Various modifications and variations can be made to this application by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of this application should be included within the scope of the claims of this application.
Claims
1. A hybrid payment-based real-time digital electronic invoice issuing method, characterized in that, The application comprises the following steps: In response to receiving a user through a user terminal to send the order to be paid, obtain the user identity information, and generate a unique payment serial number for the order to be paid; Create a transaction state machine instance for the payment serial number, and set the initial state of the transaction state machine instance to a to-be-processed state, and initialize the version number to 1; Before synchronously initiating a payment request to the payment platform through a payment settlement interface, a payment compensation instruction is constructed, which includes the payment serial number, a reversal interface address, a reversal amount, a version number and a to-be-executed state identifier; The payment compensation instruction is written into a compensation instruction ledger in a pre-write log mode, and a disk flushing confirmation is waited for, wherein the compensation instruction ledger is implemented in the form of an append-only log file and stored in a disk; After receiving the disk flushing confirmation signal, the payment serial number is bound with the order to be paid, a payment request is synchronously initiated to the payment platform through a payment settlement interface, and the state of the transaction state machine instance is updated to a processing state, wherein the payment request carries the payment serial number and payment details, the payment platform is used to complete public account fund transfer and personal special account deduction, and an account payment result is returned; In the case that the account payment result is successful, a self-payment request is asynchronously initiated through a multi-payment channel SDK, and a self-payment result is received; In the case that the account payment result is successful and the self-payment result is failed, a reverse transaction request is initiated to the payment platform, and the reverse transaction request is used to cancel the payment; In response to receiving the reverse transaction success information returned by the payment platform, the state of the order to be paid is updated to a payment failure state, and the payment failure state is sent to the user terminal; In the case that the account payment result and the self-payment result are both successful, the account payment result and the self-payment result are aggregated, a payment success state is generated, and an electronic invoice is issued in real time through an electronic invoice platform, wherein the electronic invoice platform interface carries the payment serial number, the public account payment amount, the personal special account payment amount, the cash payment amount and the user identity information; In response to receiving the electronic invoice access link returned by the electronic invoice platform, the electronic invoice access link is bound with the order to be paid, and the payment success state and the electronic invoice access link are sent to the user terminal.
2. The method of claim 1, wherein, The electronic invoice is issued in real time through the electronic invoice platform, comprising: According to the payment serial number, the public account payment amount, the personal special account payment amount, the cash payment amount and the user identity information, generate an electronic invoice issuing request data; The electronic invoice issuing request data is sent to the electronic invoice platform, and the electronic invoice platform is used to verify the electronic invoice issuing request data, and generate an electronic invoice after verification is successful.
3. The method of claim 1, wherein, The payment compensation instruction is written into the compensation instruction ledger in a pre-write log mode, and a disk flushing confirmation is waited for, comprising: serializing the payment compensation instruction into a log record, and writing the log record to the end of an append-only log file corresponding to the compensation instruction ledger in an append manner; calling a file system synchronization interface to force flush the log record in the append-only log file from a memory buffer to a persistent storage medium of a disk; generating a flush confirmation signal after the flush is completed; periodically creating a checkpoint, scanning the append-only log file corresponding to the compensation instruction ledger, applying a compensation instruction with a completed state in the append-only log file to a main state database, and marking a corresponding log record in the main state database as a cleanable state.
4. The method of claim 1, wherein, In the case that the account payment result is success and the self-payment result is failure, before initiating the reverse transaction request to the payment platform, further comprising: updating the state of the transaction state machine instance to a cash failure compensation pending state; retrieving the payment compensation instruction identified by the state of the pending state from the compensation instruction ledger according to the payment serial number; determining the fuse state corresponding to the reversal interface address; in the case that the fuse state is an open state, putting the payment compensation instruction into a delay queue and terminating this compensation execution; in the case that the fuse state is a closed state or a semi-open state, executing the step of initiating the reverse transaction request to the payment platform.
5. The method of claim 4, wherein, The step of initiating the reverse transaction request to the payment platform, comprising: extracting the version number from the payment compensation instruction; constructing a reverse transaction request, the reverse transaction request comprising the payment serial number, the reversal amount and the version number; sending the reverse transaction request to the payment platform, the payment platform being configured to maintain a compensation state vector for each transaction, the compensation state vector being configured to record a compensation version number that has been successfully executed; wherein, in the case that the version number in the reversal request is greater than the compensation version number recorded in the compensation state vector, the payment platform performs a reversal operation and updates the compensation version number in the compensation state vector after the reversal is successful; in the case that the version number in the reversal request is less than or equal to the compensation version number recorded in the compensation state vector, the payment platform directly returns a reversal success response.
6. The method of claim 5, wherein, After the step of initiating the reverse transaction request to the payment platform, further comprising: in the case that a reversal success response returned by the payment platform is received, updating the state of the payment compensation instruction in the compensation instruction ledger to a completed state, and updating the state of the transaction state machine instance to a revoked state; in the case that a reversal failure response returned by the payment platform is received, recording a compensation failure number and updating a failure counter of the fuse; calculating a next retry time interval according to the compensation failure number; in the case that the failure counter reaches a preset failure threshold, setting the fuse state to the open state and setting a fuse duration; after the fuse duration ends, setting the fuse state to the semi-open state.
7. A hybrid payment based real time electronic invoice system, characterized in that, comprising: A communication device is configured to establish a communication connection with a user terminal, a payment platform, a multi-payment channel and a digital invoice platform; A processor is configured to: In response to receiving a to-be-paid order sent by a user through a user terminal, obtain user identity information, and generate a unique payment serial number for the to-be-paid order; Create a transaction state machine instance for the payment serial number, and set the initial state of the transaction state machine instance to a to-be-processed state, and initialize the version number to 1; Before synchronously initiating a payment request to the payment platform through a payment settlement interface, a payment compensation instruction is constructed, the payment compensation instruction includes the payment serial number, a reversal interface address, a reversal amount, a version number and a to-be-executed state identifier; The payment compensation instruction is written into a compensation instruction ledger in a pre-write log manner, and a disk flush confirmation is waited for, wherein the compensation instruction ledger is implemented in the form of an append-only log file and stored in a disk; After receiving the disk flush confirmation signal, the payment serial number is bound with the to-be-paid order, a payment request is synchronously initiated to the payment platform through a payment settlement interface, and the state of the transaction state machine instance is updated to a processing state, wherein the payment request carries the payment serial number and payment details, the payment platform is used to complete public account fund transfer and personal special account deduction, and account payment result is returned; In the case that the account payment result is successful, a self-payment request is asynchronously initiated through a multi-payment channel SDK, and a self-payment result is received; In the case that the account payment result is successful and the self-payment result is failed, a reverse transaction request is initiated to the payment platform, the reverse transaction request is used to cancel the payment; In response to receiving reverse transaction success information returned by the payment platform, the state of the to-be-paid order is updated to a payment failure state, and the payment failure state is sent to the user terminal; In the case that the account payment result and the self-payment result are both successful, the account payment result and the self-payment result are aggregated, a payment success state is generated, and a digital invoice is issued in real time through a digital invoice platform, wherein the digital invoice platform interface carries the payment serial number, the public account payment amount, the personal special account payment amount, the cash payment amount and the user identity information; In response to receiving a digital invoice access link returned by the digital invoice platform, the digital invoice access link is bound with the to-be-paid order, and the payment success state and the digital invoice access link are sent to the user terminal.
8. A machine-readable storage medium, characterized in that, The machine readable storage medium has instructions stored thereon for causing a machine to execute a hybrid payment-based digital invoice real-time issuing method according to any one of claims 1 to 6.
Citation Information
Patent Citations
Hybrid payment method and device based on air-railway linkage, and electronic equipment
CN120975786A