From 14b386a5502923781e5160505e14d7cad8e42ce3 Mon Sep 17 00:00:00 2001 From: Ivan Sadovin Date: Fri, 25 Sep 2026 16:42:38 +0300 Subject: [PATCH] feat: paygw_moneta 1.0.0, MONETA.Assistant payment gateway for Moodle --- LICENSE | 674 ++++++++++++++++++ README.md | 180 +++-- amd/build/gateways_modal.min.js | 13 + amd/build/gateways_modal.min.js.map | 1 + amd/src/gateways_modal.js | 60 ++ callback.php | 53 ++ checkout.php | 71 ++ classes/gateway.php | 131 ++++ classes/local/BuyerNotifier.php | 117 +++ classes/local/CmsInfo.php | 47 ++ classes/local/CurrencySymbol.php | 32 + classes/local/ErrorLogLogger.php | 22 + classes/local/GatewayConfig.php | 77 ++ classes/local/GatewayConfigRepository.php | 70 ++ classes/local/Logger.php | 19 + classes/local/Money.php | 117 +++ classes/local/PaymentFormPage.php | 93 +++ classes/local/ReportTable.php | 109 +++ classes/local/callback/CallbackHandler.php | 174 +++++ classes/local/callback/CheckHandler.php | 70 ++ .../local/callback/NotificationHandler.php | 20 + classes/local/callback/PayHandler.php | 153 ++++ classes/local/order/CurrentPrice.php | 51 ++ classes/local/order/Order.php | 79 ++ classes/local/order/OrderFactory.php | 156 ++++ classes/local/order/OrderSnapshot.php | 99 +++ classes/local/order/RejectionReason.php | 32 + classes/local/order/TransactionRepository.php | 253 +++++++ classes/local/order/TransactionStatus.php | 42 ++ classes/local/protocol/AssistantProtocol.php | 39 + .../local/protocol/AssistantTransactionId.php | 53 ++ .../local/protocol/CallbackNotification.php | 151 ++++ classes/local/protocol/CallbackResponse.php | 39 + classes/local/protocol/CheckResponse.php | 75 ++ classes/local/protocol/MntResponseXml.php | 79 ++ classes/local/protocol/PayResponse.php | 56 ++ classes/local/protocol/PaymentRequest.php | 90 +++ classes/local/protocol/PaymentServer.php | 40 ++ classes/local/protocol/ResultCode.php | 49 ++ classes/local/protocol/Signature.php | 106 +++ classes/local/receipt/Client.php | 110 +++ classes/local/receipt/JsonNumber.php | 40 ++ classes/local/receipt/PaymentMethod.php | 23 + classes/local/receipt/PaymentObject.php | 32 + classes/local/receipt/Receipt.php | 156 ++++ classes/local/receipt/ReceiptItem.php | 127 ++++ classes/local/receipt/ReceiptText.php | 38 + classes/local/receipt/Vat.php | 60 ++ classes/privacy/provider.php | 176 +++++ db/install.php | 36 + db/install.xml | 40 ++ db/messages.php | 46 ++ db/upgrade.php | 33 + environment.xml | 10 + lang/en/paygw_moneta.php | 135 ++++ lang/ru/paygw_moneta.php | 135 ++++ pay.php | 65 ++ pix/icon.svg | 4 + pix/img.svg | 9 + report.php | 45 ++ return.php | 72 ++ settings.php | 52 ++ styles.css | 86 +++ templates/payment_form.mustache | 83 +++ version.php | 31 + 65 files changed, 5377 insertions(+), 59 deletions(-) create mode 100644 LICENSE create mode 100644 amd/build/gateways_modal.min.js create mode 100644 amd/build/gateways_modal.min.js.map create mode 100644 amd/src/gateways_modal.js create mode 100644 callback.php create mode 100644 checkout.php create mode 100644 classes/gateway.php create mode 100644 classes/local/BuyerNotifier.php create mode 100644 classes/local/CmsInfo.php create mode 100644 classes/local/CurrencySymbol.php create mode 100644 classes/local/ErrorLogLogger.php create mode 100644 classes/local/GatewayConfig.php create mode 100644 classes/local/GatewayConfigRepository.php create mode 100644 classes/local/Logger.php create mode 100644 classes/local/Money.php create mode 100644 classes/local/PaymentFormPage.php create mode 100644 classes/local/ReportTable.php create mode 100644 classes/local/callback/CallbackHandler.php create mode 100644 classes/local/callback/CheckHandler.php create mode 100644 classes/local/callback/NotificationHandler.php create mode 100644 classes/local/callback/PayHandler.php create mode 100644 classes/local/order/CurrentPrice.php create mode 100644 classes/local/order/Order.php create mode 100644 classes/local/order/OrderFactory.php create mode 100644 classes/local/order/OrderSnapshot.php create mode 100644 classes/local/order/RejectionReason.php create mode 100644 classes/local/order/TransactionRepository.php create mode 100644 classes/local/order/TransactionStatus.php create mode 100644 classes/local/protocol/AssistantProtocol.php create mode 100644 classes/local/protocol/AssistantTransactionId.php create mode 100644 classes/local/protocol/CallbackNotification.php create mode 100644 classes/local/protocol/CallbackResponse.php create mode 100644 classes/local/protocol/CheckResponse.php create mode 100644 classes/local/protocol/MntResponseXml.php create mode 100644 classes/local/protocol/PayResponse.php create mode 100644 classes/local/protocol/PaymentRequest.php create mode 100644 classes/local/protocol/PaymentServer.php create mode 100644 classes/local/protocol/ResultCode.php create mode 100644 classes/local/protocol/Signature.php create mode 100644 classes/local/receipt/Client.php create mode 100644 classes/local/receipt/JsonNumber.php create mode 100644 classes/local/receipt/PaymentMethod.php create mode 100644 classes/local/receipt/PaymentObject.php create mode 100644 classes/local/receipt/Receipt.php create mode 100644 classes/local/receipt/ReceiptItem.php create mode 100644 classes/local/receipt/ReceiptText.php create mode 100644 classes/local/receipt/Vat.php create mode 100644 classes/privacy/provider.php create mode 100644 db/install.php create mode 100644 db/install.xml create mode 100644 db/messages.php create mode 100644 db/upgrade.php create mode 100644 environment.xml create mode 100644 lang/en/paygw_moneta.php create mode 100644 lang/ru/paygw_moneta.php create mode 100644 pay.php create mode 100644 pix/icon.svg create mode 100644 pix/img.svg create mode 100644 report.php create mode 100644 return.php create mode 100644 settings.php create mode 100644 styles.css create mode 100644 templates/payment_form.mustache create mode 100644 version.php diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index c5d0190..cffc1c2 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,155 @@ -# Moodle +# 🌟 Платёжный модуль Moneta для [Moodle](https://moodle.org/) +![Moodle](https://img.shields.io/badge/Moodle-4.3%2B-orange?logo=moodle&logoColor=white) +![PHP](https://img.shields.io/badge/PHP-8.1%2B-purple) +![License](https://img.shields.io/badge/License-GPLv3%2B-blue) +> **© Правообладатель:** НКО «МОНЕТА» (ООО) -## Getting started +> **📦 Версия модуля: 1.0.0** -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +> **ℹ️ Требования:** +> PHP 8.1+ +> Payment API Moodle 4.3+ -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +> **ℹ️ Примечание по валюте:** +> Данный модуль работает **только с валютой RUB (Российский рубль)**. Использование других валют не поддерживается. -## Add your files +> Стоимость курса в `enrol_fee` должна быть задана в рублях, иначе платежный модуль **"Moneta"** не будет предложен. -* [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files -* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: +## 🚀 Установка и настройка модуля -``` -cd existing_repo -git remote add origin https://git.moneta.ru:8000/products/cashier/cms/Moodle.git -git branch -M main -git push -uf origin main -``` +### 1. 📥 Скачайте модуль -## Integrate with your tools +[Архив последнего релиза](https://git.pub.moneta.ru/CMS/Moodle/releases/latest) — файл +`paygw_moneta-<версия>.zip` в разделе «Файлы» релиза. Внутри архива — папка `moneta`, +распаковывать его не нужно. -* [Set up project integrations](https://git.moneta.ru:8000/products/cashier/cms/Moodle/-/settings/integrations) +> ⚠️ Не берите «Исходный код (ZIP)» / «Исходный код (TAR.GZ)» — их сервис добавляет к +> каждому релизу автоматически, и корневая папка в них названа не `moneta`. Если такой +> архив всё же скачан, при установке (шаг 2) нажмите **«Показать больше…»** и в поле +> **«Переименовать корневой каталог»** укажите `moneta`. -## Collaborate with your team +### 2. 📂 Установите плагин -* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/) -* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/) -* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically) -* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/) -* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) +**Через интерфейс Moodle** (нужны права администратора сайта): -## Test and Deploy +1. **Администрирование → Плагины → Установка плагинов**. +2. Добавьте архив в поле **«ZIP-пакет»** одним из способов: + - перетащите файл в поле; + - или нажмите **«Выберите файл...»**, в открывшемся окне выберите **«Загрузить файл»**, + укажите архив на компьютере и нажмите **«Загрузить этот файл»**. -Use the built-in continuous integration in GitLab. + Затем нажмите **«Установить плагин из ZIP-файла»**. Moodle сам определит тип плагина + (платёжный шлюз) и папку назначения. +3. Нажмите **«Продолжить»** на странице проверки, затем **«Обновить Moodle»** — создастся + таблица заказов и шлюз Moneta включится автоматически. -* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/) -* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/) -* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/) -* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/) -* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/) +**Вручную** (если установка из ZIP отключена на сервере): распакуйте архив так, чтобы +получилась папка `payment/gateway/moneta` в корне Moodle (в Moodle 5.1 и новее — +`public/payment/gateway/moneta`), и откройте **Администрирование → Уведомления**, +чтобы завершить установку. -*** +### 3. ✅ Проверьте, что включено нужное -# Editing this README +1. **Администрирование → Плагины → Платежные шлюзы → Управление платежными шлюзами** — + у **Moneta** включён значок видимости. +2. **Администрирование → Плагины → Способы зачисления → Управление способами зачисления** — + включён способ **«Зачисление за оплату»** (штатный плагин Moodle `enrol_fee`, через него + курсы продаются). -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +### 4. 💳 Создайте платёжный счёт Moodle и подключите к нему Moneta -## Suggestions for a good README +1. **Администрирование → Платежи → Платежные счета → Создать платежный счет** — + придумайте название (например, номер вашего счёта MONETA.RU) и сохраните. +2. В строке счёта, в списке его шлюзов, нажмите **Монета**, включите шлюз и + заполните реквизиты по таблице ниже. +3. Скопируйте **URL для уведомлений** кнопкой «Скопировать в буфер обмена» — он понадобится в + личном кабинете MONETA.RU. -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +### 5. 🎓 Назначьте цену курсу -## Name -Choose a self-explaining name for your project. +В курсе: **Участники → Способы зачисления на курс → Добавить способ → +Зачисление за оплату**. Укажите **Платежный счет** (созданный на шаге 4), +**Оплата за зачисление** (цену) и валюту **RUB**, сохраните. -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +**Название способа** заполнять не обязательно. Если его задать, в Moodle 5.x оно +заменит заголовок «Для зачисления на этот курс требуется оплата» на странице +записи на курс; в списке способов зачисления его видят преподаватели. На оплату +не влияет: в чеке и на странице перехода к оплате всегда полное название курса. -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +Студент увидит на странице курса кнопку оплаты, выберет **Moneta**, проверит +курс и сумму на странице перехода к оплате и нажмёт **«Оплатить»**. После +подтверждения оплаты от MONETA.RU доступ к курсу открывается автоматически. -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +### 6. 🧪 Проверьте оплату -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +Для проверки без реальных денег используйте **Сервер платежей: Демо** со +счётом на [demo.moneta.ru](https://demo.moneta.ru/) и оплатите курс от имени +студента. Заказы и причины отказов видны в **Администрирование → Платежи → +Заказы Монета**. Покупатель получает сообщения «Ссылка на оплату» и «Оплата +принята» по своим настройкам уведомлений (веб-уведомление и/или письмо, если +на сайте настроена исходящая почта). -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +### Обновление -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +Скачайте новый архив и установите его так же, как в шаге 2 (Moodle предложит +заменить текущую версию), либо замените папку `payment/gateway/moneta` вручную +и откройте **Администрирование → Уведомления**. Настройки счетов и заказы +сохраняются. -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +### Реквизиты шлюза в платёжном аккаунте -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +| Поле | Значение | +|---------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **Номер счёта** | Обязательно. Ваш номер расширенного счёта в системе [MONETA.RU](https://moneta.ru/) | +| **Код проверки целостности данных** | Обязательно. Код проверки целостности данных, указанный в настройках расширенного счёта в системе [MONETA.RU](https://moneta.ru/) | +| **Сервер платежей** | `Боевой` (по умолчанию) / `Демо` (demo.moneta.ru, отдельный номер счёта) | +| **Тестовый режим** | Должен совпадать с флагом «Тестовый режим» в настройках счёта | +| **Email для чеков** | Обязательно. Подставляется в чек, если у покупателя нет ни email, ни телефона — чек придёт на этот адрес, а ФИО покупателя в чеке сохранится | +| **Фискализация чеков** | Фискализация чеков по 54-ФЗ средствами системы [MONETA.RU](https://moneta.ru/) сервисом [kassa.payanyway.ru](https://kassa.payanyway.ru/) | +| **Ставка НДС** | Ставка для позиции «доступ к курсу» в чеке | +| **Отправлять ссылку оплаты на почту** | При создании заказа покупателю приходит сообщение со ссылкой на оплату — можно оплатить позже (по умолчанию включено) | +| **URL для уведомлений** | `https://<сайт>/payment/gateway/moneta/callback.php` — его нужно указать в настройках расширенного счёта `Check URL` / `Pay URL` в системе [MONETA.RU](https://moneta.ru/) | -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +## 🔧 Настройка счёта в личном кабинете [MONETA.RU](https://moneta.ru/) -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. +1. 📝 [Зарегистрируйтесь](https://moneta.ru/partnerRegistration.htm) в платёжной системе MONETA.RU и заполните все + необходимые данные. Дождитесь проверки аккаунта и создайте **расширенный счет**. +2. ⚙️ Заполните настройки расширенного счета (раздел **«Мой счет» → «Управление счетами» → «Редактировать счет» → + «Показать дополнительные поля»**): -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +| Параметр | Значение | +|------------------------------------------|------------------------------------------------------| +| **Псевдоним** | `Монета` | +| **Тестовый режим** | `Нет` | +| **Check URL** | `https://<сайт>/payment/gateway/moneta/callback.php` | +| **Pay URL** | `https://<сайт>/payment/gateway/moneta/callback.php` | +| **HTTP метод (PayUrl, CheckUrl)** | `GET` / `POST` | +| **Код проверки целостности данных** | `ваш_код` (произвольный набор символов) | +| **Подпись формы оплаты обязательна** | `Да` | +| **Можно переопределять настройки в url** | `Да` | +| **Success URL** | Оставить пустым | +| **Fail URL** | Оставить пустым | +| **InProgress URL** | Оставить пустым | +| **Return URL** | Оставить пустым | +| **Target (возврат для iframe)** | Оставить пустым | -## License -For open source projects, say how it is licensed. +> ⚠️ **Важно!** Для кириллического домена PayURL и CheckURL должны быть указаны в кодировке [Punycode](https://2ip.ru/punycode/). -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +3. Для фискализации чеков по 54-ФЗ средствами за рамками **Moodle**, настройте вашу кассу в сервисе [kassa.payanyway.ru](https://kassa.payanyway.ru), + в настройках Вашего расширенного счёта в системе [MONETA.RU](https://moneta.ru/) установите Pay URL: https://kassa.payanyway.ru/index.php?do=invoicepayurl, + а в настройках кассы в сервисе [kassa.payanyway.ru](https://kassa.payanyway.ru) пропишите ссылку на Pay URL Вашего интернет-магазина. + В этом случае будет пробиваться чек по 54-ФЗ через сервис [kassa.payanyway.ru]([kassa.payanyway.ru](https://kassa.payanyway.ru)), а запрос на Pay URL + магазина будет проходить транзитом через сервис [kassa.payanyway.ru](https://kassa.payanyway.ru). + +--- + +## 📚 Полезные ресурсы + +- [Документация Moodle](https://docs.moodle.org/) +- [Документация Moneta](https://docs.moneta.ru/) + +--- + +**✅ Модуль настроен, приятных платежей!** 💰🎉 \ No newline at end of file diff --git a/amd/build/gateways_modal.min.js b/amd/build/gateways_modal.min.js new file mode 100644 index 0000000..0318229 --- /dev/null +++ b/amd/build/gateways_modal.min.js @@ -0,0 +1,13 @@ +define("paygw_moneta/gateways_modal",["exports","core/config"],(function(_exports,_config){var obj; +/** + * Запуск оплаты через Moneta из модального окна «Выберите способ оплаты». + * + * Заказ создаёт pay.php по POST с sesskey — поэтому здесь не редирект, + * а отправка скрытой формы. + * + * @module paygw_moneta/gateways_modal + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.process=void 0,_config=(obj=_config)&&obj.__esModule?obj:{default:obj};_exports.process=(component,paymentArea,itemId,description)=>{const form=document.createElement("form");form.method="post",form.action="".concat(_config.default.wwwroot,"/payment/gateway/moneta/pay.php"),form.style.display="none";const fields={sesskey:_config.default.sesskey,component:component,paymentarea:paymentArea,itemid:itemId,description:description};return Object.entries(fields).forEach((_ref=>{let[name,value]=_ref;const input=document.createElement("input");input.type="hidden",input.name=name,input.value=value,form.appendChild(input)})),document.body.appendChild(form),form.submit(),new Promise((()=>null))}})); + +//# sourceMappingURL=gateways_modal.min.js.map \ No newline at end of file diff --git a/amd/build/gateways_modal.min.js.map b/amd/build/gateways_modal.min.js.map new file mode 100644 index 0000000..afa5dfd --- /dev/null +++ b/amd/build/gateways_modal.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gateways_modal.min.js","sources":["../src/gateways_modal.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see .\n\n/**\n * Запуск оплаты через Moneta из модального окна «Выберите способ оплаты».\n *\n * Заказ создаёт pay.php по POST с sesskey — поэтому здесь не редирект,\n * а отправка скрытой формы.\n *\n * @module paygw_moneta/gateways_modal\n * @copyright 2026 Moneta Labs {@link https://moneta.ru/}\n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\nimport Config from 'core/config';\n\n/**\n * Обработчик, который ядро вызывает после выбора шлюза.\n *\n * @param {string} component компонент оплачиваемого объекта\n * @param {string} paymentArea область оплаты\n * @param {number} itemId идентификатор объекта\n * @param {string} description описание из модального окна\n * @returns {Promise} никогда не разрешается: страница уходит на pay.php\n */\nexport const process = (component, paymentArea, itemId, description) => {\n const form = document.createElement('form');\n form.method = 'post';\n form.action = `${Config.wwwroot}/payment/gateway/moneta/pay.php`;\n form.style.display = 'none';\n const fields = {\n sesskey: Config.sesskey,\n component,\n paymentarea: paymentArea,\n itemid: itemId,\n description,\n };\n Object.entries(fields).forEach(([name, value]) => {\n const input = document.createElement('input');\n input.type = 'hidden';\n input.name = name;\n input.value = value;\n form.appendChild(input);\n });\n document.body.appendChild(form);\n form.submit();\n\n return new Promise(() => null);\n};\n"],"names":["component","paymentArea","itemId","description","form","document","createElement","method","action","Config","wwwroot","style","display","fields","sesskey","paymentarea","itemid","Object","entries","forEach","_ref","name","value","input","type","appendChild","body","submit","Promise"],"mappings":";;;;;;;;;;8JAoCuB,CAACA,UAAWC,YAAaC,OAAQC,qBAC9CC,KAAOC,SAASC,cAAc,QACpCF,KAAKG,OAAS,OACdH,KAAKI,iBAAYC,gBAAOC,2CACxBN,KAAKO,MAAMC,QAAU,aACfC,OAAS,CACXC,QAASL,gBAAOK,QAChBd,UAAAA,UACAe,YAAad,YACbe,OAAQd,OACRC,YAAAA,oBAEJc,OAAOC,QAAQL,QAAQM,SAAQC,WAAEC,KAAMC,kBAC7BC,MAAQlB,SAASC,cAAc,SACrCiB,MAAMC,KAAO,SACbD,MAAMF,KAAOA,KACbE,MAAMD,MAAQA,MACdlB,KAAKqB,YAAYF,UAErBlB,SAASqB,KAAKD,YAAYrB,MAC1BA,KAAKuB,SAEE,IAAIC,SAAQ,IAAM"} \ No newline at end of file diff --git a/amd/src/gateways_modal.js b/amd/src/gateways_modal.js new file mode 100644 index 0000000..571213e --- /dev/null +++ b/amd/src/gateways_modal.js @@ -0,0 +1,60 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . + +/** + * Запуск оплаты через Moneta из модального окна «Выберите способ оплаты». + * + * Заказ создаёт pay.php по POST с sesskey — поэтому здесь не редирект, + * а отправка скрытой формы. + * + * @module paygw_moneta/gateways_modal + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +import Config from 'core/config'; + +/** + * Обработчик, который ядро вызывает после выбора шлюза. + * + * @param {string} component компонент оплачиваемого объекта + * @param {string} paymentArea область оплаты + * @param {number} itemId идентификатор объекта + * @param {string} description описание из модального окна + * @returns {Promise} никогда не разрешается: страница уходит на pay.php + */ +export const process = (component, paymentArea, itemId, description) => { + const form = document.createElement('form'); + form.method = 'post'; + form.action = `${Config.wwwroot}/payment/gateway/moneta/pay.php`; + form.style.display = 'none'; + const fields = { + sesskey: Config.sesskey, + component, + paymentarea: paymentArea, + itemid: itemId, + description, + }; + Object.entries(fields).forEach(([name, value]) => { + const input = document.createElement('input'); + input.type = 'hidden'; + input.name = name; + input.value = value; + form.appendChild(input); + }); + document.body.appendChild(form); + form.submit(); + + return new Promise(() => null); +}; diff --git a/callback.php b/callback.php new file mode 100644 index 0000000..be0f09e --- /dev/null +++ b/callback.php @@ -0,0 +1,53 @@ +. + +/** + * Check URL и Pay URL протокола MONETA.Assistant. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +define('NO_MOODLE_COOKIES', true); +define('NO_DEBUG_DISPLAY', true); + +require_once(__DIR__ . '/../../../config.php'); + +use paygw_moneta\local\callback\CallbackHandler; +use paygw_moneta\local\ErrorLogLogger; +use paygw_moneta\local\protocol\CallbackResponse; + +$method = $_SERVER['REQUEST_METHOD'] ?? ''; +$fields = match ($method) { + 'POST' => $_POST, + 'GET' => $_GET, + default => null, +}; + +$response = null; +if ($fields !== null) { + try { + $response = (new CallbackHandler())->handle($fields); + } catch (\Throwable $exception) { + (new ErrorLogLogger())->error('Колбэк отклонён: ' . get_class($exception)); + } +} +$response ??= CallbackResponse::fail(); + +header('Cache-Control: no-store'); +header('Content-Type: ' . $response->contentType); +echo $response->body; diff --git a/checkout.php b/checkout.php new file mode 100644 index 0000000..6597365 --- /dev/null +++ b/checkout.php @@ -0,0 +1,71 @@ +. + +/** + * Продолжение оплаты по ссылке из письма «Ссылка на оплату». + * + * GET безопасен: заказ уже создан, страница лишь заново показывает подписанную + * форму. Открыть её может только покупатель заказа и только пока заказ открыт, + * а реквизиты, тестовый режим и цена не изменились — иначе Pay URL всё равно + * отклонит оплату. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use paygw_moneta\local\GatewayConfigRepository; +use paygw_moneta\local\order\CurrentPrice; +use paygw_moneta\local\order\TransactionRepository; +use paygw_moneta\local\order\TransactionStatus; +use paygw_moneta\local\PaymentFormPage; + +require_once(__DIR__ . '/../../../config.php'); + +require_login(); + +$merchantorderid = required_param('order', PARAM_ALPHANUMEXT); + +$order = TransactionRepository::isMerchantOrderId($merchantorderid) + ? (new TransactionRepository())->findByMerchantOrderId($merchantorderid) + : null; +// Чужой заказ неотличим от несуществующего. +if ($order === null || $order->userId !== (int) $USER->id) { + throw new moodle_exception('error:ordernotfound', 'paygw_moneta'); +} + +$successurl = core_payment\helper::get_success_url($order->component, $order->paymentArea, $order->itemId); +if ($order->isPaid()) { + redirect($successurl, get_string('paymentconfirmed', 'paygw_moneta'), 0, \core\output\notification::NOTIFY_SUCCESS); +} + +$PAGE->set_context(context_system::instance()); +$PAGE->set_url(PaymentFormPage::resumeUrl($order)); +$PAGE->set_pagelayout('standard'); +$PAGE->set_title(get_string('confirmpayment', 'paygw_moneta')); +$PAGE->set_heading(get_string('confirmpayment', 'paygw_moneta')); + +$config = (new GatewayConfigRepository())->forAccount($order->accountId); + +echo $OUTPUT->header(); +if (PaymentFormPage::canResume($order, $config, new CurrentPrice())) { + echo $OUTPUT->render_from_template('paygw_moneta/payment_form', PaymentFormPage::context($order, $config)); +} else { + $reason = $order->status === TransactionStatus::Failed ? 'error:orderinprogress' : 'error:paymentlinkexpired'; + echo $OUTPUT->notification(get_string($reason, 'paygw_moneta'), \core\output\notification::NOTIFY_WARNING); + echo $OUTPUT->single_button($successurl, get_string('continue'), 'get'); +} +echo $OUTPUT->footer(); diff --git a/classes/gateway.php b/classes/gateway.php new file mode 100644 index 0000000..64cb46c --- /dev/null +++ b/classes/gateway.php @@ -0,0 +1,131 @@ +\gateway`). + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class gateway extends \core_payment\gateway +{ + public static function get_supported_currencies(): array + { + return [AssistantProtocol::CURRENCY]; + } + + public static function add_configuration_to_gateway_form(account_gateway $form): void + { + $mform = $form->get_mform(); + + $mform->addElement('text', 'accountnumber', get_string('accountnumber', 'paygw_moneta')); + $mform->setType('accountnumber', PARAM_ALPHANUMEXT); + $mform->addRule('accountnumber', null, 'required', null, 'client'); + $mform->addHelpButton('accountnumber', 'accountnumber', 'paygw_moneta'); + + $mform->addElement('passwordunmask', 'integritycode', get_string('integritycode', 'paygw_moneta')); + $mform->setType('integritycode', PARAM_RAW_TRIMMED); + $mform->addRule('integritycode', null, 'required', null, 'client'); + $mform->addHelpButton('integritycode', 'integritycode', 'paygw_moneta'); + + $servers = []; + foreach (PaymentServer::cases() as $server) { + $servers[$server->value] = get_string($server->label(), 'paygw_moneta'); + } + $mform->addElement('select', 'paymentserver', get_string('paymentserver', 'paygw_moneta'), $servers); + $mform->setDefault('paymentserver', PaymentServer::Prod->value); + $mform->addHelpButton('paymentserver', 'paymentserver', 'paygw_moneta'); + + $mform->addElement('advcheckbox', 'testmode', get_string('testmode', 'paygw_moneta')); + $mform->addHelpButton('testmode', 'testmode', 'paygw_moneta'); + + $mform->addElement('text', 'receiptemail', get_string('receiptemail', 'paygw_moneta')); + $mform->setType('receiptemail', PARAM_RAW_TRIMMED); + $mform->addRule('receiptemail', null, 'required', null, 'client'); + $mform->addHelpButton('receiptemail', 'receiptemail', 'paygw_moneta'); + + $mform->addElement('advcheckbox', 'fiscalization', get_string('fiscalization', 'paygw_moneta')); + $mform->addHelpButton('fiscalization', 'fiscalization', 'paygw_moneta'); + + $vatOptions = []; + foreach (Vat::cases() as $vat) { + $vatOptions[$vat->value] = get_string($vat->langKey(), 'paygw_moneta'); + } + $mform->addElement('select', 'vat', get_string('vat', 'paygw_moneta'), $vatOptions); + $mform->addHelpButton('vat', 'vat', 'paygw_moneta'); + $mform->setDefault('vat', Vat::None->value); + + $mform->addElement('advcheckbox', 'sendpaymentlink', get_string('sendpaymentlink', 'paygw_moneta')); + $mform->addHelpButton('sendpaymentlink', 'sendpaymentlink', 'paygw_moneta'); + $mform->setDefault('sendpaymentlink', 1); + + $mform->addElement('static', 'callbackurl', get_string('callbackurl', 'paygw_moneta'), self::callbackUrlHtml()); + $mform->addHelpButton('callbackurl', 'callbackurl', 'paygw_moneta'); + } + + public static function validate_gateway_form( + account_gateway $form, + stdClass $data, + array $files, + array &$errors, + ): void { + $accountNumber = trim((string) ($data->accountnumber ?? '')); + if ($accountNumber === '') { + $errors['accountnumber'] = get_string('required'); + } elseif (preg_match('/\A[0-9]{1,20}\z/', $accountNumber) !== 1) { + $errors['accountnumber'] = get_string('error:accountnumber', 'paygw_moneta'); + } + + $receiptEmail = trim((string) ($data->receiptemail ?? '')); + if (Client::normalizeEmail($receiptEmail) === null) { + $errors['receiptemail'] = get_string('error:receiptemail', 'paygw_moneta'); + } + + if (trim((string) ($data->integritycode ?? '')) === '') { + $errors['integritycode'] = get_string('required'); + } + } + + /** + * Адрес Check URL / Pay URL только для чтения и кнопка «Скопировать» + * (`core/copy_to_clipboard`: сам вешает обработчик на `data-action`). + */ + private static function callbackUrlHtml(): string + { + global $PAGE; + + $PAGE->requires->js_amd_inline("require(['core/copy_to_clipboard']);"); + $id = \html_writer::random_id('paygw-moneta-callbackurl'); + + return \html_writer::div( + \html_writer::empty_tag('input', [ + 'type' => 'text', + 'id' => $id, + 'class' => 'form-control', + 'value' => (new \moodle_url('/payment/gateway/moneta/callback.php'))->out(false), + 'readonly' => 'readonly', + 'size' => 60, + ]) + . \html_writer::tag('button', get_string('copytoclipboard'), [ + 'type' => 'button', + 'class' => 'btn btn-secondary', + 'data-action' => 'copytoclipboard', + 'data-clipboard-target' => '#' . $id, + 'data-clipboard-success-message' => get_string('callbackurl:copied', 'paygw_moneta'), + ]), + 'input-group', + ); + } +} diff --git a/classes/local/BuyerNotifier.php b/classes/local/BuyerNotifier.php new file mode 100644 index 0000000..f252e45 --- /dev/null +++ b/classes/local/BuyerNotifier.php @@ -0,0 +1,117 @@ +send( + order: $order, + provider: self::PROVIDER, + stringKey: 'message:paid', + extra: static fn(Order $order): array => [ + 'operationid' => (string) $order->providerTransactionId, + 'url' => helper::get_success_url($order->component, $order->paymentArea, $order->itemId)->out(false), + ], + ); + } + + /** + * Ссылка на оплату только что созданного заказа (настройка шлюза «Отправлять + * ссылку оплаты на почту»): покупатель может оплатить позже, со страницы + * `checkout.php`. Сбой отправки не мешает перейти к оплате сейчас. + * + * @return int|false id сообщения либо false, если отправка не состоялась + */ + public function notifyPaymentLink(Order $order): int|false + { + return $this->send( + order: $order, + provider: self::PROVIDER_LINK, + stringKey: 'message:link', + extra: static fn(Order $order): array => [ + 'url' => PaymentFormPage::resumeUrl($order)->out(false), + ], + ); + } + + /** + * @param callable(Order): array $extra поля строки сообщения сверх общих; `url` обязателен + */ + private function send(Order $order, string $provider, string $stringKey, callable $extra): int|false + { + try { + $user = core_user::get_user($order->userId); + if ($user === false || !empty($user->deleted) || isguestuser($user)) { + return false; + } + + // Значения для подстановок {$a->…} в строках message:* (имя $a задаёт get_string()). + $placeholders = (object) ([ + 'firstname' => $user->firstname, + 'fullname' => fullname($user), + 'description' => $order->snapshot->description, + 'amount' => helper::get_cost_as_string((float) $order->amount->toDecimal(), $order->currency), + 'sitename' => format_string(get_site()->fullname), + ] + $extra($order)); + $body = get_string($stringKey, 'paygw_moneta', $placeholders); + + $bodyForHtml = get_string( + $stringKey, + 'paygw_moneta', + (object) (['url' => '<' . $placeholders->url . '>'] + (array) $placeholders), + ); + + $message = new message(); + $message->component = 'paygw_moneta'; + $message->name = $provider; + $message->userfrom = core_user::get_noreply_user(); + $message->userto = $user; + $message->subject = get_string($stringKey . ':subject', 'paygw_moneta', $placeholders); + $message->fullmessage = $body; + $message->fullmessageformat = FORMAT_MARKDOWN; + $message->fullmessagehtml = markdown_to_html($bodyForHtml); + $message->smallmessage = $message->subject; + $message->notification = 1; + $message->contexturl = $placeholders->url; + $message->contexturlname = $order->snapshot->description; + + return message_send($message); + } catch (\Throwable $exception) { + $this->logger->error('Сообщение покупателю не отправлено: ' . get_class($exception)); + + return false; + } + } +} diff --git a/classes/local/CmsInfo.php b/classes/local/CmsInfo.php new file mode 100644 index 0000000..6dbeb0a --- /dev/null +++ b/classes/local/CmsInfo.php @@ -0,0 +1,47 @@ +|PHP |Moneta v`. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +final class CmsInfo +{ + private const CMS_NAME = 'Moodle'; + private const MODULE_NAME = 'Moneta'; + + private function __construct() {} + + public static function getCmsModuleVersion(): string + { + global $CFG; + + $pluginInfo = \core_plugin_manager::instance()->get_plugin_info('paygw_moneta'); + $moduleVersion = $pluginInfo?->release ?? (string) ($pluginInfo?->versiondisk ?? 'unknown'); + + return self::format( + cmsVersion: (string) ($CFG->release ?? 'unknown'), + phpVersion: PHP_VERSION, + moduleVersion: (string) $moduleVersion, + ); + } + + public static function format(string $cmsVersion, string $phpVersion, string $moduleVersion): string + { + return sprintf( + '%s v%s|PHP %s|%s v%s', + self::CMS_NAME, + $cmsVersion, + $phpVersion, + self::MODULE_NAME, + $moduleVersion, + ); + } +} diff --git a/classes/local/CurrencySymbol.php b/classes/local/CurrencySymbol.php new file mode 100644 index 0000000..cff35d7 --- /dev/null +++ b/classes/local/CurrencySymbol.php @@ -0,0 +1,32 @@ + '₽', + ]; + + private function __construct() {} + + public static function of(?string $currencyCode): string + { + if ($currencyCode === null || $currencyCode === '') { + return ''; + } + + return self::SYMBOLS[strtoupper($currencyCode)] ?? $currencyCode; + } +} diff --git a/classes/local/ErrorLogLogger.php b/classes/local/ErrorLogLogger.php new file mode 100644 index 0000000..e980130 --- /dev/null +++ b/classes/local/ErrorLogLogger.php @@ -0,0 +1,22 @@ + $config значения формы {@see \paygw_moneta\Gateway} + */ + public static function fromArray(array $config, bool $enabled = true): self + { + return new self( + trim((string) ($config['accountnumber'] ?? '')), + (string) ($config['integritycode'] ?? ''), + PaymentServer::fromSetting($config['paymentserver'] ?? null), + !empty($config['testmode']), + !empty($config['fiscalization']), + Vat::tryFrom((string) ($config['vat'] ?? '')) ?? Vat::None, + $enabled, + Client::normalizeEmail((string) ($config['receiptemail'] ?? '')), + !empty($config['sendpaymentlink']), + ); + } + + /** + * Можно ли создавать новые заказы: реквизиты и «Email для чеков», без + * которого чек покупателя без контактов не собрать. Колбэки проверяют + * только {@see isComplete()} — уже оплаченный заказ должен дойти до + * зачисления, даже если настройку потом очистили. + */ + public function acceptsNewOrders(): bool + { + return $this->isComplete() && $this->enabled && $this->receiptEmail !== null; + } + + public function isComplete(): bool + { + return $this->accountNumber !== '' && $this->integrityCode !== ''; + } + + public function signature(): Signature + { + return new Signature($this->integrityCode); + } +} diff --git a/classes/local/GatewayConfigRepository.php b/classes/local/GatewayConfigRepository.php new file mode 100644 index 0000000..07b4e5c --- /dev/null +++ b/classes/local/GatewayConfigRepository.php @@ -0,0 +1,70 @@ +get_record('payment_gateways', ['accountid' => $accountId, 'gateway' => GatewayConfig::GATEWAY]); + if ($record === false) { + return null; + } + + return self::fromRecord($record); + } + + /** + * Заполненные настройки с данным номером счёта MONETA.RU — чтобы проверить + * подпись уведомления по заказу, которого нет в БД. + */ + public function findByAccountNumber(string $accountNumber): ?GatewayConfig + { + global $DB; + + foreach ($DB->get_records('payment_gateways', ['gateway' => GatewayConfig::GATEWAY]) as $record) { + $config = self::fromRecord($record); + if ($config->isComplete() && $config->accountNumber === $accountNumber) { + return $config; + } + } + + return null; + } + + private static function fromRecord(\stdClass $record): GatewayConfig + { + $config = json_decode((string) $record->config, true); + + return GatewayConfig::fromArray(is_array($config) ? $config : [], (bool) $record->enabled); + } +} diff --git a/classes/local/Logger.php b/classes/local/Logger.php new file mode 100644 index 0000000..81db301 --- /dev/null +++ b/classes/local/Logger.php @@ -0,0 +1,19 @@ +toMinorUnits() > self::fromMax()->toMinorUnits()) { + throw new InvalidArgumentException('Сумма превышает допустимый максимум.'); + } + + return $money; + } + + /** + * Сумма в копейках; безопасный путь для арифметики. + */ + public static function fromMinorUnits(int $minorUnits): self + { + if ($minorUnits < 0) { + throw new InvalidArgumentException('Сумма не может быть отрицательной.'); + } + + return self::fromDecimal(sprintf('%d.%02d', intdiv($minorUnits, 100), $minorUnits % 100)); + } + + /** + * Граница с хостом: Moodle считает стоимость `float` (`helper::get_rounded_cost`). + * Округление до копеек делается здесь один раз, дальше `float` не используется. + */ + public static function fromFloat(float $amount): self + { + if ($amount < 0 || !is_finite($amount)) { + throw new InvalidArgumentException('Сумма хоста должна быть конечным неотрицательным числом.'); + } + + return self::fromDecimal(number_format($amount, 2, '.', '')); + } + + public function toDecimal(): string + { + return $this->value; + } + + public function toMinorUnits(): int + { + [$units, $cents] = explode('.', $this->value); + + return ((int) $units * 100) + (int) $cents; + } + + public function isPositive(): bool + { + return $this->toMinorUnits() > 0; + } + + public function equals(self $other): bool + { + return $this->value === $other->value; + } + + public function add(self $other): self + { + return self::fromMinorUnits($this->toMinorUnits() + $other->toMinorUnits()); + } + + public function multiply(int $quantity): self + { + if ($quantity < 0) { + throw new InvalidArgumentException('Количество не может быть отрицательным.'); + } + + return self::fromMinorUnits($this->toMinorUnits() * $quantity); + } + + public function __toString(): string + { + return $this->value; + } + + private static function fromMax(): self + { + return new self(self::MAX); + } +} diff --git a/classes/local/PaymentFormPage.php b/classes/local/PaymentFormPage.php new file mode 100644 index 0000000..b56434b --- /dev/null +++ b/classes/local/PaymentFormPage.php @@ -0,0 +1,93 @@ +} + */ + public static function context(Order $order, GatewayConfig $config): array + { + global $CFG, $OUTPUT; + + $request = new PaymentRequest( + accountId: $config->accountNumber, + transactionId: AssistantTransactionId::build($order->merchantOrderId), + amount: $order->amount, + subscriberId: $order->subscriberId(), + testMode: $order->snapshot->testMode, + signature: $config->signature(), + description: $order->snapshot->description, + successUrl: (new moodle_url(self::RETURN_PATH, ['outcome' => 'success']))->out(false), + failUrl: (new moodle_url(self::RETURN_PATH, ['outcome' => 'fail']))->out(false), + returnUrl: (new moodle_url(self::RETURN_PATH, ['outcome' => 'cancel']))->out(false), + server: $config->paymentServer, + locale: AssistantProtocol::normalizeLocale(current_language()), + cms: CmsInfo::getCmsModuleVersion(), + ); + + $fields = []; + foreach ($request->getFields() as $name => $value) { + $fields[] = ['name' => $name, 'value' => $value]; + } + + return [ + 'action' => empty($CFG->paygw_moneta_assistant_url) + ? $request->getActionUrl() + : (string) $CFG->paygw_moneta_assistant_url, + // Сумма для покупателя — как в остальном Moodle: «120,25 ₽». + 'cost' => helper::get_cost_as_string((float) $order->amount->toDecimal(), $order->currency), + 'description' => $order->snapshot->description, + 'iscourse' => $order->component === 'enrol_fee', + 'logourl' => $OUTPUT->image_url('img', 'paygw_moneta')->out(false), + 'fields' => $fields, + ]; + } + + /** + * Можно ли продолжить оплату открытого заказа по ссылке из письма: реквизиты, + * тестовый режим и цена те же, что при создании, — иначе Pay URL всё равно + * отклонит оплату (`PayHandler`). + */ + public static function canResume(Order $order, ?GatewayConfig $config, CurrentPrice $currentPrice): bool + { + return $order->status->isOpen() + && $config !== null + && $config->acceptsNewOrders() + && $config->accountNumber === $order->snapshot->accountNumber + && $config->testMode === $order->snapshot->testMode + && $currentPrice->matches($order); + } + + /** + * Адрес страницы продолжения оплаты — его получает покупатель в письме. + */ + public static function resumeUrl(Order $order): moodle_url + { + return new moodle_url('/payment/gateway/moneta/checkout.php', ['order' => $order->merchantOrderId]); + } +} diff --git a/classes/local/ReportTable.php b/classes/local/ReportTable.php new file mode 100644 index 0000000..492e54b --- /dev/null +++ b/classes/local/ReportTable.php @@ -0,0 +1,109 @@ +define_columns( + [ + 'timecreated', + 'user', + 'description', + 'amount', + 'status', + 'providertransactionid', + 'lasterror', + ], + ); + + $this->define_headers([ + get_string('report:time', 'paygw_moneta'), + get_string('report:user', 'paygw_moneta'), + get_string('report:description', 'paygw_moneta'), + get_string('report:amount', 'paygw_moneta'), + get_string('report:status', 'paygw_moneta'), + get_string('report:operation', 'paygw_moneta'), + get_string('report:lasterror', 'paygw_moneta'), + ]); + $this->define_baseurl($baseUrl); + $this->sortable(true, 'timecreated', SORT_DESC); + $this->no_sorting('description'); + $this->no_sorting('lasterror'); + $this->collapsible(false); + $this->pageable(true); + + $userFields = \core_user\fields::for_name()->get_sql('u')->selects; + $this->set_sql( + 't.*' . $userFields, + '{' . TransactionRepository::TABLE . '} t JOIN {user} u ON u.id = t.userid', + '1 = 1', + ); + } + + public function col_timecreated(stdClass $row): string + { + return userdate((int) $row->timecreated, get_string('strftimedatetimeshort', 'langconfig')); + } + + public function col_user(stdClass $row): string + { + return html_writer::link(new moodle_url('/user/profile.php', ['id' => $row->userid]), fullname($row)); + } + + public function col_description(stdClass $row): string + { + $snapshot = json_decode((string) $row->snapshot, true); + + return s((string) ($snapshot['description'] ?? '')); + } + + public function col_amount(stdClass $row): string + { + return Money::fromFloat((float) $row->amount)->toDecimal() . ' ' . s(CurrencySymbol::of((string) $row->currency)); + } + + public function col_status(stdClass $row): string + { + $status = TransactionStatus::tryFrom((string) $row->status); + $label = $status === null ? s((string) $row->status) : get_string('status:' . $status->value, 'paygw_moneta'); + $class = match ($status) { + TransactionStatus::Paid => 'badge bg-success text-white', + TransactionStatus::Failed => 'badge bg-danger text-white', + TransactionStatus::Canceled => 'badge bg-secondary text-white', + default => 'badge bg-info text-white', + }; + + return html_writer::span($label, $class); + } + + public function col_providertransactionid(stdClass $row): string + { + return s((string) ($row->providertransactionid ?? '')); + } + + public function col_lasterror(stdClass $row): string + { + return s((string) ($row->lasterror ?? '')); + } +} diff --git a/classes/local/callback/CallbackHandler.php b/classes/local/callback/CallbackHandler.php new file mode 100644 index 0000000..d6f9736 --- /dev/null +++ b/classes/local/callback/CallbackHandler.php @@ -0,0 +1,174 @@ +check = new CheckHandler($repository); + $this->pay = new PayHandler( + repository: $repository, + deliverOrder: $deliverOrder ?? helper::deliver_order(...), + notifier: $notifier, + currentPrice: $currentPrice, + logger: $logger, + ); + } + + /** + * @param array $fields + */ + public function handle(array $fields): CallbackResponse + { + try { + $notification = new CallbackNotification($fields); + } catch (\InvalidArgumentException) { + return CallbackResponse::fail(); + } + + $merchantOrderId = AssistantTransactionId::parse($notification->getTransactionId()); + if ($merchantOrderId === null) { + return CallbackResponse::fail(); + } + + $order = $this->repository->findByMerchantOrderId($merchantOrderId); + if ($order === null) { + return $this->unknownOrder($notification); + } + + $config = $this->configs->forAccount($order->accountId); + if ($config === null || !$config->isComplete()) { + return CallbackResponse::fail(); + } + + if ( + $notification->getAccountId() !== $config->accountNumber + || $notification->getAccountId() !== $order->snapshot->accountNumber + || !$notification->isSignedBy($config->signature()) + ) { + $this->logger->error('Уведомление отклонено: подпись или номер счёта не совпадают.'); + + return CallbackResponse::fail(); + } + + $lock = lock_config::get_lock_factory('paygw_moneta')->get_lock($order->merchantOrderId, self::LOCK_TIMEOUT); + if (!$lock) { + return CallbackResponse::fail(); + } + try { + $order = $this->repository->findById($order->id) ?? $order; + + return $this->handleSigned($notification, $order, $config); + } finally { + $lock->release(); + } + } + + private function handleSigned(CallbackNotification $notification, Order $order, GatewayConfig $config): CallbackResponse + { + $error = $this->validate($notification, $order); + if ($error !== null) { + $this->repository->noteError($order, $error); + + return CallbackResponse::fail(); + } + + $handler = $notification->isCheck() ? $this->check : $this->pay; + + return $handler->handle($notification, $order, $config); + } + + private function validate(CallbackNotification $notification, Order $order): ?RejectionReason + { + if ($notification->getCurrency() !== $order->currency) { + return RejectionReason::Currency; + } + + if ($notification->isTestMode() !== $order->snapshot->testMode) { + return RejectionReason::TestMode; + } + + if ($notification->getSubscriberId() !== '' && $notification->getSubscriberId() !== $order->subscriberId()) { + return RejectionReason::Subscriber; + } + + $amount = $notification->getAmount(); + if ($amount !== null && !$amount->equals($order->amount)) { + return RejectionReason::Amount; + } + + return null; + } + + private function unknownOrder(CallbackNotification $notification): CallbackResponse + { + $config = $this->configs->findByAccountNumber($notification->getAccountId()); + if ($config === null || !$notification->isSignedBy($config->signature())) { + return CallbackResponse::fail(); + } + + if (!$notification->isCheck()) { + $this->logger->error( + sprintf( + 'Оплачено уведомление по неизвестному заказу %s (операция %s).', + $notification->getTransactionId(), + $notification->getOperationId(), + ), + ); + + return CallbackResponse::fail(); + } + + $response = new CheckResponse( + accountId: $config->accountNumber, + transactionId: $notification->getTransactionId(), + amount: $notification->getAmount() ?? Money::fromMinorUnits(0), + resultCode: ResultCode::Rejected, + signature: $config->signature(), + cms: CmsInfo::getCmsModuleVersion(), + ); + + return $response->toXml(); + } +} diff --git a/classes/local/callback/CheckHandler.php b/classes/local/callback/CheckHandler.php new file mode 100644 index 0000000..916f9c7 --- /dev/null +++ b/classes/local/callback/CheckHandler.php @@ -0,0 +1,70 @@ +status->isOpen() && !$config->enabled) { + $order = $this->repository->markCanceled($order, RejectionReason::GatewayDisabled); + } + + $code = match ($order->status) { + TransactionStatus::Paid => ResultCode::Paid, + // Failed — оплата у сервиса прошла, не удалась доставка: новую оплату + // по этому заказу не начинаем, повтор Pay URL её доставит. + TransactionStatus::Canceled, TransactionStatus::Failed => ResultCode::Rejected, + TransactionStatus::New, TransactionStatus::Pending => $notification->getAmount() === null + ? ResultCode::WithAmount + : ResultCode::AwaitingPayment, + }; + + if ($order->status === TransactionStatus::New) { + $order = $this->repository->markPending($order); + } + + $response = new CheckResponse( + accountId: $config->accountNumber, + transactionId: $notification->getTransactionId(), + amount: $order->amount, + resultCode: $code, + signature: $config->signature(), + cms: CmsInfo::getCmsModuleVersion(), + ); + + if (!$order->snapshot->fiscalization) { + return $response->toXml(); + } + + try { + return $response->toJson($order->snapshot->receipt); + } catch (\InvalidArgumentException) { + $this->repository->noteError($order, RejectionReason::Receipt); + + return CallbackResponse::fail(); + } + } +} diff --git a/classes/local/callback/NotificationHandler.php b/classes/local/callback/NotificationHandler.php new file mode 100644 index 0000000..26a8a33 --- /dev/null +++ b/classes/local/callback/NotificationHandler.php @@ -0,0 +1,20 @@ +status === TransactionStatus::Paid) { + // Повторная доставка того же уведомления — тот же ответ, без второго зачисления. + if ($order->providerTransactionId === $notification->getOperationId()) { + return $this->paid($notification, $order, $config, ResultCode::Paid, $order->snapshot->receipt); + } + + // Вторая операция по оплаченному заказу: деньги списаны дважды — нужен человек. + $this->repository->noteError($order, RejectionReason::DuplicateOperation); + + return CallbackResponse::fail(); + } + if ($order->status === TransactionStatus::Canceled) { + // Оплата отменённого заказа: повторы бессмысленны, но след должен остаться. + return $this->paid($notification, $order, $config, ResultCode::Rejected, null); + } + + // Снимок защищает легитимный заказ от смены настроек, но не должен позволять + // дожать сохранённую форму после того, как администратор выключил тестовый + // режим или поднял цену: сверяемся ещё и с текущим состоянием. + if ($notification->isTestMode() !== $config->testMode) { + $this->repository->noteError($order, RejectionReason::TestMode); + + return CallbackResponse::fail(); + } + if (!$config->enabled) { + $this->repository->noteError($order, RejectionReason::GatewayDisabled); + + return CallbackResponse::fail(); + } + if (!$this->currentPrice->matches($order)) { + $this->repository->noteError($order, RejectionReason::AmountChanged); + + return CallbackResponse::fail(); + } + + $paid = $this->deliver($notification, $order); + if ($paid === null) { + return CallbackResponse::fail(); + } + $this->notifier->notifyPaid($paid); + + return $this->paid($notification, $paid, $config, ResultCode::Paid, $paid->snapshot->receipt); + } + + /** + * Платёж ядра, доставка заказа и статус — одной транзакцией БД. При сбое + * заказ помечается `Failed`, чтобы повтор уведомления попробовал ещё раз. + */ + private function deliver(CallbackNotification $notification, Order $order): ?Order + { + global $DB; + + $transaction = $DB->start_delegated_transaction(); + try { + $paymentId = helper::save_payment( + $order->accountId, + $order->component, + $order->paymentArea, + $order->itemId, + $order->userId, + (float) $order->amount->toDecimal(), + $order->currency, + GatewayConfig::GATEWAY, + ); + if (!($this->deliverOrder)( + $order->component, + $order->paymentArea, + $order->itemId, + $paymentId, + $order->userId, + )) { + throw new \RuntimeException('Доставка заказа вернула false.'); + } + $paid = $this->repository->markPaid($order, $notification->getOperationId(), $paymentId); + $transaction->allow_commit(); + + return $paid; + } catch (\Throwable $exception) { + try { + // rollback() перебрасывает исключение — гасим его здесь, причина уходит в lasterror. + $transaction->rollback($exception); + } catch (\Throwable) { + // Откат выполнен, исключение уже обработано. + } + $this->repository->markFailed($order, RejectionReason::Delivery); + $this->logger->error('Доставка заказа не удалась: ' . get_class($exception)); + } + + return null; + } + + private function paid( + CallbackNotification $notification, + Order $order, + GatewayConfig $config, + ResultCode $code, + ?Receipt $receipt, + ): CallbackResponse { + $payResponse = new PayResponse( + accountId: $config->accountNumber, + transactionId: $notification->getTransactionId(), + amount: $order->amount, + resultCode: $code, + signature: $config->signature(), + cms: CmsInfo::getCmsModuleVersion(), + receipt: $receipt, + ); + + return $payResponse->toXml(); + } +} diff --git a/classes/local/order/CurrentPrice.php b/classes/local/order/CurrentPrice.php new file mode 100644 index 0000000..35d2a8c --- /dev/null +++ b/classes/local/order/CurrentPrice.php @@ -0,0 +1,51 @@ +component, $order->paymentArea, $order->itemId); + $current = Money::fromFloat( + helper::get_rounded_cost( + $payable->get_amount(), + $payable->get_currency(), + helper::get_gateway_surcharge(GatewayConfig::GATEWAY), + ), + ); + } catch (\Throwable $exception) { + $this->logger->error('Оплачиваемый объект недоступен: ' . get_class($exception)); + + return false; + } + + return $payable->get_currency() === $order->currency && $current->equals($order->amount); + } +} diff --git a/classes/local/order/Order.php b/classes/local/order/Order.php new file mode 100644 index 0000000..21c3b7d --- /dev/null +++ b/classes/local/order/Order.php @@ -0,0 +1,79 @@ +id, + (int) $record->accountid, + (int) $record->userid, + (string) $record->component, + (string) $record->paymentarea, + (int) $record->itemid, + (string) $record->merchantorderid, + $record->providertransactionid === null ? null : (string) $record->providertransactionid, + $record->paymentid === null ? null : (int) $record->paymentid, + // Единственное место, где сумма приходит из БД числом (NUMBER(20,5)). + Money::fromFloat((float) $record->amount), + (string) $record->currency, + TransactionStatus::from((string) $record->status), + OrderSnapshot::fromJson((string) $record->snapshot), + $record->lasterror === null ? null : RejectionReason::tryFrom((string) $record->lasterror), + (int) $record->timecreated, + (int) $record->timemodified, + $record->timecompleted === null ? null : (int) $record->timecompleted, + ); + } + + /** + * `MNT_SUBSCRIBER_ID`, с которым заказ ушёл на платёжную форму. + */ + public function subscriberId(): string + { + return $this->snapshot->subscriberId; + } + + public function isPaid(): bool + { + return $this->status === TransactionStatus::Paid; + } +} diff --git a/classes/local/order/OrderFactory.php b/classes/local/order/OrderFactory.php new file mode 100644 index 0000000..240739a --- /dev/null +++ b/classes/local/order/OrderFactory.php @@ -0,0 +1,156 @@ +acceptsNewOrders()) { + throw new moodle_exception('gatewaynotfound', 'payment'); + } + + // Оплата у сервиса прошла, доставка сорвалась: новый заказ создавать нельзя, + // иначе покупатель заплатит дважды, а повтор уведомления по старому доставит его. + if ($this->repository->findFailedForItem((int) $user->id, $component, $paymentArea, $itemId) !== null) { + throw new moodle_exception('error:orderinprogress', 'paygw_moneta'); + } + + $payable = helper::get_payable($component, $paymentArea, $itemId); + $currency = $payable->get_currency(); + if ($currency !== AssistantProtocol::CURRENCY) { + throw new moodle_exception('error:unsupportedcurrency', 'paygw_moneta'); + } + $surcharge = helper::get_gateway_surcharge(GatewayConfig::GATEWAY); + $amount = Money::fromFloat(helper::get_rounded_cost($payable->get_amount(), $currency, $surcharge)); + if (!$amount->isPositive()) { + throw new moodle_exception('error:invalidamount', 'paygw_moneta'); + } + + $itemName = self::itemName($component, $paymentArea, $itemId); + + $client = Client::fromContacts( + email: (string) ($user->email ?? ''), + phone: self::phone($user), + name: self::fullName($user), + fallbackEmail: $config->receiptEmail, + ) ?? throw new moodle_exception('gatewaynotfound', 'payment'); + + $snapshot = new OrderSnapshot( + accountNumber: $config->accountNumber, + testMode: $config->testMode, + fiscalization: $config->fiscalization, + vat: $config->vat, + receipt: Receipt::forCourse($itemName, $amount, $client, $config->vat), + description: $itemName, + subscriberId: self::subscriberId($user), + ); + + return $this->repository->obtain( + accountId: $payable->get_account_id(), + userId: (int) $user->id, + component: $component, + paymentArea: $paymentArea, + itemId: $itemId, + amount: $amount, + currency: $currency, + snapshot: $snapshot, + created: $created, + ); + } + + private static function itemName(string $component, string $paymentArea, int $itemId): string + { + global $DB; + + if ($component === 'enrol_fee' && $paymentArea === 'fee') { + $courseId = $DB->get_field('enrol', 'courseid', ['id' => $itemId, 'enrol' => 'fee']); + $name = $courseId ? $DB->get_field('course', 'fullname', ['id' => $courseId]) : false; + if (is_string($name) && ReceiptText::sanitize($name) !== '') { + return $name; + } + } + + return get_string('genericitem', 'paygw_moneta'); + } + + public static function subscriberId(stdClass $user): string + { + $email = trim((string) ($user->email ?? '')); + if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) !== false) { + return $email; + } + + return Client::normalizePhone(self::phone($user)) ?? (string) $user->id; + } + + /** + * Первый заполненный телефон профиля: рабочий, затем мобильный. + */ + private static function phone(stdClass $user): string + { + $phone = trim((string) ($user->phone1 ?? '')); + + return $phone !== '' ? $phone : trim((string) ($user->phone2 ?? '')); + } + + /** + * ФИО для чека в порядке «Фамилия Имя Отчество» — как `name` объекта + * `client` в `kassaspecification.pdf`, независимо от настройки отображения имён. + */ + private static function fullName(stdClass $user): string + { + $parts = array_filter( + array_map( + static fn(string $field): string => trim((string) ($user->$field ?? '')), + ['lastname', 'firstname', 'middlename'], + ), + static fn(string $part): bool => $part !== '', + ); + + return implode(' ', $parts); + } +} diff --git a/classes/local/order/OrderSnapshot.php b/classes/local/order/OrderSnapshot.php new file mode 100644 index 0000000..60786db --- /dev/null +++ b/classes/local/order/OrderSnapshot.php @@ -0,0 +1,99 @@ + + */ + public function toArray(): array + { + return [ + 'accountnumber' => $this->accountNumber, + 'testmode' => $this->testMode, + 'fiscalization' => $this->fiscalization, + 'vat' => $this->vat->value, + 'receipt' => $this->receipt->toArray(), + 'description' => $this->description, + 'subscriberid' => $this->subscriberId, + ]; + } + + public function toJson(): string + { + return json_encode($this->toArray(), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE); + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + accountNumber: (string) ($data['accountnumber'] ?? ''), + testMode: (bool) ($data['testmode'] ?? false), + fiscalization: (bool) ($data['fiscalization'] ?? false), + vat: Vat::from((string) ($data['vat'] ?? '')), + receipt: Receipt::fromArray(is_array($data['receipt'] ?? null) ? $data['receipt'] : []), + description: (string) ($data['description'] ?? ''), + subscriberId: (string) ($data['subscriberid'] ?? ''), + ); + } + + public static function fromJson(string $json): self + { + $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); + if (!is_array($data)) { + throw new InvalidArgumentException('Снимок заказа повреждён.'); + } + + return self::fromArray($data); + } + + /** + * Совпадение реквизитов и чека; описание не сравнивается — оно не влияет + * на оплату и не должно плодить заказы. + */ + public function equals(self $other): bool + { + $mine = $this->toArray(); + $theirs = $other->toArray(); + unset($mine['description'], $theirs['description']); + + return $mine === $theirs; + } +} diff --git a/classes/local/order/RejectionReason.php b/classes/local/order/RejectionReason.php new file mode 100644 index 0000000..0ef4adb --- /dev/null +++ b/classes/local/order/RejectionReason.php @@ -0,0 +1,32 @@ +findOpenForItem($userId, $component, $paymentArea, $itemId); + $created = false; + if ($open !== null + && $open->accountId === $accountId + && $open->amount->equals($amount) + && $open->snapshot->equals($snapshot) + ) { + return $open; + } + $created = true; + + return $this->create($accountId, $userId, $component, $paymentArea, $itemId, $amount, $currency, $snapshot); + } + + public function create( + int $accountId, + int $userId, + string $component, + string $paymentArea, + int $itemId, + Money $amount, + string $currency, + OrderSnapshot $snapshot, + ): Order { + global $DB; + + if (strtoupper($currency) !== AssistantProtocol::CURRENCY) { + throw new InvalidArgumentException(get_string('error:unsupportedcurrency', 'paygw_moneta')); + } + if (!$amount->isPositive()) { + throw new InvalidArgumentException(get_string('error:invalidamount', 'paygw_moneta')); + } + + $now = time(); + $record = (object) [ + 'paymentid' => null, + 'accountid' => $accountId, + 'userid' => $userId, + 'component' => $component, + 'paymentarea' => $paymentArea, + 'itemid' => $itemId, + 'merchantorderid' => \core\uuid::generate(), + 'providertransactionid' => null, + 'amount' => $amount->toDecimal(), + 'currency' => AssistantProtocol::CURRENCY, + 'status' => TransactionStatus::New->value, + 'lasterror' => null, + 'snapshot' => $snapshot->toJson(), + 'timecreated' => $now, + 'timemodified' => $now, + 'timecompleted' => null, + ]; + $record->id = $DB->insert_record(self::TABLE, $record); + + return Order::fromRecord($record); + } + + public function findByMerchantOrderId(string $merchantOrderId): ?Order + { + global $DB; + + $record = $DB->get_record(self::TABLE, ['merchantorderid' => $merchantOrderId]); + + return $record === false ? null : Order::fromRecord($record); + } + + public function findById(int $id): ?Order + { + global $DB; + + $record = $DB->get_record(self::TABLE, ['id' => $id]); + + return $record === false ? null : Order::fromRecord($record); + } + + public function findOpenForItem(int $userId, string $component, string $paymentArea, int $itemId): ?Order + { + global $DB; + + [$statusSql, $params] = $DB->get_in_or_equal( + [TransactionStatus::New->value, TransactionStatus::Pending->value], + SQL_PARAMS_NAMED, + 'status', + ); + $records = $DB->get_records_select( + self::TABLE, + "userid = :userid AND component = :component AND paymentarea = :paymentarea AND itemid = :itemid AND status {$statusSql}", + $params + [ + 'userid' => $userId, + 'component' => $component, + 'paymentarea' => $paymentArea, + 'itemid' => $itemId, + ], + 'timecreated DESC, id DESC', + '*', + 0, + 1, + ); + $record = reset($records); + + return $record === false ? null : Order::fromRecord($record); + } + + /** + * Заказ покупателя по товару, у которого оплата прошла, а доставка сорвалась: + * новую оплату начинать нельзя — повтор уведомления доставит этот. + */ + public function findFailedForItem(int $userId, string $component, string $paymentArea, int $itemId): ?Order + { + global $DB; + + $records = $DB->get_records( + self::TABLE, + [ + 'userid' => $userId, + 'component' => $component, + 'paymentarea' => $paymentArea, + 'itemid' => $itemId, + 'status' => TransactionStatus::Failed->value, + ], + 'timecreated DESC, id DESC', + '*', + 0, + 1, + ); + $record = reset($records); + + return $record === false ? null : Order::fromRecord($record); + } + + /** + * Сервис начал оплату: пришёл проверочный запрос. + */ + public function markPending(Order $order): Order + { + if ($order->status !== TransactionStatus::New) { + return $order; + } + + return $this->update($order, ['status' => TransactionStatus::Pending->value]); + } + + /** + * Оплата подтверждена и доставлена: фиксируем операцию сервиса и платёж ядра. + */ + public function markPaid(Order $order, string $providerTransactionId, int $paymentId): Order + { + if (!$order->status->isPayable()) { + throw new InvalidArgumentException('Оплатить можно только неоплаченный и не отменённый заказ.'); + } + + return $this->update($order, [ + 'status' => TransactionStatus::Paid->value, + 'providertransactionid' => $providerTransactionId, + 'paymentid' => $paymentId, + 'lasterror' => null, + 'timecompleted' => time(), + ]); + } + + public function markCanceled(Order $order, RejectionReason $reason): Order + { + if (!$order->status->isOpen()) { + throw new InvalidArgumentException('Отменить можно только открытый заказ.'); + } + + return $this->update($order, ['status' => TransactionStatus::Canceled->value, 'lasterror' => $reason->value]); + } + + /** + * Зачисление сорвалось после подтверждённой оплаты — заказ требует внимания администратора. + */ + public function markFailed(Order $order, RejectionReason $reason): Order + { + if ($order->status === TransactionStatus::Paid) { + throw new InvalidArgumentException('Оплаченный заказ нельзя пометить ошибочным.'); + } + + return $this->update($order, ['status' => TransactionStatus::Failed->value, 'lasterror' => $reason->value]); + } + + /** + * Код причины последнего отказа без смены статуса (для отчёта администратора). + */ + public function noteError(Order $order, RejectionReason $reason): Order + { + return $this->update($order, ['lasterror' => $reason->value]); + } + + /** + * @param array $fields + */ + private function update(Order $order, array $fields): Order + { + global $DB; + + $record = (object) ($fields + ['id' => $order->id, 'timemodified' => time()]); + $DB->update_record(self::TABLE, $record); + $fresh = $DB->get_record(self::TABLE, ['id' => $order->id], '*', MUST_EXIST); + + return Order::fromRecord($fresh); + } +} diff --git a/classes/local/order/TransactionStatus.php b/classes/local/order/TransactionStatus.php new file mode 100644 index 0000000..9e0700a --- /dev/null +++ b/classes/local/order/TransactionStatus.php @@ -0,0 +1,42 @@ +isOpen() || $this === self::Failed; + } +} diff --git a/classes/local/protocol/AssistantProtocol.php b/classes/local/protocol/AssistantProtocol.php new file mode 100644 index 0000000..edb2be2 --- /dev/null +++ b/classes/local/protocol/AssistantProtocol.php @@ -0,0 +1,39 @@ +' . self::ORDER_ID . ') # UUID заказа + ' . self::SEPARATOR . ' # разделитель + [0-9]{14} # метка времени YmdHis + (?:[A-Z0-9+\-]{1,6})? # пояс: MSK, +03 — не обязателен + \z/x'; + + private function __construct() {} + + public static function build(string $orderId, ?DateTimeImmutable $now = null): string + { + $now ??= new DateTimeImmutable('now', core_date::get_server_timezone_object()); + + return $orderId . self::SEPARATOR . $now->format('YmdHisT'); + } + + public static function parse(string $raw): ?string + { + return preg_match(self::PATTERN, $raw, $matches) === 1 ? $matches['id'] : null; + } +} diff --git a/classes/local/protocol/CallbackNotification.php b/classes/local/protocol/CallbackNotification.php new file mode 100644 index 0000000..9b03ca7 --- /dev/null +++ b/classes/local/protocol/CallbackNotification.php @@ -0,0 +1,151 @@ + $fields + */ + public function __construct(array $fields) + { + $this->command = self::optional($fields, 'MNT_COMMAND'); + if (!in_array($this->command, ['', AssistantProtocol::COMMAND_CHECK], true)) { + throw new InvalidArgumentException('Неизвестная команда уведомления.'); + } + $this->accountId = self::required($fields, 'MNT_ID', self::ACCOUNT_ID_MAX_LENGTH); + $this->transactionId = self::required($fields, 'MNT_TRANSACTION_ID', self::TRANSACTION_ID_MAX_LENGTH); + $this->operationId = self::optional($fields, 'MNT_OPERATION_ID', self::OPERATION_ID_MAX_LENGTH); + $this->rawAmount = self::optional($fields, 'MNT_AMOUNT'); + $this->amount = $this->rawAmount === '' ? null : Money::fromDecimal($this->rawAmount); + $this->currency = self::required($fields, 'MNT_CURRENCY_CODE', 3); + $this->subscriberId = self::optional($fields, 'MNT_SUBSCRIBER_ID', self::SUBSCRIBER_ID_MAX_LENGTH); + $this->rawTestMode = self::required($fields, 'MNT_TEST_MODE', 1); + if (!in_array($this->rawTestMode, ['0', '1'], true)) { + throw new InvalidArgumentException('Недопустимое значение MNT_TEST_MODE.'); + } + $this->signature = self::required($fields, 'MNT_SIGNATURE', 32); + if (($this->amount === null || $this->operationId === '') && !$this->isCheck()) { + throw new InvalidArgumentException('Уведомлению об оплате нужны сумма и номер операции.'); + } + } + + public function isCheck(): bool + { + return $this->command === AssistantProtocol::COMMAND_CHECK; + } + + public function getCommand(): string + { + return $this->command; + } + + public function getAccountId(): string + { + return $this->accountId; + } + + public function getTransactionId(): string + { + return $this->transactionId; + } + + public function getOperationId(): string + { + return $this->operationId; + } + + public function getRawAmount(): string + { + return $this->rawAmount; + } + + public function getAmount(): ?Money + { + return $this->amount; + } + + public function getCurrency(): string + { + return $this->currency; + } + + public function getSubscriberId(): string + { + return $this->subscriberId; + } + + public function getRawTestMode(): string + { + return $this->rawTestMode; + } + + public function isTestMode(): bool + { + return $this->rawTestMode === '1'; + } + + public function isSignedBy(Signature $signature): bool + { + return Signature::equals($signature->forNotification($this), $this->signature); + } + + /** + * @param array $fields + */ + private static function required(array $fields, string $name, int $maxLength): string + { + $value = self::optional($fields, $name, $maxLength); + if ($value === '') { + throw new InvalidArgumentException("Не передано поле {$name}."); + } + + return $value; + } + + /** + * @param array $fields + */ + private static function optional(array $fields, string $name, int $maxLength = 255): string + { + if (!array_key_exists($name, $fields)) { + return ''; + } + + $value = $fields[$name]; + if (!is_string($value)) { + throw new InvalidArgumentException("Поле {$name} должно быть строкой."); + } + if (strlen($value) > $maxLength) { + throw new InvalidArgumentException("Поле {$name} длиннее допустимого."); + } + + return $value; + } +} diff --git a/classes/local/protocol/CallbackResponse.php b/classes/local/protocol/CallbackResponse.php new file mode 100644 index 0000000..49b1560 --- /dev/null +++ b/classes/local/protocol/CallbackResponse.php @@ -0,0 +1,39 @@ +resultCode; + } + + /** + * XML без атрибутов — для мерчанта без кассового сервиса. + */ + public function toXml(): CallbackResponse + { + return CallbackResponse::xml( + MntResponseXml::build( + accountId: $this->accountId, + transactionId: $this->transactionId, + resultCode: $this->resultCode, + amount: $this->amount, + signature: $this->sign(), + cms: $this->cms, + ), + ); + } + + /** + * JSON с чеком — для мерчанта с подключённой кассой. + */ + public function toJson(Receipt $receipt): CallbackResponse + { + if (!$receipt->matchesAmount($this->amount)) { + throw new InvalidArgumentException('Сумма позиций чека не совпадает с суммой заказа.'); + } + + return CallbackResponse::json(JsonNumber::encode([ + 'id' => $this->accountId, + 'transactionId' => $this->transactionId, + 'amount' => JsonNumber::placeholder($this->amount), + 'signature' => $this->sign(), + 'resultCode' => (string) $this->resultCode->value, + 'description' => $this->resultCode->description(), + 'cms' => $this->cms, + 'receipt' => $receipt->toCheckReceipt(), + ])); + } + + private function sign(): string + { + return $this->signature->forResponse($this->resultCode, $this->accountId, $this->transactionId); + } +} diff --git a/classes/local/protocol/MntResponseXml.php b/classes/local/protocol/MntResponseXml.php new file mode 100644 index 0000000..8a5cce3 --- /dev/null +++ b/classes/local/protocol/MntResponseXml.php @@ -0,0 +1,79 @@ + $attributes пары KEY → VALUE для `MNT_ATTRIBUTES` + * @throws \DOMException + */ + public static function build( + string $accountId, + string $transactionId, + ResultCode $resultCode, + Money $amount, + string $signature, + string $cms, + array $attributes = [], + ): string { + $document = new DOMDocument('1.0', 'UTF-8'); + $response = $document->appendChild($document->createElement('MNT_RESPONSE')); + $elements = [ + 'MNT_ID' => $accountId, + 'MNT_TRANSACTION_ID' => $transactionId, + 'MNT_RESULT_CODE' => (string) $resultCode->value, + 'MNT_DESCRIPTION' => $resultCode->description(), + 'MNT_AMOUNT' => $amount->toDecimal(), + 'MNT_SIGNATURE' => $signature, + 'MNT_CMS' => $cms, + ]; + foreach ($elements as $name => $value) { + self::text($document, $response, $name, $value); + } + if ($attributes !== []) { + $container = $response->appendChild($document->createElement('MNT_ATTRIBUTES')); + foreach ($attributes as $key => $value) { + $attribute = $container->appendChild($document->createElement('ATTRIBUTE')); + self::text($document, $attribute, 'KEY', $key); + self::text($document, $attribute, 'VALUE', $value); + } + } + + $xml = $document->saveXML(); + if ($xml === false) { + throw new \RuntimeException('Не удалось сериализовать MNT_RESPONSE.'); + } + + return $xml; + } + + /** + * Текстовый узел, а не `createElement($name, $value)`: второй не экранирует `&`. + */ + private static function text(DOMDocument $document, DOMNode $parent, string $name, string $value): void + { + $parent->appendChild($document->createElement($name))->appendChild($document->createTextNode($value)); + } +} diff --git a/classes/local/protocol/PayResponse.php b/classes/local/protocol/PayResponse.php new file mode 100644 index 0000000..9f69eda --- /dev/null +++ b/classes/local/protocol/PayResponse.php @@ -0,0 +1,56 @@ +receipt !== null) { + $attributes['INVENTORY'] = $this->receipt->toInventoryAttribute(); + $attributes['CLIENT'] = $this->receipt->toClientAttribute(); + $duplicates = [ + 'CUSTOMER' => $this->receipt->toCustomerAttribute(), + 'PHONE' => $this->receipt->toPhoneAttribute(), + ]; + $attributes += array_filter($duplicates, static fn(?string $value): bool => $value !== null); + } + + return CallbackResponse::xml( + MntResponseXml::build( + accountId: $this->accountId, + transactionId: $this->transactionId, + resultCode: $this->resultCode, + amount: $this->amount, + signature: $this->signature->forResponse($this->resultCode, $this->accountId, $this->transactionId), + cms: $this->cms, + attributes: $attributes, + ), + ); + } +} diff --git a/classes/local/protocol/PaymentRequest.php b/classes/local/protocol/PaymentRequest.php new file mode 100644 index 0000000..2e1d1a1 --- /dev/null +++ b/classes/local/protocol/PaymentRequest.php @@ -0,0 +1,90 @@ +isPositive()) { + throw new InvalidArgumentException('Сумма платежа должна быть больше нуля.'); + } + } + + public function getActionUrl(): string + { + return $this->server->url(); + } + + /** + * @return array + */ + public function getFields(): array + { + return [ + 'MNT_ID' => $this->accountId, + 'MNT_TRANSACTION_ID' => $this->transactionId, + 'MNT_AMOUNT' => $this->amount->toDecimal(), + 'MNT_CURRENCY_CODE' => AssistantProtocol::CURRENCY, + 'MNT_SUBSCRIBER_ID' => $this->subscriberId, + 'MNT_TEST_MODE' => AssistantProtocol::testModeFlag($this->testMode), + 'MNT_DESCRIPTION' => mb_substr($this->description, 0, self::DESCRIPTION_MAX_LENGTH), + 'MNT_SUCCESS_URL' => $this->successUrl, + 'MNT_FAIL_URL' => $this->failUrl, + 'MNT_RETURN_URL' => $this->returnUrl, + 'moneta.locale' => $this->locale, + 'MNT_CMS' => $this->cms, + 'MNT_SIGNATURE' => $this->signature->forPaymentForm( + accountId: $this->accountId, + transactionId: $this->transactionId, + amount: $this->amount, + currency: AssistantProtocol::CURRENCY, + subscriberId: $this->subscriberId, + testMode: $this->testMode, + ), + ]; + } +} diff --git a/classes/local/protocol/PaymentServer.php b/classes/local/protocol/PaymentServer.php new file mode 100644 index 0000000..8738c9c --- /dev/null +++ b/classes/local/protocol/PaymentServer.php @@ -0,0 +1,40 @@ + 'https://www.payanyway.ru/assistant.htm', + self::Demo => 'https://demo.moneta.ru/assistant.htm', + }; + } + + /** + * Ключ строки интерфейса (`server_prod`, `server_demo`). + */ + public function label(): string + { + return 'server_' . strtolower($this->value); + } + + public static function fromSetting(?string $value): self + { + return self::tryFrom((string) $value) ?? self::Prod; + } +} diff --git a/classes/local/protocol/ResultCode.php b/classes/local/protocol/ResultCode.php new file mode 100644 index 0000000..4e1fa91 --- /dev/null +++ b/classes/local/protocol/ResultCode.php @@ -0,0 +1,49 @@ + 'Order amount', + self::Paid => 'Order is paid', + self::InProgress => 'Order is being processed', + self::AwaitingPayment => 'Order created, but not paid', + self::Rejected => 'Order is not available', + }; + } +} diff --git a/classes/local/protocol/Signature.php b/classes/local/protocol/Signature.php new file mode 100644 index 0000000..dcbe44e --- /dev/null +++ b/classes/local/protocol/Signature.php @@ -0,0 +1,106 @@ +hash( + $accountId + . $transactionId + . $amount->toDecimal() + . $currency + . $subscriberId + . AssistantProtocol::testModeFlag($testMode), + ); + } + + /** + * Формула 2 — входящий запрос на Check URL / Pay URL (сервис → модуль). + * + * md5(MNT_COMMAND + MNT_ID + MNT_TRANSACTION_ID + MNT_OPERATION_ID + MNT_AMOUNT + * + MNT_CURRENCY_CODE + MNT_SUBSCRIBER_ID + MNT_TEST_MODE + КОД) + * + * Значения берутся из запроса как пришли: подпись сверяется с тем, что + * подписал сервис, а не с нашим представлением о заказе. + */ + public function forNotification(CallbackNotification $notification): string + { + return $this->hash( + $notification->getCommand() + . $notification->getAccountId() + . $notification->getTransactionId() + . $notification->getOperationId() + . $notification->getRawAmount() + . $notification->getCurrency() + . $notification->getSubscriberId() + . $notification->getRawTestMode(), + ); + } + + /** + * Формула 3 — ответ модуля на Check URL и Pay URL. + * + * md5(MNT_RESULT_CODE + MNT_ID + MNT_TRANSACTION_ID + КОД) + */ + public function forResponse(ResultCode $resultCode, string $accountId, string $transactionId): string + { + return $this->hash((string) $resultCode->value . $accountId . $transactionId); + } + + /** + * Сравнение без утечки по времени; регистр hex-строки не важен. + */ + public static function equals(string $expected, string $received): bool + { + if (preg_match(self::PATTERN, $received) !== 1) { + return false; + } + + return hash_equals(strtolower($expected), strtolower($received)); + } + + private function hash(string $payload): string + { + return md5($payload . $this->integrityCode); + } +} diff --git a/classes/local/receipt/Client.php b/classes/local/receipt/Client.php new file mode 100644 index 0000000..1b65211 --- /dev/null +++ b/classes/local/receipt/Client.php @@ -0,0 +1,110 @@ + + */ + public function toArray(): array + { + return array_filter( + ['name' => $this->name, 'email' => $this->email, 'phone' => $this->phone], + static fn(?string $value): bool => $value !== null, + ); + } + + public static function normalizeEmail(?string $email): ?string + { + $email = trim((string) $email); + if ( + $email === '' + || strlen($email) > self::EMAIL_MAX_LENGTH + || filter_var($email, FILTER_VALIDATE_EMAIL) === false + ) { + return null; + } + + return $email; + } + + public static function normalizePhone(?string $phone): ?string + { + $digits = preg_replace('/[^0-9]/', '', (string) $phone) ?? ''; + if ($digits === '' || strlen($digits) + 1 > self::PHONE_MAX_LENGTH) { + return null; + } + + return '+' . $digits; + } + + private static function normalizeName(?string $name): ?string + { + $name = ReceiptText::validate((string) $name, self::NAME_MAX_LENGTH); + + return $name === '' ? null : $name; + } +} diff --git a/classes/local/receipt/JsonNumber.php b/classes/local/receipt/JsonNumber.php new file mode 100644 index 0000000..ba5d19b --- /dev/null +++ b/classes/local/receipt/JsonNumber.php @@ -0,0 +1,40 @@ +toDecimal(); + } + + /** + * @param array $payload + * @throws \JsonException + */ + public static function encode(array $payload): string + { + $json = json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + return preg_replace('/"' . preg_quote(self::PREFIX, '/') . '([0-9]+\.[0-9]{2})"/', '$1', $json) ?? $json; + } +} diff --git a/classes/local/receipt/PaymentMethod.php b/classes/local/receipt/PaymentMethod.php new file mode 100644 index 0000000..5d003db --- /dev/null +++ b/classes/local/receipt/PaymentMethod.php @@ -0,0 +1,23 @@ + */ + public readonly array $items; + + /** + * @param list $items + */ + public function __construct( + public readonly Client $client, + array $items, + ) { + if ($items === []) { + throw new InvalidArgumentException('Чек без позиций.'); + } + + foreach ($items as $item) { + if (!$item instanceof ReceiptItem) { + throw new InvalidArgumentException('Позиция чека должна быть ReceiptItem.'); + } + } + $this->items = array_values($items); + } + + /** + * Единственная позиция «доступ к курсу» на всю сумму заказа. + */ + public static function forCourse(string $courseName, Money $amount, Client $client, Vat $vat): self + { + return new self($client, [ + new ReceiptItem( + name: $courseName, + price: $amount, + quantity: 1, + vat: $vat, + paymentMethod: PaymentMethod::FullPayment, + paymentObject: PaymentObject::Service, + ), + ]); + } + + public function total(): Money + { + $total = Money::fromMinorUnits(0); + foreach ($this->items as $item) { + $total = $total->add($item->total()); + } + + return $total; + } + + public function matchesAmount(Money $amount): bool + { + return $this->total()->equals($amount); + } + + /** + * Объект `receipt` JSON-ответа Check URL. + * + * @return array{client: array, items: list>} + */ + public function toCheckReceipt(): array + { + return [ + 'client' => $this->client->toArray(), + 'items' => array_map(static fn(ReceiptItem $item): array => $item->toCheckItem(), $this->items), + ]; + } + + /** + * Значение атрибута `INVENTORY` — JSON-массив позиций. + * + * @throws \JsonException + */ + public function toInventoryAttribute(): string + { + return json_encode( + array_map(static fn(ReceiptItem $item): array => $item->toInventoryPosition(), $this->items), + JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, + ); + } + + /** + * Значение атрибута `CLIENT` — JSON-массив из одного объекта. + * + * @throws \JsonException + */ + public function toClientAttribute(): string + { + return json_encode( + [$this->client->toArray()], + JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, + ); + } + + /** + * Значение атрибута `CUSTOMER` — e-mail покупателя строкой, по + * `cmsspecification.pdf`; дублирует `CLIENT.email`, чтобы чек принимался при + * любой трактовке документов. `null` — у покупателя + * только телефон. + */ + public function toCustomerAttribute(): ?string + { + return $this->client->email; + } + + /** + * Значение атрибута `PHONE` — телефон покупателя без `+`, как в примере + * `cmsspecification.pdf`; дублирует `CLIENT.phone`. `null` — телефона нет. + */ + public function toPhoneAttribute(): ?string + { + $phone = $this->client->phone; + + return $phone === null ? null : ltrim($phone, '+'); + } + + /** + * @return array{client: array, items: list>} + */ + public function toArray(): array + { + return [ + 'client' => $this->client->toArray(), + 'items' => array_map(static fn(ReceiptItem $item): array => $item->toArray(), $this->items), + ]; + } + + /** + * @param array{client?: array, items?: list>} $data + */ + public static function fromArray(array $data): self + { + $client = Client::fromArray(is_array($data['client'] ?? null) ? $data['client'] : []); + $items = array_map(static fn(array $item): ReceiptItem => ReceiptItem::fromArray($item), $data['items'] ?? []); + + return new self($client, $items); + } +} diff --git a/classes/local/receipt/ReceiptItem.php b/classes/local/receipt/ReceiptItem.php new file mode 100644 index 0000000..d15742e --- /dev/null +++ b/classes/local/receipt/ReceiptItem.php @@ -0,0 +1,127 @@ +name = ($name === '') ? self::FALLBACK_NAME : $name; + + if ($quantity < 1 || $quantity > 99999) { + throw new InvalidArgumentException('Количество позиции вне допустимых границ.'); + } + + $max = Money::fromDecimal(self::PRICE_MAX)->toMinorUnits(); + if ($price->toMinorUnits() > $max || $this->total()->toMinorUnits() > $max) { + throw new InvalidArgumentException('Цена позиции превышает потолок кассы.'); + } + } + + public function total(): Money + { + return $this->price->multiply($this->quantity); + } + + /** + * Элемент `items` для JSON-ответа Check URL: числа — числа, ставка — строкой `vat`. + * Цена подставляется меткой, чтобы в JSON осталось ровно два знака (`100.00`). + * + * @return array + */ + public function toCheckItem(): array + { + return [ + 'name' => $this->name, + 'price' => JsonNumber::placeholder($this->price), + 'quantity' => $this->quantity, + 'measure' => self::MEASURE, + 'paymentMethod' => $this->paymentMethod->value, + 'paymentObject' => $this->paymentObject->value, + 'vat' => $this->vat->value, + ]; + } + + /** + * Объект `inventPositions` для атрибута `INVENTORY`: цена и количество — + * строками, как в примере спецификации Moneta. + * + * @return array + */ + public function toInventoryPosition(): array + { + return [ + 'name' => $this->name, + 'price' => $this->price->toDecimal(), + 'quantity' => (string) $this->quantity, + 'measure' => self::MEASURE, + 'vatTag' => $this->vat->tag(), + 'pm' => $this->paymentMethod->value, + 'po' => $this->paymentObject->value, + ]; + } + + /** + * @return array + */ + public function toArray(): array + { + return [ + 'name' => $this->name, + 'price' => $this->price->toDecimal(), + 'quantity' => $this->quantity, + 'vat' => $this->vat->value, + 'paymentMethod' => $this->paymentMethod->value, + 'paymentObject' => $this->paymentObject->value, + ]; + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + name: (string) ($data['name'] ?? ''), + price: Money::fromDecimal((string) ($data['price'] ?? '')), + quantity: (int) ($data['quantity'] ?? 0), + vat: Vat::from((string) ($data['vat'] ?? '')), + paymentMethod: PaymentMethod::from((string) ($data['paymentMethod'] ?? '')), + paymentObject: PaymentObject::from((string) ($data['paymentObject'] ?? '')), + ); + } + +} diff --git a/classes/local/receipt/ReceiptText.php b/classes/local/receipt/ReceiptText.php new file mode 100644 index 0000000..c8656ac --- /dev/null +++ b/classes/local/receipt/ReceiptText.php @@ -0,0 +1,38 @@ + 3 ? '...' : ''); + } + + public static function sanitize(string $value): string + { + $decoded = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + $whitelisted = preg_replace('/[^\p{L}\p{N}\s.,()_№+-]/u', '', $decoded) ?? ''; + $collapsed = preg_replace('/\s+/u', ' ', $whitelisted) ?? $whitelisted; + + return trim($collapsed); + } +} diff --git a/classes/local/receipt/Vat.php b/classes/local/receipt/Vat.php new file mode 100644 index 0000000..e14a297 --- /dev/null +++ b/classes/local/receipt/Vat.php @@ -0,0 +1,60 @@ + '1105', + self::Vat0 => '1104', + self::Vat5 => '1108', + self::Vat7 => '1109', + self::Vat10 => '1103', + self::Vat20 => '1102', + self::Vat22 => '1113', + self::Vat105 => '1110', + self::Vat107 => '1111', + self::Vat110 => '1107', + self::Vat120 => '1106', + self::Vat122 => '1114', + }; + } + + /** + * Ключ строки в `lang/{ru,en}/paygw_moneta.php`. + */ + public function langKey(): string + { + return 'vat:' . $this->value; + } +} diff --git a/classes/privacy/provider.php b/classes/privacy/provider.php new file mode 100644 index 0000000..78c321d --- /dev/null +++ b/classes/privacy/provider.php @@ -0,0 +1,176 @@ +add_database_table(TransactionRepository::TABLE, [ + 'userid' => 'privacy:metadata:transactions:userid', + 'amount' => 'privacy:metadata:transactions:amount', + 'status' => 'privacy:metadata:transactions:status', + 'merchantorderid' => 'privacy:metadata:transactions:merchantorderid', + 'providertransactionid' => 'privacy:metadata:transactions:providertransactionid', + 'snapshot' => 'privacy:metadata:transactions:snapshot', + 'timecreated' => 'privacy:metadata:transactions:timecreated', + ], 'privacy:metadata:transactions'); + $collection->add_external_location_link('moneta', [ + 'userid' => 'privacy:metadata:moneta:userid', + 'fullname' => 'privacy:metadata:moneta:fullname', + 'email' => 'privacy:metadata:moneta:email', + 'phone' => 'privacy:metadata:moneta:phone', + 'amount' => 'privacy:metadata:moneta:amount', + ], 'privacy:metadata:moneta'); + + return $collection; + } + + public static function get_contexts_for_userid(int $userid): contextlist + { + global $DB; + + $contextlist = new contextlist(); + if ($DB->record_exists(TransactionRepository::TABLE, ['userid' => $userid])) { + $contextlist->add_system_context(); + } + + return $contextlist; + } + + public static function get_users_in_context(userlist $userlist): void + { + if (!$userlist->get_context() instanceof context_system) { + return; + } + $userlist->add_from_sql('userid', 'SELECT userid FROM {' . TransactionRepository::TABLE . '}', []); + } + + public static function export_user_data(approved_contextlist $contextlist): void + { + global $DB; + + foreach ($contextlist->get_contexts() as $context) { + if (!$context instanceof context_system) { + continue; + } + + $records = $DB->get_records( + TransactionRepository::TABLE, + ['userid' => $contextlist->get_user()->id], + 'timecreated', + ); + + $orders = []; + foreach ($records as $record) { + $orders[] = self::describe(Order::fromRecord($record)); + } + if ($orders !== []) { + writer::with_context($context)->export_data( + [get_string('gatewayname', 'paygw_moneta')], + (object) ['orders' => $orders], + ); + } + } + } + + public static function delete_data_for_all_users_in_context(context $context): void + { + global $DB; + + if ($context instanceof context_system) { + $DB->delete_records(TransactionRepository::TABLE); + } + } + + public static function delete_data_for_user(approved_contextlist $contextlist): void + { + global $DB; + + foreach ($contextlist->get_contexts() as $context) { + if ($context instanceof context_system) { + $DB->delete_records(TransactionRepository::TABLE, ['userid' => $contextlist->get_user()->id]); + } + } + } + + public static function delete_data_for_users(approved_userlist $userlist): void + { + global $DB; + + if (!$userlist->get_context() instanceof context_system || $userlist->get_userids() === []) { + return; + } + [$sql, $params] = $DB->get_in_or_equal($userlist->get_userids(), SQL_PARAMS_NAMED); + $DB->delete_records_select(TransactionRepository::TABLE, "userid {$sql}", $params); + } + + public static function export_payment_data(context $context, array $subcontext, \stdClass $payment): void + { + global $DB; + + $record = $DB->get_record(TransactionRepository::TABLE, ['paymentid' => $payment->id]); + if ($record === false) { + return; + } + + $subcontext[] = get_string('gatewayname', 'paygw_moneta'); + writer::with_context($context)->export_data($subcontext, self::describe(Order::fromRecord($record))); + } + + public static function delete_data_for_payment_sql(string $paymentsql, array $paymentparams): void + { + global $DB; + + $DB->delete_records_select(TransactionRepository::TABLE, "paymentid IN ({$paymentsql})", $paymentparams); + } + + /** + * Заказ в выгрузке: без внутренних идентификаторов и без данных кассы сверх контактов. + */ + private static function describe(Order $order): \stdClass + { + return (object) [ + 'merchantorderid' => $order->merchantOrderId, + 'providertransactionid' => $order->providerTransactionId, + 'amount' => $order->amount->toDecimal() . ' ' . $order->currency, + 'status' => $order->status->value, + 'description' => $order->snapshot->description, + 'client' => $order->snapshot->receipt->client->toArray(), + 'timecreated' => transform::datetime($order->timeCreated), + 'timecompleted' => $order->timeCompleted === null ? null : transform::datetime($order->timeCompleted), + ]; + } +} diff --git a/db/install.php b/db/install.php new file mode 100644 index 0000000..7a20476 --- /dev/null +++ b/db/install.php @@ -0,0 +1,36 @@ +. + +/** + * Действия после установки платёжного шлюза Moneta. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Включает шлюз в «Управлении платёжными шлюзами», чтобы мерчанту оставалось + * только настроить платёжный аккаунт. Пока у аккаунта не заданы реквизиты, + * шлюз покупателю не предлагается (`GatewayConfig::acceptsNewOrders`). + * + * @return bool + */ +function xmldb_paygw_moneta_install(): bool { + \core\plugininfo\paygw::enable_plugin('moneta', 1); + + return true; +} diff --git a/db/install.xml b/db/install.xml new file mode 100644 index 0000000..f1bafa9 --- /dev/null +++ b/db/install.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
diff --git a/db/messages.php b/db/messages.php new file mode 100644 index 0000000..09a2d62 --- /dev/null +++ b/db/messages.php @@ -0,0 +1,46 @@ +. + +/** + * Провайдеры сообщений шлюза Moneta. + * + * `payment_received` — покупателю после подтверждённой оплаты (Pay URL). + * `payment_link` — покупателю ссылка на оплату созданного заказа (настройка + * шлюза «Отправлять ссылку оплаты на почту»). + * Канал (веб-уведомление, e-mail, приложение) выбирает пользователь в своих + * настройках уведомлений; значения по умолчанию задаёт администратор. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$messageproviders = [ + 'payment_received' => [ + 'defaults' => [ + 'popup' => MESSAGE_PERMITTED + MESSAGE_DEFAULT_ENABLED, + 'email' => MESSAGE_PERMITTED + MESSAGE_DEFAULT_ENABLED, + ], + ], + 'payment_link' => [ + 'defaults' => [ + 'popup' => MESSAGE_PERMITTED + MESSAGE_DEFAULT_ENABLED, + 'email' => MESSAGE_PERMITTED + MESSAGE_DEFAULT_ENABLED, + ], + ], +]; diff --git a/db/upgrade.php b/db/upgrade.php new file mode 100644 index 0000000..cff256f --- /dev/null +++ b/db/upgrade.php @@ -0,0 +1,33 @@ +. + +/** + * Шаги обновления платёжного шлюза Moneta. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Обновление плагина до текущей версии. + * + * @param int $oldversion установленная версия + * @return bool + */ +function xmldb_paygw_moneta_upgrade(int $oldversion): bool { + return true; +} diff --git a/environment.xml b/environment.xml new file mode 100644 index 0000000..b543a52 --- /dev/null +++ b/environment.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/lang/en/paygw_moneta.php b/lang/en/paygw_moneta.php new file mode 100644 index 0000000..d09a16e --- /dev/null +++ b/lang/en/paygw_moneta.php @@ -0,0 +1,135 @@ +. + +/** + * Строки платёжного шлюза Moneta (английский). + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$string['pluginname'] = 'Moneta'; +$string['gatewayname'] = $string['pluginname']; +$string['gatewaydescription'] = 'Accepting payments by bank cards, via SBP and Pay services'; +$string['pluginname_desc'] = "The plugin allows you to receive payments via {$string['pluginname']}"; +$string['settingsintro'] = 'Account credentials are set on the payment account: Site administration → Payments → Payment accounts'; + +$string['accountnumber'] = 'Account number'; +$string['accountnumber_help'] = 'Extended account number in MONETA.RU'; +$string['integritycode'] = 'Data integrity code'; +$string['integritycode_help'] = 'Data integrity code from the extended account settings in MONETA.RU'; +$string['paymentserver'] = 'Payment server'; +$string['paymentserver_help'] = 'Use the live server for real payments; the demo platform is for checking the connection'; +$string['server_demo'] = 'Demo'; +$string['server_prod'] = 'Production'; +$string['testmode'] = 'Test mode'; +$string['testmode_help'] = 'Simulated payment without charging money. Must match the account setting in MONETA.RU'; +$string['receiptemail'] = 'Receipt email'; +$string['receiptemail_help'] = 'Used in the receipt only when the buyer has neither an email nor a phone in their profile: the fiscal service rejects a receipt without a contact, so it is sent to this address instead (the buyer name stays in the receipt)'; +$string['error:receiptemail'] = 'Enter a valid email address of at most 64 characters'; +$string['fiscalization'] = 'Fiscal receipts'; +$string['fiscalization_help'] = 'Enable only if the kassa.payanyway.ru service is connected to the account: the check request response will contain receipt data'; +$string['vat'] = 'VAT rate'; +$string['vat_help'] = 'VAT rate for the "course access" receipt line'; +$string['vat:none'] = 'No VAT'; +$string['vat:vat0'] = 'VAT 0%'; +$string['vat:vat5'] = 'VAT 5%'; +$string['vat:vat7'] = 'VAT 7%'; +$string['vat:vat10'] = 'VAT 10%'; +$string['vat:vat20'] = 'VAT 20%'; +$string['vat:vat22'] = 'VAT 22%'; +$string['vat:vat105'] = 'VAT 5% (calculated rate 5/105)'; +$string['vat:vat107'] = 'VAT 7% (calculated rate 7/107)'; +$string['vat:vat110'] = 'VAT 10% (calculated rate 10/110)'; +$string['vat:vat120'] = 'VAT 20% (calculated rate 20/120)'; +$string['vat:vat122'] = 'VAT 22% (calculated rate 22/122)'; +$string['sendpaymentlink'] = 'Send payment link by email'; +$string['sendpaymentlink_help'] = 'If enabled, the buyer receives a message with a payment link when an order is created, so they can pay later. The link works while the order is unpaid and the price and credentials are unchanged. The channel (email, site notification) follows Moodle notification preferences'; +$string['callbackurl'] = 'Notification URL'; +$string['callbackurl:copied'] = 'Notification URL copied'; +$string['callbackurl_help'] = 'Set this address as both Pay URL and Check URL in the MONETA.RU account settings. It must be reachable from the internet over HTTPS'; + +$string['checkout:access'] = 'Access to the course opens automatically after payment.'; +$string['checkout:course'] = 'Course payment'; +$string['checkout:item'] = 'Payment'; +$string['checkout:secure'] = "You will be taken to the secure {$string['pluginname']} payment page."; +$string['checkout:total'] = 'Amount due'; +$string['confirmpayment'] = "Proceeding to {$string['pluginname']} payment"; +$string['pay'] = 'Pay {$a}'; +$string['redirecting'] = 'Proceeding to payment…'; +$string['paymentconfirmed'] = 'Payment confirmed'; +$string['paymentpending'] = 'Waiting for payment confirmation'; +$string['paymentpending_help'] = 'Returning from the payment page does not confirm the payment yet. Access is granted after a verified notification from MONETA.RU, usually within a minute'; +$string['paymentnotcompleted'] = 'The payment was not completed. You can try again'; + +$string['genericitem'] = 'Payment in Moodle'; +$string['error:orderinprogress'] = 'The previous payment is still being processed. If access does not appear within an hour, contact the site administrator'; +$string['environmentrequirephp81'] = 'The paygw_moneta plugin requires PHP 8.1 or later'; +$string['messageprovider:payment_received'] = "Payment received ({$string['pluginname']})"; +$string['message:paid:subject'] = 'Payment received: {$a->description}'; +$string['message:paid'] = 'Hello {$a->firstname}, + +Your payment of **{$a->amount}** for "{$a->description}" at {$a->sitename} has been received and access is open. + +MONETA.RU operation number: {$a->operationid}. + +Go to: {$a->url}'; +$string['messageprovider:payment_link'] = "Payment link ({$string['pluginname']})"; +$string['message:link:subject'] = 'Payment link: {$a->description}'; +$string['message:link'] = 'Hello {$a->firstname}, + +An order for "{$a->description}" of **{$a->amount}** has been created at {$a->sitename}. + +Pay: {$a->url} + +The link works while the order is unpaid and the price and payment settings are unchanged.'; +$string['error:paymentlinkexpired'] = 'This payment link is no longer valid: the order was canceled or the price or payment settings changed. Please start the payment again from the course page'; +$string['error:invalidamount'] = 'The payment amount must be greater than zero'; +$string['error:unsupportedcurrency'] = "{$string['pluginname']} only supports payments in RUB"; +$string['error:accountnumber'] = 'The account number consists of digits only'; +$string['error:ordernotfound'] = 'Order not found'; + +$string['report:title'] = "{$string['pluginname']} orders"; +$string['report:time'] = 'Created'; +$string['report:user'] = 'Buyer'; +$string['report:description'] = 'Order'; +$string['report:amount'] = 'Amount'; +$string['report:status'] = 'Status'; +$string['report:operation'] = 'MONETA.RU operation'; +$string['report:lasterror'] = 'Last rejection'; +$string['status:new'] = 'Created'; +$string['status:pending'] = 'Paying'; +$string['status:paid'] = 'Paid'; +$string['status:canceled'] = 'Canceled'; +$string['status:failed'] = 'Delivery failed'; + +$string['privacy:metadata:transactions'] = "Orders created when paying through {$string['pluginname']}"; +$string['privacy:metadata:transactions:userid'] = 'Buyer'; +$string['privacy:metadata:transactions:amount'] = 'Order amount'; +$string['privacy:metadata:transactions:status'] = 'Payment status'; +$string['privacy:metadata:transactions:merchantorderid'] = 'Order identifier sent to MONETA.RU'; +$string['privacy:metadata:transactions:providertransactionid'] = 'Operation number in MONETA.RU'; +$string['privacy:metadata:transactions:snapshot'] = 'Snapshot of settings and receipt: course name, buyer full name, e-mail and phone, buyer identifier for MONETA.RU'; +$string['privacy:metadata:transactions:timecreated'] = 'Order creation time'; +$string['privacy:metadata:moneta'] = 'Data sent to the MONETA.RU payment service to process the payment and issue a receipt'; +$string['privacy:metadata:moneta:userid'] = 'Buyer identifier (MNT_SUBSCRIBER_ID): e-mail, otherwise phone, otherwise Moodle user id'; +$string['privacy:metadata:moneta:fullname'] = 'Buyer full name for the fiscal receipt'; +$string['privacy:metadata:moneta:email'] = 'Buyer e-mail for the receipt'; +$string['privacy:metadata:moneta:phone'] = 'Buyer phone for the receipt'; +$string['privacy:metadata:moneta:amount'] = 'Payment amount'; diff --git a/lang/ru/paygw_moneta.php b/lang/ru/paygw_moneta.php new file mode 100644 index 0000000..3a2f344 --- /dev/null +++ b/lang/ru/paygw_moneta.php @@ -0,0 +1,135 @@ +. + +/** + * Строки платёжного шлюза Moneta (русский). + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$string['pluginname'] = 'Монета'; +$string['gatewayname'] = $string['pluginname']; +$string['gatewaydescription'] = 'Приём платежей банковскими картами, через СБП и Pay‑сервисы'; +$string['pluginname_desc'] = "Плагин позволяет получать платежи через {$string['pluginname']}"; +$string['settingsintro'] = 'Реквизиты счёта задаются в платёжном аккаунте: Администрирование сайта → Платежи → Платёжные аккаунты'; + +$string['accountnumber'] = 'Номер счёта'; +$string['accountnumber_help'] = 'Номер расширенного счёта в системе MONETA.RU'; +$string['integritycode'] = 'Код проверки целостности данных'; +$string['integritycode_help'] = 'Код проверки целостности данных из настроек расширенного счёта в системе MONETA.RU'; +$string['paymentserver'] = 'Сервер платежей'; +$string['paymentserver_help'] = 'Для реальных платежей используйте боевой сервер; демо-площадка — для проверки подключения'; +$string['server_demo'] = 'Демо'; +$string['server_prod'] = 'Боевой'; +$string['testmode'] = 'Тестовый режим'; +$string['testmode_help'] = 'Имитация оплаты без реального списания средств. Режим должен совпадать с настройкой счёта в MONETA.RU'; +$string['receiptemail'] = 'Email для чеков'; +$string['receiptemail_help'] = 'Подставляется в чек, только если у покупателя в профиле нет ни e-mail, ни телефона: без контакта касса чек не примет, поэтому он уйдёт на этот адрес (ФИО покупателя в чеке остаётся)'; +$string['error:receiptemail'] = 'Укажите корректный e-mail не длиннее 64 символов'; +$string['fiscalization'] = 'Фискализация чеков'; +$string['fiscalization_help'] = 'Включайте только если к счёту подключён кассовый сервис kassa.payanyway.ru: ответ на проверочный запрос будет содержать данные чека по 54-ФЗ'; +$string['vat'] = 'Ставка НДС'; +$string['vat_help'] = 'Ставка НДС для позиции «доступ к курсу» в кассовом чеке'; +$string['vat:none'] = 'Без НДС'; +$string['vat:vat0'] = 'НДС 0%'; +$string['vat:vat5'] = 'НДС 5%'; +$string['vat:vat7'] = 'НДС 7%'; +$string['vat:vat10'] = 'НДС 10%'; +$string['vat:vat20'] = 'НДС 20%'; +$string['vat:vat22'] = 'НДС 22%'; +$string['vat:vat105'] = 'НДС 5% (расчётная ставка 5/105)'; +$string['vat:vat107'] = 'НДС 7% (расчётная ставка 7/107)'; +$string['vat:vat110'] = 'НДС 10% (расчётная ставка 10/110)'; +$string['vat:vat120'] = 'НДС 20% (расчётная ставка 20/120)'; +$string['vat:vat122'] = 'НДС 22% (расчётная ставка 22/122)'; +$string['sendpaymentlink'] = 'Отправлять ссылку оплаты на почту'; +$string['sendpaymentlink_help'] = 'Если включено, при создании заказа покупателю приходит сообщение со ссылкой на оплату — оплатить можно позже. Ссылка действует, пока заказ не оплачен и не изменились цена или реквизиты. Канал (почта, уведомление на сайте) — по настройкам уведомлений Moodle'; +$string['callbackurl'] = 'URL для уведомлений'; +$string['callbackurl:copied'] = 'URL для уведомлений скопирован'; +$string['callbackurl_help'] = 'Укажите этот адрес в настройках счёта MONETA.RU как Pay URL и Check URL. Он должен быть доступен из интернета по HTTPS'; + +$string['checkout:access'] = 'Доступ к курсу откроется автоматически после оплаты.'; +$string['checkout:course'] = 'Оплата курса'; +$string['checkout:item'] = 'Оплата'; +$string['checkout:secure'] = "Вы перейдёте на защищённую страницу оплаты {$string['pluginname']}."; +$string['checkout:total'] = 'К оплате'; +$string['confirmpayment'] = "Переход к оплате через {$string['pluginname']}"; +$string['pay'] = 'Оплатить {$a}'; +$string['redirecting'] = 'Переходим к оплате…'; +$string['paymentconfirmed'] = 'Оплата подтверждена'; +$string['paymentpending'] = 'Ожидание подтверждения оплаты'; +$string['paymentpending_help'] = 'Возврат с платёжной страницы ещё не подтверждает оплату. Доступ будет открыт после проверенного уведомления от MONETA.RU — обычно в течение минуты'; +$string['paymentnotcompleted'] = 'Оплата не была завершена. Вы можете попробовать ещё раз.'; + +$string['genericitem'] = 'Оплата в Moodle'; +$string['error:orderinprogress'] = 'Предыдущая оплата ещё обрабатывается. Если доступ не появился в течение часа, обратитесь к администратору сайта'; +$string['environmentrequirephp81'] = 'Плагину paygw_moneta нужен PHP 8.1 или новее'; +$string['messageprovider:payment_received'] = "Оплата принята ({$string['pluginname']})"; +$string['message:paid:subject'] = 'Оплата принята: {$a->description}'; +$string['message:paid'] = 'Здравствуйте, {$a->firstname}! + +Ваша оплата **{$a->amount}** за «{$a->description}» на сайте {$a->sitename} принята, доступ открыт. + +Номер операции в MONETA.RU: {$a->operationid}. + +Перейти: {$a->url}'; +$string['messageprovider:payment_link'] = "Ссылка на оплату ({$string['pluginname']})"; +$string['message:link:subject'] = 'Ссылка на оплату: {$a->description}'; +$string['message:link'] = 'Здравствуйте, {$a->firstname}! + +Создан заказ на оплату «{$a->description}» на сумму **{$a->amount}** на сайте {$a->sitename}. + +Оплатить: {$a->url} + +Ссылка действует, пока заказ не оплачен и не изменились цена или настройки оплаты.'; +$string['error:paymentlinkexpired'] = 'Эта ссылка на оплату больше не действует: заказ отменён или изменились цена или настройки оплаты. Начните оплату заново со страницы курса'; +$string['error:invalidamount'] = 'Сумма платежа должна быть больше нуля'; +$string['error:unsupportedcurrency'] = "{$string['pluginname']} поддерживает платежи только в RUB"; +$string['error:accountnumber'] = 'Номер счёта состоит только из цифр'; +$string['error:ordernotfound'] = 'Заказ не найден'; + +$string['report:title'] = "Заказы {$string['pluginname']}"; +$string['report:time'] = 'Создан'; +$string['report:user'] = 'Покупатель'; +$string['report:description'] = 'Заказ'; +$string['report:amount'] = 'Сумма'; +$string['report:status'] = 'Статус'; +$string['report:operation'] = 'Операция MONETA.RU'; +$string['report:lasterror'] = 'Последний отказ'; +$string['status:new'] = 'Создан'; +$string['status:pending'] = 'Оплачивается'; +$string['status:paid'] = 'Оплачен'; +$string['status:canceled'] = 'Отменён'; +$string['status:failed'] = 'Ошибка зачисления'; + +$string['privacy:metadata:transactions'] = "Заказы, созданные при оплате через {$string['pluginname']}"; +$string['privacy:metadata:transactions:userid'] = 'Покупатель'; +$string['privacy:metadata:transactions:amount'] = 'Сумма заказа'; +$string['privacy:metadata:transactions:status'] = 'Статус оплаты'; +$string['privacy:metadata:transactions:merchantorderid'] = 'Идентификатор заказа, переданный в MONETA.RU'; +$string['privacy:metadata:transactions:providertransactionid'] = 'Номер операции в MONETA.RU'; +$string['privacy:metadata:transactions:snapshot'] = 'Снимок настроек и чека: название курса, ФИО, e-mail и телефон покупателя, идентификатор покупателя для MONETA.RU'; +$string['privacy:metadata:transactions:timecreated'] = 'Время создания заказа'; +$string['privacy:metadata:moneta'] = 'Данные, передаваемые платёжному сервису MONETA.RU для проведения оплаты и формирования чека'; +$string['privacy:metadata:moneta:userid'] = 'Идентификатор покупателя (MNT_SUBSCRIBER_ID): e-mail, иначе телефон, иначе id пользователя в Moodle'; +$string['privacy:metadata:moneta:fullname'] = 'ФИО покупателя для кассового чека'; +$string['privacy:metadata:moneta:email'] = 'E-mail покупателя для отправки чека'; +$string['privacy:metadata:moneta:phone'] = 'Телефон покупателя для отправки чека'; +$string['privacy:metadata:moneta:amount'] = 'Сумма оплаты'; diff --git a/pay.php b/pay.php new file mode 100644 index 0000000..51c2966 --- /dev/null +++ b/pay.php @@ -0,0 +1,65 @@ +. + +/** + * Создаёт заказ и отправляет покупателя на платёжную форму MONETA.Assistant. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use paygw_moneta\local\BuyerNotifier; +use paygw_moneta\local\GatewayConfigRepository; +use paygw_moneta\local\order\OrderFactory; +use paygw_moneta\local\order\TransactionRepository; +use paygw_moneta\local\PaymentFormPage; + +require_once(__DIR__ . '/../../../config.php'); + +require_login(); +require_sesskey(); +if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + throw new moodle_exception('invalidrequest', 'error'); +} + +$component = required_param('component', PARAM_COMPONENT); +$paymentarea = required_param('paymentarea', PARAM_AREA); +$itemid = required_param('itemid', PARAM_INT); + +$PAGE->set_context(context_system::instance()); +$PAGE->set_url('/payment/gateway/moneta/pay.php'); +$PAGE->set_pagelayout('popup'); +$PAGE->set_title(get_string('confirmpayment', 'paygw_moneta')); +$PAGE->set_heading(get_string('confirmpayment', 'paygw_moneta')); + +$config = (new GatewayConfigRepository())->forPayable($component, $paymentarea, $itemid); +$order = (new OrderFactory(new TransactionRepository()))->start( + component: $component, + paymentArea: $paymentarea, + itemId: $itemid, + user: $USER, + config: $config, + created: $created, +); + +if ($created && $config->sendPaymentLink) { + (new BuyerNotifier())->notifyPaymentLink($order); +} + +echo $OUTPUT->header(); +echo $OUTPUT->render_from_template('paygw_moneta/payment_form', PaymentFormPage::context($order, $config)); +echo $OUTPUT->footer(); diff --git a/pix/icon.svg b/pix/icon.svg new file mode 100644 index 0000000..3bd29e7 --- /dev/null +++ b/pix/icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/pix/img.svg b/pix/img.svg new file mode 100644 index 0000000..39f4c07 --- /dev/null +++ b/pix/img.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/report.php b/report.php new file mode 100644 index 0000000..e72a1ac --- /dev/null +++ b/report.php @@ -0,0 +1,45 @@ +. + +/** + * Отчёт администратора по заказам Moneta. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use paygw_moneta\local\ReportTable; + +require_once(__DIR__ . '/../../../config.php'); +require_once($CFG->libdir . '/adminlib.php'); +require_once($CFG->libdir . '/tablelib.php'); + +admin_externalpage_setup('paygw_moneta_report'); + +$url = new moodle_url('/payment/gateway/moneta/report.php'); +$table = new ReportTable('paygw_moneta_report', $url); +$download = optional_param('download', '', PARAM_ALPHA); +$table->is_downloading($download, 'moneta-orders', get_string('report:title', 'paygw_moneta')); + +if (!$table->is_downloading()) { + echo $OUTPUT->header(); + echo $OUTPUT->heading(get_string('report:title', 'paygw_moneta')); +} +$table->out(50, true); +if (!$table->is_downloading()) { + echo $OUTPUT->footer(); +} diff --git a/return.php b/return.php new file mode 100644 index 0000000..d9f114d --- /dev/null +++ b/return.php @@ -0,0 +1,72 @@ +. + +/** + * Возврат покупателя с платёжной формы (Success URL / Fail URL / Return URL). + * + * Возврат браузера не доказывает оплату: доступ выдаёт только Pay URL. + * Здесь лишь показываем состояние заказа и ведём дальше. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use paygw_moneta\local\order\TransactionRepository; +use paygw_moneta\local\protocol\AssistantTransactionId; + +require_once(__DIR__ . '/../../../config.php'); + +require_login(); + +$transactionid = required_param('MNT_TRANSACTION_ID', PARAM_RAW_TRIMMED); +$outcome = optional_param('outcome', 'success', PARAM_ALPHA); + +$merchantorderid = AssistantTransactionId::parse($transactionid); + +$order = $merchantorderid === null ? null : (new TransactionRepository())->findByMerchantOrderId($merchantorderid); +if ($order === null) { + throw new moodle_exception('error:ordernotfound', 'paygw_moneta'); +} +if ($order->userId !== (int) $USER->id && !is_siteadmin()) { + throw new moodle_exception('error:ordernotfound', 'paygw_moneta'); +} + +$successurl = core_payment\helper::get_success_url($order->component, $order->paymentArea, $order->itemId); +if ($order->isPaid()) { + redirect($successurl, get_string('paymentconfirmed', 'paygw_moneta'), 0, \core\output\notification::NOTIFY_SUCCESS); +} + +$PAGE->set_context(context_system::instance()); +$PAGE->set_url('/payment/gateway/moneta/return.php', ['MNT_TRANSACTION_ID' => $transactionid, 'outcome' => $outcome]); +$PAGE->set_title(get_string('paymentpending', 'paygw_moneta')); +$PAGE->set_heading(get_string('paymentpending', 'paygw_moneta')); + +echo $OUTPUT->header(); +if ($outcome === 'success') { + echo $OUTPUT->notification( + get_string('paymentpending_help', 'paygw_moneta'), + \core\output\notification::NOTIFY_INFO, + ); +} else { + echo $OUTPUT->notification( + get_string('paymentnotcompleted', 'paygw_moneta'), + \core\output\notification::NOTIFY_WARNING, + ); +} + +echo $OUTPUT->single_button($successurl, get_string('continue'), 'get'); +echo $OUTPUT->footer(); diff --git a/settings.php b/settings.php new file mode 100644 index 0000000..27be3ac --- /dev/null +++ b/settings.php @@ -0,0 +1,52 @@ +. + +/** + * Общие настройки шлюза Moneta (Администрирование → Плагины → Платежи). + * + * Реквизиты счёта живут в платёжном аккаунте ({@see \paygw_moneta\gateway}); + * здесь только штатные настройки ядра: наценка. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +if ($hassiteconfig) { + $ADMIN->add( + 'payment', + new admin_externalpage( + name: 'paygw_moneta_report', + visiblename: get_string('report:title', 'paygw_moneta'), + url: new moodle_url('/payment/gateway/moneta/report.php'), + req_capability: 'moodle/site:config', + ), + ); +} + +if ($ADMIN->fulltree) { + $settings->add( + new admin_setting_heading( + name: 'paygw_moneta_settings', + heading: '', + information: html_writer::tag('p', get_string('pluginname_desc', 'paygw_moneta')) + . html_writer::tag('p', get_string('settingsintro', 'paygw_moneta')), + ), + ); + \core_payment\helper::add_common_gateway_settings($settings, 'paygw_moneta'); +} diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..11fbe2f --- /dev/null +++ b/styles.css @@ -0,0 +1,86 @@ +.core_payment_gateways_modal .moneta .icon { + height: 30px; + width: auto; + max-width: none; +} + +/* Карточка перехода к оплате (templates/payment_form.mustache). */ +.paygw-moneta-checkout { + max-width: 30rem; + margin-top: 1rem; + border-radius: 1.25rem; +} + +.paygw-moneta-checkout-brand { + display: inline-block; + margin-bottom: 1.5rem; +} + +.paygw-moneta-checkout-logo { + display: block; + height: 36px; + width: auto; + max-width: 100%; +} + +.paygw-moneta-checkout-label { + margin-bottom: 0.5rem; + color: var(--bs-secondary-color, #6c757d); + font-size: 0.8125rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +/* Название курса бывает длинным: переносим по словам, а слишком длинное слово — где угодно. */ +.paygw-moneta-checkout-title { + margin: 0 0 1.5rem; + font-size: 1.5rem; + font-weight: 700; + line-height: 1.3; + overflow-wrap: anywhere; + hyphens: auto; +} + +@media (max-width: 575.98px) { + .paygw-moneta-checkout-title { + font-size: 1.25rem; + } +} + +.paygw-moneta-checkout-total { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 0.25rem 1rem; + margin-bottom: 1.5rem; + padding: 1.25rem 0; + border-top: 1px solid var(--bs-border-color, #dee2e6); + border-bottom: 1px solid var(--bs-border-color, #dee2e6); +} + +.paygw-moneta-checkout-cost { + margin-left: auto; + font-size: 2rem; + font-weight: 700; + line-height: 1.2; + white-space: nowrap; +} + +.paygw-moneta-checkout-button { + border-radius: 0.75rem; + font-weight: 600; +} + +.paygw-moneta-checkout-note { + display: flex; + align-items: flex-start; + gap: 0.5rem; + margin-top: 1.25rem; +} + +.paygw-moneta-checkout-note .icon { + flex-shrink: 0; + margin: 0.2em 0 0; +} diff --git a/templates/payment_form.mustache b/templates/payment_form.mustache new file mode 100644 index 0000000..bc2a9fb --- /dev/null +++ b/templates/payment_form.mustache @@ -0,0 +1,83 @@ +{{! + This file is part of Moodle - http://moodle.org/ + + Moodle is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Moodle is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Moodle. If not, see . +}} +{{! + @template paygw_moneta/payment_form + + Карточка перехода на платёжную страницу MONETA.Assistant: логотип со + ссылкой на moneta.ru, что оплачивается, сумма, кнопка и пояснение. Сама не + уходит — покупатель нажимает «Оплатить»; после нажатия кнопка блокируется, + чтобы повторный клик не отправил форму дважды. Название может быть длинным: + переносится, не растягивая карточку. + + Context variables required for this template: + * action - адрес платёжной формы + * cost - сумма с валютой для показа + * description - описание заказа + * iscourse - оплачивается запись на курс (enrol_fee) + * logourl - адрес логотипа + * fields - подписанные поля формы: name, value + + Example context (json): + { + "action": "https://demo.moneta.ru/assistant.htm", + "cost": "120,25 ₽", + "description": "Монета", + "iscourse": true, + "logourl": "https://example.test/theme/image.php/boost/paygw_moneta/1/img", + "fields": [{"name": "MNT_ID", "value": "54600817"}] + } +}} +
+
+ + + {{#str}}opensinnewwindow{{/str}} + +
+ {{#iscourse}}{{#str}}checkout:course, paygw_moneta{{/str}}{{/iscourse}} + {{^iscourse}}{{#str}}checkout:item, paygw_moneta{{/str}}{{/iscourse}} +
+

{{description}}

+
+ {{#str}}checkout:total, paygw_moneta{{/str}} + {{cost}} +
+
+ {{#fields}} + + {{/fields}} + +
+
+ {{#pix}}i/lock, core{{/pix}} +
+
{{#str}}checkout:secure, paygw_moneta{{/str}}
+ {{#iscourse}}
{{#str}}checkout:access, paygw_moneta{{/str}}
{{/iscourse}} +
+
+
+
+{{#js}} +(function() { + var form = document.getElementById('paygw-moneta-form-{{uniqid}}'); + form.addEventListener('submit', function() { + var button = form.querySelector('button[type="submit"]'); + button.disabled = true; + button.textContent = {{#quote}}{{#str}}redirecting, paygw_moneta{{/str}}{{/quote}}; + }); +})(); +{{/js}} diff --git a/version.php b/version.php new file mode 100644 index 0000000..ff4e85a --- /dev/null +++ b/version.php @@ -0,0 +1,31 @@ +. + +/** + * Plugin version and other meta-data are defined here. + * + * @package paygw_moneta + * @copyright 2026 Moneta Labs {@link https://moneta.ru/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$plugin->component = 'paygw_moneta'; +$plugin->version = 2026092500; +$plugin->requires = 2023100900; +$plugin->maturity = MATURITY_STABLE; +$plugin->release = '1.0.0';