feat: paygw_moneta 1.0.0, MONETA.Assistant payment gateway for Moodle

This commit is contained in:
2026-09-25 16:42:38 +03:00
parent 70464af858
commit 14b386a550
65 changed files with 5377 additions and 59 deletions
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+121 -59
View File
@@ -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/)
---
**✅ Модуль настроен, приятных платежей!** 💰🎉
+13
View File
@@ -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
+1
View File
@@ -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 <http://www.gnu.org/licenses/>.\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<void>} никогда не разрешается: страница уходит на 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"}
+60
View File
@@ -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 <http://www.gnu.org/licenses/>.
/**
* Запуск оплаты через 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<void>} никогда не разрешается: страница уходит на 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);
};
+53
View File
@@ -0,0 +1,53 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* 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;
+71
View File
@@ -0,0 +1,71 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Продолжение оплаты по ссылке из письма «Ссылка на оплату».
*
* 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();
+131
View File
@@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
namespace paygw_moneta;
use core_payment\form\account_gateway;
use paygw_moneta\local\protocol\AssistantProtocol;
use paygw_moneta\local\protocol\PaymentServer;
use paygw_moneta\local\receipt\Client;
use paygw_moneta\local\receipt\Vat;
use stdClass;
/**
* Платёжный шлюз Moneta для Payment API Moodle: валюта и форма настроек
* платёжного аккаунта. Имя класса и методов задаёт ядро (`\paygw_<name>\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',
);
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
use core\message\message;
use core_payment\helper;
use core_user;
use paygw_moneta\local\order\Order;
/**
* Сообщения покупателю через систему сообщений Moodle (`db/messages.php`):
* «оплата принята» (`payment_received`) и «ссылка на оплату» (`payment_link`).
* Плагин не выбирает канал и не шлёт почту сам: веб-уведомление и/или письмо
* через исходящую почту сайта — по настройкам уведомлений пользователя.
*
* @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 BuyerNotifier
{
public const PROVIDER = 'payment_received';
public const PROVIDER_LINK = 'payment_link';
public function __construct(
private readonly Logger $logger = new ErrorLogLogger(),
) {}
/**
* Сообщение по оплаченному заказу; сбой отправки не должен ломать ответ на
* Pay URL, поэтому ошибки только логируются.
*
* @return int|false id сообщения либо false, если отправка не состоялась
*/
public function notifyPaid(Order $order): int|false
{
return $this->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<string, string> $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;
}
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
/**
* Идентификатор CMS и модуля для `MNT_CMS`:
* `Moodle v<release>|PHP <version>|Moneta v<release>`.
*
* @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,
);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
/**
* Символ валюты для показа сумм администратору («120.25 ₽»).
* Известен только рубль; любой другой код остаётся кодом («USD»),
* пустой — пустой строкой.
*
* @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 CurrencySymbol
{
private const SYMBOLS = [
'RUB' => '₽',
];
private function __construct() {}
public static function of(?string $currencyCode): string
{
if ($currencyCode === null || $currencyCode === '') {
return '';
}
return self::SYMBOLS[strtoupper($currencyCode)] ?? $currencyCode;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
/**
* Журнал в `error_log` PHP. Не `debugging()`: тот пишет только при включённой
* отладке, а на странице (`pay.php`) при отладке с Whoops сам бросает
* исключение и роняет переход к оплате.
*
* @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 ErrorLogLogger implements Logger
{
public function error(string $message): void
{
error_log('paygw_moneta: ' . $message);
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
use paygw_moneta\local\protocol\PaymentServer;
use paygw_moneta\local\protocol\Signature;
use paygw_moneta\local\receipt\Client;
use paygw_moneta\local\receipt\Vat;
/**
* Настройки шлюза Moneta у платёжного аккаунта Moodle (`payment_gateways.config`);
* читает их из БД {@see GatewayConfigRepository}.
* Единственный читатель кода проверки целостности: дальше он живёт только
* внутри {@see Signature}.
*
* @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 GatewayConfig
{
public const GATEWAY = 'moneta';
public function __construct(
public readonly string $accountNumber,
#[\SensitiveParameter]
private readonly string $integrityCode,
public readonly PaymentServer $paymentServer,
public readonly bool $testMode,
public readonly bool $fiscalization,
public readonly Vat $vat,
public readonly bool $enabled,
public readonly ?string $receiptEmail = null,
public readonly bool $sendPaymentLink = false,
) {}
/**
* @param array<string, mixed> $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);
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
use core_payment\helper;
/**
* Загрузка {@see GatewayConfig} из платёжных аккаунтов Moodle
* (`payment_gateways`). Сам `GatewayConfig` — только значения, без обращения
* к БД; здесь — всё, что его читает.
*
* @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 GatewayConfigRepository
{
/**
* Настройки для оплачиваемого объекта — тот же путь, что у ядра при показе модального окна.
*/
public function forPayable(string $component, string $paymentArea, int $itemId): GatewayConfig
{
return GatewayConfig::fromArray(
helper::get_gateway_configuration($component, $paymentArea, $itemId, GatewayConfig::GATEWAY),
);
}
/**
* Настройки аккаунта заказа — для колбэков и ссылки на оплату, где
* оплачиваемый объект уже известен по заказу.
*/
public function forAccount(int $accountId): ?GatewayConfig
{
global $DB;
$record = $DB->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);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
/**
* Единая точка журнала модуля. Только события без секретов: ни кода проверки,
* ни `MNT_SIGNATURE`, ни набора параметров запроса — классы исключений, коды
* отказов и номера заказов/операций.
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface Logger
{
public function error(string $message): void;
}
+117
View File
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
use InvalidArgumentException;
/**
* Денежная сумма в формате MONETA.Assistant: десятичная строка ровно с двумя
* знаками после точки (`120.25`, `100.00`), без знака, без разделителей тысяч.
*
* Внутри — только строка и целые копейки; `float` появляется лишь на границе
* с хостом ({@see self::fromFloat()}), где Moodle отдаёт стоимость числом.
*
* @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 Money
{
/** Верхняя граница суммы по JSON-схеме Check URL (`number_amount.maximum`). */
public const MAX = '10000000000000.00';
/** Целая часть — до 14 знаков без ведущих нулей, дробная — ровно два. */
private const PATTERN = '/\A(?:0|[1-9][0-9]{0,13})\.[0-9]{2}\z/';
private function __construct(private string $value) {}
/**
* Строгий разбор десятичной строки; всё, что не `^\d+\.\d{2}$`, отклоняется.
*/
public static function fromDecimal(string $value): self
{
if (preg_match(self::PATTERN, $value) !== 1) {
throw new InvalidArgumentException('Сумма должна быть десятичной строкой с двумя знаками после точки.');
}
$money = new self($value);
if ($money->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);
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
use core_payment\helper;
use moodle_url;
use paygw_moneta\local\order\CurrentPrice;
use paygw_moneta\local\order\Order;
use paygw_moneta\local\protocol\AssistantProtocol;
use paygw_moneta\local\protocol\AssistantTransactionId;
use paygw_moneta\local\protocol\PaymentRequest;
/**
* Контекст шаблона `paygw_moneta/payment_form` — подписанная форма перехода на
* MONETA.Assistant для заказа. Общий для `pay.php` (новый заказ из модального
* окна) и `checkout.php` (ссылка на оплату из письма).
*
* @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 PaymentFormPage
{
private const RETURN_PATH = '/payment/gateway/moneta/return.php';
private function __construct() {}
/**
* @return array{action: string, cost: string, description: string, iscourse: bool, logourl: string, fields: list<array{name: string, value: string}>}
*/
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]);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local;
use html_writer;
use moodle_url;
use paygw_moneta\local\order\TransactionRepository;
use paygw_moneta\local\order\TransactionStatus;
use stdClass;
use table_sql;
/**
* Таблица заказов для администратора (Администрирование → Платежи → Заказы Монета).
* Показывает статусы и коды последних отказов — первое, о чём спрашивает мерчант.
*
* @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 ReportTable extends table_sql
{
public function __construct(string $uniqueId, moodle_url $baseUrl)
{
parent::__construct($uniqueId);
$this->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 ?? ''));
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\callback;
use core\lock\lock_config;
use core_payment\helper;
use paygw_moneta\local\BuyerNotifier;
use paygw_moneta\local\CmsInfo;
use paygw_moneta\local\ErrorLogLogger;
use paygw_moneta\local\GatewayConfig;
use paygw_moneta\local\GatewayConfigRepository;
use paygw_moneta\local\Logger;
use paygw_moneta\local\Money;
use paygw_moneta\local\order\CurrentPrice;
use paygw_moneta\local\order\Order;
use paygw_moneta\local\order\RejectionReason;
use paygw_moneta\local\order\TransactionRepository;
use paygw_moneta\local\protocol\AssistantTransactionId;
use paygw_moneta\local\protocol\CallbackNotification;
use paygw_moneta\local\protocol\CallbackResponse;
use paygw_moneta\local\protocol\CheckResponse;
use paygw_moneta\local\protocol\ResultCode;
/**
* @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 CallbackHandler
{
private const LOCK_TIMEOUT = 10;
private readonly NotificationHandler $check;
private readonly NotificationHandler $pay;
/**
* @param \Closure(string, string, int, int, int): bool|null $deliverOrder
*/
public function __construct(
private readonly TransactionRepository $repository = new TransactionRepository(),
?\Closure $deliverOrder = null,
BuyerNotifier $notifier = new BuyerNotifier(),
private readonly Logger $logger = new ErrorLogLogger(),
private readonly GatewayConfigRepository $configs = new GatewayConfigRepository(),
CurrentPrice $currentPrice = new CurrentPrice(),
) {
$this->check = new CheckHandler($repository);
$this->pay = new PayHandler(
repository: $repository,
deliverOrder: $deliverOrder ?? helper::deliver_order(...),
notifier: $notifier,
currentPrice: $currentPrice,
logger: $logger,
);
}
/**
* @param array<string, mixed> $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();
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\callback;
use paygw_moneta\local\CmsInfo;
use paygw_moneta\local\GatewayConfig;
use paygw_moneta\local\order\Order;
use paygw_moneta\local\order\RejectionReason;
use paygw_moneta\local\order\TransactionRepository;
use paygw_moneta\local\order\TransactionStatus;
use paygw_moneta\local\protocol\CallbackNotification;
use paygw_moneta\local\protocol\CallbackResponse;
use paygw_moneta\local\protocol\CheckResponse;
use paygw_moneta\local\protocol\ResultCode;
/**
* @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 CheckHandler implements NotificationHandler
{
public function __construct(
private readonly TransactionRepository $repository,
) {}
public function handle(CallbackNotification $notification, Order $order, GatewayConfig $config): CallbackResponse
{
if ($order->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();
}
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\callback;
use paygw_moneta\local\GatewayConfig;
use paygw_moneta\local\order\Order;
use paygw_moneta\local\protocol\CallbackNotification;
use paygw_moneta\local\protocol\CallbackResponse;
/**
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
interface NotificationHandler
{
public function handle(CallbackNotification $notification, Order $order, GatewayConfig $config): CallbackResponse;
}
+153
View File
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\callback;
use core_payment\helper;
use paygw_moneta\local\BuyerNotifier;
use paygw_moneta\local\CmsInfo;
use paygw_moneta\local\GatewayConfig;
use paygw_moneta\local\Logger;
use paygw_moneta\local\order\CurrentPrice;
use paygw_moneta\local\order\Order;
use paygw_moneta\local\order\RejectionReason;
use paygw_moneta\local\order\TransactionRepository;
use paygw_moneta\local\order\TransactionStatus;
use paygw_moneta\local\protocol\CallbackNotification;
use paygw_moneta\local\protocol\CallbackResponse;
use paygw_moneta\local\protocol\PayResponse;
use paygw_moneta\local\protocol\ResultCode;
use paygw_moneta\local\receipt\Receipt;
/**
* @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 PayHandler implements NotificationHandler
{
/**
* @param \Closure(string, string, int, int, int): bool $deliverOrder
*/
public function __construct(
private readonly TransactionRepository $repository,
private readonly \Closure $deliverOrder,
private readonly BuyerNotifier $notifier,
private readonly CurrentPrice $currentPrice,
private readonly Logger $logger,
) {}
public function handle(CallbackNotification $notification, Order $order, GatewayConfig $config): CallbackResponse
{
if ($order->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();
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
use core_payment\helper;
use paygw_moneta\local\ErrorLogLogger;
use paygw_moneta\local\GatewayConfig;
use paygw_moneta\local\Logger;
use paygw_moneta\local\Money;
/**
* Текущая цена оплачиваемого объекта (с наценкой шлюза) против суммы заказа:
* 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
*/
class CurrentPrice
{
public function __construct(
private readonly Logger $logger = new ErrorLogLogger(),
) {}
/**
* Сумма заказа равна текущей стоимости объекта. Объект мог исчезнуть —
* тогда и оплачивать нечего.
*/
public function matches(Order $order): bool
{
try {
$payable = helper::get_payable($order->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);
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
use paygw_moneta\local\Money;
use stdClass;
/**
* Локальный заказ — строка `paygw_moneta_transactions` в типизированном виде.
* Создаётся до ухода покупателя на платёжную форму и живёт до Pay URL;
* у ядра Moodle записи о платеже до его подтверждения нет.
*
* Объект неизменяемый; переходы статусов делает {@see TransactionRepository}.
*
* @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 Order
{
public function __construct(
public readonly int $id,
public readonly int $accountId,
public readonly int $userId,
public readonly string $component,
public readonly string $paymentArea,
public readonly int $itemId,
public readonly string $merchantOrderId,
public readonly ?string $providerTransactionId,
public readonly ?int $paymentId,
public readonly Money $amount,
public readonly string $currency,
public readonly TransactionStatus $status,
public readonly OrderSnapshot $snapshot,
public readonly ?RejectionReason $lastError,
public readonly int $timeCreated,
public readonly int $timeModified,
public readonly ?int $timeCompleted,
) {}
public static function fromRecord(stdClass $record): self
{
return new self(
(int) $record->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;
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
use core_payment\helper;
use moodle_exception;
use paygw_moneta\local\GatewayConfig;
use paygw_moneta\local\Money;
use paygw_moneta\local\protocol\AssistantProtocol;
use paygw_moneta\local\receipt\Client;
use paygw_moneta\local\receipt\Receipt;
use paygw_moneta\local\receipt\ReceiptText;
use stdClass;
/**
* Создание заказа для оплачиваемого объекта Moodle: сумма от ядра, снимок
* настроек шлюза, чек с одной позицией, покупатель из профиля.
*
* @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 OrderFactory
{
public function __construct(
private readonly TransactionRepository $repository,
) {}
/**
* @param stdClass $user покупатель (`$USER`): id, email, phone1, phone2, ФИО
* @param GatewayConfig $config настройки шлюза для этого объекта (`GatewayConfigRepository::forPayable`)
* @param bool|null $created true — заказ создан сейчас, false — переиспользован открытый
*/
public function start(
string $component,
string $paymentArea,
int $itemId,
stdClass $user,
GatewayConfig $config,
?bool &$created = null,
): Order {
if (!in_array(
GatewayConfig::GATEWAY,
helper::get_available_gateways($component, $paymentArea, $itemId),
true,
)) {
throw new moodle_exception('gatewaynotfound', 'payment');
}
if (!$config->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);
}
}
+99
View File
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
use InvalidArgumentException;
use paygw_moneta\local\receipt\Receipt;
use paygw_moneta\local\receipt\Vat;
/**
* Снимок настроек счёта и данных чека на момент создания заказа.
*
* Колбэки сверяют уведомление с тем, что реально было запрошено (сумма, режим,
* данные чека, `MNT_SUBSCRIBER_ID`), а не с текущей ценой курса и профилем. Номер счёта в снимке —
* дополнительная защита: он обязан совпадать и с текущей настройкой, потому что
* ключ подписи всегда берётся из неё; заказы, созданные до смены счёта,
* оплатить нельзя. Секрет (код проверки целостности) в снимок не попадает.
*
* @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 OrderSnapshot
{
public function __construct(
public readonly string $accountNumber,
public readonly bool $testMode,
public readonly bool $fiscalization,
public readonly Vat $vat,
public readonly Receipt $receipt,
public readonly string $description,
public readonly string $subscriberId,
) {
if ($accountNumber === '') {
throw new InvalidArgumentException('В снимке заказа нет номера счёта.');
}
}
/**
* @return array<string, mixed>
*/
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<string, mixed> $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;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
/**
* Причина отказа по подписанному уведомлению — пишется в `lasterror` заказа и
* показывается администратору в отчёте.
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum RejectionReason: string
{
/** Сумма уведомления не совпала с суммой заказа. */
case Amount = 'AMOUNT';
/** Цена оплачиваемого объекта изменилась после создания заказа. */
case AmountChanged = 'AMOUNT_CHANGED';
case Currency = 'CURRENCY';
/** Тестовый режим уведомления не совпал со снимком или с текущими настройками. */
case TestMode = 'TEST_MODE';
case Subscriber = 'SUBSCRIBER';
/** Вторая операция по уже оплаченному заказу: деньги списаны дважды. */
case DuplicateOperation = 'DUPLICATE_OPERATION';
/** Оплата подтверждена, но зачисление не удалось. */
case Delivery = 'DELIVERY';
/** Чек из снимка не собрался в JSON-ответ Check URL. */
case Receipt = 'RECEIPT';
case GatewayDisabled = 'GATEWAY_DISABLED';
}
@@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
use InvalidArgumentException;
use paygw_moneta\local\Money;
use paygw_moneta\local\protocol\AssistantProtocol;
use paygw_moneta\local\protocol\AssistantTransactionId;
/**
* Хранилище заказов. Единственное место, где меняется `status`: хендлеры
* зовут именованные переходы, а не пишут поля напрямую.
*
* @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 TransactionRepository
{
public const TABLE = 'paygw_moneta_transactions';
/**
* Свой номер заказа — UUID в нижнем регистре ({@see self::create()}); в
* `MNT_TRANSACTION_ID` он уходит с меткой времени ({@see AssistantTransactionId}).
*/
public static function isMerchantOrderId(string $value): bool
{
return preg_match('/\A' . AssistantTransactionId::ORDER_ID . '\z/', $value) === 1;
}
/**
* Находит открытый заказ покупателя по тому же товару с той же суммой и
* настройками либо создаёт новый. Повторное нажатие «Оплатить» не должно
* плодить заказы: у сервиса на каждый `MNT_TRANSACTION_ID` своя операция.
*
* @param bool|null $created true — заказ создан сейчас, false — переиспользован
*/
public function obtain(
int $accountId,
int $userId,
string $component,
string $paymentArea,
int $itemId,
Money $amount,
string $currency,
OrderSnapshot $snapshot,
?bool &$created = null,
): Order {
$open = $this->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<string, mixed> $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);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\order;
/**
* Статус локального заказа.
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum TransactionStatus: string
{
/** Заказ создан, покупатель отправлен на платёжную форму. */
case New = 'new';
/** Сервис прислал проверочный запрос — оплата идёт. */
case Pending = 'pending';
/** Оплата подтверждена Pay URL, доступ выдан. */
case Paid = 'paid';
/** Заказ отменён на нашей стороне; сервису отвечаем 500. */
case Canceled = 'canceled';
/** Подтверждение оплаты не удалось довести до конца (ошибка зачисления). */
case Failed = 'failed';
/** Заказ ещё не ушёл в оплату: его переиспользует повторное нажатие «Оплатить». */
public function isOpen(): bool
{
return $this === self::New || $this === self::Pending;
}
/** Уведомление об оплате по такому заказу зачисляется (в том числе повтор после сбоя доставки). */
public function isPayable(): bool
{
return $this->isOpen() || $this === self::Failed;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
/**
* Константы протокола MONETA.Assistant, общие для формы и колбэков.
* Адреса платёжной формы — в {@see PaymentServer}.
*
* @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 AssistantProtocol
{
public const CURRENCY = 'RUB';
public const COMMAND_CHECK = 'CHECK';
public const TEXT_SUCCESS = 'SUCCESS';
public const TEXT_FAIL = 'FAIL';
private function __construct() {}
/**
* `MNT_TEST_MODE` передаётся как «1» или строковый «0» (`cmsspecification.pdf`).
*/
public static function testModeFlag(bool $testMode): string
{
return $testMode ? '1' : '0';
}
/**
* Язык интерфейса Moodle → `moneta.locale` платёжной формы (ru/en).
*/
public static function normalizeLocale(string $language): string
{
return str_starts_with(strtolower($language), 'ru') ? 'ru' : 'en';
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use core_date;
use DateTimeImmutable;
/**
* `MNT_TRANSACTION_ID` — идентификатор заказа, который модуль отдаёт в платёжной
* форме и получает обратно в Check URL, Pay URL и на странице возврата: UUID заказа
* плюс метка времени, `0192b4c1-…_20260924143005MSK`. Метка — только для людей
* (в личном кабинете Moneta и в переписке с поддержкой по ней видно, когда открыта форма),
* поэтому она в часовом поясе сайта, а не в UTC; обратно она не читается, parse()
* берёт только UUID.
*
* @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 AssistantTransactionId
{
/**
* Номер заказа — UUID в нижнем регистре ({@see \paygw_moneta\local\order\TransactionRepository::create()}).
* Фрагмент шаблона без якорей: его же проверяет
* {@see \paygw_moneta\local\order\TransactionRepository::isMerchantOrderId()}.
*/
public const ORDER_ID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
public const SEPARATOR = '_';
private const PATTERN = '/\A
(?<id>' . 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;
}
}
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use InvalidArgumentException;
use paygw_moneta\local\Money;
/**
* @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 CallbackNotification
{
private const ACCOUNT_ID_MAX_LENGTH = 20;
private const TRANSACTION_ID_MAX_LENGTH = 255;
private const OPERATION_ID_MAX_LENGTH = 255;
private const SUBSCRIBER_ID_MAX_LENGTH = 255;
private readonly string $command;
private readonly string $accountId;
private readonly string $transactionId;
private readonly string $operationId;
private readonly string $rawAmount;
private readonly ?Money $amount;
private readonly string $currency;
private readonly string $subscriberId;
private readonly string $rawTestMode;
private readonly string $signature;
/**
* @param array<string, mixed> $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<string, mixed> $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<string, mixed> $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;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
/**
* Тело и тип ответа модуля на Check 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
*/
final class CallbackResponse
{
public const CONTENT_TYPE_XML = 'application/xml; charset=UTF-8';
public const CONTENT_TYPE_JSON = 'application/json; charset=UTF-8';
public const CONTENT_TYPE_TEXT = 'text/plain; charset=UTF-8';
public function __construct(
public readonly string $contentType,
public readonly string $body,
) {}
public static function fail(): self
{
return new self(self::CONTENT_TYPE_TEXT, AssistantProtocol::TEXT_FAIL);
}
public static function xml(string $body): self
{
return new self(self::CONTENT_TYPE_XML, $body);
}
public static function json(string $body): self
{
return new self(self::CONTENT_TYPE_JSON, $body);
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use InvalidArgumentException;
use paygw_moneta\local\Money;
use paygw_moneta\local\receipt\JsonNumber;
use paygw_moneta\local\receipt\Receipt;
/**
* @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 CheckResponse
{
public function __construct(
private readonly string $accountId,
private readonly string $transactionId,
private readonly Money $amount,
private readonly ResultCode $resultCode,
private readonly Signature $signature,
private readonly string $cms,
) {}
public function getResultCode(): ResultCode
{
return $this->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);
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use DOMDocument;
use DOMNode;
use paygw_moneta\local\Money;
/**
* Сборка `MNT_RESPONSE` (`MONETA.Assistant.ru.pdf`, гл. 4–5). Общая часть
* ответов Check URL и Pay URL: обязательные элементы, подпись по формуле 3
* и необязательные `MNT_ATTRIBUTES`.
*
* `MNT_CMS` в схеме ответа нет — это решение разработчика (2026-09-12,
* `docs/moneta/_pdf/README.md`): идентификатор CMS передаётся везде, где
* модуль отвечает 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
*/
final class MntResponseXml
{
private function __construct() {}
/**
* @param array<string, string> $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));
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use paygw_moneta\local\Money;
use paygw_moneta\local\receipt\Receipt;
/**
* @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 PayResponse
{
public function __construct(
private readonly string $accountId,
private readonly string $transactionId,
private readonly Money $amount,
private readonly ResultCode $resultCode,
private readonly Signature $signature,
private readonly string $cms,
private readonly ?Receipt $receipt = null,
) {}
/**
* @throws \DOMException
* @throws \JsonException
*/
public function toXml(): CallbackResponse
{
$attributes = [];
if ($this->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,
),
);
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use InvalidArgumentException;
use paygw_moneta\local\Money;
/**
* @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 PaymentRequest
{
public const DESCRIPTION_MAX_LENGTH = 500;
/**
* @param string $accountId номер расширенного счёта (`MNT_ID`)
* @param string $transactionId идентификатор заказа в модуле (`MNT_TRANSACTION_ID`)
* @param Money $amount сумма к оплате
* @param string $subscriberId идентификатор покупателя (`MNT_SUBSCRIBER_ID`)
* @param bool $testMode тестовый режим счёта
* @param Signature $signature подпись с кодом проверки целостности счёта
* @param string $description описание заказа для покупателя
* @param string $successUrl возврат покупателя после успешной оплаты
* @param string $failUrl возврат после отказа
* @param string $returnUrl возврат при отмене покупателем
* @param PaymentServer $server боевой сервер или демо-площадка
* @param string $locale язык платёжной формы (`moneta.locale`)
* @param string $cms идентификатор CMS и модуля (`MNT_CMS`)
*/
public function __construct(
private readonly string $accountId,
private readonly string $transactionId,
private readonly Money $amount,
private readonly string $subscriberId,
private readonly bool $testMode,
private readonly Signature $signature,
private readonly string $description,
private readonly string $successUrl,
private readonly string $failUrl,
private readonly string $returnUrl,
private readonly PaymentServer $server,
private readonly string $locale,
private readonly string $cms,
) {
if ($accountId === '' || $transactionId === '') {
throw new InvalidArgumentException('Номер счёта и идентификатор заказа обязательны.');
}
if (!$amount->isPositive()) {
throw new InvalidArgumentException('Сумма платежа должна быть больше нуля.');
}
}
public function getActionUrl(): string
{
return $this->server->url();
}
/**
* @return array<string, string>
*/
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,
),
];
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
/**
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum PaymentServer: string
{
case Prod = 'PROD';
case Demo = 'DEMO';
/**
* Адрес платёжной формы MONETA.Assistant.
*/
public function url(): string
{
return match ($this) {
self::Prod => '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;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
/**
* Коды `MNT_RESULT_CODE` ответов модуля (`MONETA.Assistant.ru.pdf`, гл. 4–5).
*
* На Check URL код описывает состояние заказа; на Pay URL сервис считает
* уведомление доставленным только при 200, при 100/302/402 повторяет его,
* при 500 прекращает попытки.
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum ResultCode: int
{
/** Ответ содержит сумму заказа — в проверочном запросе `MNT_AMOUNT` не было. */
case WithAmount = 100;
/** Заказ оплачен, уведомление доставлено. */
case Paid = 200;
/** Заказ в обработке, точный статус определить нельзя. */
case InProgress = 302;
/** Заказ создан и готов к оплате. */
case AwaitingPayment = 402;
/** Заказ неактуален (отменён, не найден); сервис прекращает повторы. */
case Rejected = 500;
/**
* Текст для `MNT_DESCRIPTION` / `description`: без кавычек, `&`, `$`, `#`
* и слэшей — требование `cmsspecification.pdf` к значениям ответа.
*/
public function description(): string
{
return match ($this) {
self::WithAmount => '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',
};
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\protocol;
use InvalidArgumentException;
use paygw_moneta\local\Money;
/**
* Три формулы подписи MONETA.Assistant (`MONETA.Assistant.ru.pdf`, гл. 3–5).
*
* Везде MD5 от конкатенации значений без разделителей плюс код проверки
* целостности; отсутствующий параметр — пустая строка. Экземпляр держит код,
* чтобы он не гулял по сигнатурам методов.
*
* @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 Signature
{
private const PATTERN = '/\A[0-9a-f]{32}\z/i';
public function __construct(
#[\SensitiveParameter]
private readonly string $integrityCode,
) {
if ($integrityCode === '') {
throw new InvalidArgumentException('Код проверки целостности не задан.');
}
}
/**
* Формула 1 — платёжная форма (модуль → сервис).
*
* md5(MNT_ID + MNT_TRANSACTION_ID + MNT_AMOUNT + MNT_CURRENCY_CODE + MNT_SUBSCRIBER_ID + MNT_TEST_MODE + КОД)
*/
public function forPaymentForm(
string $accountId,
string $transactionId,
Money $amount,
string $currency,
string $subscriberId,
bool $testMode,
): string {
return $this->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);
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
use InvalidArgumentException;
/**
* Покупатель в чеке — объект `client` из `kassaspecification.pdf`: обязательно
* хотя бы одно из `email`/`phone`; при обоих чек уходит только на e-mail.
* `name` — ФИО покупателя, передаётся только вместе с контактом.
*
* @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 Client
{
public const NAME_MAX_LENGTH = 256;
public const EMAIL_MAX_LENGTH = 64;
/** По `kassaspecification.pdf` (принимающая сторона); JSON-схема Check URL даёт 13. */
public const PHONE_MAX_LENGTH = 19;
private function __construct(
public readonly ?string $name,
public readonly ?string $email,
public readonly ?string $phone,
) {}
/**
* Строит покупателя из «сырых» данных профиля; невалидные значения
* отбрасываются. Если у покупателя нет ни e-mail, ни телефона, подставляется
* `$fallbackEmail` — настройка «Email для чеков» (чек уходит продавцу, ФИО
* покупателя остаётся); без неё покупателя нет (`null`).
*/
public static function fromContacts(
?string $email,
?string $phone,
?string $name = null,
?string $fallbackEmail = null,
): ?self {
$email = self::normalizeEmail($email);
$phone = self::normalizePhone($phone);
if ($email === null && $phone === null) {
$email = self::normalizeEmail($fallbackEmail);
}
if ($email === null && $phone === null) {
return null;
}
return new self(self::normalizeName($name), $email, $phone);
}
/**
* @param array{name?: ?string, email?: ?string, phone?: ?string} $data
*/
public static function fromArray(array $data): self
{
$client = self::fromContacts($data['email'] ?? null, $data['phone'] ?? null, $data['name'] ?? null);
if ($client === null) {
throw new InvalidArgumentException('У покупателя нет ни e-mail, ни телефона.');
}
return $client;
}
/**
* @return array<string, string>
*/
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;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
use paygw_moneta\local\Money;
/**
* Денежные числа в JSON без `float`: спецификация требует «два знака после
* точки, даже если это нули», а `json_encode(100.0)` даст `100.0`. Сумма
* кодируется меткой и после `json_encode` заменяется на десятичную строку без
* кавычек — получается литерал `100.00`, валидный JSON-number.
*
* @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 JsonNumber
{
private const PREFIX = '__paygw_moneta_number:';
private function __construct() {}
public static function placeholder(Money $amount): string
{
return self::PREFIX . $amount->toDecimal();
}
/**
* @param array<string, mixed> $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;
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
/**
* Признак способа расчёта (`pm` / `paymentMethod`), перечень из `cmsspecification.pdf`.
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum PaymentMethod: string
{
case FullPrepayment = 'full_prepayment';
case Prepayment = 'prepayment';
case Advance = 'advance';
case FullPayment = 'full_payment';
case PartialPayment = 'partial_payment';
case Credit = 'credit';
case CreditPayment = 'credit_payment';
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
/**
* Признак предмета расчёта (`po` / `paymentObject`), перечень из `cmsspecification.pdf`.
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum PaymentObject: string
{
case Commodity = 'commodity';
case Excise = 'excise';
case Job = 'job';
case Service = 'service';
case GamblingBet = 'gambling_bet';
case GamblingPrize = 'gambling_prize';
case Lottery = 'lottery';
case LotteryPrize = 'lottery_prize';
case IntellectualActivity = 'intellectual_activity';
case Payment = 'payment';
case AgentCommission = 'agent_commission';
case Composite = 'composite';
case Another = 'another';
case PropertyRight = 'property_right';
case SalesTax = 'sales_tax';
case ResortFee = 'resort_fee';
}
+156
View File
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
use InvalidArgumentException;
use paygw_moneta\local\Money;
/**
* Чек 54-ФЗ: покупатель и позиции. Сумма позиций обязана совпадать с суммой
* операции до копейки — иначе номенклатура не пройдёт валидацию кассы.
*
* @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 Receipt
{
/** @var list<ReceiptItem> */
public readonly array $items;
/**
* @param list<ReceiptItem> $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<string, string>, items: list<array<string, mixed>>}
*/
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<string, string>, items: list<array<string, string|int>>}
*/
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<string, ?string>, items?: list<array<string, mixed>>} $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);
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
use InvalidArgumentException;
use paygw_moneta\local\Money;
/**
* Позиция чека — объект `inventPositions` (`kassaspecification.pdf`) и элемент
* `items` JSON-ответа Check URL (`cmsspecification.pdf`).
*
* @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 ReceiptItem
{
public const NAME_MAX_LENGTH = 128;
/** Максимальная цена позиции и произведения `price * quantity`. */
public const PRICE_MAX = '42949672.95';
/** Пустое имя касса не примет; остаётся, если после чистки ничего нет. */
private const FALLBACK_NAME = 'Услуга';
/** Единица измерения из перечня кассы; для доступа к курсу иной не бывает. */
private const MEASURE = 'unit';
public readonly string $name;
public function __construct(
string $name,
public readonly Money $price,
public readonly int $quantity,
public readonly Vat $vat,
public readonly PaymentMethod $paymentMethod,
public readonly PaymentObject $paymentObject,
) {
$name = ReceiptText::validate($name, self::NAME_MAX_LENGTH);
$this->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<string, mixed>
*/
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<string, string>
*/
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<string, string|int>
*/
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<string, mixed> $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'] ?? '')),
);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
/**
* Текстовые поля чека: «значения не должны содержать кавычек, знаков &, $, #,
* обратных и прямых слэшей» (`cmsspecification.pdf`).
*
* @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 ReceiptText
{
private function __construct() {}
public static function validate(string $value, int $maxLength): string
{
$maxLength = max(0, $maxLength);
$value = self::sanitize($value);
if (mb_strlen($value, 'UTF-8') <= $maxLength) {
return $value;
}
return mb_substr($value, 0, max(0, $maxLength - 3), 'UTF-8') . ($maxLength > 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);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\local\receipt;
/**
* Ставка НДС позиции чека. Значение case — код `vat` для JSON-ответа Check URL
* (`cmsspecification.pdf`), оно же хранится в настройке шлюза и снимке заказа;
* {@see self::tag()} даёт тег `vatTag` для `INVENTORY` Pay URL
* (`kassaspecification.pdf`).
*
* @package paygw_moneta
* @copyright 2026 Moneta Labs {@link https://moneta.ru/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
enum Vat: string
{
case None = 'none';
case Vat0 = 'vat0';
case Vat5 = 'vat5';
case Vat7 = 'vat7';
case Vat10 = 'vat10';
case Vat20 = 'vat20';
case Vat22 = 'vat22';
case Vat105 = 'vat105';
case Vat107 = 'vat107';
case Vat110 = 'vat110';
case Vat120 = 'vat120';
case Vat122 = 'vat122';
/**
* Тег `vatTag` для `INVENTORY` Pay URL (`kassaspecification.pdf`).
*/
public function tag(): string
{
return match ($this) {
self::None => '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;
}
}
+176
View File
@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
namespace paygw_moneta\privacy;
use context;
use context_system;
use core_payment\privacy\paygw_provider;
use core_privacy\local\metadata\collection;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\approved_userlist;
use core_privacy\local\request\contextlist;
use core_privacy\local\request\core_userlist_provider;
use core_privacy\local\request\transform;
use core_privacy\local\request\userlist;
use core_privacy\local\request\writer;
use paygw_moneta\local\order\Order;
use paygw_moneta\local\order\TransactionRepository;
/**
* Privacy API: заказы `paygw_moneta_transactions` содержат id покупателя,
* сумму, статус и снимок чека с его e-mail/телефоном.
*
* Оплаченные заказы ядро выгружает и удаляет вместе с платежом
* ({@see paygw_provider}); неоплаченные не привязаны к платежу, поэтому
* плагин обслуживает их сам в системном контексте.
*
* @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 provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\plugin\provider,
core_userlist_provider,
paygw_provider
{
public static function get_metadata(collection $collection): collection
{
$collection->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),
];
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Действия после установки платёжного шлюза 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;
}
+40
View File
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="payment/gateway/moneta/db" VERSION="20260915" COMMENT="XMLDB file for the Moneta payment gateway"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../lib/xmldb/xmldb.xsd">
<TABLES>
<TABLE NAME="paygw_moneta_transactions" COMMENT="Заказы: попытки оплаты через MONETA.Assistant">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="paymentid" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="accountid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="component" TYPE="char" LENGTH="100" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="paymentarea" TYPE="char" LENGTH="50" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="itemid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="merchantorderid" TYPE="char" LENGTH="64" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="providertransactionid" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="amount" TYPE="number" LENGTH="20" DECIMALS="5" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="currency" TYPE="char" LENGTH="3" NOTNULL="true" DEFAULT="RUB" SEQUENCE="false"/>
<FIELD NAME="status" TYPE="char" LENGTH="32" NOTNULL="true" DEFAULT="new" SEQUENCE="false"/>
<FIELD NAME="lasterror" TYPE="text" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="snapshot" TYPE="text" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="timecompleted" TYPE="int" LENGTH="10" NOTNULL="false" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
<KEY NAME="paymentid" TYPE="foreign" FIELDS="paymentid" REFTABLE="payments" REFFIELDS="id"/>
<KEY NAME="accountid" TYPE="foreign" FIELDS="accountid" REFTABLE="payment_accounts" REFFIELDS="id"/>
<KEY NAME="userid" TYPE="foreign" FIELDS="userid" REFTABLE="user" REFFIELDS="id"/>
</KEYS>
<INDEXES>
<INDEX NAME="merchantorderid" UNIQUE="true" FIELDS="merchantorderid"/>
<INDEX NAME="providertransactionid" UNIQUE="true" FIELDS="providertransactionid"/>
<INDEX NAME="paymentitem" UNIQUE="false" FIELDS="component, paymentarea, itemid, userid"/>
<INDEX NAME="status" UNIQUE="false" FIELDS="status"/>
</INDEXES>
</TABLE>
</TABLES>
</XMLDB>
+46
View File
@@ -0,0 +1,46 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Провайдеры сообщений шлюза 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,
],
],
];
+33
View File
@@ -0,0 +1,33 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Шаги обновления платёжного шлюза 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;
}
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<COMPATIBILITY_MATRIX>
<PLUGIN name="paygw_moneta">
<PHP version="8.1" level="required">
<FEEDBACK>
<ON_ERROR message="environmentrequirephp81" />
</FEEDBACK>
</PHP>
</PLUGIN>
</COMPATIBILITY_MATRIX>
+135
View File
@@ -0,0 +1,135 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Строки платёжного шлюза 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';
+135
View File
@@ -0,0 +1,135 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Строки платёжного шлюза 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'] = 'Сумма оплаты';
+65
View File
@@ -0,0 +1,65 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Создаёт заказ и отправляет покупателя на платёжную форму 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();
+4
View File
@@ -0,0 +1,4 @@
<svg width="120" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="100" width="16" height="120" fill="#F6BC25"/>
<path d="M4 43V94H16.9048V62.6191L30.521 88.4565H39.7677L53.4855 62.5002V94H67V43H51.25L35.4149 73.4677L19.3435 43H4Z" fill="#007CB5"/>
</svg>

After

Width:  |  Height:  |  Size: 298 B

+9
View File
@@ -0,0 +1,9 @@
<svg width="119" height="44" viewBox="0 0 119 44" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M118.25 0H112.263V44H118.25V0Z" fill="#F6BC25"/>
<path d="M0 33.8614V19.8333H4.24615L8.99845 28.788L8.40793 28.7602L13.0759 19.8333H17.4345V33.8614H13.6945V21.1917L15.0724 22.6056L9.89829 32.3365H7.33936L2.16525 22.5778L3.57126 21.4135V33.8614H0Z" fill="#007CB5"/>
<path d="M28.2882 34.3051C26.7323 34.3051 25.3451 33.991 24.1265 33.3625C22.9268 32.7157 21.9894 31.8285 21.3145 30.7011C20.6396 29.5737 20.3022 28.2891 20.3022 26.8475C20.3022 25.3875 20.6396 24.0936 21.3145 22.9662C21.9894 21.8388 22.9268 20.9608 24.1265 20.3325C25.3451 19.704 26.7323 19.3899 28.2882 19.3899C29.8818 19.3899 31.2784 19.704 32.4783 20.3325C33.678 20.9608 34.6154 21.8388 35.2902 22.9662C35.9651 24.0936 36.3025 25.3782 36.3025 26.8197C36.3025 28.2799 35.9651 29.5737 35.2902 30.7011C34.6154 31.8285 33.678 32.7157 32.4783 33.3625C31.2784 33.991 29.8818 34.3051 28.2882 34.3051ZM28.3165 30.8674C29.0288 30.8674 29.6569 30.7011 30.2004 30.3685C30.7442 30.0172 31.1659 29.5459 31.4658 28.9545C31.7658 28.3446 31.9158 27.6423 31.9158 26.8475C31.9158 26.0527 31.7658 25.3504 31.4658 24.7406C31.1659 24.1307 30.7442 23.6594 30.2004 23.3266C29.6569 22.9755 29.0288 22.7999 28.3165 22.7999C27.604 22.7999 26.9667 22.9755 26.4043 23.3266C25.8606 23.6594 25.4388 24.1307 25.1389 24.7406C24.839 25.3504 24.6889 26.0527 24.6889 26.8475C24.6889 27.6423 24.839 28.3446 25.1389 28.9545C25.4388 29.5459 25.8606 30.0172 26.4043 30.3685C26.9667 30.7011 27.604 30.8674 28.3165 30.8674Z" fill="#007CB5"/>
<path d="M48.9728 33.8614V19.8333H53.2189V33.8614H48.9728ZM39.187 33.8614V19.8333H43.4051V33.8614H39.187ZM41.1554 28.1782V24.8513H51.4474V28.1782H41.1554Z" fill="#007CB5"/>
<path d="M68.9348 29.3427L71.0719 31.8656C70.3594 32.6233 69.4316 33.224 68.288 33.6675C67.1444 34.0926 65.8977 34.3051 64.548 34.3051C62.8609 34.3051 61.3797 33.991 60.105 33.3625C58.849 32.7342 57.8648 31.8656 57.1525 30.7566C56.44 29.629 56.0837 28.3353 56.0837 26.8753C56.0837 25.3966 56.4213 24.0936 57.0962 22.9662C57.7898 21.8388 58.7178 20.9608 59.8801 20.3325C61.0611 19.704 62.3828 19.3899 63.845 19.3899C65.2698 19.3899 66.5352 19.704 67.6412 20.3325C68.7473 20.9424 69.6097 21.7926 70.2283 22.883C70.8657 23.9735 71.1844 25.2395 71.1844 26.6812V26.8475H67.0507V26.4318C67.0507 25.637 66.9195 24.9531 66.657 24.3802C66.3945 23.8072 66.0195 23.3637 65.5321 23.0493C65.0636 22.7167 64.4918 22.5504 63.817 22.5504C63.1421 22.5504 62.542 22.7259 62.0172 23.0771C61.4924 23.4097 61.0798 23.8904 60.7799 24.5187C60.4987 25.1287 60.3581 25.8773 60.3581 26.7644C60.3581 27.707 60.5456 28.5016 60.9206 29.1486C61.2953 29.7955 61.8204 30.2853 62.4952 30.6179C63.1701 30.9321 63.9388 31.0892 64.8011 31.0892C66.4132 31.0892 67.7912 30.507 68.9348 29.3427ZM71.1844 28.0674H58.7271V25.5445H70.7063L71.1844 26.709V28.0674Z" fill="#007CB5"/>
<path d="M77.0263 33.8614V21.3026H81.2444V33.8614H77.0263ZM72.3584 23.1601V19.8333H85.9122V23.1601H72.3584Z" fill="#007CB5"/>
<path d="M101.036 33.8616H97.2119V31.0339L97.015 30.6733V25.3782C97.015 24.454 96.7058 23.7517 96.0872 23.2712C95.4871 22.7721 94.6624 22.5227 93.6125 22.5227C92.8252 22.5227 92.0847 22.6705 91.3911 22.9662C90.7162 23.2434 90.1163 23.6407 89.5913 24.1583L87.5105 21.6632C88.2604 20.9424 89.1789 20.3879 90.2662 19.9997C91.3723 19.5931 92.5533 19.3899 93.8094 19.3899C95.2529 19.3899 96.5089 19.6209 97.5775 20.0829C98.6647 20.5266 99.5084 21.1918 100.108 22.0791C100.727 22.9662 101.036 24.0382 101.036 25.295V33.8616ZM92.5721 34.3051C91.4661 34.3051 90.4913 34.1111 89.6476 33.7229C88.804 33.3163 88.1478 32.7711 87.6793 32.0872C87.2293 31.4034 87.0044 30.5995 87.0044 29.6753C87.0044 28.7142 87.2856 27.8918 87.8479 27.2079C88.429 26.524 89.2446 25.9974 90.2944 25.6276C91.363 25.2581 92.6097 25.0732 94.0343 25.0732H97.3806V27.6515H94.3155C93.397 27.6515 92.6658 27.8178 92.1223 28.1506C91.5785 28.4832 91.3067 28.936 91.3067 29.509C91.3067 30.0265 91.5222 30.4516 91.9535 30.7842C92.3846 31.0986 92.9377 31.2555 93.6125 31.2555C94.2687 31.2555 94.8686 31.117 95.4123 30.8398C95.9558 30.5441 96.3965 30.1559 96.7338 29.6753C97.0901 29.1764 97.2963 28.6219 97.3526 28.0118L98.4773 28.4832C98.4773 29.6477 98.2337 30.6733 97.7462 31.5606C97.2588 32.4292 96.5652 33.1037 95.6653 33.5844C94.7655 34.0648 93.7344 34.3051 92.5721 34.3051Z" fill="#007CB5"/>
</svg>

After

Width:  |  Height:  |  Size: 4.3 KiB

+45
View File
@@ -0,0 +1,45 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Отчёт администратора по заказам 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();
}
+72
View File
@@ -0,0 +1,72 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Возврат покупателя с платёжной формы (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();
+52
View File
@@ -0,0 +1,52 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* Общие настройки шлюза 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');
}
+86
View File
@@ -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;
}
+83
View File
@@ -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 <http://www.gnu.org/licenses/>.
}}
{{!
@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"}]
}
}}
<div class="paygw-moneta-checkout card mx-auto">
<div class="card-body p-4">
<a class="paygw-moneta-checkout-brand" href="https://moneta.ru/" target="_blank" rel="noopener noreferrer">
<img class="paygw-moneta-checkout-logo" src="{{logourl}}" alt="{{#str}}pluginname, paygw_moneta{{/str}}">
<span class="sr-only visually-hidden">{{#str}}opensinnewwindow{{/str}}</span>
</a>
<div class="paygw-moneta-checkout-label">
{{#iscourse}}{{#str}}checkout:course, paygw_moneta{{/str}}{{/iscourse}}
{{^iscourse}}{{#str}}checkout:item, paygw_moneta{{/str}}{{/iscourse}}
</div>
<h3 class="paygw-moneta-checkout-title">{{description}}</h3>
<div class="paygw-moneta-checkout-total">
<span class="text-muted">{{#str}}checkout:total, paygw_moneta{{/str}}</span>
<strong class="paygw-moneta-checkout-cost">{{cost}}</strong>
</div>
<form method="post" action="{{action}}" id="paygw-moneta-form-{{uniqid}}">
{{#fields}}
<input type="hidden" name="{{name}}" value="{{value}}">
{{/fields}}
<button type="submit" class="btn btn-primary btn-lg w-100 paygw-moneta-checkout-button">{{#str}}pay, paygw_moneta, {{cost}}{{/str}}</button>
</form>
<div class="paygw-moneta-checkout-note text-muted small">
{{#pix}}i/lock, core{{/pix}}
<div>
<div>{{#str}}checkout:secure, paygw_moneta{{/str}}</div>
{{#iscourse}}<div class="mt-1">{{#str}}checkout:access, paygw_moneta{{/str}}</div>{{/iscourse}}
</div>
</div>
</div>
</div>
{{#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}}
+31
View File
@@ -0,0 +1,31 @@
<?php
// 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 <http://www.gnu.org/licenses/>.
/**
* 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';